]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/sugar_grp_emails.js
Release 6.1.5
[Github/sugarcrm.git] / include / javascript / sugar_grp_emails.js
1
2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
3
4 /**
5  * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6  * dragged element is inserted before the dragged-over element.
7  *
8  * @extends YAHOO.util.DDProxy
9  * @constructor
10  * @param {String} id the id of the linked element
11  * @param {String} sGroup the group of related DragDrop objects
12  */
13 function ygDDList(id, sGroup) {
14
15         if (id) {
16                 this.init(id, sGroup);
17                 this.initFrame();
18                 //this.logger = new ygLogger("ygDDList");
19         }
20
21         var s = this.getDragEl().style;
22         s.borderColor = "transparent";
23         s.backgroundColor = "#f6f5e5";
24         s.opacity = 0.76;
25         s.filter = "alpha(opacity=76)";
26 }
27
28 ygDDList.prototype = new YAHOO.util.DDProxy();
29
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
32
33 ygDDList.prototype.startDrag = function(x, y) {
34         //this.logger.debug(this.id + " startDrag");
35
36         var dragEl = this.getDragEl();
37         var clickEl = this.getEl();
38
39         dragEl.innerHTML = clickEl.innerHTML;
40         dragElObjects = dragEl.getElementsByTagName('object');
41
42         
43         dragEl.className = clickEl.className;
44         dragEl.style.color = clickEl.style.color;
45         dragEl.style.border = "1px solid #aaa";
46
47         // save the style of the object 
48         clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
49         
50         this.borderDiv = document.createElement('div'); // create a div to display border
51         this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52         this.borderDiv.style.border = '2px dashed #cccccc';
53         
54         for(i in clickEl.childNodes) { // hide contents of the target elements contents
55                 if(typeof clickEl.childNodes[i].style != 'undefined') {
56                         this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57                         clickEl.childNodes[i].style.display = 'none';
58                 }
59
60         }
61         clickEl.appendChild(this.borderDiv);
62 };
63
64 ygDDList.prototype.endDrag = function(e) {
65         // disable moving the linked element
66         var clickEl = this.getEl();
67
68         clickEl.removeChild(this.borderDiv); // remove border div
69         
70         for(i in clickEl.childNodes) { // show target elements contents
71                 if(typeof clickEl.childNodes[i].style != 'undefined') {
72                         clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
73                 }
74         }
75         
76         if(this.clickHeight) 
77             clickEl.style.height = this.clickHeight;
78         else 
79                 clickEl.style.height = '';
80         
81         if(this.clickBorder) 
82             clickEl.style.border = this.clickBorder;
83         else 
84                 clickEl.style.border = '';
85                 
86         dragEl = this.getDragEl();
87         dragEl.innerHTML = '';
88
89         this.afterEndDrag(e);
90 };
91
92 ygDDList.prototype.afterEndDrag = function(e) {
93
94 }
95
96 ygDDList.prototype.onDrag = function(e, id) {
97     
98 };
99
100 ygDDList.prototype.onDragOver = function(e, id) {
101         // this.logger.debug(this.id.toString() + " onDragOver " + id);
102         var el;
103         
104     if ("string" == typeof id) {
105         el = YAHOO.util.DDM.getElement(id);
106     } else { 
107         el = YAHOO.util.DDM.getBestMatch(id).getEl();
108     }
109     
110         dragEl = this.getDragEl();
111         elRegion = YAHOO.util.Dom.getRegion(el);
112             
113 //    this.logger.debug('id: ' + el.id);
114 //    this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 //    this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116         var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 //    this.logger.debug('mid: ' + mid);
118         
119 //    this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " <  " + mid);
120 //    this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
121         
122         if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123                 var el2 = this.getEl();
124                 var p = el.parentNode;
125                 p.insertBefore(el2, el);
126         }
127         if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128                 var el2 = this.getEl();
129                 var p = el.parentNode;
130                 p.insertBefore(el2, el.nextSibling);
131         }
132 };
133
134 ygDDList.prototype.onDragEnter = function(e, id) {
135         // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136         // this.getDragEl().style.border = "1px solid #449629";
137 };
138
139 ygDDList.prototype.onDragOut = function(e, id) {
140     // I need to know when we are over nothing
141         // this.getDragEl().style.border = "1px solid #964428";
142 }
143
144 /////////////////////////////////////////////////////////////////////////////
145
146 function ygDDListBoundary(id, sGroup) {
147         if (id) {
148                 this.init(id, sGroup);
149                 //this.logger = new ygLogger("ygDDListBoundary");
150                 this.isBoundary = true;
151         }
152 }
153
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
156                                 
157 /*********************************************************************************
158  * SugarCRM is a customer relationship management program developed by
159  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
160  *
161  * This program is free software; you can redistribute it and/or modify it under
162  * the terms of the GNU Affero General Public License version 3 as published by the
163  * Free Software Foundation with the addition of the following permission added
164  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
167  *
168  * This program is distributed in the hope that it will be useful, but WITHOUT
169  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
171  * details.
172  *
173  * You should have received a copy of the GNU Affero General Public License along with
174  * this program; if not, see http://www.gnu.org/licenses or write to the Free
175  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
176  * 02110-1301 USA.
177  *
178  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
180  *
181  * The interactive user interfaces in modified source and object code versions
182  * of this program must display Appropriate Legal Notices, as required under
183  * Section 5 of the GNU Affero General Public License version 3.
184  *
185  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186  * these Appropriate Legal Notices must retain the display of the "Powered by
187  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188  * technical reasons, the Appropriate Legal Notices must display the words
189  * "Powered by SugarCRM".
190  ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span>&nbsp;</span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace('&#039;',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML='&nbsp;';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};addToValidate(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,'email',this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
216 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
217 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
218 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
219 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
220 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
221 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
222 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
223 if(SUGAR.isIE){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
224 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
225 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();// End of File include/SugarEmailAddress/SugarEmailAddress.js
226                                 
227 /*********************************************************************************
228  * SugarCRM is a customer relationship management program developed by
229  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
230  *
231  * This program is free software; you can redistribute it and/or modify it under
232  * the terms of the GNU Affero General Public License version 3 as published by the
233  * Free Software Foundation with the addition of the following permission added
234  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
235  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
236  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
237  *
238  * This program is distributed in the hope that it will be useful, but WITHOUT
239  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
240  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
241  * details.
242  *
243  * You should have received a copy of the GNU Affero General Public License along with
244  * this program; if not, see http://www.gnu.org/licenses or write to the Free
245  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
246  * 02110-1301 USA.
247  *
248  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
249  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
250  *
251  * The interactive user interfaces in modified source and object code versions
252  * of this program must display Appropriate Legal Notices, as required under
253  * Section 5 of the GNU Affero General Public License version 3.
254  *
255  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
256  * these Appropriate Legal Notices must retain the display of the "Powered by
257  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
258  * technical reasons, the Appropriate Legal Notices must display the words
259  * "Powered by SugarCRM".
260  ********************************************************************************/
261 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
262 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
263 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
264 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
265 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
266 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
267 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
268 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
269 this.js_more();this.js_more();}
270 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
271 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
272 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
273 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
274 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&&currentNode.tagName=='SPAN'){currentNode.id=/_input/.test(currentNode.id)?this.field_element_name+'_input_div_'+this.fields_count:this.field_element_name+'_radio_div_'+this.fields_count;if(/_input/.test(currentNode.id)){currentNode.name='teamset_div';}
275 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
276 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
277 currentNode.name=new_name;currentNode.id=new_name;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_name;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
278 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
279 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
280 arrow.value='show';}
281 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
282 break;}}
283 if(!has_primary){return false;}
284 return true;}
285 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
286 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
287 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
288 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
289 if(noAdd){enableQS(false);}
290 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_collection_"+i);var id_field=document.getElementById("id_"+this.field+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].id==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
291 divCount++;}}
292 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
293 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
294 return false;}}
295 SUGAR.collection.safe_clone=function(e,recursive)
296 {if(e.nodeName=="#text")
297 {return document.createTextNode(e.data);}
298 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];for(var i in properties)
299 {if(e[properties[i]])
300 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
301 newNode[properties[i]]=e[properties[i]];}}
302 if(recursive)
303 {for(var i in e.childNodes)
304 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
305 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
306 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
307                                 
308 /*********************************************************************************
309  * SugarCRM is a customer relationship management program developed by
310  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
311  *
312  * This program is free software; you can redistribute it and/or modify it under
313  * the terms of the GNU Affero General Public License version 3 as published by the
314  * Free Software Foundation with the addition of the following permission added
315  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
316  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
317  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
318  *
319  * This program is distributed in the hope that it will be useful, but WITHOUT
320  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
321  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
322  * details.
323  *
324  * You should have received a copy of the GNU Affero General Public License along with
325  * this program; if not, see http://www.gnu.org/licenses or write to the Free
326  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
327  * 02110-1301 USA.
328  *
329  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
330  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
331  *
332  * The interactive user interfaces in modified source and object code versions
333  * of this program must display Appropriate Legal Notices, as required under
334  * Section 5 of the GNU Affero General Public License version 3.
335  *
336  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
337  * these Appropriate Legal Notices must retain the display of the "Powered by
338  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
339  * technical reasons, the Appropriate Legal Notices must display the words
340  * "Powered by SugarCRM".
341  ********************************************************************************/
342 SUGAR.inboundEmail={};Rot13={map:null,convert:function(a){Rot13.init();var s="";for(i=0;i<a.length;i++){var b=a.charAt(i);s+=((b>='A'&&b<='Z')||(b>='a'&&b<='z')?Rot13.map[b]:b);}
343 return s;},init:function(){if(Rot13.map!=null)
344 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
345 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
346 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
347 function getEncryptedPassword(login,password,mailbox){var words=new Array(login,password,mailbox);for(i=0;i<3;i++){word=words[i];if(word.indexOf('&')>0){fragment1=word.substr(0,word.indexOf('&'));fragment2=word.substr(word.indexOf('&')+1,word.length);newWord=fragment1+'::amp::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
348 if(word.indexOf('+')>0){fragment1=word.substr(0,word.indexOf('+'));fragment2=word.substr(word.indexOf('+')+1,word.length);newWord=fragment1+'::plus::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
349 if(word.indexOf('%')>0){fragment1=word.substr(0,word.indexOf('%'));fragment2=word.substr(word.indexOf('%')+1,word.length);newWord=fragment1+'::percent::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}}
350 return words;}
351 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName)
352 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
353 ie_id=document.getElementById(formName).ie_id.value;URL='index.php?'
354 +'module='+module_name
355 +'&to_pdf=1'
356 +'&action='+action
357 +'&target='+pageTarget
358 +'&target1='+pageTarget
359 +'&server_url='+mail_server
360 +'&email_user='+words[0]
361 +'&protocol='+protocol
362 +'&port='+port
363 +'&email_password='+words[1]
364 +'&mailbox='+words[2]
365 +'&ssl='+ssl
366 +'&ie_id='+ie_id
367 +'&personal='+isPersonal;var SI=SUGAR.inboundEmail;if(!SI.testDlg){SI.testDlg=new YAHOO.widget.SimpleDialog("testSettingsDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.testDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);if(this.evalJS)
368 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
369 this.body.style.width=w}}
370 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
371 title=SUGAR.language.get('InboundEmail','LBL_TEST_SETTINGS');SI.testDlg.setHeader(title);SI.testDlg.setBody(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.testDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.testDlg._updateContent,failure:SI.testDlg.hide,scope:SI.testDlg});SI.testDlg.show();}
372 function isDataValid(formName,validateMonitoredFolder){var formObject=document.getElementById(formName);var errors=new Array();var out=new String();if(trim(formObject.server_url.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_SERVER'));}
373 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
374 if(trim(formObject.email_password.value)==""&&trim(formObject.ie_id.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PASSWORD'));}
375 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
376 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
377 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
378 if(errors.length>0){out=SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_DESC');for(i=0;i<errors.length;i++){if(out!=""){out+="\n";}
379 out+=errors[i];}
380 alert(out);return false;}else{return true;}}
381 function getFoldersListForInboundAccount(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,searchFieldValue,formName){if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';URL='index.php?'
382 +'module='+module_name
383 +'&to_pdf=1'
384 +'&action='+action
385 +'&target='+pageTarget
386 +'&target1='+pageTarget
387 +'&server_url='+mail_server
388 +'&email_user='+words[0]
389 +'&protocol='+protocol
390 +'&port='+port
391 +'&email_password='+words[1]
392 +'&mailbox='+words[2]
393 +'&ssl='+ssl
394 +'&personal='+isPersonal
395 +'&searchField='+searchFieldValue;var SI=SUGAR.inboundEmail;if(!SI.listDlg){SI.listDlg=new YAHOO.widget.SimpleDialog("selectFoldersDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.listDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
396 this.body.style.width=w}}
397 SI.listDlg.setHeader(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.listDlg.setBody('');SI.listDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.listDlg._updateContent,failure:SI.listDlg.hide,scope:SI.listDlg});SI.listDlg.show();}
398 function setPortDefault(){var prot=document.getElementById('protocol');var ssl=document.getElementById('ssl');var port=document.getElementById('port');var stdPorts=new Array("110","143","993","995");var stdBool=new Boolean(false);if(port.value==''){stdBool.value=true;}else{for(i=0;i<stdPorts.length;i++){if(stdPorts[i]==port.value){stdBool.value=true;}}}
399 if(stdBool.value==true){if(prot.value=='imap'&&ssl.checked==false){port.value="143";}else if(prot.value=='imap'&&ssl.checked==true){port.value='993';}else if(prot.value=='pop3'&&ssl.checked==false){port.value='110';}else if(prot.value=='pop3'&&ssl.checked==true){port.value='995';}}}
400 function toggle_monitored_folder(field){var field1=document.getElementById('protocol');var mailbox=document.getElementById('mailbox');var label_inbox=document.getElementById('label_inbox');var subscribeFolderButton=document.getElementById('subscribeFolderButton');var trashFolderRow=document.getElementById('trashFolderRow');var trashFolderRow1=document.getElementById('trashFolderRow1');var sentFolderRow=document.getElementById('sentFolderRow');if(field1.value=='imap'){mailbox.disabled=false;try{mailbox.style.display='';trashFolderRow.style.display='';sentFolderRow.style.display='';trashFolderRow1.style.display='';subscribeFolderButton.style.display='';}catch(e){};label_inbox.style.display='';}
401 else{mailbox.value="INBOX";mailbox.disabled=false;try{mailbox.style.display="none";trashFolderRow.style.display="none";sentFolderRow.style.display="none";trashFolderRow1.style.display="none";subscribeFolderButton.style.display="none";}catch(e){};label_inbox.style.display="none";}}// End of File modules/InboundEmail/InboundEmail.js
402                                 
403 /*********************************************************************************
404  * SugarCRM is a customer relationship management program developed by
405  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
406  * 
407  * This program is free software; you can redistribute it and/or modify it under
408  * the terms of the GNU Affero General Public License version 3 as published by the
409  * Free Software Foundation with the addition of the following permission added
410  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
411  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
412  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
413  * 
414  * This program is distributed in the hope that it will be useful, but WITHOUT
415  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
416  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
417  * details.
418  * 
419  * You should have received a copy of the GNU Affero General Public License along with
420  * this program; if not, see http://www.gnu.org/licenses or write to the Free
421  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
422  * 02110-1301 USA.
423  * 
424  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
425  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
426  * 
427  * The interactive user interfaces in modified source and object code versions
428  * of this program must display Appropriate Legal Notices, as required under
429  * Section 5 of the GNU Affero General Public License version 3.
430  * 
431  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
432  * these Appropriate Legal Notices must retain the display of the "Powered by
433  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
434  * technical reasons, the Appropriate Legal Notices must display the words
435  * "Powered by SugarCRM".
436  ********************************************************************************/
437
438 SUGAR.email2 = {
439     cache : new Object(),
440     o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
441     reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
442     templates : {},
443     tinyInstances : {
444         currentHtmleditor : ''
445     },
446
447     /**
448      * preserves hits from email server
449      */ 
450     _setDetailCache : function(ret) {
451         if(ret.meta) {
452             var compKey = ret.meta.mbox + ret.meta.uid;
453
454             if(!SUGAR.email2.cache[compKey]) {
455                 SUGAR.email2.cache[compKey] = ret;
456             }
457         }
458     },
459
460     autoSetLayout : function() {
461         var c = document.getElementById('container');
462         var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
463         //Ensure a minimum height.
464         tHeight = Math.max(tHeight, 550);
465         c.style.height = tHeight + "px";
466         SUGAR.email2.complexLayout.set('height', tHeight);
467         SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
468         SUGAR.email2.complexLayout.render();
469         SUGAR.email2.listViewLayout.resizePreview();        
470     }
471 };
472
473 /**
474  * Shows overlay progress message
475  */
476 function overlayModal(title, body) {
477     overlay(title, body);
478 }
479 function overlay(reqtitle, body, type, additconfig) {
480     var config = { };
481     if (typeof(additconfig) == "object") {
482         var config = additconfig;
483     }
484     config.type = type;
485     config.title = reqtitle;
486     config.msg = body;
487     YAHOO.SUGAR.MessageBox.show(config);
488 };
489
490 function hideOverlay() {
491         YAHOO.SUGAR.MessageBox.hide();
492 };
493 // End of File modules/Emails/javascript/EmailUIShared.js
494                                 
495 /*********************************************************************************
496  * SugarCRM is a customer relationship management program developed by
497  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
498  * 
499  * This program is free software; you can redistribute it and/or modify it under
500  * the terms of the GNU Affero General Public License version 3 as published by the
501  * Free Software Foundation with the addition of the following permission added
502  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
503  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
504  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
505  * 
506  * This program is distributed in the hope that it will be useful, but WITHOUT
507  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
508  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
509  * details.
510  * 
511  * You should have received a copy of the GNU Affero General Public License along with
512  * this program; if not, see http://www.gnu.org/licenses or write to the Free
513  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
514  * 02110-1301 USA.
515  * 
516  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
517  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
518  * 
519  * The interactive user interfaces in modified source and object code versions
520  * of this program must display Appropriate Legal Notices, as required under
521  * Section 5 of the GNU Affero General Public License version 3.
522  * 
523  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
524  * these Appropriate Legal Notices must retain the display of the "Powered by
525  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
526  * technical reasons, the Appropriate Legal Notices must display the words
527  * "Powered by SugarCRM".
528  ********************************************************************************/
529
530
531 (function() {
532         var sw = YAHOO.SUGAR,
533                 Event = YAHOO.util.Event,
534                 Connect = YAHOO.util.Connect,
535             Dom = YAHOO.util.Dom
536             SE = SUGAR.email2;
537
538 ///////////////////////////////////////////////////////////////////////////////
539 ////    EMAIL ACCOUNTS
540 SE.accounts = {
541     outboundDialog : null,
542     inboundAccountEditDialog : null,
543     inboundAccountsSettingsTable : null,
544     outboundAccountsSettingsTable : null,
545     testOutboundDialog : null,
546     errorStyle : 'input-error',
547     normalStyle : '',
548     newAddedOutboundId : '',
549
550     /**
551      * makes async call to retrieve an outbound instance for editting
552      */
553      //EXT111
554     editOutbound : function(obi) {
555
556             AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
557
558     },
559     deleteOutbound : function(obi) {
560
561         if(obi.match(/^(add|line|sendmail)+/)) {
562             alert('Invalid Operation');
563         } else {
564                 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
565             AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
566         }
567     },
568     //EXT111
569     getReplyAddress : function() {
570         var primary = '';
571
572         for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
573             var addy = SE.userPrefs.current_user.emailAddresses[i];
574
575             if(addy.primary_address == "1") {
576                 primary = addy.email_address;
577             }
578
579             if(addy.reply_to == "1") {
580                 return addy.email_address;
581             }
582         }
583
584         return primary;
585     },
586
587     /**
588      * Called on "Accounts" tab activation event
589      */
590     lazyLoad : function() {
591
592         this._setupInboundAccountTable();
593         this._setupOutboundAccountTable();
594
595     },
596
597     _setupInboundAccountTable: function()
598     {
599         //Setup the inbound mail settings
600         if(!this.inboundAccountsSettingsTable)
601         {
602                   this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
603                                         var clckEvent = oColumn.key;
604                                         var imgSrc = "";
605                                         var is_group = oRecord.getData("is_group");
606                                         if(!is_group)
607                                         {
608                                         if(oColumn.key == 'edit')
609                                         {
610                                                 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
611                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
612                                         }
613                                         else if(oColumn.key == 'delete')
614                                         {
615                                                 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
616                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
617                                         }
618                                 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
619                                         }
620                    };
621
622                    this.showBoolean = function(el, oRecord, oColumn, oData)
623                    {
624                        var is_group = oRecord.getData("is_group");
625                        var bChecked = oData;
626                        bChecked = (bChecked) ? " checked" : "";
627                        if(!is_group)
628                        {
629                        el.innerHTML = "<input type=\"radio\"" + bChecked +
630                            " name=\"col" + oColumn.getId() + "-radio\"" +
631                            " class=\"yui-dt-radio\">";
632                        }
633                    };
634
635
636                 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
637                 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
638
639                 var typeHoverHelp = '&nbsp;<div id="rollover"><a href="#" class="rollover">'+
640                                     '<img border="0" src="themes/default/images/helpInline.gif">' +
641                                     '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
642
643
644                 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
645                                       {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
646                                       {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
647                                       {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
648                                       {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
649                                       {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
650                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
651                 this.ieDataSource = new YAHOO.util.DataSource(query);
652                         this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
653                         this.ieDataSource.responseSchema = {
654                                 resultsList: "account_list",
655                                 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
656                         };
657                 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
658                         this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
659
660                     var elCheckbox = oArgs.target;
661                     var oColumn = this.getColumn(elCheckbox);
662                         if(oColumn.key == 'is_active')
663                         {
664                                 var oRecord = this.getRecord(elCheckbox);
665                                 oRecord.setData("is_active",elCheckbox.checked);
666                                 var t_id = oRecord.getData('id');
667                         var isGroupFolder = oRecord.getData('has_groupfolder');
668
669                         if(isGroupFolder)
670                             SUGAR.email2.folders.updateSubscriptions();
671                         else
672                         SUGAR.email2.folders.setFolderSelection();
673
674                         }
675                 });
676                         var lastDefaultSelectedId = "";
677                 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
678
679                     var elRadio = oArgs.target;
680                     var oColumn = this.getColumn(elRadio);
681                         if(oColumn.key == 'is_default')
682                         {
683                                 var oRecord = this.getRecord(elRadio);
684                                 var t_id = oRecord.getData('id');
685                                 var t_isGroup = oRecord.getData('is_group');
686                                 if(t_id != lastDefaultSelectedId && !t_isGroup)
687                                 {
688                                                 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
689                                         lastDefaultSelectedId = t_id;
690                                         AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
691                                 }
692                                 else if(t_isGroup)
693                                    YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
694
695                         }
696                 });
697
698                         this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
699                         this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
700         }
701     },
702      _setupOutboundAccountTable: function()
703     {
704         if(!this.outboundAccountsSettingsTable)
705         {
706                 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
707                                         var clckEvent = oColumn.key;
708                                         var imgSrc = "";
709                                         var isEditable = oRecord.getData("is_editable");
710                                         var type = oRecord.getData("type");
711                                         if(isEditable)
712                                         {
713                                         if(oColumn.key == 'edit')
714                                         {
715                                                 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
716                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
717                                         }
718                                         else if(oColumn.key == 'delete' && type == 'user')
719                                         {
720                                                 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
721                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
722                                         }
723                                         if(imgSrc != '')
724                                     elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
725                                         }
726                 };
727
728                 //Custom formatter to display any error messages.
729                         this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
730
731                     if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
732                                             SUGAR.email2.composeLayout.outboundAccountErrors = {};
733
734                         var id = oRecord.getData('id');
735                                         var message = oRecord.getData("errors");
736                                         if(message != '')
737                                         {
738                                     elLiner.innerHTML = '<span class="required">' + message + '</span>';
739                                         //Add the id and message for all outbound accounts.
740                                         SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
741                                         }
742                                         else
743                                         {
744                                             if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
745                                             delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
746                                         }
747                 };
748                 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
749                 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
750
751                 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
752                                                                    {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
753                                                                    {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
754                                                                    {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
755
756                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
757                 this.obDataSource = new YAHOO.util.DataSource(query);
758                         this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
759                         this.obDataSource.responseSchema = {
760
761                                 resultsList: "outbound_account_list",
762                                 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
763                         };
764
765                 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
766
767
768                         this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
769                         this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
770                 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
771         }
772     },
773     /**
774      * Displays a modal diaglogue to edit outbound account settings
775      */
776     showEditInboundAccountDialogue : function(clear) {
777
778         if(!this.inboundAccountEditDialog) {
779                 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
780                 modal:true,
781                                 visible:true,
782                 fixedcenter:true,
783                 constraintoviewport: true,
784                 width   : "600px",
785                 shadow  : true
786             });
787                         EAD.showEvent.subscribe(function() {
788                 var el = this.element;
789                 var viewH = YAHOO.util.Dom.getViewportHeight();
790                 if (this.header && el && viewH - 50 < el.clientHeight) {
791                     var body = this.header.nextElementSibling;
792                                         body.style.overflow = "auto";
793                     body.style.height = (viewH - 50) + "px";
794                 }
795             }, EAD);
796             EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
797                         Dom.removeClass("editAccountDialogue", "yui-hidden");
798
799         } // end lazy load
800
801         if(clear == undefined || clear == true)
802         {
803                 SE.accounts.clearInboundAccountEditScreen();
804                 //Set default protocol to IMAP when creating new records
805                 document.forms['ieAccount'].elements['protocol'].value = "imap";
806                 SE.accounts.setPortDefault();
807         }
808
809         //Check if we should display username/password fields for outbound account if errors were detected.
810         this.checkOutBoundSelection();
811
812         this.inboundAccountEditDialog.render();
813         this.inboundAccountEditDialog.show();
814         SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
815     },
816
817     /**
818     *  Set all fields on the outbound edit form to either enabled/disabled
819     *  except for the username/password.
820     *
821     */
822     toggleOutboundAccountDisabledFields: function(disable)
823     {
824         var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
825         for(var i=0;i<fields.length;i++)
826         {
827             document.getElementById(fields[i]).disabled = disable;
828         }
829         if(disable)
830             Dom.addClass("mail_smtpssl_row", "yui-hidden");
831         else
832             Dom.removeClass('mail_smtpssl_row', "yui-hidden");
833
834     },
835     /**
836     * Refresh the inbound accounts table.
837     */
838     refreshInboundAccountTable : function()
839     {
840             this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
841                 {
842                         success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
843                                 scope: this.inboundAccountsSettingsTable }
844                         );
845     },
846     /**
847     * Refresh the outbound accounts table.
848     */
849     refreshOuboundAccountTable : function()
850     {
851             this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
852                 {
853                         success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
854                                 scope: this.outboundAccountsSettingsTable }
855                         );
856     },
857     /**
858      * Displays a modal diaglogue to add a SMTP server
859      */
860     showAddSmtp : function() {
861         // lazy load dialogue
862         if(!this.outboundDialog) {
863                 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
864                 modal:true,
865                                 visible:true,
866                 fixedcenter:true,
867                 constraintoviewport: true,
868                 width   : "750px",
869                 shadow  : true
870             });
871             this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
872             this.outboundDialog.hideEvent.subscribe(function(){
873                 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
874                 var out = Dom.get("outbound_email");
875                 if (out && out.value == "SYSTEM_ADD")
876                 {
877                         out.value = out.options[0].value;
878                 }
879                 //Check if we should display username/password for system account.
880                 SE.accounts.checkOutBoundSelection();
881                 return true;
882             });
883
884             Dom.removeClass("outboundDialog", "yui-hidden");
885         } // end lazy load
886
887         // clear out form
888         var form = document.getElementById('outboundEmailForm');
889         for(i=0; i<form.elements.length; i++) {
890             if(form.elements[i].name == 'mail_smtpport') {
891                 form.elements[i].value = 25;
892             } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
893                 form.elements[i].value = '';
894             } else if(form.elements[i].type == 'checkbox') {
895                 form.elements[i].checked = false;
896             }
897         }
898         //Render the SMTP buttons
899         if ( !SUGAR.smtpButtonGroup ) {
900             SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
901             SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
902             {
903                 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
904                 document.getElementById('smtp_settings').style.display = '';
905                 form.mail_smtptype.value = e.newValue.get('value');
906             });
907             YAHOO.widget.Button.addHiddenFieldsToForm(form);
908         }
909         //Hide Username/Password
910         SUGAR.email2.accounts.smtp_authenticate_field_display();
911         //Unset readonly fields
912         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
913         SUGAR.email2.accounts.changeEmailScreenDisplay('other');
914                 this.outboundDialog.render();
915         this.outboundDialog.show();
916     },
917
918     /**
919      * Accounts' Advanced Settings view toggle
920      */
921     toggleAdv : function() {
922         var adv = document.getElementById("ie_adv");
923         if(adv.style.display == 'none') {
924             adv.style.display = "";
925         } else {
926             adv.style.display = 'none';
927         }
928     },
929
930         smtp_authenticate_field_display : function() {
931                 var smtpauth_req = document.getElementById("mail_smtpauth_req");
932                 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
933                 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
934         },
935
936     /**
937      * Changes the display used in the outbound email SMTP dialog to match the
938      */
939     changeEmailScreenDisplay : function(smtptype, isSystemAccount)
940     {
941         document.getElementById("smtpButtonGroupTD").style.display = '';
942         document.getElementById("chooseEmailProviderTD").style.display = '';
943         document.getElementById("mailsettings1").style.display = '';
944         document.getElementById("mailsettings2").style.display = '';
945         document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
946         document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
947         document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
948         document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
949
950         switch (smtptype) {
951         case "yahoomail":
952             document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
953             document.getElementById("mail_smtpport").value = '465';
954             document.getElementById("mail_smtpauth_req").checked = true;
955             var ssl = document.getElementById("mail_smtpssl");
956             for(var j=0;j<ssl.options.length;j++) {
957                 if(ssl.options[j].text == 'SSL') {
958                     ssl.options[j].selected = true;
959                     break;
960                 }
961             }
962             document.getElementById("mailsettings1").style.display = 'none';
963             document.getElementById("mailsettings2").style.display = 'none';
964             document.getElementById("mail_smtppass_label").innerHTML =
965             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
966             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
967             break;
968         case "gmail":
969             document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
970             document.getElementById("mail_smtpport").value = '587';
971             document.getElementById("mail_smtpauth_req").checked = true;
972             var ssl = document.getElementById("mail_smtpssl");
973             for(var j=0;j<ssl.options.length;j++) {
974                 if(ssl.options[j].text == 'TLS') {
975                     ssl.options[j].selected = true;
976                     break;
977                 }
978             }
979             document.getElementById("mailsettings1").style.display = 'none';
980             document.getElementById("mailsettings2").style.display = 'none';
981             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
982             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
983             break;
984         case "exchange":
985             if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
986                     || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
987                 document.getElementById("mail_smtpserver").value = '';
988             }
989             document.getElementById("mail_smtpport").value = '25';
990             document.getElementById("mail_smtpauth_req").checked = true;
991             document.getElementById("mailsettings1").style.display = '';
992             document.getElementById("mailsettings2").style.display = '';
993             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
994             document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
995             document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
996             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
997             break;
998         }
999         if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1000         {
1001             document.getElementById("smtpButtonGroupTD").style.display = 'none';
1002             document.getElementById("chooseEmailProviderTD").style.display = 'none';
1003             document.getElementById("mailsettings2").style.display = 'none';
1004         }
1005
1006         SUGAR.email2.accounts.smtp_authenticate_field_display();
1007     },
1008
1009     /**
1010     * Fill the gmail default values for inbound accounts.
1011     */
1012     fillInboundGmailDefaults: function () {
1013
1014         document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1015         document.forms['ieAccount'].elements['ssl'].checked = true;
1016         document.forms['ieAccount'].elements['protocol'].value = "imap";
1017         SUGAR.email2.accounts.setPortDefault();
1018         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1019     },
1020     /**
1021      * Sets Port field to selected protocol and SSL settings defaults
1022      */
1023     setPortDefault : function() {
1024         var prot = document.getElementById('protocol');
1025         var ssl  = document.getElementById('ssl');
1026         var port = document.getElementById('port');
1027         var stdPorts= new Array("110", "143", "993", "995");
1028         var stdBool    = new Boolean(false);
1029         var mailboxdiv = document.getElementById("mailboxdiv");
1030         var trashFolderdiv = document.getElementById("trashFolderdiv");
1031         var sentFolderdiv = document.getElementById("sentFolderdiv");
1032                 var monitoredFolder = document.getElementById("subscribeFolderButton");
1033         if(port.value == '') {
1034             stdBool.value = true;
1035         } else {
1036             for(i=0; i<stdPorts.length; i++) {
1037                 if(stdPorts[i] == port.value) {
1038                     stdBool.value = true;
1039                 }
1040             }
1041         }
1042
1043         if(stdBool.value == true) {
1044             if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1045                 port.value = "143";
1046             } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1047                 port.value = '993';
1048             } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1049                 port.value = '110';
1050             } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1051                 port.value = '995';
1052             }
1053         }
1054
1055         if (prot.value == 'imap') {
1056                 mailboxdiv.style.display = "";
1057                 trashFolderdiv.style.display = "";
1058                 sentFolderdiv.style.display = "";
1059                 monitoredFolder.style.display = "";
1060                 if (document.getElementById('mailbox').value == "") {
1061                         document.getElementById('mailbox').value = "INBOX";
1062                 }
1063         } else {
1064                 mailboxdiv.style.display = "none";
1065                 trashFolderdiv.style.display = "none";
1066                 sentFolderdiv.style.display = "none";
1067                         monitoredFolder.style.display = "none";
1068                 document.getElementById('mailbox').value = "";
1069         } // else
1070     },
1071
1072     /**
1073      * Draws/removes red boxes around required fields.
1074      */
1075     ieAccountError : function(style) {
1076         document.getElementById('server_url').className = style;
1077         document.getElementById('email_user').className = style;
1078         document.getElementById('email_password').className = style;
1079         document.getElementById('protocol').className = style;
1080         document.getElementById('port').className = style;
1081     },
1082
1083     checkOutBoundSelection: function() {
1084         var select = Dom.get('outbound_email');
1085         if (!select || select.selectedIndex == -1) { return; }
1086
1087         var v = select.options[select.selectedIndex].value;
1088
1089         if(v == '')
1090         {
1091                 select.options[select.selectedIndex].selected = false;
1092                 v = select.options[0].value;
1093         }
1094         else if (v == 'SYSTEM_ADD')
1095                 SUGAR.email2.accounts.showAddSmtp();
1096
1097         var foundError = false;
1098         var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1099                 for(i in errorAccounts)
1100                 {
1101                     if(v == i)
1102                     {
1103                         foundError = true;
1104                         break;
1105                     }
1106                 }
1107
1108                 //Should username/password fields for outbound account.
1109                 if(foundError)
1110                     this.toggleInboundOutboundFields(true);
1111                 else
1112                     this.toggleInboundOutboundFields(false);
1113
1114
1115
1116     },
1117     toggleInboundOutboundFields : function (display)
1118     {
1119         if(display)
1120         {
1121             Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1122                     Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1123         }
1124         else
1125         {
1126             Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1127                     Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1128         }
1129     },
1130     /**
1131      * rebuilds the select options for mailer options
1132      */
1133     rebuildMailerOptions : function() {
1134         var select = document.forms['ieAccount'].elements['outbound_email'];
1135         SE.util.emptySelectOptions(select);
1136
1137         //Get the available sugar mailers
1138         var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1139
1140         for(i=0;i<a_outbound.length;i++)
1141         {
1142                 var t_record = a_outbound[i];
1143                 var key = t_record.getData('id');
1144                 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1145
1146                 var opt = new Option(display, key);
1147                 select.options.add(opt);
1148                 if (key == SE.accounts.newAddedOutboundId) {
1149                         select.options.selectedIndex = i;
1150                 }
1151         }
1152
1153         select.options.add(new Option('',''));
1154         select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1155         //Hide/Show username password fields if necessary.
1156         SE.accounts.checkOutBoundSelection();
1157     },
1158     /**
1159      * Empties all the fields in the accounts edit view
1160      */
1161     clearInboundAccountEditScreen:function() {
1162
1163         document.getElementById('ie_id').value = '';
1164         document.getElementById('ie_name').value = '';
1165         document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1166         document.getElementById('ie_from_addr').value = this.getReplyAddress();
1167         document.getElementById('reply_to_addr').value = '';
1168         document.getElementById('server_url').value = '';
1169         document.getElementById('email_user').value = '';
1170         document.getElementById('email_password').value = '';
1171         document.getElementById('port').value = '';
1172         document.getElementById('inbound_mail_smtpuser').value = '';
1173         document.getElementById('inbound_mail_smtppass').value = '';
1174         document.ieAccount.protocol.options[0].selected = true;
1175         // handle SSL
1176         document.getElementById('ssl').checked = false;
1177         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1178     },
1179
1180     /**
1181      * Populates an account's fields in Settings->Accounts
1182      */
1183     fillIeAccount:function(jsonstr) {
1184         var o = JSON.parse(jsonstr);
1185
1186         document.getElementById('ie_id').value = o.id;
1187         document.getElementById('ie_name').value = o.name;
1188         if (o.stored_options != null) {
1189                 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1190                 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1191                 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1192                 if (o.stored_options.trashFolder != null) {
1193                         document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1194                 }
1195                 if (o.stored_options.sentFolder != null) {
1196                         document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1197                 }
1198         }
1199         document.getElementById('server_url').value = o.server_url;
1200         document.getElementById('email_user').value = o.email_user;
1201         document.getElementById('port').value = o.port;
1202         document.getElementById('group_id').value = o.group_id;
1203         document.getElementById('mailbox').value = o.mailbox;
1204
1205
1206         var i = 0;
1207
1208         // handle SSL
1209         if(typeof(o.service[2]) != 'undefined') {
1210             document.getElementById('ssl').checked = true;
1211         }
1212
1213         // handle protocol
1214         if(document.getElementById('protocol').value != o.protocol) {
1215             var prot = document.getElementById('protocol');
1216             for(i=0; i<prot.options.length; i++) {
1217                 if(prot.options[i].value == o.service[3]) {
1218                     prot.options[i].selected = true;
1219                     this.setPortDefault();
1220                 }
1221             }
1222         }
1223  // handle SMTP selection
1224         if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1225             var opts = document.getElementById('outbound_email').options;
1226             for(i=0; i<opts.length; i++) {
1227                 if(opts[i].value == o.stored_options.outbound_email) {
1228                     opts[i].selected = true;
1229                 }
1230             }
1231         }
1232     },
1233
1234     deleteIeAccount : function(IeAccountID,IeGroupID) {
1235         if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1236         {
1237             overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1238
1239             AjaxObject.target = 'frameFlex';
1240             AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1241             SUGAR.email2.accounts.refreshInboundAccountTable();
1242          }
1243      },
1244
1245        // Null check for Outbound Settings.
1246     checkOutboundSettings: function() {
1247         var errorMessage = '';
1248         var isError = false;
1249         if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1250             var mailName = document.getElementById('mail_name').value;
1251             var smtpServer = document.getElementById('mail_smtpserver').value;
1252             var smtpPort = document.getElementById('mail_smtpport').value;
1253
1254             var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1255             if(trim(mailName) == '') {
1256                 isError = true;
1257                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1258             }
1259             if(trim(smtpServer) == '') {
1260                 isError = true;
1261                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1262             }
1263             if(trim(smtpPort) == '') {
1264                 isError = true;
1265                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1266             }
1267             if(mailsmtpauthreq.checked) {
1268                 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1269                     isError = true;
1270                     errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1271                 }
1272             }
1273         }
1274         if(isError) {
1275             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1276             return false;
1277         } else {
1278             return true;
1279         }
1280     },
1281
1282     testOutboundSettings: function() {
1283         var errorMessage = '';
1284         var isError = false;
1285         var fromAddress = document.getElementById("outboundtest_from_address").value;
1286         if (trim(fromAddress) == "") {
1287             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1288             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1289             return false;
1290
1291         }
1292         else if (!isValidEmail(fromAddress)) {
1293             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1294             overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1295             return false;
1296         }
1297
1298         //Hide the dialogue and show an in progress indicator.
1299         SE.accounts.testOutboundDialog.hide();
1300         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1301
1302         //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1303         //nothing is sent in the request.
1304         var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1305         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1306
1307         YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1308         if(outboundType == 'system-override')
1309             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1310
1311         var data = "&emailUIAction=testOutbound&outboundtest_from_address=" +  fromAddress;
1312         AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1313
1314     },
1315
1316     testOutboundSettingsDialog: function() {
1317         //Ensure that all settings are correct before proceeding to send test email.
1318         if(!SE.accounts.checkOutboundSettings())
1319             return;
1320
1321         // lazy load dialogue
1322         if(!SE.accounts.testOutboundDialog) {
1323                 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1324                 modal:true,
1325                                 visible:true,
1326                 fixedcenter:true,
1327                 constraintoviewport: true,
1328                 width   : 600,
1329                 shadow  : true
1330             });
1331             SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1332             Dom.removeClass("testOutboundDialog", "yui-hidden");
1333         } // end lazy load
1334         SE.accounts.testOutboundDialog.render();
1335         SE.accounts.testOutboundDialog.show();
1336     },
1337
1338     /**
1339      * Saves Outbound email settings
1340      */
1341     saveOutboundSettings : function() {
1342         if(SE.accounts.checkOutboundSettings()) {
1343             //Enable the form fields for the post.
1344             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1345             YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1346             AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1347         } else {
1348             return false;
1349         }
1350     },
1351
1352     saveIeAccount : function() {
1353
1354         //Before saving check if there are any error messages associated with the outbound account.
1355         var outboundID = document.getElementById('outbound_email').value;
1356
1357         if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1358             'validateSMTPCreds':true}) )
1359         {
1360             document.getElementById('saveButton').disabled = true;
1361
1362             overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1363
1364             var formObject = document.getElementById('ieAccount');
1365             YAHOO.util.Connect.setForm(formObject);
1366
1367             AjaxObject._reset();
1368             AjaxObject.target = 'frameFlex';
1369             AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1370         }
1371     },
1372
1373     testSettings : function() {
1374         form = document.getElementById('ieAccount');
1375
1376         if(SE.accounts.checkIeCreds()) {
1377             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");
1378         }
1379     },
1380
1381     getFoldersListForInboundAccountForEmail2 : function() {
1382         form = document.getElementById('ieAccount');
1383         if(SE.accounts.checkIeCreds()) {
1384                 var mailBoxValue = form.mailbox.value;
1385                 if (form.searchField.value.length > 0) {
1386                         mailBoxValue = "";
1387                 } // if
1388             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 );
1389         } // if
1390
1391     },
1392
1393     checkIeCreds : function(validateRules) {
1394         if(typeof(validateRules) == 'undefined')
1395             validateRules = {};
1396
1397         var errors = new Array();
1398         var out = new String();
1399
1400         var ie_name = Dom.get('ie_name').value;
1401         var fromAddress = Dom.get('ie_from_addr').value;
1402         var server_url = Dom.get('server_url').value;
1403         var email_user = Dom.get('email_user').value;
1404         var email_password = Dom.get('email_password').value;
1405         var protocol = Dom.get('protocol').value;
1406         var port = Dom.get('port').value;
1407         var oe = Dom.get('outbound_email');
1408         var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1409
1410         var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1411         var outboundPass = Dom.get('inbound_mail_smtppass').value;
1412
1413         //If the username and password were provided then ignore the error messge
1414
1415         var outboundCredentialsFound = false;
1416
1417         if(outboundUserName != "" && outboundPass != "")
1418             outboundCredentialsFound = true;
1419
1420         var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1421
1422         if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1423              && validateSMTPCreds)
1424         {
1425             if(trim(outboundUserName) == "") {
1426                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1427             }
1428             if(trim(outboundPass) == "") {
1429                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1430             }
1431         }
1432
1433         if(trim(ie_name) == "") {
1434             errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1435         }
1436
1437         if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1438         {
1439             if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1440                 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1441             }
1442         }
1443
1444
1445         if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1446              || trim(oe_value) == "SYSTEM_ADD") ) {
1447             errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1448         }
1449         if(trim(server_url) == "") {
1450             errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1451         }
1452         if(trim(email_user) == "") {
1453             errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1454         }
1455         if(protocol == "") {
1456             errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1457         }
1458         if (protocol == 'imap') {
1459                 var mailbox = document.getElementById('mailbox').value;
1460                 if (trim(mailbox) == "") {
1461                         errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1462                 } // if
1463                 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1464                         var trashFolder = document.getElementById('trashFolder').value;
1465                         if (trim(trashFolder) == "") {
1466                                 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1467                         } // if
1468                         } // if
1469         }
1470         if(port == "") {
1471             errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1472         }
1473
1474         if(errors.length > 0) {
1475             out = app_strings.LBL_EMAIL_ERROR_DESC;
1476             for(i=0; i<errors.length; i++) {
1477                 if(out != "") {
1478                     out += "\n";
1479                 }
1480                 out += errors[i];
1481             }
1482
1483             alert(out);
1484             return false;
1485         } else {
1486
1487             return true;
1488         }
1489     },
1490
1491     getIeAccount : function(ieId) {
1492         if(ieId == '')
1493             return;
1494
1495         overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1496                 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1497
1498         AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1499     },
1500
1501     /**
1502      * Iterates through TreeView nodes to apply styles dependent nature of node
1503      */
1504     renderTree:function() {
1505         SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1506         SE.tree.render();
1507     },
1508
1509     //Sets the style for any nodes that need it.
1510     setNodeStyle : function(node) {
1511         if (!node.data.origText) {
1512             node.data.origText = node.data.text;
1513         }
1514         //Set unread
1515         if (typeof(node.data.unseen) != 'undefined') {
1516                 if (node.data.unseen > 0) {
1517                                 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1518                         }
1519                         else {
1520                                 node.setUpLabel(node.data.origText);
1521                         }
1522         } else {
1523                 node.setUpLabel('<span>' + node.data.origText + '</span>');
1524         }
1525         SE.accounts.setupDDTarget(node);
1526     },
1527
1528     setupDDTarget : function(node) {
1529         if (node.ddTarget) {
1530                 node.ddTarget.removeFromGroup();
1531                 delete node.ddTarget;
1532         }
1533         var id = node.getElId();
1534         var num = id.substring(4);
1535         if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1536                         node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1537                         node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1538
1539                 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1540         }
1541         else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1542                 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1543         }
1544     },
1545
1546     /**
1547      * Async call to rebuild the folder list.  After a folder delete or account delete
1548      */
1549     rebuildFolderList : function() {
1550         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1551         AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1552     },
1553
1554     /**
1555      * Returns the number of remote accounts the user has active.
1556      */
1557     getAccountCount : function() {
1558         var tree = SE.tree;
1559         var count = 0;
1560         for(i=0; i<tree._nodes.length; i++) {
1561             var node = tree._nodes[i];
1562
1563             if(typeof(node) != 'undefined' && node.data.ieId) {
1564                 count++;
1565             }
1566         }
1567         return count;
1568     }
1569 };
1570 ////    END ACCOUNTS
1571 ///////////////////////////////////////////////////////////////////////////////
1572
1573
1574
1575
1576 ///////////////////////////////////////////////////////////////////////////////
1577 ////    CONTEXT MENU CALLS
1578 SE.contextMenus = {
1579
1580     assignToDialogue : null,
1581     /**
1582      * Archives from context menu
1583      * @param Array uids
1584      * @param string ieId
1585      * @param string folder
1586      */
1587     _archiveToSugar : function(uids, ieId, folder) {
1588         var ser = '';
1589
1590         for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1591             if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1592             ser += uids[i];
1593         }
1594         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1595     },
1596
1597     /**
1598      * Archives from context menu
1599      */
1600     archiveToSugar : function(menuItem) {
1601         SE.contextMenus.emailListContextMenu.hide();
1602
1603         var rows = SE.grid.getSelectedRows();
1604         var uids = [];
1605         /* iterate through available rows JIC a row is deleted - use first available */
1606         for(var i=0; i<rows.length; i++) {
1607             uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1608         }
1609         var data = SE.grid.getRecord(rows[0]).getData();
1610         SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1611     },
1612
1613     /**
1614      * Popup the printable version and start system's print function.
1615      */
1616     viewPrintable : function(menuItem) {
1617         var rows = SE.grid.getSelectedRows();
1618         var data = SE.grid.getRecord(rows[0]).getData();
1619         SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1620     },
1621
1622     /**
1623      * Marks email flagged on mail server
1624      */
1625     markRead : function(type, contextMenuId) {
1626         SE.contextMenus.markEmail('read');
1627     },
1628
1629     /**
1630      * Assign this emails to people based on assignment rules
1631      */
1632     assignEmailsTo : function(type, contextMenuId) {
1633         if(!SE.contextMenus.assignToDialogue)
1634         {
1635                 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1636                 modal:true,
1637                                 visible:false,
1638                 fixedcenter:true,
1639                 constraintoviewport: true,
1640                 width   : "600px",
1641                 shadow  : true
1642             });
1643             SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1644             enableQS(true);
1645         }
1646
1647         Dom.removeClass("assignToDiv", "yui-hidden");
1648         SE.contextMenus.assignToDialogue.render();
1649         SE.contextMenus.assignToDialogue.show();
1650     },
1651
1652     /**
1653      * Marks email flagged on mail server
1654      */
1655     markFlagged : function(contextMenuId) {
1656         SE.contextMenus.markEmail('flagged');
1657     },
1658
1659     /**
1660      * Marks email unflagged on mail server
1661      */
1662     markUnflagged : function(contextMenuId) {
1663         SE.contextMenus.markEmail('unflagged');
1664     },
1665
1666     /**
1667      * Marks email unread on mail server
1668      */
1669     markUnread : function() {
1670         SE.contextMenus.markEmail('unread');
1671     },
1672
1673     /**
1674      * Deletes an email from context menu
1675      */
1676     markDeleted : function() {
1677         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1678                 document.getElementById('_blank').innerHTML = "";
1679                 SE.contextMenus.markEmail('deleted');
1680         }
1681     },
1682
1683     /**
1684      * generic call API to apply a flag to emails on the server and on sugar
1685      * @param string type "read" | "unread" | "flagged" | "deleted"
1686      */
1687     markEmail : function(type) {
1688         SE.contextMenus.emailListContextMenu.hide();
1689
1690         //var dm = SE.grid.getStore();
1691         //var uids = SE.grid.getSelectedRowIds();
1692         //var indexes = SE.grid.getSelectedRowIndexes();
1693         var rows = SE.grid.getSelectedRows();
1694         if (rows.length == 0)
1695                 rows = [SE.contextMenus.currentRow];
1696         var ser = [ ];
1697
1698         for(var i=0; i<rows.length; i++) {
1699             ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1700         }
1701
1702         ser = YAHOO.lang.JSON.stringify(ser);
1703
1704         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1705         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1706
1707
1708         var count = 0;
1709
1710
1711         if(type == 'read' || type == 'deleted') {
1712             // mark read
1713             for(var j=0; j<rows.length; j++) {
1714                 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1715                     count = count + 1;
1716                     SE.grid.getRecord(rows[j]).setData("seen", "1");
1717                 }
1718             }
1719            //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1720             if(ieId){
1721             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1722             var unseenCount = node.data.unseen;
1723             if (isNaN(unseenCount)) {
1724                 unseenCount = 0;
1725             }
1726             var finalCount = parseInt(unseenCount) - count;
1727             node.data.unseen = finalCount;
1728
1729             SE.accounts.renderTree();
1730             }
1731         } else if(type == 'unread') {
1732             // mark unread
1733             for(var j=0; j<rows.length; j++) {
1734                 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1735                     count = count + 1;
1736                 }
1737             }
1738
1739             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1740             var unseenCount = node.data.unseen;
1741             if (isNaN(unseenCount)) {
1742                 unseenCount = 0;
1743             }
1744             var finalCount = parseInt(unseenCount) + count;
1745             node.data.unseen = finalCount;
1746             SE.accounts.renderTree();
1747         }
1748
1749         if (type == 'unread') {
1750                 for(var i=0; i<rows.length; i++) {
1751                     SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1752                 } // for
1753         }
1754
1755                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1756         AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1757     },
1758
1759     /**
1760      * refreshes the ListView to show changes to cache
1761      */
1762     markEmailCleanup : function() {
1763         SE.accounts.renderTree();
1764         hideOverlay();
1765         SE.listView.refreshGrid();
1766     },
1767
1768         showAssignmentDialog : function() {
1769                 if (SE.contextMenus.assignmentDialog == null) {
1770                         AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1771                 } else {
1772                         SE.contextMenus.assignmentDialog.show();
1773                 } // else
1774         },
1775
1776         /**
1777      * shows the import dialog with only relate visible.
1778      */
1779     relateTo : function() {
1780         SE.contextMenus.emailListContextMenu.hide();
1781
1782         var rows = SE.grid.getSelectedRows();
1783         var data = SE.grid.getRecord(rows[0]).getData();
1784         var ieId = data.ieId;
1785         var folder = data.mbox;
1786         var uids = [];
1787         /* iterate through available rows JIC a row is deleted - use first available */
1788         for(var i=0; i<rows.length; i++) {
1789             uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1790         }
1791         var ser = JSON.stringifyNoSecurity(uids);
1792
1793         AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1794     },
1795
1796         /**
1797      * shows the import dialog with only relate visible.
1798      */
1799     showDetailView : function() {
1800         SE.contextMenus.emailListContextMenu.hide();
1801         var rows = SE.grid.getSelectedRows();
1802         if (rows.length > 1) {
1803                 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1804                 return;
1805         }
1806         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1807         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1808         /* iterate through available rows JIC a row is deleted - use first available */
1809         var uid = SE.grid.getRecord(rows[0]).getData().uid;
1810         SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1811     },
1812
1813     /**
1814      *
1815      */
1816     showEmailDetailViewInPopup : function(ieId,uid, folder) {
1817         overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1818         AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1819     },
1820
1821     /**
1822      * Opens multiple messages from ListView context click
1823      */
1824     openMultiple : function() {
1825         SE.contextMenus.emailListContextMenu.hide();
1826
1827         var rows = SE.grid.getSelectedRows();
1828         var uids = SE.listView.getUidsFromSelection();
1829
1830         if(uids.length > 0) {
1831             var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1832             var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1833             SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1834         }
1835     },
1836
1837     /**
1838      * Replies/forwards email
1839      */
1840     replyForwardEmailContext : function() {
1841         SE.contextMenus.emailListContextMenu.hide();
1842
1843         var indexes = SE.grid.getSelectedRows();
1844         //var dm = SE.grid.getDataModel();
1845         var type = this.id;
1846
1847         for(var i=0; i<indexes.length; i++) {
1848             var row = SE.grid.getRecord(indexes[i]).getData();
1849             SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1850         }
1851     },
1852
1853     //show menu functions
1854     showEmailsListMenu : function(grid, row) {
1855
1856        var data = row.getData();
1857        var draft = (data.type == "draft");
1858        var menu = SE.contextMenus.emailListContextMenu;
1859        var folderNode;
1860
1861        if (SE.tree)
1862        {
1863                if (data.mbox == 'sugar::Emails')
1864                    folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1865                else
1866                    folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1867
1868                if (  folderNode != null && typeof(folderNode) != "undefined"  && typeof(folderNode.data) != "undefined"
1869                    && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1870                   ||  (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1871                        menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1872                else
1873                    menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1874        }
1875        else
1876            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1877
1878        menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1879        menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1880        menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1881        menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1882        menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1883
1884
1885        if (data.mbox == "sugar::Emails")
1886        {
1887            //Allow users to reassign imported emails
1888            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1889            menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1890            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1891            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1892        }
1893        else
1894        {
1895            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1896            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1897        }
1898     },
1899
1900     showFolderMenu : function(grid, rowIndex, event) {
1901        event.stopEvent();
1902        var coords = event.getXY();
1903        SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1904     }
1905 };
1906
1907 SE.contextMenus.dv = {
1908     archiveToSugar : function(contextMenuId) {
1909
1910         SE.contextMenus._archiveToSugar(uids, ieId, folder);
1911     },
1912
1913     replyForwardEmailContext : function(all) {
1914         SE.contextMenus.detailViewContextMenu.hide();
1915     }
1916
1917 };
1918
1919
1920
1921
1922
1923 ////    END SE.contextMenus
1924 ///////////////////////////////////////////////////////////////////////////////
1925
1926
1927
1928 ///////////////////////////////////////////////////////////////////////////////
1929 ////    DETAIL VIEW
1930 SE.detailView = {
1931     consumeMetaDetail : function(ret) {
1932         // handling if the Email drafts
1933         if(ret.type == 'draft') {
1934             SE.composeLayout.c0_composeDraft();
1935             return;
1936         }
1937
1938
1939         // cache contents browser-side
1940         SE._setDetailCache(ret);
1941
1942         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1943         // 2 below must be in global context
1944         meta = ret.meta;
1945         meta['panelId'] = SE.util.getPanelId();
1946
1947         email = ret.meta.email;
1948         var out = displayTemplate.exec({
1949             'app_strings' : app_strings,
1950             'theme' : theme,
1951             'idx' : targetDiv.id,
1952             'meta' : meta,
1953             'email' : meta.email,
1954             'linkBeans' : linkBeans
1955         });
1956         var tabLabel = meta.email.name;
1957         if (tabLabel != null && tabLabel.length > 25) {
1958                 tabLabel = tabLabel.substring(0, 25) + "...";
1959         } // if
1960         targetDiv.set("label", tabLabel);
1961         targetDiv.set("content", out);
1962
1963         var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1964         if (SUGAR.email2.util.isIe()) {
1965                 displayEmailFrameDiv.style.height = "390px";
1966         } else {
1967                 displayEmailFrameDiv.style.height = "410px";
1968         }
1969
1970         var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1971         displayFrame.contentWindow.document.write(email.description);
1972         displayFrame.contentWindow.document.close();
1973
1974         // hide archive links
1975         if(ret.meta.is_sugarEmail) {
1976                         document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1977             document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1978         } else {
1979             if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1980                 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1981         } // else
1982
1983     },
1984
1985     consumeMetaPreview : function(ret) {
1986         // cache contents browser-side
1987         SE._setDetailCache(ret);
1988
1989
1990
1991         var currrow = SE.grid.getLastSelectedRecord();
1992         currrow = SE.grid.getRecord(currrow);
1993         if (!currrow) {
1994             document.getElementById('_blank').innerHTML = '';
1995             return;
1996         }
1997         // handling if the Email drafts
1998         if(ret.type == 'draft'){
1999             if (currrow.getData().uid == ret.uid) {
2000                 SE.composeLayout.c0_composeDraft();
2001             }
2002             return;
2003         }
2004
2005         if (currrow.getData().uid != ret.meta.uid) {
2006            return;
2007         }
2008
2009         // remove loading sprite
2010         document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2011         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2012         meta = ret.meta;
2013         meta['panelId'] = SE.util.getPanelId();
2014         email = ret.meta.email;
2015
2016         document.getElementById('_blank').innerHTML = displayTemplate.exec({
2017             'app_strings' : app_strings,
2018             'theme' : theme,
2019             'idx' : 'Preview',
2020             'meta' : meta,
2021             'email' :meta.email,
2022             'linkBeans' : linkBeans
2023         });
2024        // document.getElementById('_blank').innerHTML = meta.email;
2025        /* displayTemplate.append('_blank', {
2026             'app_strings' : app_strings,
2027             'theme' : theme,
2028             'idx' : 'Preview',
2029             'meta' : meta,
2030             'email' :meta.email,
2031             'linkBeans' : linkBeans
2032         });*/
2033
2034         var displayFrame = document.getElementById('displayEmailFramePreview');
2035         displayFrame.contentWindow.document.write(email.description);
2036         displayFrame.contentWindow.document.close();
2037
2038         SE.listViewLayout.resizePreview();
2039
2040         // hide archive links
2041         if(ret.meta.is_sugarEmail) {
2042             document.getElementById("archiveEmailPreview").innerHTML = "&nbsp;";
2043             document.getElementById("btnEmailViewPreview").style.display = "none";
2044             document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2045         } else {
2046           //hide view relationship link
2047                  document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2048         }
2049     },
2050
2051     /**
2052      * wraps emailDelete() for single messages, comes from preview or tab
2053      */
2054     emailDeleteSingle : function(ieId, uid, mbox) {
2055         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2056             // find active panel and close if the user double clicked the email to view.
2057             var activeTabId = SE.util.getPanelId();
2058             if(activeTabId != 'Preview')
2059                 SE.innerLayout.get("activeTab").close();
2060
2061             document.getElementById('_blank').innerHTML = "";
2062                 var ser = [ ];
2063                         ser.push(uid);
2064                 uid = JSON.stringifyNoSecurity(ser);
2065             this.emailDelete(ieId, uid, mbox);
2066         }
2067     },
2068
2069     /**
2070      * Sends async call to delete a given message
2071      * @param
2072      */
2073     emailDelete : function(ieId, uid, mbox) {
2074        overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2075        AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2076            uid + "&ieId=" + ieId + "&folder=" + mbox);
2077     },
2078
2079     /**
2080      * retrieves one email to display in the preview pane.
2081      */
2082     getEmailPreview : function() {
2083         var row = SUGAR.email2.listView.currentRow;
2084         var data = row.getData();
2085             if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2086                var setRead = (data['seen'] == 0) ? true : false;
2087                    SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2088                    SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2089             }
2090     },
2091
2092     /**
2093      * Imports one email into Sugar
2094      */
2095     importEmail : function(ieId, uid, mbox) {
2096         SE.util.clearHiddenFieldValues('emailUIForm');
2097
2098         overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2099
2100         var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2101         AjaxObject.target = '';
2102         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2103     },
2104
2105     /**
2106      * Populates the frameFlex div with the contents of an email
2107      */
2108     populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2109         SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2110
2111         var mboxStr = new String(mbox);
2112         var compKey = mbox + uid;
2113
2114         if(setRead == true) {
2115                 SE.listView.boldUnreadRows()
2116                 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2117         }
2118
2119         if(destination == SE.innerLayout) {
2120                 /*
2121              * loading email into a tab, peer with ListView
2122              * targetDiv must remain in the global namespace as it is used by AjaxObject
2123              */
2124                 //Check if we already have a tab of the email open
2125                 var tabs = SE.innerLayout.get("tabs");
2126                 for (var t in tabs) {
2127                         if (tabs[t].id && tabs[t].id == uid) {
2128                                 SE.innerLayout.set("activeTab", tabs[t]);
2129                                 return;
2130                         }
2131                 }
2132
2133                 targetDiv = new YAHOO.SUGAR.ClosableTab({
2134                                 label: loadingSprite,
2135                                         scroll : true,
2136                                         content : "",
2137                                         active : true
2138                 }, SE.innerLayout);
2139                 targetDiv.id = uid;
2140                 SE.innerLayout.addTab(targetDiv);
2141
2142             // use cache if available
2143             if(SE.cache[compKey]) {
2144                 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2145             } else {
2146                 // open email as peer-tab to listView
2147                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2148                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2149             }
2150         } else {
2151             // loading email into preview pane
2152             document.getElementById('_blank').innerHTML = loadingSprite;
2153
2154             // use cache if available
2155             if(SE.cache[compKey]) {
2156                 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2157             } else {
2158                 AjaxObject.forceAbort = true;
2159                 // open in preview window
2160                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2161                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2162             }
2163         }
2164     },
2165
2166     requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2167     {
2168         if(mboxStr.substring(0,7) == 'sugar::') {
2169             // display an email from Sugar
2170             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2171         } else {
2172             // display an email from an email server
2173             document.getElementById('emailUIAction').value = 'getSingleMessage';
2174         }
2175         document.getElementById('mbox').value = mbox;
2176         document.getElementById('ieId').value = ieId;
2177         document.getElementById('uid').value = uid;
2178
2179         YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2180
2181         AjaxObject.forceAbort = true;
2182         AjaxObject.target = '_blank';
2183         AjaxObject.startRequest(callback, null);
2184     },
2185
2186     /**
2187      * Retrieves multiple emails for DetailView
2188      */
2189     populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2190         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2191         SE.util.clearHiddenFieldValues('emailUIForm');
2192
2193         var mboxStr = new String(mbox);
2194
2195         uids = SE.util.cleanUids(uids);
2196
2197         if(mboxStr.substring(0,7) == 'sugar::') {
2198             // display an email from Sugar
2199             document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2200             document.getElementById('uid').value = uids;
2201         } else {
2202             // display an email from an email server
2203             document.getElementById('emailUIAction').value = 'getMultipleMessages';
2204             document.getElementById('mbox').value = mbox;
2205             document.getElementById('ieId').value = ieId;
2206             document.getElementById('uid').value = uids;
2207         }
2208
2209         var formObject = document.getElementById('emailUIForm');
2210         YAHOO.util.Connect.setForm(formObject);
2211
2212         AjaxObject.target = 'frameFlex';
2213         AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2214
2215         if(setRead == true) {
2216             var c = uids.split(",");
2217             SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2218         }
2219     },
2220
2221     /**
2222      * Makes async call to get QuickCreate form
2223      * Renders a modal edit view for a given module
2224      */
2225     quickCreate : function(module, ieId, uid, mailbox) {
2226         var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2227
2228         if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2229             get += "&sugarEmail=true";
2230         }
2231
2232         AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2233     },
2234
2235     /**
2236      * Makes async call to save a quick create
2237      * @param bool
2238      */
2239     saveQuickCreate : function(action) {
2240         var qcd = SE.detailView.quickCreateDialog;
2241         if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2242                 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2243                 var theCallback = callbackQuickCreateSave;
2244                 var accountType = '&sugarEmail=true';
2245                 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2246                    accountType = '&ieId=' + qcd.ieId;
2247                 }
2248
2249             if (action == 'reply') {
2250                    theCallback = callbackQuickCreateSaveAndReply;
2251                 } else if (action == true) {
2252                     theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2253                 }
2254                 formObject.action.value = 'EmailUIAjax';
2255                 YAHOO.util.Connect.setForm(formObject);
2256                 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2257                 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2258                                        accountType + '&mbox=' + qcd.mbox);
2259         }
2260     },
2261
2262     /**
2263      * Code to show/hide long list of email address in DetailView
2264      */
2265     showCroppedEmailList : function(el) {
2266         el.style.display = 'none';
2267         el.previousSibling.style.display = 'inline'
2268     },
2269     showFullEmailList : function(el) {
2270         el.style.display = 'none';
2271         el.nextSibling.style.display = 'inline';
2272     },
2273
2274     /**
2275      * Shows the QuickCreate overlay
2276      * @param string ieId
2277      * @param string uid
2278      * @param string mailbox
2279      */
2280     showQuickCreate : function(ieId, uid, mailbox) {
2281         var panelId = SE.util.getPanelId();
2282         var context = document.getElementById("quickCreateSpan" + panelId);
2283
2284         if (!SE.detailView.cqMenus)
2285                 SE.detailView.cqMenus = {};
2286
2287         if (SE.detailView.cqMenus[context])
2288                 SE.detailView.cqMenus[context].destroy();
2289
2290             var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2291                 lazyload:true,
2292                 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2293         });
2294
2295             for (var i=0; i < this.qcmodules.length; i++) {
2296             var module = this.qcmodules[i];
2297             menu.addItem({
2298                 text:   app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2299                 modulename: module,
2300                 value: module,
2301                 onclick: { fn: function() {
2302                                 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2303                         }
2304                 }
2305             });
2306         }
2307
2308                 menu.render(document.body);
2309                 menu.show();
2310     },
2311
2312     /**
2313      * Displays the "View" submenu in the detailView
2314      * @param string ieId
2315      * @param string uid
2316      * @param string mailbox
2317      */
2318     showViewMenu : function(ieId, uid, mailbox) {
2319         var panelId = SE.util.getPanelId();
2320         var context = "btnEmailView" + panelId;
2321         if (!SE.detailView.viewMenus)
2322                 SE.detailView.viewMenus = {};
2323
2324         if (SE.detailView.viewMenus[context])
2325                 SE.detailView.viewMenus[context].destroy();
2326
2327             var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2328                 lazyload:true,
2329                 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2330                 clicktohide: true
2331         });
2332                 menu.addItems(
2333                                 (ieId == 'null' || ieId == null) ?
2334                         //No ieId - Sugar Email
2335                         [{
2336                                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2337                                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2338             }]
2339                         :
2340                         //IeID exists, on a remote server
2341                         [{
2342                 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2343                 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2344             },{
2345                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2346                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2347             }]
2348         );
2349                 menu.render(document.body);
2350                 menu.show();
2351
2352
2353         /*
2354         //#23108 jchi@07/17/2008
2355         menu.render('quickCreateSpan'+ panelId);*/
2356         //this.viewMenu = menu;
2357         //this.viewMenu.show(context);
2358     },
2359     /**
2360      * Makes async call to get an email's headers
2361      */
2362     viewHeaders : function(ieId, uid, mailbox) {
2363         var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2364         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2365     },
2366
2367     /**
2368      * Makes async call to get a printable version
2369      */
2370     viewPrintable : function(ieId, uid, mailbox) {
2371         if(mailbox == 'sugar::Emails') {
2372             // display an email from Sugar
2373             var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2374         } else {
2375             // display an email from an email server
2376             var emailUIAction = '&emailUIAction=getSingleMessage';
2377         }
2378
2379         var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2380         AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2381     },
2382
2383     /**
2384      * Makes async call to get an email's raw source
2385      */
2386     viewRaw : function(ieId, uid, mailbox) {
2387         var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2388         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2389     },
2390
2391     /**
2392      * Display all email addresses in detailview.
2393      */
2394     displayAllAddrs : function(el) {
2395         el.style.display = 'none';
2396         Dom.getNextSibling(el).style.display = 'inline';
2397     }
2398 };
2399 ////    END SE.detailView
2400 ///////////////////////////////////////////////////////////////////////////////
2401
2402
2403
2404 ///////////////////////////////////////////////////////////////////////////////
2405 ////    SE.folders
2406 SE.folders = {
2407     contextMenuFocus : new Object(),
2408
2409     /**
2410      * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2411      * SugarFolder ID - folder strings
2412      */
2413     _createFolderId : function(node) {
2414         var ret = '';
2415
2416         if(!node.data.id)
2417             return ret;
2418
2419         if(node.data.ieId) {
2420             /* we have a local Sugar folder */
2421             if(node.data.ieId == 'folder') {
2422                 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2423             } else if(node.data.ieId.match(SE.reGUID)) {
2424                 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2425             }
2426         } else {
2427             ret = node.data.id;
2428         }
2429
2430         return ret;
2431     },
2432
2433     addChildNode : function(parentNode, childNode) {
2434         var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2435         var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2436         var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2437
2438         if(childNode.nodes) {
2439             if(childNode.nodes.length > 0) {
2440                 for(j=0; j<childNode.nodes.length; j++) {
2441                     var newChildNode = childNode.nodes[j];
2442                     this.addChildNode(node, newChildNode);
2443                 }
2444             }
2445         }
2446     },
2447
2448     /**
2449      * Builds and returns a new TreeView Node
2450      * @param string name
2451      * @param string id
2452      * @param int is_group
2453      * @return object
2454      */
2455     buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2456         var node = new YAHOO.widget.TextNode(name, parentNode, true);
2457
2458         //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2459         node.expanded = expanded;
2460         node.data = new Object;
2461         node.data['id'] = id;
2462         node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2463         node.data['label'] = name;
2464         node.data['ieId'] = 'folder';
2465         node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2466         node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2467         node.data['unseen'] = unseen;
2468         return node;
2469     },
2470
2471     /**
2472      * ensures that a new folder has a valid name
2473      */
2474     checkFolderName : function(name) {
2475         if(name == "")
2476             return false;
2477
2478         this.folderAdd(name);
2479     },
2480
2481     /**
2482      * Pings email servers for new email - forces refresh of folder pane
2483      */
2484     checkEmailAccounts : function() {
2485         this.checkEmailAccountsSilent(true);
2486     },
2487
2488     checkEmailAccountsSilent : function(showOverlay) {
2489         if(typeof(SE.folders.checkingMail)) {
2490             clearTimeout(SE.folders.checkingMail);
2491         }
2492
2493         // don't stomp an on-going request
2494         if(AjaxObject.currentRequestObject.conn == null) {
2495             if(showOverlay) {
2496                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2497                       app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2498             }
2499             AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2500         } else {
2501             // wait 5 secs before trying again.
2502             SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2503         }
2504     },
2505
2506     /**
2507      * Starts check of all email Accounts using a loading bar for large POP accounts
2508      */
2509     startEmailAccountCheck : function() {
2510         // don't do two checks at the same time
2511        if(!AjaxObject.requestInProgress()) {
2512             overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2513             SE.accounts.ieIds = SE.folders.getIeIds();
2514             if (SE.accounts.ieIds.length > 0) {
2515                 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2516                                 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "&currentCount=0");
2517             } else {
2518                hideOverlay();
2519             }
2520         } else {
2521             // wait 5 secs before trying again.
2522             SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2523         }
2524     },
2525
2526     /**
2527      * Checks a single Account check based on passed ieId
2528      */
2529      startEmailCheckOneAccount : function(ieId, synch) {
2530             if (synch) {
2531                 synch = true;
2532             } else {
2533                 synch = false;
2534             }
2535             var mbox = "";
2536             var node = SE.clickedFolderNode;
2537             if (node && !synch) {
2538                 mbox = node.data.mbox;
2539             } // if
2540             overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2541             SE.accounts.ieIds = [ieId];
2542             AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2543                                 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "&currentCount=0&synch=" + synch);
2544       },
2545
2546
2547     /**
2548      * Empties trash for subscribed accounts
2549      */
2550     emptyTrash : function() {
2551         SE.contextMenus.frameFoldersContextMenu.hide();
2552         overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2553         AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2554     },
2555
2556     /**
2557      * Clears Cache files of the inboundemail account
2558      */
2559     clearCacheFiles : function(ieId) {
2560         SE.contextMenus.frameFoldersContextMenu.hide();
2561         overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2562         AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2563     },
2564
2565
2566     /**
2567      * Returns an array of all the active accounts in the folder view
2568      */
2569     getIeIds : function() {
2570          var ieIds = [];
2571          var root = SE.tree.getRoot();
2572          for(i=0; i < root.children.length; i++) {
2573            if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2574                         (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2575                ieIds.push(root.children[i].children[0].data.ieId);
2576            }
2577          }
2578          return ieIds;
2579      },
2580
2581     /**
2582      * loads folder lists in Settings->Folders
2583      */
2584     lazyLoadSettings : function() {
2585         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2586         AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2587     },
2588
2589     /**
2590      * After the add new folder is done via folders tab on seetings, this function should get called
2591      * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2592      */
2593     loadSettingFolder : function() {
2594         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2595         AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2596     },
2597
2598     /**
2599      * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2600      */
2601     removeSugarFolders : function() {
2602         var tree = SE.tree;
2603         var root = tree.getRoot();
2604         var folder = SE.util.findChildNode(root, "ieId", "folder");
2605         while(folder) {
2606             tree.removeNode(folder);
2607             folder = SE.util.findChildNode(root, "ieId", "folder");
2608         }
2609         if (!root.childrenRendered) {
2610                 root.childrenRendered = true;
2611         }
2612     },
2613
2614     rebuildFolders : function(silent) {
2615       if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2616        AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2617     },
2618
2619
2620
2621     /**
2622      * Updates TreeView with Sugar Folders
2623      */
2624     setSugarFolders : function(delay) {
2625         this.removeSugarFolders();
2626                 //AjaxObject.forceAbort = true;
2627                 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2628     },
2629
2630     /**
2631      * Takes async data object and creates the sugar folders in TreeView
2632      */
2633     setSugarFoldersEnd : function(o) {
2634         var root = SE.tree.getRoot();
2635         addChildNodes(root, {nodes: o});
2636         SE.accounts.renderTree();
2637         //If nothing is loaded in the grid, load "My Inbox"
2638         if (SE.grid.params.ieId == "undefined") {
2639                 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2640         }
2641     },
2642
2643     startCheckTimer : function() {
2644         if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2645             var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2646
2647             if(typeof(SE.folders.checkTimer) != 'undefined') {
2648                 clearTimeout(SE.folders.checkTimer);
2649             }
2650
2651             SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2652             if (!SE.userPrefs.emailSettings.firstAutoCheck)
2653             {
2654                 SE.userPrefs.emailSettings.firstAutoCheck = true;
2655                 SE.folders.checkEmailAccountsSilent(false);
2656             }
2657         }
2658     },
2659
2660     /**
2661      * makes an async call to save user preference and refresh folder view
2662      * @param object SELECT list object
2663      */
2664     setFolderSelection : function() {
2665         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2666
2667         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2668         var a_active_accnts = "";
2669         for(i=0;i<a_rs.length;i++)
2670         {
2671                 var t_record = a_rs[i];
2672                 var is_active = t_record.getData('is_active');
2673                 if(is_active)
2674                         a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2675         }
2676
2677         if(a_active_accnts == "")
2678                 a_active_accnts = "&ieIdShow[]=";
2679
2680         var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2681
2682         AjaxObject.startRequest(callbackFolders, urlStandard + query);
2683     },
2684
2685     /**
2686      * makes async call to save user preference for a given node's open state
2687      * @param object node YUI TextNode object
2688      */
2689     setOpenState : function(node) {
2690         SE.util.clearHiddenFieldValues('emailUIForm');
2691         var nodePath = node.data.id;
2692         var nodeParent = node.parent;
2693
2694         while(nodeParent != null) {
2695             // root node has no ID param
2696             if(nodeParent.data != null) {
2697                 nodePath = nodeParent.data.id + "::" + nodePath;
2698             }
2699
2700             var nodeParent = nodeParent.parent;
2701         }
2702
2703         document.getElementById('emailUIAction').value = 'setFolderOpenState';
2704         document.getElementById('focusFolder').value = nodePath;
2705
2706         if(node.expanded == true) {
2707             document.getElementById('focusFolderOpen').value = 'open';
2708         } else {
2709             document.getElementById('focusFolderOpen').value = 'closed';
2710         }
2711
2712         var formObject = document.getElementById('emailUIForm');
2713         YAHOO.util.Connect.setForm(formObject);
2714
2715         AjaxObject.startRequest(null, null);
2716     },
2717
2718     getNodeFromMboxPath : function(path) {
2719         var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2720         var a = JSON.parse(path);
2721
2722         var node = tree.getRoot();
2723
2724         var i = 0;
2725         while(i < a.length) {
2726             node = this.getChildNodeFromLabel(node, a[i]);
2727             i++;
2728         }
2729
2730         return node;
2731     },
2732
2733     getChildNodeFromLabel : function(node, nodeLabel) {
2734         for(i=0; i<node.children.length; i++) {
2735             if(node.children[i].data.id == nodeLabel) {
2736                 return node.children[i];
2737             }
2738         }
2739     },
2740
2741     /**
2742      * returns the node that presumably under the user's right-click
2743      */
2744     getNodeFromContextMenuFocus : function() {
2745         //// get the target(parent) node
2746         var tree = YAHOO.widget.TreeView.trees.frameFolders;
2747         var index = -1;
2748         var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2749
2750         // filter local folders
2751         if(target.className == 'localFolder' || target.className == 'groupInbox') {
2752             while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2753                 if(target.id == '') {
2754                     target = target.parentNode;
2755                 } else {
2756                     break;
2757                 }
2758             }
2759         }
2760
2761         var targetNode = document.getElementById(target.id);
2762         re = new RegExp(/ygtv[a-z]*(\d+)/i);
2763
2764         try {
2765             var matches = re.exec(targetNode.id);
2766         } catch(ex) {
2767             return document.getElementById(ygtvlabelel1);
2768         }
2769
2770         if(matches) {
2771             index = matches[1];
2772         } else {
2773             // usually parent node
2774             matches = re.exec(targetNode.parentNode.id);
2775
2776             if(matches) {
2777                 index = matches[1];
2778             }
2779         }
2780
2781         var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2782         parentNode.expand();
2783
2784         return parentNode;
2785     },
2786
2787     /**
2788      * Decrements the Unread Email count in folder text
2789      * @param string ieId ID to look for
2790      * @param string mailbox name
2791      * @param count how many to decrement
2792      */
2793     decrementUnreadCount : function(ieId, mbox, count) {
2794
2795         if(mbox == null)
2796             return;
2797
2798         if(mbox.indexOf("sugar::") === 0) {
2799             var node = this.getNodeFromId(ieId);
2800         } else {
2801             var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2802         }
2803         if(node) {
2804             var unseen = node.data.unseen;
2805             if(unseen > 0) {
2806                 var check = unseen - count;
2807                 var finalCount = (check >= 0) ? check : 0;
2808                 node.data.unseen = finalCount;
2809             }
2810             SE.accounts.renderTree();
2811         }
2812     },
2813
2814     /**
2815      * gets the TreeView node with a given ID/ieId
2816      * @param string id ID to look for
2817      * @return object Node
2818      */
2819     getNodeFromId : function(id) {
2820         SE.folders.focusNode = null;
2821         SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2822             if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2823                 SE.folders.focusNode = this;
2824                 return false;
2825             }
2826         }, null, [id]);
2827         return SE.folders.focusNode;
2828     },
2829
2830     /**
2831      * Uses ieId and mailbox to try to find a node in the tree
2832      */
2833     getNodeFromIeIdAndMailbox : function(id, mbox) {
2834                 SE.folders.focusNode = null;
2835         if (mbox == "sugar::Emails") {
2836                 mbox = id;
2837                 id = "folder";
2838         } // if
2839         SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2840                 if (varsarray instanceof Array) {
2841             if (this.data.ieId && this.data.ieId == varsarray[0]
2842                     && this.data.mbox == varsarray[1]) {
2843                 SE.folders.focusNode = this;
2844                 return false;
2845             } }
2846                 else {
2847                         if (this.data.ieId && this.data.ieId == varsarray) {
2848                                 SE.folders.focusNode = this;
2849                     return false;
2850                         }
2851                 }
2852         }, null, [id, mbox]);
2853         return SE.folders.focusNode;
2854     },
2855
2856     unhighliteAll : function() {
2857         SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2858     },
2859
2860     /**
2861      * Displays a short form
2862      */
2863     folderAdd : function() {
2864         SE.contextMenus.frameFoldersContextMenu.hide();
2865
2866         var node = SE.clickedFolderNode;
2867
2868         if(node != null && node.data) {
2869             overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2870                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2871                     'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2872         } else {
2873             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2874         }
2875     },
2876
2877     folderAddRegisterEnter : function() {
2878         this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2879                                                                                                                         {keys: YAHOO.util.KeyListener.KEY.ENTER},
2880                                                                                                                         this.buttons[1].handler);
2881
2882                 this.enterKeyListener.enable();
2883     },
2884
2885     folderRemoveRegisterEnter : function() {
2886         this.enterKeyListener.disable();
2887     },
2888
2889     folderAddXmlCall : function(name) {
2890         if (trim(name) == "") {
2891                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2892                 return false;
2893         }
2894         name = escape(name);
2895         var post = '';
2896         var type = 'sugar';
2897
2898         var parentNode = SE.clickedFolderNode;
2899
2900         this.contextMenuFocus = parentNode;
2901
2902         if(parentNode.data.ieId) {
2903             if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2904                 type = 'imap';
2905             }
2906         }
2907         if(type == 'imap') {
2908                 // make an IMAP folder
2909             post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2910             AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2911         } else if(type == 'sugar') {
2912             // make a Sugar folder
2913             if(SE.folders.isUniqueFolderName(name)) {
2914                 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2915                 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2916             } else {
2917                 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2918                 SE.folders.folderAdd();
2919                 return;
2920             }
2921         } else {
2922             alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2923         }
2924
2925         // hide add-folder diaglogue
2926         SE.e2overlay.hide();
2927     },
2928
2929     /**
2930      * Removes either an IMAP folder or a Sugar Folder
2931      */
2932     folderDelete : function() {
2933         SE.contextMenus.frameFoldersContextMenu.hide();
2934
2935         if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2936             var post = '';
2937             var parentNode = SE.clickedFolderNode;
2938
2939             if(parentNode != null && parentNode.data) {
2940                 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2941                     overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2942                     return;
2943                 }
2944
2945                 AjaxObject.target = 'frameFlex';
2946
2947                 if(parentNode.data.ieId != 'folder') {
2948                     // delete an IMAP folder
2949                     post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2950                 } else {
2951                     // delete a sugar folder
2952                     post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2953                 }
2954                 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2955                 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2956             } else {
2957                 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2958             }
2959         }
2960     },
2961
2962     /**
2963      * Rename folder form
2964      */
2965      //EXT111
2966     folderRename : function() {
2967         SE.contextMenus.frameFoldersContextMenu.hide();
2968         var node = SE.clickedFolderNode;
2969
2970         if(node != null) {
2971             if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2972                 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2973                 return;
2974             }
2975
2976                         overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2977                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2978                     'prompt',
2979                     {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2980         } else {
2981             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2982         }
2983     },
2984
2985     /**
2986      * fills an Object with key-value pairs of available folders
2987      */
2988     getAvailableFoldersObject : function() {
2989         var ret = new Object();
2990         var tree = SE.tree.root;
2991
2992         if(tree.children) {
2993             for(var i=0; i<tree.children.length; i++) {
2994                 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
2995             }
2996         } else {
2997             ret['none'] = app_strings.LBL_NONE;
2998         }
2999
3000         return ret;
3001     },
3002
3003     /**
3004      * Fills in key-value pairs for dependent dropdowns
3005      * @param object ret Associative array
3006      * @param object node TreeView node in focus
3007      * @param string currentPath Built up path thus far
3008      * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3009      */
3010     getFolderFromChild : function(ret, node, currentPath, spacer) {
3011         if(node.data != null && node.depth > 0) {
3012             /* handle visual separtors differentiating b/t mailserver and local */
3013             if(node.data.ieId && node.data.ieId == 'folder') {
3014                 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3015             }
3016
3017             if(!ret.spacer0) {
3018                 ret['spacer0'] = spacer;
3019             } else if(ret.spacer0 != spacer) {
3020                 ret['spacer1'] = spacer
3021             }
3022
3023             var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3024             var depthMarker = currentPath;
3025             var retIndex = SE.folders._createFolderId(node);
3026             ret[retIndex] = depthMarker + theLabel;
3027         }
3028
3029         if(node.children != null) {
3030             if(theLabel) {
3031                 currentPath += theLabel + "/";
3032             }
3033
3034             for(var i=0; i<node.children.length; i++) {
3035                 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3036             }
3037         }
3038
3039         return ret;
3040     },
3041
3042     /**
3043      * Wrapper to refresh folders tree
3044      */
3045     getFolders : function() {
3046         SE.accounts.rebuildFolderList();
3047     },
3048
3049     /**
3050      * handles events around folder-rename input field changes
3051      * @param object YUI event object
3052      */
3053     handleEnter : function(e) {
3054         switch(e.browserEvent.type) {
3055             case 'click':
3056                 e.preventDefault(); // click in text field
3057             break;
3058
3059             case 'blur':
3060                 SE.folders.submitFolderRename(e);
3061             break;
3062
3063             case 'keypress':
3064                 var kc = e.browserEvent.keyCode;
3065                 switch(kc) {
3066                     case 13: // enter
3067                         e.preventDefault();
3068                         SE.folders.submitFolderRename(e);
3069                     break;
3070
3071                     case 27: // esc
3072                         e.preventDefault(e);
3073                         SE.folders.cancelFolderRename(e);
3074                     break;
3075                 }
3076             break;
3077         }
3078     },
3079     /**
3080     * Called when a node is clicked on in the folder tree
3081     * @param node, The node clicked on
3082     * @param e, The click event
3083     */
3084     handleClick : function(o) {
3085         var node = o.node;
3086         //If the click was on a sugar folder
3087         if (node.data.ieId == "folder") {
3088             SE.listView.populateListFrameSugarFolder(node, node.id, false);
3089         }
3090         else {
3091             SE.listView.populateListFrame(node, node.data.ieId, false);
3092         }
3093        //eval(node.data.click);
3094        //debugger;
3095     },
3096
3097     /**
3098     * Called when a node is right-clicked on in the folder tree
3099     */
3100     handleRightClick : function(e) {
3101         YAHOO.util.Event.preventDefault(e);
3102                 //Get the Tree Node
3103                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3104                 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3105
3106                 //If the click was on a sugar folder
3107         SE.clickedFolderNode = node;
3108         var inbound = (node.data.ieId && node.data.ieId != 'folder');
3109                 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3110                 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3111                 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3112                 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3113                 menu.getItem(3).cfg.setProperty("disabled", false);
3114                 menu.getItem(4).cfg.setProperty("disabled", false);
3115                 menu.getItem(5).cfg.setProperty("disabled", false);
3116                 menu.getItem(6).cfg.setProperty("disabled", true);
3117                 //Group folder
3118                 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3119                         menu.getItem(0).cfg.setProperty("disabled", true);
3120                         menu.getItem(1).cfg.setProperty("disabled", true);
3121                         menu.getItem(2).cfg.setProperty("disabled", true);
3122                         menu.getItem(3).cfg.setProperty("disabled", true);
3123                         menu.getItem(4).cfg.setProperty("disabled", true);
3124                 }
3125         if (node.data.protocol != null) {
3126                 menu.getItem(6).cfg.setProperty("disabled", false);
3127         }
3128                 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3129                                 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3130                         //Sent or Draft folders
3131                         menu.getItem(3).cfg.setProperty("disabled", true);
3132                         menu.getItem(4).cfg.setProperty("disabled", true);
3133                         menu.getItem(5).cfg.setProperty("disabled", true);
3134                 }
3135
3136                 //For group with auto inbound, disable everything.
3137                 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3138                 {
3139                     menu.getItem(0).cfg.setProperty("disabled", true);
3140                 menu.getItem(1).cfg.setProperty("disabled", true);
3141                 menu.getItem(2).cfg.setProperty("disabled", true);
3142                 menu.getItem(3).cfg.setProperty("disabled", true);
3143                 menu.getItem(4).cfg.setProperty("disabled", true);
3144                 menu.getItem(5).cfg.setProperty("disabled", true);
3145                 menu.getItem(6).cfg.setProperty("disabled", true);
3146                 }
3147
3148                 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3149                 menu.show();
3150     },
3151
3152     /**
3153     * Called when a row is dropped on a node
3154     */
3155     handleDrop : function(rows, targetFolder) {
3156         var rowData = rows[0].getData();
3157         if (rowData.mbox != targetFolder.data.mbox) {
3158             var srcIeId = rowData.ieId;
3159             var srcFolder = rowData.mbox;
3160             var destIeId = targetFolder.data.ieId;
3161             var destFolder = targetFolder.data.mbox;
3162             var uids = [];
3163             for(var i=0; i<rows.length; i++) {
3164                 uids[i] = rows[i].getData().uid;
3165             }
3166             SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3167         }
3168     },
3169
3170     /**
3171     * Called when something is dragged over a Folder Node
3172     */
3173     dragOver : function(dragObject) {
3174        return true;
3175     },
3176
3177     /**
3178      * Determines if a folder name is unique to the folder tree
3179      * @param string name
3180      */
3181     isUniqueFolderName : function(name) {
3182         uniqueFolder = true;
3183         var root = SE.tree.getRoot();
3184         SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3185             if (this.attributes && this.attributes.ieId == "folder") {
3186                 if (this.attributes.text == name) {
3187                     uniqueFolder = false;
3188                     return false;
3189                 }
3190             }
3191         }, null, [name]);
3192         return uniqueFolder;
3193     },
3194
3195     /**
3196      * Makes async call to rename folder in focus
3197      * @param object e Event Object
3198      */
3199     submitFolderRename : function(newName) {
3200         if (trim(newName) == "") {
3201                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3202                 return false;
3203         }
3204                 newName = escape(newName);
3205         var node = SE.clickedFolderNode;
3206         var origName = node.data.text
3207         //Ignore no change
3208         if (newName == origName) {
3209             return true;
3210         }
3211         if(SE.folders.isUniqueFolderName(newName)) {
3212             overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3213             if (node.data.ieId == "folder") {
3214                 //Sugar Folder
3215                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3216             }
3217             else {
3218                 //IMAP folder or POP mailbox
3219                 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3220                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3221                     + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3222             }
3223             return true;
3224         } else {
3225             alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3226             return false;
3227         }
3228     },
3229
3230     moveFolder : function(folderId, parentFolderId) {
3231         if (folderId != parentFolderId)
3232         {
3233                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3234                     + folderId + "&newParentId=" + parentFolderId);
3235         }
3236     },
3237
3238     /**
3239      * makes async call to do a full synchronization of all accounts
3240      */
3241     synchronizeAccounts : function() {
3242         if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3243             overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3244             AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3245         }
3246     },
3247
3248     /**
3249      * Updates user's folder subscriptsion (Sugar only)
3250      * @param object SELECT DOM object in focus
3251      * @param string type of Folder selection
3252      */
3253     updateSubscriptions : function() {
3254         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3255
3256         var active = "";
3257
3258         select = document.getElementById('userFolders');
3259
3260         for(i=0; i<select.options.length; i++) {
3261             var opt = select.options[i];
3262              if(opt.selected && opt.value != "") {
3263                  if(active != "") {
3264                      active += "::";
3265                  }
3266                  active += opt.value;
3267              }
3268         }
3269
3270         //Add the group folder ids.
3271         var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3272         for(i=0; i<group_folders.length; i++)
3273         {
3274             active += ("::" + group_folders[i]);
3275         }
3276
3277         AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3278     },
3279     /**
3280      * Updates user's group folder subscriptsion (Sugar only)
3281      * @param ieID The group folder to add to the tree view
3282      */
3283     retrieveGroupFolderSubscriptions : function() {
3284
3285         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3286         var activeGroupFolders = "";
3287         var activeGroupIds = [];
3288         for(i=0;i<a_rs.length;i++)
3289         {
3290                 var t_record = a_rs[i];
3291                 var is_active = t_record.getData('is_active');
3292                 var isGroupFolder = t_record.getData('has_groupfolder');
3293                 var ieID = t_record.getData('id');
3294                 if( isGroupFolder )
3295                 {
3296                     if(is_active)
3297                       activeGroupIds.push(ieID);
3298                 }
3299         }
3300
3301         return activeGroupIds;
3302     }
3303
3304 };
3305
3306 SE.folders.checkEmail2 = function() {
3307     AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3308 }
3309 ////    END FOLDERS OBJECT
3310 ///////////////////////////////////////////////////////////////////////////////
3311
3312
3313 ///////////////////////////////////////////////////////////////////////////////
3314 ////    SE.keys
3315 /**
3316  * Keypress Event capture and processing
3317  */
3318 SE.keys = {
3319     overall : function(e) {
3320         switch(e.charCode) {
3321             case 119: // "w"
3322                 if(e.ctrlKey || e.altKey) {
3323                     var focusRegion = SE.innerLayout.regions.center;
3324                     if(focusRegion.activePanel.closable == true) {
3325                         focusRegion.remove(focusRegion.activePanel);
3326                     }
3327                 }
3328             break;
3329         }
3330     }
3331 };
3332 ////    END SE.keys
3333 ///////////////////////////////////////////////////////////////////////////////
3334
3335
3336 ///////////////////////////////////////////////////////////////////////////////
3337 ////    SE.listView
3338 /**
3339  * ListView object methods and attributes
3340  */
3341 SE.listView = {
3342     currentRowId : -1,
3343
3344     /**
3345      * Fills the ListView pane with detected messages.
3346      */
3347     populateListFrame : function(node, ieId, forceRefresh) {
3348         SE.innerLayout.selectTab(0);
3349                 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3350
3351         Dom.get('_blank').innerHTML = "";
3352         SE.grid.params['emailUIAction'] = 'getMessageList';
3353         SE.grid.params['mbox'] = node.data.mbox;
3354         SE.grid.params['ieId'] = ieId;
3355         forcePreview = true; // loads the preview pane with first item in grid
3356         SE.listView.refreshGrid();
3357     },
3358
3359     /**
3360      * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3361      */
3362     populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3363         SE.innerLayout.selectTab(0);
3364         Dom.get('_blank').innerHTML = "";
3365         SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3366         SE.grid.params['ieId'] = node.data.id;
3367         SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3368         SE.listView.refreshGrid();
3369     },
3370
3371     /**Mac
3372      * Sets sort order as user preference
3373      * @param
3374      */
3375     saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3376         ieId = ieIdPassed;
3377         ieName = ieNamePassed;
3378         focusFolder = focusFolderPassed;
3379
3380         SE.util.clearHiddenFieldValues('emailUIForm');
3381         var previousSort = document.getElementById('sortBy').value;
3382
3383         document.getElementById('sortBy').value = sortBy;
3384         document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3385         document.getElementById('focusFolder').value = focusFolder;
3386         document.getElementById('ieId').value = ieId;
3387
3388         if(sortBy == previousSort) {
3389             document.getElementById('reverse').value = '1';
3390         }
3391
3392         var formObject = document.getElementById('emailUIForm');
3393         YAHOO.util.Connect.setForm(formObject);
3394
3395         AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3396     },
3397
3398
3399     /**
3400      * Enables click/arrow select of grid items which then populate the preview pane.
3401      */
3402     selectFirstRow : function() {
3403         SE.grid.selModel.selectFirstRow();
3404     },
3405
3406     selectLastRow : function() {
3407         SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3408     },
3409
3410     setEmailListStyles : function() {
3411         SE.listView.boldUnreadRows();
3412         return;
3413         var ds = SE.grid.getStore();
3414         if (SE.grid.getSelections().length == 0) {
3415             document.getElementById('_blank').innerHTML = '';
3416         }
3417
3418         var acctMbox = '';
3419         if(typeof(ds.baseParams.mbox) != 'undefined') {
3420             acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3421             var cm = SE.grid.getColumnModel();
3422             if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3423                 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3424                 //SE.grid.render();
3425             } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3426                 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3427                 //SE.grid.render();
3428             }
3429         }
3430         var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3431         SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3432
3433
3434         // 4/20/2007 added to hide overlay after search
3435         //hideOverlay();
3436         if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3437             var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3438             var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3439             if (node) node.data.unseen = unread;
3440         }
3441         SE.accounts.renderTree();
3442
3443
3444         // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3445         if(forcePreview && ds.totalCount > 0) {
3446             SE.detailView.getEmailPreview();
3447             forcePreview = false;
3448         }
3449     },
3450
3451     /**
3452      * Removes a row if found via its UID
3453      */
3454     removeRowByUid : function(uid) {
3455         uid = new String(uid);
3456         uids = uid.split(',');
3457         var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3458
3459         for(j=0; j<uids.length; j++) {
3460             var theUid = uids[j];
3461             for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3462                 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3463                         SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3464                 }
3465             } // for
3466         }
3467     },
3468
3469     displaySelectedEmails : function(rows) {
3470         var dm = SE.grid.getDataModel();
3471         var uids = '';
3472
3473         for(i=0; i<rows.length; i++) {
3474             var rowIndex = rows[i].rowIndex;
3475             var metadata = dm.data[rowIndex];
3476
3477             if(uids != "") {
3478                 uids += ",";
3479             }
3480             uids += metadata[5];
3481
3482             // unbold unseen email
3483             this.unboldRow(rowIndex);
3484         }
3485
3486         SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3487     },
3488
3489     /**
3490      * exception handler for data load failures
3491      */
3492     loadException : function(dataModel, ex, response) {
3493         //debugger;
3494     },
3495
3496     /**
3497      * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3498      * @param string sourceIeId Email's source I-E id
3499      * @param string sourceFolder Email's current folder
3500      * @param destinationIeId Destination I-E id
3501      * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3502      *
3503      * @param array emailUids Array of email's UIDs
3504      */
3505     moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3506         if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3507             overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3508         } else {
3509             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3510             // remove rows from visibility
3511             for(row in selectedRows) {
3512                 //SE.grid.getStore().remove(row);
3513             }
3514
3515             var baseUrl =    '&sourceIeId=' + sourceIeId +
3516                             '&sourceFolder=' + sourceFolder +
3517                             '&destinationIeId=' + destinationIeId +
3518                             '&destinationFolder=' + destinationFolder;
3519             var uids = '';
3520
3521             for(i=0; i<emailUids.length; i++) {
3522                 if(uids != '') {
3523                     uids += app_strings.LBL_EMAIL_DELIMITER;
3524                 }
3525                 uids += emailUids[i];
3526             }
3527             if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3528                 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3529             } else {
3530                 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3531             }
3532         }
3533     },
3534
3535     /**
3536      * Unbolds text in the grid view to denote read status
3537      */
3538     markRead : function(index, record) {
3539         // unbold unseen email
3540         var row = SE.grid.getRecord(record);
3541         row.getData().seen = 1;
3542         SE.grid.getTrEl(record).style.fontWeight = "normal";
3543     },
3544
3545     /**
3546      * grid row output, bolding unread emails
3547      */
3548     boldUnreadRows : function() {
3549         // bold unread emails
3550         var trEl = SE.grid.getFirstTrEl();
3551         while(trEl != null) {
3552                 if(SE.grid.getRecord(trEl).getData().seen == "0")
3553                         trEl.style.fontWeight = "bold";
3554                 else
3555                         trEl.style.fontWeight = "";
3556                 trEl = SE.grid.getNextTrEl(trEl);
3557         }
3558     },
3559
3560     /**
3561      * Show preview for an email if 1 and only 1 is selected
3562      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3563      */
3564     handleRowSelect : function(e) {
3565         if(e.selectedRows.length == 1) {
3566             SE.detailView.getEmailPreview();
3567         }
3568     },
3569
3570     handleDrop : function(e, dd, targetId, e2) {
3571         switch(targetId) {
3572             case 'htmleditordiv':
3573                 var rows = SE.grid.getSelectedRows();
3574                 if(rows.length > 0) {
3575                     SE.listView.displaySelectedEmails(rows);
3576                 }
3577             break;
3578
3579             default:
3580                 var targetElId = new String(targetId);
3581                 var targetIndex = targetElId.replace('ygtvlabelel',"");
3582                 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3583                 var dm = SE.grid.getDataModel();
3584                 var emailUids = new Array();
3585                 var destinationIeId = targetNode.data.ieId;
3586                 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3587
3588
3589                 var rows = SE.grid.getSelectedRows();
3590                 // iterate through dragged rows
3591                 for(i=0; i<rows.length; i++) {
3592                     //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3593                     var rowIndex = rows[i].rowIndex;
3594                     var dataModelRow = dm.data[rowIndex];
3595                     var sourceIeId = dataModelRow[7];
3596                     var sourceFolder = dataModelRow[6];
3597                     emailUids[i] = dataModelRow[5];
3598                 }
3599
3600                 // event wrapped call - need FQ
3601                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3602                 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3603             break;
3604         }
3605     },
3606
3607     /**
3608      * Hack-around to get double-click and single clicks to work on the grid
3609      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3610      */
3611     handleClick : function(o) {
3612         SUGAR.email2.grid.clearTextSelection();
3613
3614         var el = SUGAR.email2.grid.getSelectedRows();
3615
3616         //Load an email preview only if a single record is selected.  For multiple selections do nothing.
3617         if ( el.length == 1)
3618         {
3619            var rowId = el[0];
3620            SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3621            SUGAR.email2.listView.currentRowIndex = rowId;
3622            clearTimeout(SUGAR.email2.detailView.previewTimer);
3623            SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3624         }
3625     },
3626
3627     /**
3628      * Custom handler for double-click/enter
3629      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3630      */
3631     getEmail : function(e) {
3632         var rows = SE.grid.getSelectedRows();
3633         var row = SE.grid.getRecord(rows[0]).getData();
3634
3635         clearTimeout(SE.detailView.previewTimer);
3636         document.getElementById("_blank").innerHTML = "";
3637
3638         if(row.type != "draft") {
3639             SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3640         } else {
3641             // circumventing yui-ext tab generation, let callback handler build new view
3642             SE.util.clearHiddenFieldValues('emailUIForm');
3643             //function(uid, mbox, ieId, setRead, destination) {
3644             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3645             document.getElementById('uid').value = row.uid; // uid;
3646             document.getElementById('mbox').value = row.mbox; // mbox;
3647             document.getElementById('ieId').value = row.ieId; // ieId;
3648
3649             YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3650             AjaxObject.target = '_blank';
3651             AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3652         }
3653     },
3654
3655     /**
3656      * Retrieves a row if found via its UID
3657      * @param string
3658      * @return int
3659      */
3660     getRowIndexByUid : function(uid) {
3661         uid = new String(uid);
3662         uids = uid.split(',');
3663
3664         for(j=0; j<uids.length; j++) {
3665             var theUid = uids[j];
3666
3667             for(i=0; i<SE.grid.getStore().data.length; i++) {
3668                 if(SE.grid.getStore().data[i].id == theUid) {
3669                     return i;
3670                 }
3671             }
3672         }
3673     },
3674
3675     /**
3676      * Returns the UID's of the seleted rows
3677      *
3678      */
3679      getUidsFromSelection : function() {
3680          var rows = SE.grid.getSelectedRows();
3681          var uids = [];
3682          /* iterate through available rows JIC a row is deleted - use first available */
3683          for(var i=0; i<rows.length; i++) {
3684                  uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3685          }
3686          return uids;
3687      },
3688
3689     refreshGrid : function() {
3690         SE.grid.getDataSource().sendRequest(
3691             SUGAR.util.paramsToUrl(SE.grid.params),
3692                 SE.grid.onDataReturnInitializeTable,
3693                 SE.grid
3694         );
3695     }
3696
3697 };
3698 ////    END SE.listView
3699 ///////////////////////////////////////////////////////////////////////////////
3700
3701 ///////////////////////////////////////////////////////////////////////////////
3702 ////    SEARCH
3703 SE.search = {
3704     /**
3705      * sends search criteria
3706      * @param reference element search field
3707      */
3708     search : function(el) {
3709         var searchCriteria = new String(el.value);
3710
3711         if(searchCriteria == '') {
3712             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3713             return false;
3714         }
3715
3716         var safeCriteria = escape(searchCriteria);
3717
3718         var accountListSearch = document.getElementById('accountListSearch');
3719         //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3720
3721         SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3722         SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3723         SE.grid.getStore().baseParams['subject'] = safeCriteria;
3724         SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3725         SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3726
3727     },
3728
3729     /**
3730      * sends advanced search criteria
3731      */
3732     searchAdvanced : function() {
3733         var formObject = document.getElementById('advancedSearchForm');
3734         var search = false;
3735
3736         //Set assigned user id to blank if name is not present.
3737         if (formObject.elements['assigned_user_name'].value == "")
3738             formObject.elements['assigned_user_id'].value = "";
3739
3740         for(i=0; i<formObject.elements.length; i++) {
3741             if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3742                 search = true;
3743             }
3744             if(formObject.elements[i].type == 'text') {
3745                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3746             }
3747             if(formObject.elements[i].type == 'hidden') {
3748                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3749             }
3750              if(formObject.elements[i].type == 'select-one') {
3751                 var el = formObject.elements[i];
3752                 var v = el.options[el.selectedIndex].value;
3753
3754                 if(v != "")
3755                     SE.grid.params[el.name] = v;
3756                 else
3757                 {
3758                     //Clear previous search results if necessary
3759                     if(typeof( SE.grid.params[el.name]) != 'undefined')
3760                         delete SE.grid.params[el.name]
3761                 }
3762              }
3763         }
3764
3765         if (search)
3766         {
3767             if(! this.validateSearchFormInput() )
3768                 return;
3769
3770                 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3771                 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3772                 var accountListSearch = document.getElementById('accountListSearch');
3773                 SE.listView.refreshGrid();
3774         } else {
3775             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3776         }
3777     },
3778
3779     /**
3780     *  Validates the search form inputs to ensure all parameters are valid
3781     *  @return bool
3782     */
3783     validateSearchFormInput: function()
3784     {
3785         addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3786         addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3787         var dateCheck = check_form('advancedSearchForm');
3788
3789         //If the parent type is selected ensure the user selected a parent_id.
3790         if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3791             return true;
3792         else
3793             return false;
3794     },
3795     /**
3796     *   Toggles the advanced options, either hidding or showing the selection.
3797     */
3798     toggleAdvancedOptions: function()
3799     {
3800         var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3801
3802         for(var i=0;i<el.length;i++)
3803         {
3804             if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3805                 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3806             else
3807                 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3808         }
3809     },
3810     /**
3811      * clears adv search form fields
3812      */
3813     searchClearAdvanced : function() {
3814         var form = document.getElementById('advancedSearchForm');
3815
3816         for(i=0; i<form.elements.length; i++) {
3817             if(form.elements[i].type != 'button') {
3818                 form.elements[i].value = '';
3819             }
3820         }
3821     }
3822 };
3823 ////    END SE.search
3824 //////////////////////////////////////////////////////////////////////////////
3825
3826
3827 //////////////////////////////////////////////////////////////////////////////
3828 ////    SE.settings
3829 SE.settings = {
3830     /******************************************************************************
3831      * USER SIGNATURES calls stolen from Users module
3832      *****************************************************************************/
3833     createSignature : function(record, the_user_id) {
3834         var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3835         if(record != "") {
3836             URL += "&record="+record;
3837         }
3838         if(the_user_id != "") {
3839             URL += "&the_user_id="+the_user_id;
3840         }
3841         var windowName = 'email_signature';
3842         var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3843
3844         var win = window.open(URL, windowName, windowFeatures);
3845         if(win && win.focus) {
3846             // put the focus on the popup if the browser supports the focus() method
3847             win.focus();
3848         }
3849     },
3850
3851     deleteSignature : function() {
3852         if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3853             overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3854                 var singature_id = document.getElementById('signature_id').value;
3855                 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3856         } // if
3857     },
3858
3859     saveOptionsGeneral :  function(displayMessage) {
3860         var formObject = document.getElementById('formEmailSettingsGeneral');
3861         if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3862                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3863                 return false;
3864         } // if
3865         YAHOO.util.Connect.setForm(formObject);
3866         SE.composeLayout.emailTemplates = null;
3867
3868         AjaxObject.target = 'frameFlex';
3869         AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3870
3871         if(displayMessage)
3872             alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3873
3874         SE.settings.settingsDialog.hide();
3875     },
3876
3877     /**
3878      * Shows settings container screen
3879      */
3880     showSettings : function() {
3881         if(!SE.settings.settingsDialog) {
3882                 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3883                 modal:true,
3884                 visible:false,
3885                 fixedcenter:true,
3886                 draggable: false,
3887                 width:"800px",
3888                                 constraintoviewport: true
3889             });
3890                         dlg.showEvent.subscribe( function (){
3891                                 var el = this.element;
3892                                 var viewH = YAHOO.util.Dom.getViewportHeight();
3893                 if (this.header && el && viewH - 50 < el.clientHeight) {
3894                     var body = this.header.nextElementSibling;
3895                                         body.style.overflow = "auto";
3896                     body.style.height = (viewH - 50) + "px";
3897                 }
3898             }, dlg);
3899                 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3900                 dlg.setBody('<div id="settingsTabDiv"/>');
3901                 dlg.beforeRenderEvent.subscribe(function() {
3902                         var dd = new YAHOO.util.DDProxy(dlg.element);
3903                         dd.setHandleElId(dlg.header);
3904                         dd.on('endDragEvent', function() {
3905                                 dlg.show();
3906                         });
3907                 }, dlg, true);
3908                 dlg.render();
3909
3910                 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3911                         var tabContent = Dom.get("tab_general");
3912                 tp.addTab(new YAHOO.widget.Tab({
3913                                 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3914                                 scroll : true,
3915                                 content :  tabContent.innerHTML,
3916                                 id : "generalSettings",
3917                                 active : true
3918                         }));
3919                 tabContent.parentNode.removeChild(tabContent);
3920                 tabContent = Dom.get("tab_accounts");
3921                 var accountTab = new YAHOO.widget.Tab({
3922                                 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3923                                 scroll : true,
3924                                 content : tabContent.innerHTML,
3925                                 id : "accountSettings"
3926                         });
3927                 tp.addTab(accountTab);
3928                 tabContent.parentNode.removeChild(tabContent);
3929
3930                         tp.appendTo(dlg.body);
3931         }
3932
3933         SE.settings.settingsDialog.show();
3934         SE.folders.lazyLoadSettings();
3935         SE.accounts.lazyLoad();
3936     },
3937
3938
3939     lazyLoadRules : function() {
3940         if(false/*!SE.settings.rules*/) {
3941             AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3942         }
3943
3944     }
3945 };
3946 ////    END SE.settings
3947 ///////////////////////////////////////////////////////////////////////////////
3948 })();
3949
3950 /******************************************************************************
3951  * UTILITIES
3952  *****************************************************************************/
3953 function removeHiddenNodes(nodes, grid) {
3954     var el;
3955         for(var i = nodes.length - 1; i > -1; i--) {
3956         el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3957         if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3958                 nodes.splice(i,1);
3959        }
3960     }
3961 }
3962
3963 function strpad(val) {
3964     return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3965 };
3966
3967 function refreshTodos() {
3968     SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3969     AjaxObject.target = 'todo';
3970     AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3971 };
3972
3973 /******************************************************************************
3974  * MUST STAY IN GLOBAL NAMESPACE
3975  *****************************************************************************/
3976 function refresh_signature_list(signature_id, signature_name) {
3977     var field=document.getElementById('signature_id');
3978     var bfound=0;
3979     for (var i=0; i < field.options.length; i++) {
3980             if (field.options[i].value == signature_id) {
3981                 if (field.options[i].selected==false) {
3982                     field.options[i].selected=true;
3983                 }
3984                 bfound=1;
3985             }
3986     }
3987     //add item to selection list.
3988     if (bfound == 0) {
3989         var newElement=document.createElement('option');
3990         newElement.text=signature_name;
3991         newElement.value=signature_id;
3992         field.options.add(newElement);
3993         newElement.selected=true;
3994     }
3995
3996     //enable the edit button.
3997     var field1=document.getElementById('edit_sig');
3998     field1.style.visibility="inherit";
3999     var deleteButt = document.getElementById('delete_sig');
4000     deleteButt.style.visibility="inherit";
4001 };
4002
4003 function setDefaultSigId(id) {
4004     var checkbox = document.getElementById("signature_default");
4005     var default_sig = document.getElementById("signatureDefault");
4006
4007     if(checkbox.checked) {
4008         default_sig.value = id;
4009     } else {
4010         default_sig.value = "";
4011     }
4012 };
4013
4014 function setSigEditButtonVisibility() {
4015     var field = document.getElementById('signature_id');
4016     var editButt = document.getElementById('edit_sig');
4017     var deleteButt = document.getElementById('delete_sig');
4018     if(field.value != '') {
4019         editButt.style.visibility = "inherit";
4020         deleteButt.style.visibility = "inherit";
4021     } else {
4022         editButt.style.visibility = "hidden";
4023         deleteButt.style.visibility = "hidden";
4024     }
4025 }// End of File modules/Emails/javascript/EmailUI.js
4026                                 
4027 /*********************************************************************************
4028  * SugarCRM is a customer relationship management program developed by
4029  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4030  * 
4031  * This program is free software; you can redistribute it and/or modify it under
4032  * the terms of the GNU Affero General Public License version 3 as published by the
4033  * Free Software Foundation with the addition of the following permission added
4034  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4035  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4036  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4037  * 
4038  * This program is distributed in the hope that it will be useful, but WITHOUT
4039  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4040  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
4041  * details.
4042  * 
4043  * You should have received a copy of the GNU Affero General Public License along with
4044  * this program; if not, see http://www.gnu.org/licenses or write to the Free
4045  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4046  * 02110-1301 USA.
4047  * 
4048  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4049  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4050  * 
4051  * The interactive user interfaces in modified source and object code versions
4052  * of this program must display Appropriate Legal Notices, as required under
4053  * Section 5 of the GNU Affero General Public License version 3.
4054  * 
4055  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4056  * these Appropriate Legal Notices must retain the display of the "Powered by
4057  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4058  * technical reasons, the Appropriate Legal Notices must display the words
4059  * "Powered by SugarCRM".
4060  ********************************************************************************/
4061
4062  (function() {
4063         var sw = YAHOO.SUGAR,
4064                 Event = YAHOO.util.Event,
4065                 Connect = YAHOO.util.Connect,
4066             Dom = YAHOO.util.Dom
4067             SE = SUGAR.email2;
4068
4069 ///////////////////////////////////////////////////////////////////////////////
4070 ////    ADDRESS BOOK
4071 SE.addressBook = {
4072     _contactCache : new Array(), // cache of contacts
4073     _dd : new Array(), // filtered list, same format as _contactCache
4074     _ddLists : new Array(), // list of Lists
4075     _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4076     _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4077     clickBubble : true, // hack to get around onclick event bubbling
4078         relatedBeanId : '',
4079         relatedBeanType : '',
4080         idx : 0,
4081
4082     itemSpacing : 'white-space:nowrap; padding:2px;',
4083     reGUID : SE.reGUID,
4084
4085
4086
4087     /**
4088     *  YUI bug fix 2527707.  Causes nested datatable's in <tables> to cause 404 errors whens earching.
4089     */
4090     initFixForDatatableSort: function () {
4091         //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4092         YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4093             var oColumn = this._oColumnSet.getColumn(column);
4094
4095             if(!oColumn) {
4096                 // Validate TD element
4097                 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4098                 if(elCell) {
4099                     oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4100                 }
4101                 // Validate TH element
4102                 else {
4103                     elCell = this.getThEl(column);
4104                     if(elCell) {
4105                         // Find by TH el ID
4106                         var allColumns = this._oColumnSet.flat;
4107                         for(var i=0, len=allColumns.length; i<len; i++) {
4108                             if(allColumns[i].getThEl().id === elCell.id) {
4109                                 oColumn = allColumns[i];
4110                             }
4111                         }
4112                     }
4113                 }
4114             }
4115
4116             return oColumn;
4117         };
4118     },
4119
4120     cancelEdit : function() {
4121         if(this.editContactDialog)
4122             this.editContactDialog.hide();
4123         if(this.editMailingListDialog)
4124             this.editMailingListDialog.hide();
4125     },
4126
4127     /**
4128      * Clears filter form
4129      */
4130     clear : function() {
4131         var t = document.getElementById('contactsFilter');
4132         t.value = '';
4133         this.filter(t);
4134     },
4135
4136     /**
4137      * handle context-menu Compose-to call
4138      * @param string type 'contacts' or 'lists'
4139      */
4140     composeTo : function(type, waited) {
4141         var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4142         if (activePanel.substring(0, 10) != "composeTab") {
4143             SE.composeLayout.c0_composeNewEmail();
4144             setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4145                 SE.contextMenus.contactsContextMenu.hide();
4146             return;
4147         }
4148         var idx = activePanel.substring(10);
4149         var rows = [ ];
4150         var id = '';
4151         // determine if we have a selection to work with
4152         if(type == 'contacts') {
4153             var ids = SE.contactView.getSelectedRows();
4154             for (var i in ids) {
4155                 rows[i] = SE.contactView.getRecord(ids[i]);
4156             }
4157             removeHiddenNodes(rows, SE.contactView);
4158         }
4159                 else { return; }
4160
4161         if(rows.length > 0) {
4162             SE.composeLayout.handleDrop(
4163                 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4164                 null, rows, 'addressTO' + idx );
4165         } else {
4166             alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4167         }
4168     },
4169
4170     editContact : function() {
4171         SE.contextMenus.contactsContextMenu.hide();
4172         var element = SE.contactView.getSelectedNodes()[0];
4173         var elementId = "";
4174         if (element.className.indexOf('address-contact') > -1) {
4175             elementId = element.id;
4176         } else if (element.className.indexOf('address-exp-contact') > -1) {
4177             elementId = element.id.substring(2);
4178         }
4179     },
4180
4181
4182     /**
4183      * Filters contact entries based on user input
4184      */
4185     filter : function(inputEl) {
4186         var ret = new Object();
4187         var re = new RegExp(inputEl.value, "gi");
4188
4189         for(var i in this._contactCache) {
4190             if(this._contactCache[i].name.match(re)) {
4191                 ret[i] = this._contactCache[i];
4192             }
4193         }
4194
4195         this.buildContactList(ret);
4196     },
4197
4198     fullForm : function(id, module) {
4199         document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4200     },
4201
4202     /**
4203      * returns a formatted email address from the addressBook cache
4204      */
4205     getFormattedAddress : function(id) {
4206         var o = this._contactCache[id];
4207         var primaryEmail = '';
4208
4209         for(var i=0; i<o.email.length; i++) {
4210             var currentEmail = o.email[i].email_address;
4211
4212             if(o.email[i].primary_address == 1) {
4213                 primaryEmail = o.email[i].email_address;
4214             }
4215         }
4216
4217         var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4218         var name = new String(o.name);
4219         var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/&#039;/gi,'\'');
4220         var ret = finalName + " <" + finalEmail.replace(/&#039;/gi,'\'') + ">";
4221
4222         return ret;
4223     },
4224
4225     /**
4226      * Sets up async call to query for matching contacts, users, etc.
4227      */
4228     searchContacts : function() {
4229         var fn = document.getElementById('input_searchField').value;
4230         var pe = document.getElementById('input_searchPerson').value;
4231
4232         var rb = document.getElementById('hasRelatedBean').checked;
4233         if (rb) {
4234                         var idx = this.idx;
4235                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4236                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4237                 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4238                 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4239         } else {
4240                 this.addressBookDataModel.params['related_bean_id'] = '';
4241         }
4242
4243         this.addressBookDataModel.params['search_field'] = fn;
4244         this.addressBookDataModel.params['person'] = pe;
4245         this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4246         this.grid._oDataSource = this.addressBookDataModel;
4247         this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params),  this.grid.onDataReturnInitializeTable, this.grid);
4248     },
4249
4250     /**
4251      * Clear Search Crieteria For Addressbook
4252      */
4253     clearAddressBookSearch : function() {
4254         document.getElementById('input_searchField').value = "";
4255         document.getElementById('input_searchPerson').selectedIndex = 0;
4256     },
4257
4258     /**
4259      * Opens modal select window to add contacts to addressbook
4260      */
4261     selectContactsDialogue : function(destId) {
4262         if(!this.contactsDialogue) {
4263                 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4264                 modal:true,
4265                 visible:false,
4266                 draggable: false,
4267                 constraintoviewport: true,
4268                 width   : 980,
4269                 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4270                            {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4271             });
4272                 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4273
4274                 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4275                 dlg.setBody(body.innerHTML);
4276                 dlg.renderEvent.subscribe(function() {
4277                 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4278                 if (iev && !SUGAR.isIE) {
4279                         this.body.style.width = "950px";
4280                 }
4281             }, dlg);
4282
4283
4284                 dlg.beforeRenderEvent.subscribe(function() {
4285                         var dd = new YAHOO.util.DDProxy(dlg.element);
4286                         dd.setHandleElId(dlg.header);
4287                         dd.on('endDragEvent', function() {
4288                                 dlg.show();
4289                         });
4290                 }, dlg, true);
4291                 dlg.render();
4292
4293                 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4294
4295                 var tabContent = SUGAR.util.getAndRemove("searchForm");
4296                 tp.addTab(new YAHOO.widget.Tab({
4297                                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4298                                 scroll : true,
4299                                 content : tabContent.innerHTML,
4300                                 id : "addressSearchTab",
4301                                 active : true
4302                         }));
4303
4304                 var addListenerFields = ['input_searchPerson','input_searchField' ]
4305                 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4306                         if (e.keyCode == 13) {
4307                                 YAHOO.util.Event.stopEvent(e);
4308                                 SUGAR.email2.addressBook.searchContacts();
4309                         }
4310                 });
4311
4312                 this.contactsDialogue.render();
4313                 dlg.center();
4314         }
4315         //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4316         if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4317             var idx = 0;
4318         else
4319         {
4320             var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4321             var idx = activePanel.substring(10);
4322         }
4323         SE.addressBook.idx = idx;
4324
4325                 var relatedBeanId;
4326         if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4327                 document.getElementById('relatedBeanColumn').style.display = '';
4328                 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4329                         var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4330                         relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4331                         document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4332                         SE.addressBook.relatedBeanType = relatedBeanType;
4333             } else {
4334                 document.getElementById('relatedBeanColumn').style.display = 'none';
4335                 document.getElementById('hasRelatedBean').checked = false;
4336             }
4337
4338             if (!SE.addressBook.grid)
4339             {
4340                 if (hasRelatedBeanId) {
4341                         document.getElementById('hasRelatedBean').checked = true;
4342                 }
4343                 AddressSearchGridInit();
4344                         SE.addressBook.relatedBeanId = relatedBeanId;
4345             }
4346             else
4347             {
4348                 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4349                 {
4350                         SE.addressBook.relatedBeanId = relatedBeanId;
4351                         document.getElementById('hasRelatedBean').checked = true;
4352                 }
4353                 if (document.getElementById('hasRelatedBean').checked == true)
4354                 {
4355                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4356                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4357                 } else {
4358                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4359                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4360                 }
4361                 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4362                         SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4363                 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params),  SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4364             }
4365
4366             //Remove any lingering rows in the result set table if the module was closed.
4367             SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4368             //Repopulate
4369             SE.addressBook.populateResulstTableEmailAddresses();
4370
4371         this.contactsDialogue.show();
4372     },
4373     /**
4374     *  Clear all email addresses from result table.
4375     *
4376     */
4377     clearAllEmailAddressFieldsFromResultTable: function () {
4378         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4379         //Unhighlight any rows currently selected if the emails were cleared.
4380         SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4381         SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4382     },
4383     /**
4384     *  Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4385     *  results table.  This function is called when the address book is displayed.
4386     */
4387     populateResulstTableEmailAddresses: function () {
4388
4389         var idx = SE.addressBook.idx;
4390         var emailFields = ['to','cc','bcc'];
4391
4392         for(var k=0;k<emailFields.length;k++)
4393         {
4394             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4395             var allEmails = document.getElementById(elKey).value;
4396             if(allEmails == '')
4397                 continue;
4398
4399             var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4400
4401                 for (var i=0; i<formatedEmails.length; i++)
4402                 {
4403                     var t_name = formatedEmails[i].name;
4404                     var t_emailAddr = formatedEmails[i].email_address;
4405                     var displayEmail = t_name + ' <' + t_emailAddr + '>';
4406                     if(t_name == '')
4407                         t_name = displayEmail = t_emailAddr;
4408
4409                     var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4410                 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4411                     'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4412                 }
4413         }
4414     },
4415
4416     /**
4417     * Checks all entries in the result table against a particular email address, returning true
4418     * if the email address is found, false otherwise.
4419     */
4420     doesEmailAdddressExistInResultTable: function(emailAddress)
4421     {
4422         if(trim(emailAddress) == '')
4423             return false;
4424
4425         var emailAddressFound = false;
4426         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4427         for (var i=0; i < contacts.length; i++)
4428         {
4429             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4430             //If we are adding to cc or bcc fields, make them visible.
4431             if(data.email_address == emailAddress)
4432             {
4433                 emailAddressFound = true;
4434                 break;
4435             }
4436         }
4437
4438         return emailAddressFound;
4439     },
4440     /**
4441     *  Takes all email addresses that the users wishes to add from the address book and populates the To
4442     *  fields on the compose tab.
4443     */
4444     populateEmailAddressFieldsFromResultTable: function()
4445     {
4446         //Clear the fields first, all email addresses are stored in the address book
4447         var idx = SE.addressBook.idx;
4448         var emailFields = ['to','cc','bcc'];
4449         for(var k=0;k<emailFields.length;k++)
4450         {
4451             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4452             document.getElementById(elKey).value = "";
4453         }
4454
4455         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4456         for (var i=0; i < contacts.length; i++)
4457         {
4458             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4459
4460             var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4461             //If we are adding to cc or bcc fields, make them visible.
4462             if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4463                 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4464             //Construct the target id
4465             var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4466
4467             var target = document.getElementById(target_id);
4468             target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4469         }
4470
4471         //Delete all rows from the result set table
4472         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4473
4474         //Hide the dialogue
4475         SE.addressBook.contactsDialogue.hide()
4476     },
4477     /**
4478     *  Insert contacts into the result table.
4479     */
4480     insertContactToResultTable : function(event,address_type) {
4481
4482         var contactsDialogue = SE.addressBook.contactsDialogue;
4483         var contacts = SE.addressBook.grid.getSelectedRows();
4484
4485         var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4486         for (var i = 0; i < rows.length; i++)
4487         {
4488                         if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4489                         {
4490                             var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4491                 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4492                 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4493                 rows[i].setData("selected",true);
4494                         }
4495         }
4496         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4497         for (var i = 0; i < checkBoxes.length; i++) {
4498             checkBoxes[i].checked = false;
4499         }
4500     },
4501     /**
4502     *
4503     */
4504     insertContactRowToResultTable : function(rowId, addressType) {
4505         var data = SE.addressBook.grid.getRecord(rowId).getData();
4506         if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4507                 return;
4508         var name = data.name.replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
4509         var ea = name + ' <' + data.email.replace(/&#039;/gi,'\'') + '>';
4510         if(addressType == null)
4511             addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4512         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});
4513     },
4514     /**
4515     * Remove a row from the gridsResult table.
4516     */
4517     removeRowFromGridResults : function(rowId,emailAddress)
4518     {
4519         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4520         for (var i=0; i < contacts.length; i++)
4521         {
4522             var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4523             var data = rec.getData();
4524             if(data.email_address == emailAddress)
4525             {
4526                 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4527                 break;
4528             }
4529         }
4530
4531        SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4532     },
4533     /**
4534     * Translates between the addressType To|Cc|Bcc labels/keys.
4535     */
4536     translateAddresType: function(addressType,fromKey)
4537     {
4538         var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4539         var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4540         var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4541         var mappingObject = {};
4542
4543         if(fromKey)
4544             mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4545         else
4546         {
4547             mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4548             mappingObject[displayCc] = 'cc';
4549             mappingObject[displayBcc] = 'bcc';
4550         }
4551
4552         return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4553
4554     },
4555     /**
4556     *
4557     */
4558     toggleSearchRowIcon : function(rowId,show)
4559     {
4560         if(show)
4561         {
4562             var idToShow = rowId + '_add_img';
4563             var idToHide = rowId + '_rm_img';
4564         }
4565         else
4566         {
4567             var idToShow = rowId + '_rm_img';
4568             var idToHide = rowId + '_add_img';
4569         }
4570
4571
4572         Dom.addClass(idToHide, "yui-hidden");
4573         Dom.removeClass(idToShow, "yui-hidden");
4574     },
4575     /**
4576     * Determine if an entry has already been added to the grid results table to prevent duplicates.
4577     */
4578     doesGridResultsEntryExist: function(emailAddrs)
4579     {
4580
4581         var contactExists = false;
4582         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4583         for (var i=0; i < contacts.length; i++)
4584         {
4585             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4586             if(data.email_address == emailAddrs)
4587             {
4588                 contactExists = true;
4589                 break;
4590             }
4591         }
4592         return contactExists;
4593     },
4594
4595     /**
4596      * adds an email address to a string, but first checks if it exists
4597      * @param string concat The string we are appending email addresses to
4598      * @param string addr Email address to add
4599      * @return string
4600      */
4601     smartAddEmailAddressToComposeField : function(concat, addr) {
4602         var re = new RegExp(addr);
4603
4604         if(!concat.match(re)) {
4605             if(concat != "") {
4606                 concat += "; " + addr;
4607             } else {
4608                 concat = addr;
4609             }
4610         }
4611
4612         return concat;
4613     }
4614 };
4615 ////    END ADDRESS BOOK
4616 ///////////////////////////////////////////////////////////////////////////////
4617
4618
4619
4620 ///////////////////////////////////////////////////////////////////////////////
4621 ////    AUTOCOMPLETE
4622 /**
4623  * Auto-complete object
4624  */
4625 SE.autoComplete = {
4626     config : {
4627         delimChar : [";", ","],
4628         useShadow :    false,
4629         useIFrame : false,
4630         typeAhead : true,
4631         prehighlightClassName : "yui-ac-prehighlight",
4632         queryDelay : 0
4633     },
4634     instances : new Array(),
4635
4636     /**
4637      * Parses an addressBook entry looking for primary address.  If not found, it will return the last found address.
4638      * @param object Contact from AddressBook
4639      * @return string
4640      */
4641     getPrimaryAddress : function(contact) {
4642         var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4643
4644         for(var eIndex in contact.email) {
4645             address = contact.email[eIndex].email_address;
4646             if(contact.email[eIndex].primary_address == 1) {
4647                 return contact.email[eIndex].email_address;
4648             }
4649         }
4650         return address;
4651     },
4652
4653
4654     /**
4655      * initializes autocomplete widgets for a given compose view
4656      * @param int idx
4657      */
4658     init : function(idx) {
4659         var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4660             "queryMatchContains" : false,
4661             "queryMatchSubset" : true
4662         });
4663
4664         this.instances[idx] = {
4665             to : null,
4666             cc : null,
4667             bcc : null
4668         };
4669
4670
4671         // instantiate the autoComplete widgets
4672         this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4673         this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4674         this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4675
4676         // enable hiding of interfering textareas
4677         this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4678         this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4679         this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4680
4681         // enable reshowing of hidden textareas
4682         this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4683         this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4684         this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4685
4686         // enable refreshes of contact lists
4687         this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4688         this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4689         this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4690     },
4691
4692     refreshDataSource : function(sType, aArgs) {
4693         var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4694         var idx;
4695         var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4696
4697         if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4698             idx = textBoxId.substr(9);
4699         } else {
4700             idx = textBoxId.substr(10);
4701         }
4702
4703         SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4704         SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4705         SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4706     },
4707
4708     /**
4709      * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4710      */
4711     returnDataSource : function(contacts) {
4712         var ret = new Array();
4713         for(var id in contacts) {
4714             if (contacts[id].name) {
4715                     var primary = this.getPrimaryAddress(contacts[id]);
4716
4717                     ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4718                     //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4719
4720                     for(var emailIndex in contacts[id].email) {
4721                         ret[ret.length] = contacts[id].email[emailIndex].email_address;
4722                     }
4723             }
4724         }
4725
4726         return ret;
4727     },
4728
4729     /**
4730      * Hides address textareas to prevent autocomplete dropdown from being obscured
4731      */
4732     toggleTextareaHide : function(sType, aArgs) {
4733         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4734         var type = "";
4735         var idx = -1;
4736
4737         if(textBoxId.indexOf("addressTO") > -1) {
4738             type = "to";
4739         } else if(textBoxId.indexOf("addressCC") > -1) {
4740             type = "cc";
4741         }
4742         idx = textBoxId.substr(9);
4743
4744         // follow through if not BCC
4745         if(type != "") {
4746             var cc = document.getElementById("addressCC" + idx);
4747             var bcc = document.getElementById("addressBCC" + idx);
4748
4749             switch(type) {
4750                 case "to":
4751                     cc.style.visibility = 'hidden';
4752                 case "cc":
4753                     bcc.style.visibility = 'hidden';
4754                 break;
4755             }
4756         }
4757     },
4758
4759     /**
4760      * Redisplays the textareas after an address is commited
4761      */
4762     toggleTextareaShow : function(sType, aArgs) {
4763         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4764         var type = "";
4765         var idx = -1;
4766
4767         if(textBoxId.indexOf("addressTO") > -1) {
4768             type = "to";
4769         } else if(textBoxId.indexOf("addressCC") > -1) {
4770             type = "cc";
4771         }
4772         idx = textBoxId.substr(9);
4773
4774         // follow through if not BCC
4775         if(type != "") {
4776             document.getElementById("addressCC" + idx).style.visibility = 'visible';
4777             document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4778         }
4779     }
4780 };
4781
4782 ////    END AUTOCOMPLETE
4783 ///////////////////////////////////////////////////////////////////////////////
4784
4785 ///////////////////////////////////////////////////////////////////////////////
4786 ////    COMPOSE & SEND
4787 /**
4788  * expands the options sidebar
4789  */
4790 SE.composeLayout = {
4791     currentInstanceId : 0,
4792     ccHidden : true,
4793     bccHidden : true,
4794     outboundAccountErrors : null,
4795     loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4796
4797     showAddressDetails : function(e) {
4798         var linkElement = document.getElementById("More"+e.id);
4799         var spanElement = document.getElementById("Detail"+e.id);
4800         var emailAddressList = e.value;
4801         if(e.value.length > 96)
4802         {
4803                 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4804             var displayArray = [];
4805                 for (var i=0; i<resultArray.length; i++)
4806                 {
4807                     var t_name = resultArray[i].name;
4808                     var t_emailAddr = resultArray[i].email_address;
4809                     if(t_name == '')
4810                        displayArray.push('<br/>&lt;' + t_emailAddr + '&gt;');
4811                     else
4812                        displayArray.push(t_name + '<br/>&lt;' + t_emailAddr + '&gt;');
4813                 }
4814
4815             var result = displayArray.join('<br/>');
4816                 // Display
4817             linkElement.style.display = "inline";
4818             linkElement.style.height="10px";
4819             linkElement.style.overflow="visible";
4820             spanElement.innerHTML = result;
4821         }
4822         else
4823                 linkElement.style.display = "none";
4824
4825         },
4826
4827    /**
4828     *  Given a string of email address, return an array containing the name portion (if available)
4829     *  and email portion.
4830     */
4831     _getEmailArrayFromString : function (emailAddressList){
4832
4833         var reg = /@.*?;/g;
4834         while ((results = reg.exec(emailAddressList)) != null)
4835         {
4836             orignial = results[0];
4837             parsedResult = results[0].replace(';', ':::::');
4838             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4839         }
4840
4841         reg = /@.*?,/g;
4842         while ((results = reg.exec(emailAddressList)) != null)
4843         {
4844             orignial = results[0];
4845             parsedResult = results[0].replace(',', ':::::');
4846             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4847         }
4848         //Administrator <johndoe@som.com>  ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4849         var emailArr = emailAddressList.split(":::::");
4850         var resultsArray = [];
4851         var newArr = [];
4852         for (var i=0; i<emailArr.length; i++)
4853         {
4854             var rposition = emailArr[i].indexOf('<');
4855             var lposition = emailArr[i].indexOf('>');
4856
4857             if(trim(emailArr[i]) != '')
4858             {
4859                 if(rposition != -1 && lposition != -1)
4860                 {
4861                     var t_name = emailArr[i].substr(0, rposition-1);
4862                     var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4863                     resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4864                 }
4865                 else
4866                 {
4867                     resultsArray.push({'name':'', 'email_address': emailArr[i]});
4868                 }
4869             }
4870         }
4871         return resultsArray;
4872     },
4873     ///////////////////////////////////////////////////////////////////////////
4874     ////    COMPOSE FLOW
4875     /**
4876      * Prepare bucket DIV and yui-ext tab panels
4877      */
4878     _0_yui : function() {
4879         var idx = this.currentInstanceId;
4880
4881         var composeTab = new YAHOO.SUGAR.ClosableTab({
4882                         label: mod_strings.LNK_NEW_SEND_EMAIL,
4883                                 scroll : true,
4884                                 content : "<div id='htmleditordiv" + idx + "'/>",
4885                                 id : "composeTab" + idx,
4886                                 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4887                                 active : true
4888         }, SE.innerLayout);
4889         SE.innerLayout.addTab(composeTab);
4890
4891         // get template engine with template
4892         if (!SE.composeLayout.composeTemplate) {
4893                 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4894         }
4895
4896         // create Tab inner layout
4897         var composePanel =  this.getComposeLayout();
4898         composePanel.getUnitByPosition("right").collapse();
4899         composePanel.autoSize();
4900
4901     },
4902         /**
4903      * Generate the quick compose layout
4904          * @method getQuickComposeLayout
4905          * @param {Pannel} parentPanel Parent pannel
4906          * @param {Object} o Options
4907          * @return {} none
4908          **/
4909     getQuickComposeLayout : function (parentPanel,o) {
4910          var idx = SE.composeLayout.currentInstanceId;
4911
4912          //Before rendering the parent pannel we need to initalize the grid layout
4913          parentPanel.beforeRenderEvent.subscribe(function() {
4914
4915                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4916                         SE.composeLayout._createComposeLayout(idx);
4917                         SE.composeLayout[idx].set('height', 350);
4918                         SE.composeLayout[idx].render();
4919            });
4920         });
4921
4922          //Wait until the Compose Layout has rendered, then add the
4923          //options tab and perform the tiny initialization.
4924          parentPanel.renderEvent.subscribe(function() {
4925
4926                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4927                 SE.composeLayout._initComposeOptionTabs(idx);
4928                 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4929                 //Initialize tinyMCE
4930                 if (!SUGAR.util.isTouchScreen())
4931                     SE.composeLayout._1_tiny();
4932                 //Init templates and address book
4933                 SE.composeLayout._2_final();
4934
4935             SE.composeLayout.quickCreateComposePackage(o);
4936
4937                 });
4938          });
4939
4940             //Check if we have the div override for the shortcut bar
4941         if(typeof o.menu_id != 'undefined') {
4942                    parentPanel.render(o.menu_id);
4943             } else {
4944                    parentPanel.render(document.body);
4945             }
4946
4947         return SE.composeLayout[idx];
4948     },
4949     /**
4950      * Fill in all fields into the quick compose layout.
4951          * @method quickCreateComposePackage
4952          * @param {Object} o Options
4953          * @return {} none
4954          **/
4955     quickCreateComposePackage: function(o)
4956     {
4957         //If we have a compose package fill in defaults.
4958         if (typeof(o.composePackage) != 'undefined')
4959         {
4960             composePackage = o.composePackage; //Set the compose data object
4961             //Hijack this method called by composePackage as it's not need for quick creates.
4962             SE.composeLayout.c0_composeNewEmail = function(){};
4963             SE.composeLayout.composePackage(); //Fill in defaults.
4964         }
4965     },
4966     getComposeLayout : function() {
4967         var idx = SE.composeLayout.currentInstanceId;
4968
4969         this._createComposeLayout(idx);
4970         SE.composeLayout[idx].render();
4971         this._initComposeOptionTabs(idx);
4972
4973         return SE.composeLayout[idx];
4974         },
4975
4976         /**
4977         *       Create the layout manager for the compose window.
4978         */
4979         _createComposeLayout : function(idx)
4980         {
4981                 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
4982                 parent: SE.complexLayout,
4983                 border:true,
4984             hideOnLayout: true,
4985             height: 400,
4986                         units: [{
4987                                         position: "center",
4988                         animate: false,
4989                         scroll: false,
4990                         split:true,
4991                         body:
4992                                 SE.composeLayout.composeTemplate.exec({
4993                                 'app_strings':app_strings,
4994                                 'mod_strings':mod_strings,
4995                                 'theme': theme,
4996                                 'linkbeans_options' : linkBeans,
4997                                 'idx' : SE.composeLayout.currentInstanceId
4998                                 })
4999                     },{
5000                         position: "right",
5001                                     scroll:true,
5002                                     collapse: true,
5003                                     collapsed: true,
5004                                     resize: true,
5005                                     border:true,
5006                                     animate: false,
5007                                     width:'230',
5008                                     body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5009                                     titlebar: true,
5010                                     split: true,
5011                                     header: app_strings.LBL_EMAIL_OPTIONS
5012                     }]
5013                 });
5014         },
5015
5016         /**
5017         *  Create compose tab which will populate the 'right' container in the compose window.
5018         */
5019         _initComposeOptionTabs : function(idx)
5020         {
5021                 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5022                 var tab = new YAHOO.widget.Tab({
5023                                 label: app_strings.LBL_EMAIL_ATTACHMENT,
5024                                 scroll : true,
5025                                 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5026                                 id : "divAttachments" + idx,
5027                                 active : true
5028                         });
5029
5030                 tab.layout = SE.composeLayout[idx];
5031
5032            tab.on("activeChange", function(o){
5033                         if (o.newValue) {
5034                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5035                         }
5036                 });
5037
5038                 cTabs.addTab(tab);
5039
5040                 tab = new YAHOO.widget.Tab({
5041                                 label: app_strings.LBL_EMAIL_OPTIONS,
5042                                 scroll : true,
5043                                 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5044                                 id : "divOptions" + idx,
5045                                 active : false
5046                         });
5047
5048                 tab.layout = SE.composeLayout[idx];
5049                 tab.on("activeChange", function(o){
5050                         if (o.newValue) {
5051                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5052                         }
5053                 });
5054                 cTabs.addTab(tab);
5055
5056                 SE.composeLayout[idx].autoSize = function() {
5057                         var pEl = this.get("element").parentNode.parentNode.parentNode;
5058                         this.set("height", pEl.clientHeight-30);
5059                         this.render();
5060                 }
5061
5062                 SE.composeLayout[idx].rightTabs = cTabs;
5063     },
5064     isParentTypeValid : function(idx) {
5065                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5066                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5067                 if (trim(parentTypeValue) == ""){
5068                         alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5069                         return false;
5070                 } // if
5071                 return true;
5072     },
5073
5074     isParentTypeAndNameValid : function(idx) {
5075                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5076                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5077                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5078                 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5079                         (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5080                                 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5081                         return false;
5082                 } // if
5083                 return true;
5084     },
5085
5086     callopenpopupForEmail2 : function(idx,options) {
5087
5088         var formName = 'emailCompose' + idx;
5089
5090         if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5091             formName = options.form_name;
5092
5093                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5094                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5095                 if (!SE.composeLayout.isParentTypeValid(idx)) {
5096                         return;
5097                 } // if
5098                 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5099                 {
5100                         call_back_function:"SE.composeLayout.popupAddEmail",
5101                         form_name:formName,
5102                         field_to_name_array:{
5103                                 id:'data_parent_id' + idx,
5104                                 name:'data_parent_name' + idx,
5105                                 email1:'email1'}
5106                 });
5107         },
5108
5109         popupAddEmail : function(o)
5110         {
5111                 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5112                 var data = o.name_to_value_array;
5113                 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5114                         && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5115         {
5116                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5117                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5118         }
5119                 set_return(o);
5120         },
5121     /**
5122      * Prepare TinyMCE
5123      */
5124     _1_tiny : function() {
5125         var idx = SE.composeLayout.currentInstanceId;
5126         var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5127         SE.tinyInstances[elId] = { };
5128         SE.tinyInstances[elId].ready = false;
5129         var t = tinyMCE.getInstanceById(elId);
5130
5131         if(typeof(t) == 'undefined')  {
5132             tinyMCE.execCommand('mceAddControl', false, elId);
5133             YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5134                 SE.composeLayout.resizeEditor(idx);
5135                 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
5136             }, this);
5137         }
5138     },
5139
5140     resizeEditor : function(idx)
5141     {
5142         var cof = Dom.get('composeOverFrame' + idx);
5143         var head = Dom.get('composeHeaderTable' + idx);
5144         var targetHeight = cof.clientHeight - head.clientHeight;
5145         var instance =  tinyMCE.get(SE.tinyInstances.currentHtmleditor);
5146
5147         var parentEl = Dom.get(instance.editorId + '_parent');
5148         var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5149         var contentEl  = instance.contentAreaContainer;
5150         var iFrame = contentEl.firstChild;
5151         var tinMceToolbarOffset = 18;
5152         iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset)  + "px";
5153     },
5154
5155     /**
5156      * Initializes d&d, auto-complete, email templates
5157      */
5158     _2_final : function() {
5159         var idx = SE.composeLayout.currentInstanceId;
5160
5161         if(this.emailTemplates) {
5162             this.setComposeOptions(idx);
5163         } else {
5164             //populate email template cache
5165             AjaxObject.target = '';
5166             AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5167         }
5168
5169         // handle drop targets for addressBook
5170        var to =  new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5171        var cc =  new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5172        var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5173        to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5174
5175         // auto-complete setup
5176         SE.autoComplete.init(idx);
5177
5178         // set focus on to:
5179         document.getElementById("addressTO" + idx).focus();
5180     },
5181
5182         /**
5183      * hide tinyMCE tool bar if send email as plaintext is checked
5184      */
5185     renderTinyMCEToolBar : function (idx, hide) {
5186         if (hide) {
5187                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5188         } else {
5189                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5190         }
5191     },
5192
5193     c1_composeEmail : function(isReplyForward, retry) {
5194         if (!retry) {
5195             this._0_yui();
5196         }
5197         if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5198             setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5199         } else {
5200                 this._1_tiny();
5201                 this._2_final();
5202
5203                 if(isReplyForward) {
5204                     this.replyForwardEmailStage2();
5205                 }
5206         }
5207     },
5208
5209     /**
5210      * takes draft info and prepopulates
5211      */
5212     c0_composeDraft : function() {
5213         this.getNewInstanceId();
5214         inCompose = true;
5215         document.getElementById('_blank').innerHTML = '';
5216         var idx = SE.composeLayout.currentInstanceId;
5217                 SE.composeLayout.draftObject = new Object();
5218                 SE.composeLayout.draftObject.id = idx;
5219                 SE.composeLayout.draftObject.isDraft = true;
5220         SE.composeLayout.currentInstanceId = idx;
5221         SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5222         SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5223         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5224
5225         SE.composeLayout._0_yui();
5226         SE.composeLayout._1_tiny();
5227
5228         // final touches
5229         SE.composeLayout._2_final();
5230
5231         /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5232         setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5233     },
5234
5235     /**
5236      * Strip & Prep editor hidden fields
5237      */
5238     c0_composeNewEmail : function() {
5239         this.getNewInstanceId();
5240         this.c1_composeEmail(false);
5241     },
5242
5243     /**
5244      * Sends async request to get the compose view.
5245      * Requests come from "reply" or "forwards"
5246      */
5247     c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5248         SE.composeLayout.replyForwardObj = new Object();
5249         SE.composeLayout.replyForwardObj.ieId = ieId;
5250         SE.composeLayout.replyForwardObj.uid = uid;
5251         SE.composeLayout.replyForwardObj.mbox = mbox;
5252         SE.composeLayout.replyForwardObj.type = type;
5253
5254         if(mbox == 'sugar::Emails') {
5255             SE.composeLayout.replyForwardObj.sugarEmail = true;
5256         }
5257
5258         SE.composeLayout.getNewInstanceId();
5259         SE.composeLayout.c1_composeEmail(true);
5260     },
5261     ////    END COMPOSE FLOW
5262     ///////////////////////////////////////////////////////////////////////////
5263
5264     /**
5265      * Called when a contact, email, or mailinglist is dropped
5266      * into one of the compose fields.
5267      */
5268     handleDrop : function (source, event, data, target) {
5269         var nodes;
5270         if (!target) {
5271             target = event.getTarget();
5272             if (data.single) {
5273                 data.nodes = [data.nodes];
5274             }
5275             nodes = data.nodes;
5276         } else {
5277             target = document.getElementById(target);
5278             nodes = data;
5279         }
5280
5281         if (target.id.indexOf('address') > -1) {
5282             // dropped onto email to/cc/bcc field
5283             for(var i in nodes) {
5284                 var node = nodes[i].getData();
5285                 var email = "";
5286                 if (node[1].indexOf('contact') > -1) {
5287                     email = SE.addressBook.getFormattedAddress(node[0]);
5288                 } else if (node[1].indexOf('address-email') > -1){
5289                     email = node[3].replace(/&nbsp;/gi, '');
5290                     email = email.replace('&lt;', '<').replace('&gt;', '>');
5291                     var tr = source.getTrEl(nodes[i]);
5292                     while (tr && !Dom.hasClass(tr, "address-contact")) {
5293                         tr = source.getPreviousTrEl(tr);
5294                     }
5295                     var CID = source.getRecord(tr).getData()[0];
5296                     var o = SE.addressBook._contactCache[CID];
5297                     var name = new String(o.name);
5298                     var finalName = name.replace(/(<([^>]+)>)/ig, "");
5299                     email = finalName + email;
5300                 }
5301                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5302             }
5303         }
5304     },
5305
5306
5307     /*/////////////////////////////////////////////////////////////////////////////
5308     ///    EMAIL TEMPLATE CODE
5309      */
5310     applyEmailTemplate : function (idx, id) {
5311
5312         //bug #20680
5313         var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5314                 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5315                 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5316
5317                 // id is selected index of email template drop-down
5318                 if(id == '' || id == "0") {
5319                         YAHOO.SUGAR.MessageBox.show({
5320                    title:box_title,
5321                    msg: box_none_msg,
5322                    type: 'confirm',
5323                    fn: function(btn){
5324                                 if(btn=='no'){return;};
5325                                 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5326                    modal:true,
5327                    scope:this
5328                });
5329                return;
5330                 }
5331
5332                 YAHOO.SUGAR.MessageBox.show({
5333            title:box_title,
5334            msg: box_msg,
5335            type: 'confirm',
5336            fn: function(btn){
5337                         if(btn=='no'){return;};
5338                         SUGAR.email2.composeLayout.processResult(idx, id);},
5339            modal:true,
5340            scope:this
5341        });
5342     },
5343
5344     processNoneResult : function(idx, id) {
5345         var tiny = SE.util.getTiny('htmleditor' + idx);
5346         var tinyHTML = tiny.getContent();
5347         var openTag = '<div><span><span>';
5348         var htmllow = tinyHTML.toLowerCase();
5349         var start = htmllow.indexOf(openTag);
5350                 if (start > -1) {
5351                 tinyHTML = tinyHTML.substr(start);
5352                 tiny.setContent(tinyHTML);
5353                 } else {
5354                 tiny.setContent('');
5355                 }
5356     },
5357
5358         processResult : function(idx , id){
5359         call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5360
5361         // get attachments if any
5362         AjaxObject.target = '';
5363         AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5364     },
5365
5366     appendEmailTemplateJSON : function() {
5367         var idx = SE.composeLayout.currentInstanceId; // post increment
5368
5369         // query based on template, contact_id0,related_to
5370         //jchi 09/10/2008 refix #7743
5371         if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5372             document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5373         }
5374
5375         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,'"');
5376
5377         // cn: bug 14361 - text-only templates don't fill compose screen
5378         if(text == '') {
5379             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/>");
5380         }
5381
5382         var tiny = SE.util.getTiny('htmleditor' + idx);
5383         var tinyHTML = tiny.getContent();
5384         var openTag = '<div><span><span>';
5385         var closeTag = '</span></span></div>';
5386         var htmllow = tinyHTML.toLowerCase();
5387         var start = htmllow.indexOf(openTag);
5388                 if (start > -1) {
5389                 var htmlPart2 = tinyHTML.substr(start);
5390                 tinyHTML = text + htmlPart2;
5391                 tiny.setContent(tinyHTML);
5392                 } else {
5393                 tiny.setContent(text);
5394                 }
5395     },
5396
5397     /**
5398      * Writes out the signature in the email editor
5399      */
5400     setSignature : function(idx) {
5401         if (!tinyMCE)
5402             return false;
5403         var hide = document.getElementById('setEditor' + idx).checked;
5404         SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5405         //wait for signatures to load before trying to set them
5406         if (!SE.composeLayout.signatures) {
5407             setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5408                         return;
5409         }
5410
5411         if(idx) {
5412             var sel = document.getElementById('signatures' + idx);
5413         } else {
5414             var sel = document.getElementById('signature_id');
5415             idx = SE.tinyInstances.currentHtmleditor;
5416         }
5417
5418         //Ensure that the tinyMCE html has been rendered.
5419         if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5420             setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5421                     return;
5422                 }
5423
5424         var signature = '';
5425
5426         try {
5427             signature = sel.options[sel.selectedIndex].value;
5428         } catch(e) {
5429
5430         }
5431
5432         var openTag = '<div><span><span>';
5433         var closeTag = '</span></span></div>';
5434         var t = SE.util.getTiny('htmleditor' + idx);
5435         //IE 6 Hack
5436         if(typeof(t) != 'undefined')
5437         {
5438             t.contentDocument = t.contentWindow.document;
5439             var html = t.getContent();
5440         }
5441         else
5442             var html = '';
5443
5444         var htmllow = html.toLowerCase();
5445         var start = htmllow.indexOf(openTag);
5446         var end = htmllow.indexOf(closeTag) + closeTag.length;
5447
5448         // selected "none" - remove signature from email
5449         if(signature == '') {
5450             if (start > -1) {
5451                 var htmlPart1 = html.substr(0, start);
5452                 var htmlPart2 = html.substr(end, html.length);
5453
5454                 html = htmlPart1 + htmlPart2;
5455                 t.setContent(html);
5456             }
5457             SE.signatures.lastAttemptedLoad = '';
5458             return false;
5459         }
5460
5461         if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5462             SE.signatures.lastAttemptedLoad = '';
5463
5464         SE.signatures.lastAttemptedLoad = signature;
5465
5466         if(typeof(SE.signatures[signature]) == 'undefined') {
5467             //lazy load
5468             SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5469             SE.signatures.targetInstance = (idx) ? idx : "";
5470             AjaxObject.target = '';
5471             AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5472         } else {
5473             var newSignature = this.prepareSignature(SE.signatures[signature]);
5474
5475             // clear out old signature
5476             if(SE.signatures.lastAttemptedLoad && start > -1) {
5477                 var htmlPart1 = html.substr(0, start);
5478                 var htmlPart2 = html.substr(end, html.length);
5479
5480                 html = htmlPart1 + htmlPart2;
5481             }
5482
5483             // [pre|ap]pend
5484                         start = html.indexOf('<div><hr></div>');
5485             if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5486                                 var htmlPart1 = html.substr(0, start);
5487                                 var htmlPart2 = html.substr(start, html.length);
5488                 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5489             } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5490                 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5491             } else {
5492                 var newHtml = html + openTag + newSignature + closeTag;
5493             }
5494             //tinyMCE.setContent(newHtml);
5495             t.setContent(newHtml);
5496         }
5497     },
5498
5499     prepareSignature : function(str) {
5500         var signature = new String(str);
5501
5502         signature = signature.replace(/&lt;/gi, '<');
5503         signature = signature.replace(/&gt;/gi, '>');
5504
5505         return signature;
5506     },
5507
5508
5509     showAttachmentPanel : function(idx) {
5510         var east = SE.composeLayout[idx].getUnitByPosition("right");
5511         var tabs = SE.composeLayout[idx].rightTabs;
5512         east.expand();
5513         tabs.set("activeTab", tabs.getTab(0));
5514     },
5515
5516     /**
5517      * expands sidebar and displays options panel
5518      */
5519     showOptionsPanel : function(idx) {
5520         var east = SE.composeLayout[idx].getUnitByPosition("right");
5521         var tabs = SE.composeLayout[idx].rightTabs;
5522         east.expand();
5523         tabs.set("activeTab", tabs.getTab(1));
5524     },
5525
5526     /**
5527      * Selects the Contacts tab
5528      */
5529     showContactsPanel : function() {
5530         SE.complexLayout.regions.west.showPanel("contactsTab");
5531     },
5532
5533     /**
5534      * Generates fields for Select Document
5535      */
5536     addDocumentField : function(idx) {
5537         var basket = document.getElementById('addedDocuments' + idx);
5538         if(basket) {
5539             var index = (basket.childNodes.length / 7) - 1;
5540             if(index < 0)
5541                 index = 0;
5542         } else {
5543             index = 0;
5544         }
5545
5546         var test = document.getElementById('documentId' + idx + index);
5547
5548         while(test != null) {
5549             index++;
5550             test = document.getElementById('documentId' + idx + index);
5551         }
5552
5553         var documentCup = document.createElement("div");
5554         documentCup.id = 'documentCup' + idx + index;
5555         documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5556                 // document id field
5557                 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5558                 // document name field
5559                 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5560                 // select button
5561                 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5562                     "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5563                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5564                 // remove button
5565                 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5566                     "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5567                  "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5568                 "<br/>";
5569
5570         basket.appendChild(documentCup);
5571         //basket.innerHTML += out;
5572         return index;
5573     },
5574
5575     /**
5576      * Makes async call to save a draft of the email
5577      * @param int Instance index
5578      */
5579     saveDraft : function(tinyInstance) {
5580         this.sendEmail(tinyInstance, true);
5581     },
5582
5583     selectDocument : function(target) {
5584         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5585         windowName = 'selectDocument';
5586         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5587
5588         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5589         if(window.focus) {
5590             // put the focus on the popup if the browser supports the focus() method
5591             win.focus();
5592         }
5593     },
5594
5595     /**
5596      * Modal popup for file attachment dialogue
5597      */
5598     addFileField : function() {
5599         if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5600             SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5601                 modal:true,
5602                 visible:false,
5603                 fixedcenter:true,
5604                 constraintoviewport: true,
5605                 scroll: true,
5606                 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5607                         fn:function(){SE.addFileDialog.hide();}
5608                 })
5609             });
5610             SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5611             SE.addFileDialog.render();
5612            // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5613         }
5614         Dom.removeClass("addFileDialog", "yui-hidden");
5615
5616         SE.addFileDialog.show();
5617     },
5618
5619     /**
5620      * Async upload of file to temp dir
5621      */
5622     uploadAttachment : function() {
5623         if(document.getElementById('email_attachment').value != "") {
5624             var formObject = document.getElementById('uploadAttachment');
5625             YAHOO.util.Connect.setForm(formObject, true, true);
5626             AjaxObject.target = '';
5627             AjaxObject.startRequest(callbackUploadAttachment, null);
5628         } else {
5629             alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5630         }
5631     },
5632
5633     /**
5634      * Adds a SugarDocument to an outbound email.  Action occurs in a popup window displaying a ListView from the Documents module
5635      * @param string target in focus compose layout
5636      */
5637     setDocument : function(idx, target, documentId, documentName, docRevId) {
5638         // fields are named/id'd [fieldName][instanceId][index]
5639         var addedDocs = document.getElementById("addedDocuments" + idx);
5640         var docId = document.getElementById('documentId' + idx + target);
5641         var docName = document.getElementById('documentName' + idx + target);
5642         var docRevisionId = document.getElementById('document' + idx + target);
5643         docId.value = documentId;
5644         docName.value = documentName;
5645         docRevisionId.value = docRevId;
5646     },
5647
5648     /**
5649      * Removes the bucket div containing the document input fields
5650      */
5651     deleteDocumentField : function(documentCup) {
5652         var f0 = document.getElementById(documentCup);
5653         f0.parentNode.removeChild(f0);
5654     },
5655
5656     /**
5657      * Removes a Template Attachment field
5658      * @param int
5659      * @param int
5660      */
5661     deleteTemplateAttachmentField : function(idx, index) {
5662         // create not-in-array values for removal filtering
5663         var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5664
5665         if(r != "") {
5666             r += "::";
5667         }
5668
5669         r += document.getElementById('templateAttachmentId' + idx + index).value;
5670         document.getElementById("templateAttachmentsRemove" + idx).value = r;
5671
5672         var target = 'templateAttachmentCup' + idx + index;
5673         d =  document.getElementById(target);
5674         d.parentNode.removeChild(d);
5675     },
5676
5677     /**
5678      * Async removal of uploaded temp file
5679      * @param string index Should be a concatenation of idx and index
5680      * @param string
5681      */
5682     deleteUploadAttachment : function(index, file) {
5683         var d = document.getElementById('email_attachment_bucket' + index);
5684         d.parentNode.removeChild(d);
5685
5686         // make async call to delete cached file
5687         AjaxObject.target = '';
5688         AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5689     },
5690
5691     /**
5692      * Attaches files coming from Email Templates
5693      */
5694     addTemplateAttachmentField : function(idx) {
5695         // expose title
5696         document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5697
5698         var basket = document.getElementById('addedTemplateAttachments' + idx);
5699
5700         if(basket) {
5701             var index = basket.childNodes.length;
5702             if(index < 0)
5703                 index = 0;
5704         } else {
5705             index = 0;
5706         }
5707
5708         var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5709                                 // remove button
5710                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5711                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5712                                         idx + "\",\"" + index + "\");'/>" +
5713                                 // file icon
5714                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5715                                 // templateAttachment field
5716                                 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5717                                 // docId field
5718                                 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5719                                 // file name
5720                                 "<span id='templateAttachmentName"  + idx + index + "'" + ">&nbsp;</span>" +
5721                                 "<br id='br" + index + "></br>" +
5722                                 "<br id='brdoc" + index + "></br>" +
5723                         "</div>";
5724                 basket.innerHTML = basket.innerHTML + out;
5725
5726         return index;
5727     },
5728
5729     /**
5730      * Sends one email via async call
5731      * @param int idx Editor instance ID
5732      * @param bool isDraft
5733      */
5734     sendEmail : function(idx, isDraft) {
5735
5736         //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5737         var obAccountID = document.getElementById('addressFrom' + idx).value;
5738
5739         if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5740         {
5741             overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5742             return false;
5743         }
5744
5745
5746         var form = document.getElementById('emailCompose' + idx);
5747         var composeOptionsFormName = "composeOptionsForm" + idx;
5748         var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5749         var html = t.getContent();
5750         var subj = document.getElementById('emailSubject' + idx).value;
5751         var to = trim(document.getElementById('addressTO' + idx).value);
5752         var cc = trim(document.getElementById('addressCC' + idx).value);
5753         var bcc = trim(document.getElementById('addressBCC' + idx).value);
5754         var email_id = document.getElementById('email_id' + idx).value;
5755         var composeType = document.getElementById('composeType').value;
5756         var parent_type = document.getElementById("parent_type").value;
5757         var parent_id = document.getElementById("parent_id").value;
5758
5759         var el_uid = document.getElementById("uid");
5760         var uid = (el_uid == null) ? '' : el_uid.value;
5761
5762         var el_ieId = document.getElementById("ieId");
5763         var ieId = (el_ieId == null) ? '' : el_ieId.value;
5764
5765         var el_mbox = document.getElementById("mbox");
5766         var mbox = (el_mbox == null) ? '' : el_mbox.value;
5767
5768         if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5769                         alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5770                 return false;
5771         }
5772
5773         if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5774                 return;
5775         } // if
5776                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5777                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5778         parent_id = parentIdValue;
5779         parent_type = parentTypeValue;
5780
5781         var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5782         // baseline viability check
5783
5784         if(to == "" && cc == '' && bcc == '' && !isDraft) {
5785             alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5786             return false;
5787         } else if(subj == '' && !isDraft) {
5788             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5789                 return false;
5790             } else {
5791                 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5792             }
5793         } else if(html == '' && !isDraft) {
5794             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5795                 return false;
5796             }
5797         }
5798
5799         SE.util.clearHiddenFieldValues('emailCompose' + idx);
5800                 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5801                 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5802         overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5803         html = html.replace(/&lt;/ig, "sugarLessThan");
5804         html = html.replace(/&gt;/ig, "sugarGreaterThan");
5805
5806         form.sendDescription.value = html;
5807         form.sendSubject.value = subj;
5808         form.sendTo.value = to;
5809         form.sendCc.value = cc;
5810         form.sendBcc.value = bcc;
5811         form.email_id.value = email_id;
5812         form.composeType.value = composeType;
5813         form.composeLayoutId.value = 'composeLayout' + idx;
5814         form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5815         form.saveToSugar.value = 1;
5816         form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5817         form.parent_type.value = parent_type;
5818         form.parent_id.value = parent_id;
5819         form.uid.value = uid;
5820         form.ieId.value = ieId;
5821         form.mbox.value = mbox;
5822
5823         // email attachments
5824         var addedFiles = document.getElementById('addedFiles' + idx);
5825         if(addedFiles) {
5826             for(i=0; i<addedFiles.childNodes.length; i++) {
5827                 var bucket = addedFiles.childNodes[i];
5828
5829                 for(j=0; j<bucket.childNodes.length; j++) {
5830                     var node = bucket.childNodes[j];
5831                     var nName = new String(node.name);
5832
5833                     if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5834                         if(form.attachments.value != '') {
5835                             form.attachments.value += "::";
5836                         }
5837                         form.attachments.value += node.value;
5838                     }
5839                 }
5840             }
5841         }
5842
5843         // sugar documents
5844         var addedDocs = document.getElementById('addedDocuments' + idx);
5845         if(addedDocs) {
5846             for(i=0; i<addedDocs.childNodes.length; i++) {
5847                 var cNode = addedDocs.childNodes[i];
5848                 for(j=0; j<cNode.childNodes.length; j++) {
5849                     var node = cNode.childNodes[j];
5850                     var nName = new String(node.name);
5851                     if(node.type == 'hidden' && nName.match(/documentId/)) {
5852                         if(form.documents.value != '') {
5853                             form.documents.value += "::";
5854                         }
5855                         form.documents.value += node.value;
5856                     }
5857                 }
5858             }
5859         }
5860
5861         // template attachments
5862         var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5863         if(addedTemplateAttachments) {
5864             for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5865                 var cNode = addedTemplateAttachments.childNodes[i];
5866                 for(j=0; j<cNode.childNodes.length; j++) {
5867                     var node = cNode.childNodes[j];
5868                     var nName = new String(node.name);
5869                     if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5870                         if(form.templateAttachments.value != "") {
5871                             form.templateAttachments.value += "::";
5872                         }
5873                         form.templateAttachments.value += node.value;
5874                     }
5875                 }
5876             }
5877         }
5878
5879         // remove attachments
5880         form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5881
5882         YAHOO.util.Connect.setForm(form);
5883
5884         AjaxObject.target = 'frameFlex';
5885
5886         // sending a draft email
5887         if(!isDraft && in_draft) {
5888             // remove row
5889             SE.listView.removeRowByUid(email_id);
5890         }
5891
5892         var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5893         var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5894
5895         AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5896     },
5897
5898     /**
5899      * Handles clicking the email address link from a given view
5900      */
5901     composePackage : function() {
5902         if(composePackage != null) {
5903             SE.composeLayout.c0_composeNewEmail();
5904
5905
5906             if(composePackage.to_email_addrs) {
5907                 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5908             } // if
5909             if (composePackage.subject != null && composePackage.subject.length > 0) {
5910                 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5911             }
5912
5913             //If no parent fields are set in the composePackage, ensure they are cleared.
5914             var parentFields = ['parent_type','parent_name','parent_id'];
5915             for(var i=0;i<parentFields.length;i++)
5916             {
5917                 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5918                     composePackage[parentFields[i]] = "";
5919             }
5920
5921             document.getElementById("parent_type").value = composePackage.parent_type;
5922             document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5923             document.getElementById("parent_id").value = composePackage.parent_id;
5924             document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5925             document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5926
5927             if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5928                 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5929             } // if
5930             if (composePackage.body != null && composePackage.body.length > 0) {
5931                         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5932                         SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5933                         setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5934             } // if
5935             if (composePackage.attachments != null) {
5936                                 SE.composeLayout.loadAttachments(composePackage.attachments);
5937             } // if
5938
5939             if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5940                                 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5941                         SE.util.emptySelectOptions(addressFrom);
5942                         var fromAccountOpts = composePackage.fromAccounts.data;
5943                         for(i=0; i<fromAccountOpts.length; i++) {
5944                               var key = fromAccountOpts[i].value;
5945                               var display = fromAccountOpts[i].text;
5946                               var opt = new Option(display, key);
5947                               if (fromAccountOpts[i].selected) {
5948                                 opt.selected = true;
5949                               }
5950                               addressFrom.options.add(opt);
5951                         }
5952
5953             } // if
5954         } // if
5955     },
5956
5957     setContentOnThisTiny : function() {
5958         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5959         var tinyHTML = tiny.getContent();
5960         composePackage.body = decodeURI(encodeURI(composePackage.body));
5961         // cn: bug 14361 - text-only templates don't fill compose screen
5962         if(composePackage.body == '') {
5963             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,'"');
5964         } // if
5965         //Flag determines if we should clear the tiny contents or just append
5966         if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5967             SE.composeLayout.tinyHTML = '';
5968         else
5969             SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
5970
5971          tiny.setContent(SE.composeLayout.tinyHTML);
5972          //Indicate that the contents has been loaded successfully.
5973          SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5974     },
5975     /**
5976      * Confirms closure of a compose screen if "x" is clicked
5977      */
5978     confirmClose : function(panel) {
5979         if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
5980             SE.composeLayout.closeCompose(panel.id);
5981             return true;
5982         } else {
5983             return false;
5984         }
5985     },
5986
5987     /**
5988      * forces close of a compose screen
5989      */
5990     forceCloseCompose : function(id) {
5991         SE.composeLayout.closeCompose(id);
5992
5993         // handle flow back to originating view
5994         if(composePackage) {
5995             // check if it's a module we need to return to
5996             if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
5997                 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
5998                     var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
5999                     window.location = url;
6000                 }
6001             }
6002         }
6003     },
6004
6005     /**
6006      * closes the editor that just sent email
6007      * @param string id ID of composeLayout tab
6008      */
6009     closeCompose : function(id) {
6010         // destroy tinyMCE instance
6011         var idx = id.substr(13, id.length);
6012         var instanceId = "htmleditor" + idx;
6013         tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6014
6015         // nullify DOM and namespace values.
6016         inCompose = false;
6017         SE.composeLayout[idx] = null;
6018         SE.tinyInstances[instanceId] = null;
6019         var tabsArray = SE.innerLayout.get("tabs");
6020         for (i = 0 ; i < tabsArray.length ; i++) {
6021                 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6022                         tabsArray[i].close();
6023                         break;
6024                 }
6025         }
6026         //SE.innerLayout.getTab(idx).close();
6027     },
6028
6029     /**
6030     *  Enable the quick search for the compose relate field or search tab
6031     */
6032     enableQuickSearchRelate: function(idx,overides){
6033
6034         if(typeof overides != 'undefined')
6035         {
6036             var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6037             var newModule = document.getElementById(newModuleID).value;
6038             var formName = overides['formName'];
6039             var fieldName = overides['fieldName'];
6040             var fieldId = overides['fieldId'];
6041             var fullName = formName + "_" + fieldName;
6042             var postBlurFunction = null;
6043         }
6044         else
6045         {
6046             var newModule = document.getElementById('data_parent_type'+idx).value;
6047             var formName = 'emailCompose'+idx;
6048             var fieldName = 'data_parent_name'+idx;
6049             var fieldId = 'data_parent_id'+idx;
6050             var fullName = formName + "_" + fieldName;
6051             var postBlurFunction = "SE.composeLayout.qsAddAddress";
6052         }
6053
6054         if(typeof sqs_objects == 'undefined')
6055             window['sqs_objects'] = new Array;
6056
6057         window['sqs_objects'][fullName] = {
6058             form:formName,
6059                         method:"query",
6060                         modules:[newModule],
6061                         group:"or",
6062             field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6063             conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6064                         post_onblur_function: postBlurFunction,
6065             order:"name","limit":"30","no_match_text":"No Match"};
6066
6067
6068         if(typeof QSProcessedFieldsArray != 'undefined')
6069                 QSProcessedFieldsArray[fullName] = false;
6070         if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6071                 QSFieldsArray[fullName].destroy();
6072                 delete QSFieldsArray[fullName];
6073         }
6074         if (Dom.get(fullName + "_results")) {
6075                 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6076         }
6077
6078         enableQS(false);
6079     },
6080
6081         qsAddAddress : function(o) {
6082         if (o.name != "" && o.email1 != "")
6083         {
6084                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6085                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6086         }
6087     },
6088     /**
6089      * Returns a new instance ID, 0-index
6090      */
6091     getNewInstanceId : function() {
6092         this.currentInstanceId = this.currentInstanceId + 1;
6093         return this.currentInstanceId;
6094     },
6095
6096     /**
6097      * 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.
6098      */
6099     loadAttachments : function(result) {
6100         var idx = SE.composeLayout.currentInstanceId;
6101
6102         if(typeof(result) == 'object') {
6103                 //jchi #20680. Clean the former template attachments;
6104                 var basket = document.getElementById('addedTemplateAttachments' + idx);
6105                         if(basket.innerHTML != ''){
6106                                 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6107                                         if (btn != 'yes'){
6108                                                 basket.innerHTML = '';
6109                                         }
6110                                 });
6111                         }
6112             for(i in result) {
6113                 if(typeof result[i] == 'object') {
6114                     var index = SE.composeLayout.addTemplateAttachmentField(idx);
6115                     var bean = result[i];
6116                     document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6117                     document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6118                 }
6119             }
6120         }
6121     },
6122
6123     /**
6124      * fills drop-down values for email templates and signatures
6125      */
6126     setComposeOptions : function(idx) {
6127         // send from accounts
6128         var addressFrom = document.getElementById('addressFrom' + idx);
6129
6130         if (addressFrom.options.length <= 0) {
6131                 SE.util.emptySelectOptions(addressFrom);
6132                 var fromAccountOpts = SE.composeLayout.fromAccounts;
6133                 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6134                       var key = fromAccountOpts[id].value;
6135                       var display = fromAccountOpts[id].text;
6136                       var is_default = false;
6137                       if(key == SUGAR.default_inbound_accnt_id)
6138                         is_default = true;
6139                       var opt = new Option(display, key);
6140                       addressFrom.options.add(opt);
6141                       addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6142                 }
6143         }
6144
6145         // email templates
6146         var et = document.getElementById('email_template' + idx);
6147         SE.util.emptySelectOptions(et);
6148
6149         for(var key in this.emailTemplates) { // iterate through assoc array
6150             var display = this.emailTemplates[key];
6151             var opt = new Option(display, key);
6152             et.options.add(opt);
6153         }
6154
6155         // signatures
6156         var sigs = document.getElementById('signatures' + idx);
6157         SE.util.emptySelectOptions(sigs);
6158
6159         for(var key in this.signatures) { // iterate through assoc array
6160             var display = this.signatures[key];
6161             var opt = new Option(display, key);
6162
6163             if(key == SE.userPrefs.signatures.signature_default) {
6164                 opt.selected = true;
6165             }
6166
6167             sigs.options.add(opt);
6168         }
6169
6170         // html/plain email?
6171         var htmlEmail = document.getElementById('setEditor' + idx);
6172         if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6173             htmlEmail.checked = true;
6174         } else {
6175                 htmlEmail.checked = false;
6176         }
6177
6178         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6179     },
6180
6181     /**
6182      * After compose screen is rendered, async call to get email body from Sugar
6183      */
6184     replyForwardEmailStage2 : function() {
6185         SE.util.clearHiddenFieldValues('emailUIForm');
6186         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6187
6188         var ieId = SE.composeLayout.replyForwardObj.ieId;
6189         var uid = SE.composeLayout.replyForwardObj.uid;
6190         var mbox = SE.composeLayout.replyForwardObj.mbox;
6191         var type = SE.composeLayout.replyForwardObj.type;
6192         var idx = SE.composeLayout.currentInstanceId;
6193
6194         var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6195
6196         document.getElementById('emailSubject' + idx).value = type;
6197         document.getElementById('emailUIAction').value = 'composeEmail';
6198         document.getElementById('composeType').value = type;
6199         document.getElementById('ieId').value = ieId;
6200         document.getElementById('uid').value = uid;
6201         document.getElementById('mbox').value = mbox;
6202                 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6203         var formObject = document.getElementById('emailUIForm');
6204         YAHOO.util.Connect.setForm(formObject);
6205
6206         var sendType = type;
6207         AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6208     },
6209
6210     /**
6211     *  Show the hidden cc or bcc fields
6212     */
6213     showHiddenAddress: function(addrType,idx){
6214
6215         Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6216         Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6217                 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6218                 this[addrType+'Hidden'+idx] = false;
6219
6220                 //After bcc or cc is added, move options below last addr field
6221                 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6222
6223                 //If both cc and bcc hidden, remove the empty row containing text.
6224                 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6225                            && ( this['ccHidden'+idx]  == false && this['bccHidden'+idx] == false) )
6226                         Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6227
6228                 SE.composeLayout.resizeEditor(idx);
6229     },
6230     /**
6231     *  Hide the cc and bcc fields if they were shown.
6232     */
6233     hideHiddenAddresses: function(idx){
6234
6235         var addrTypes = ['cc','bcc'];
6236         for(var i = 0;i<addrTypes.length;i++)
6237         {
6238             Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6239             Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6240             this[addrTypes[i] + 'Hidden'+idx] = true
6241         }
6242
6243         Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6244         Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6245         Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6246     }
6247 };
6248
6249 ////    END SE.composeLayout
6250 ///////////////////////////////////////////////////////////////////////////////
6251 ///////////////////////////////////////////////////////////////////////////////
6252 ////    SE.util
6253 SE.util = {
6254     /**
6255      * Cleans serialized UID lists of duplicates
6256      * @param string
6257      * @return string
6258      */
6259     cleanUids : function(str) {
6260         var seen = new Object();
6261         var clean = "";
6262         var arr = new String(str).split(",");
6263
6264         for(var i=0; i<arr.length; i++) {
6265             if(seen[arr[i]]) {
6266                 continue;
6267             }
6268
6269             clean += (clean != "") ? "," : "";
6270             clean += arr[i];
6271             seen[arr[i]] = true;
6272         }
6273
6274         return clean;
6275     },
6276
6277     /**
6278      * Clears hidden field values
6279      * @param string id ID of form element to clear
6280      */
6281     clearHiddenFieldValues : function(id) {
6282         var form = document.getElementById(id);
6283
6284         for(i=0; i<form.elements.length; i++) {
6285             if(form.elements[i].type == 'hidden') {
6286                 var e = form.elements[i];
6287                 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6288                     e.value = '';
6289                 }
6290             }
6291         }
6292     },
6293
6294     /**
6295      * Reduces a SELECT drop-down to 0 items to prepare for new ones
6296      */
6297     emptySelectOptions : function(el) {
6298         if(el) {
6299             for(i=el.childNodes.length - 1; i >= 0; i--) {
6300                 if(el.childNodes[i]) {
6301                     el.removeChild(el.childNodes[i]);
6302                 }
6303             }
6304         }
6305     },
6306
6307     /**
6308      * Returns the MBOX path in the manner php_imap expects:
6309      * ie: INBOX.DEBUG.test
6310      * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6311      */
6312     generateMboxPath : function(str) {
6313         var ex = str.split("::");
6314
6315         /* we have a serialized MBOX path */
6316         if(ex.length > 1) {
6317             var start = false;
6318             var ret = '';
6319             for(var i=0; i<ex.length; i++) {
6320                 if(ex[i] == 'INBOX') {
6321                     start = true;
6322                 }
6323
6324                 if(start == true) {
6325                     if(ret != "") {
6326                         ret += ".";
6327                     }
6328                     ret += ex[i];
6329                 }
6330             }
6331         } else {
6332             /* we have a Sugar folder GUID - do nothing */
6333             return str;
6334         }
6335
6336         return ret;
6337     },
6338
6339     /**
6340      * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6341      * @param HTMLElement el
6342      * @return string GUID of found element or empty on failure
6343      */
6344     getGuidFromElement : function(el) {
6345         var GUID = '';
6346         var iterations = 4;
6347         var passedEl = el;
6348
6349         // upwards
6350         for(var i=0; i<iterations; i++) {
6351             if(el) {
6352                 if(el.id.match(SE.reGUID)) {
6353                     return el.id;
6354                 } else {
6355                     el = el.parentNode;
6356                 }
6357             }
6358         }
6359
6360         return GUID;
6361     },
6362
6363     /**
6364      * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6365      * @return string
6366      */
6367     getPanelId : function() {
6368         return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6369     },
6370
6371     /**
6372      * wrapper to handle weirdness with IE
6373      * @param string instanceId
6374      * @return tinyMCE Controller object
6375      */
6376     getTiny : function(instanceId) {
6377         if(instanceId == '') {
6378             return null;
6379         }
6380
6381         var t = tinyMCE.getInstanceById(instanceId);
6382
6383         if(this.isIe()) {
6384             this.sleep(200);
6385             YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6386         }
6387         return t;
6388     },
6389
6390     /**
6391      * Simple check for MSIE browser
6392      * @return bool
6393      */
6394     isIe : function() {
6395         var nav = new String(navigator.appVersion);
6396         if(nav.match(/MSIE/)) {
6397             return true;
6398         }
6399         return false;
6400     },
6401
6402     /**
6403      * Recursively removes an element from the DOM
6404      * @param HTMLElement
6405      */
6406     removeElementRecursive : function(el) {
6407         this.emptySelectOptions(el);
6408     },
6409
6410     /**
6411      * Fakes a sleep
6412      * @param int
6413      */
6414     sleep : function(secs) {
6415         setTimeout("void(0);", secs);
6416     },
6417
6418     /**
6419      * Converts a <select> element to an Ext.form.combobox
6420      */
6421      convertSelect : function(select) {
6422        alert('in convertSelect');
6423        if (typeof(select) == "string") {
6424            select = document.getElementById(select);
6425        }
6426      },
6427
6428      findChildNode : function (parent, property, value) {
6429          for (i in parent.children) {
6430                  var child = parent.children[i];
6431                  if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6432                          return child;
6433                  var searchChild = SE.util.findChildNode(child, property, value);
6434                  if (searchChild)
6435                          return searchChild;
6436          }
6437          return false;
6438      },
6439
6440      cascadeNodes : function (parent, fn, scope, args) {
6441          for (i in parent.children) {
6442                  var child = parent.children[i];
6443                  var s = scope ? scope : child;
6444                  var a = args ? args : child;
6445                  fn.call(s, a);
6446                  SE.util.cascadeNodes(child, fn, scope, args);
6447          }
6448      }
6449 };
6450
6451
6452 ////    END UTIL
6453 ///////////////////////////////////////////////////////////////////////////////
6454
6455
6456 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6457                                 
6458 /*********************************************************************************
6459  * SugarCRM is a customer relationship management program developed by
6460  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6461  * 
6462  * This program is free software; you can redistribute it and/or modify it under
6463  * the terms of the GNU Affero General Public License version 3 as published by the
6464  * Free Software Foundation with the addition of the following permission added
6465  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6466  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6467  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6468  * 
6469  * This program is distributed in the hope that it will be useful, but WITHOUT
6470  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6471  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
6472  * details.
6473  * 
6474  * You should have received a copy of the GNU Affero General Public License along with
6475  * this program; if not, see http://www.gnu.org/licenses or write to the Free
6476  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6477  * 02110-1301 USA.
6478  * 
6479  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6480  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6481  * 
6482  * The interactive user interfaces in modified source and object code versions
6483  * of this program must display Appropriate Legal Notices, as required under
6484  * Section 5 of the GNU Affero General Public License version 3.
6485  * 
6486  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6487  * these Appropriate Legal Notices must retain the display of the "Powered by
6488  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6489  * technical reasons, the Appropriate Legal Notices must display the words
6490  * "Powered by SugarCRM".
6491  ********************************************************************************/
6492
6493
6494 if (typeof console == "undefined")
6495         console = { log: function(o) {alert(o)} };
6496
6497 var AjaxObject = {
6498         ret : '',
6499         currentRequestObject : null,
6500         //timeout : 30000, // 30 second timeout default
6501         timeout : 9999999999, // 30 second timeout default
6502         forceAbort : false,
6503         trail : new Array(),
6504
6505         /**
6506          */
6507         _reset : function() {
6508                 this.timeout = 30000;
6509                 this.forceAbort = false;
6510         },
6511
6512         folderRenameCleanup : function() {
6513                 SUGAR.email2.folders.setSugarFolders();
6514         },
6515
6516         fullSyncCleanup : function(o) {
6517                 this.folders.checkMailCleanup(o);
6518                 SUGAR.email2.settings.settingsDialog.hide();
6519         },
6520
6521         /**
6522          */
6523         composeCache : function(o) {
6524                 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6525                 // get email templates and user signatures
6526                 var ret = JSON.parse(o.responseText);
6527
6528                 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6529                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6530                 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6531
6532                 SUGAR.email2.composeLayout.setComposeOptions(idx);
6533
6534                 //Set the error array so we can notify the user when they try to hit send if any errors
6535                 //are present.  We will also notify them now (after hitting compose button).
6536                 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6537
6538
6539                 //if error element is returning an array, then check the length to make sure we have error messages
6540                 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6541                         //add error messages for display
6542                         for(i in ret.errorArray)
6543                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6544                 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6545                         //if error element is returning an object, and the object value is not empty or null, then display error message
6546                         for(i in ret.errorArray)
6547                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6548                 }
6549
6550                 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6551                 if(SUGAR.isIE) {
6552                         var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6553                         if(overlayPanel) {
6554                           overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6555                         }
6556                 }
6557         },
6558
6559
6560         handleDeleteSignature : function(o) {
6561                 hideOverlay();
6562                 var ret = JSON.parse(o.responseText);
6563                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6564         var field = document.getElementById('signature_id');
6565                 SUGAR.email2.util.emptySelectOptions(field);
6566
6567                 for(var i in ret.signatures) { // iterate through assoc array
6568                         var opt = new Option(ret.signatures[i], i);
6569                         field.options.add(opt);
6570                 }
6571                 setSigEditButtonVisibility();
6572         },
6573
6574         /**
6575          */
6576         handleDeleteReturn : function(o) {
6577                 // force refresh ListView
6578                 hideOverlay();
6579                 if(document.getElementById('focusEmailMbox')) {
6580                         YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6581                 }
6582
6583                 // need to display success message before calling next async call?
6584                 document.getElementById(this.target).innerHTML = o.responseText;
6585         },
6586
6587         /**
6588          */
6589     handleFailure : function(o) {
6590                 // Failure handler
6591                 overlay('Exception occurred...', o.statusText, 'alert');
6592         },
6593
6594         handleReplyForward : function(o) {
6595                 var a = JSON.parse(o.responseText);
6596                 globalA = a;
6597                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6598
6599                 document.getElementById('email_id' + idx).value = a.uid;
6600                 document.getElementById('emailSubject' + idx).value = a.name;
6601                 document.getElementById('addressTO' + idx).value = a.from;
6602                 document.getElementById('uid' + idx).value = a.uid;
6603                 if(a.cc) {
6604                         document.getElementById('addressCC' + idx).value = a.cc;
6605                         SE.composeLayout.showHiddenAddress('cc', idx);
6606                 }
6607
6608                 if(a.type) {
6609                         document.getElementById('type' + idx).value = a.type;
6610                 }
6611
6612                 // apply attachment values
6613                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6614
6615                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6616         },
6617
6618         handleReplyForwardForDraft : function(o) {
6619                 var a = JSON.parse(o.responseText);
6620                 globalA = a;
6621                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6622
6623                 document.getElementById('email_id' + idx).value = a.uid;
6624                 document.getElementById('emailSubject' + idx).value = a.name;
6625                 document.getElementById('addressTO' + idx).value = a.to;
6626
6627                 if(a.cc) {
6628                         document.getElementById('addressCC' + idx).value = a.cc;
6629                         SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6630                 }
6631
6632                 if(a.bcc) {
6633                         document.getElementById('addressBCC' + idx).value = a.bcc;
6634                         SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6635                 }
6636
6637
6638                 if(a.type) {
6639                         document.getElementById('type' + idx).value = a.type;
6640                 }
6641
6642
6643                 // apply attachment values
6644                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6645
6646                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6647         },
6648
6649         /**
6650          */
6651         handleSuccess : function(o) {
6652                 document.getElementById(this.target).innerHTML = o.responseText;
6653                 hideOverlay();
6654         },
6655
6656         /**
6657          */
6658         ieDeleteSuccess : function(o) {
6659                 hideOverlay();
6660
6661                 var ret = JSON.parse(o.responseText);
6662
6663                 SUGAR.email2.accounts.refreshInboundAccountTable();
6664                 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6665                 SUGAR.email2.accounts.rebuildFolderList();
6666
6667         },
6668
6669         /**
6670          */
6671         ieSaveSuccess : function(o) {
6672                 document.getElementById('saveButton').disabled = false;
6673                 var a = JSON.parse(o.responseText);
6674                 if (a) {
6675                         if(a.error) {
6676                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6677                                 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6678                         } else {
6679                                 resp = JSON.parse(o.responseText);
6680                                 SUGAR.email2.accounts.refreshInboundAccountTable();
6681                                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6682                                 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6683                                 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6684                         }
6685                 } else {
6686                      hideOverlay();
6687                      overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6688                 }
6689
6690         },
6691
6692         /**
6693          */
6694         loadAttachments : function(o) {
6695                 var result = JSON.parse(o.responseText);
6696
6697                 SUGAR.email2.composeLayout.loadAttachments(result);
6698         },
6699
6700         /**
6701          */
6702         loadSignature : function(o) {
6703                 var ret = JSON.parse(o.responseText);
6704                 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6705                 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6706         },
6707
6708         /**
6709          * Follow up to mark email read|unread|flagged
6710          */
6711         markEmailCleanup : function(o) {
6712                 var ret = JSON.parse(o.responseText);
6713                 if (!ret['status']) {
6714                 hideOverlay();
6715                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6716                 } else {
6717                         SUGAR.email2.contextMenus.markEmailCleanup();
6718                 } // else
6719         },
6720
6721         /**
6722          */
6723         rebuildShowFolders : function(o) {
6724                 var t = JSON.parse(o.responseText);
6725                 var show = document.getElementById('ieAccountListShow');
6726
6727                 SUGAR.email2.util.emptySelectOptions(show);
6728
6729                 for(i=0; i<t.length; i++) { // iterate through assoc array
6730                         var opt = new Option(t[i].text, t[i].value, t[i].selected);
6731                         opt.selected = t[i].selected;
6732                         show.options.add(opt);
6733                 }
6734
6735                 SUGAR.email2.accounts.renderTree();
6736         },
6737         /**
6738          */
6739         saveListViewSortOrderPart2 : function() {
6740                 // create the JSON string the func expects
6741                 focusFolderPath = '[ "Home", "' + ieName + '"';
6742
6743                 var f = new String(focusFolder);
6744                 var fEx = f.split('.');
6745
6746                 for(i=0; i<fEx.length; i++) {
6747                         focusFolderPath += ', "' + fEx[i] +'"'
6748                 }
6749
6750                 focusFolderPath += ']';
6751
6752                 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6753                 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6754         },
6755
6756         /**
6757          *
6758          */
6759         sendEmailCleanUp : function(o) {
6760                 hideOverlay();
6761                 var ret = JSON.parse(o.responseText);
6762                 if (ret) {
6763                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6764                   //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6765                 } else if (o.responseText) {
6766                   overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6767                 }
6768
6769                 if (typeof(SE.grid) != 'undefined')
6770                         SE.listView.refreshGrid();
6771                 //Disabled while address book is disabled
6772
6773                 //If this call back was initiated by quick compose from a Detail View page, refresh the
6774                 //history subpanel.  If it was initiated by quickcreate from shortcut bar, then
6775                 //close the shortcut bar menu
6776                 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6777                         if(action_sugar_grp1 == 'DetailView') {
6778                                 showSubPanel('history',null,true);
6779                         } else if(action_sugar_grp1 == 'quickcreate') {
6780                                 closeEmailOverlay();
6781                         }
6782                 }
6783
6784         },
6785
6786         ieSendSuccess : function(o) {
6787                 hideOverlay();
6788                 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6789         },
6790
6791         /**
6792          */
6793         settingsFolderRefresh : function(o) {
6794                 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6795                 var ret = JSON.parse(o.responseText);
6796                 var user = document.getElementById('userFolders');
6797
6798                 SUGAR.email2.util.emptySelectOptions(user);
6799
6800                 for(i=0; i<ret.userFolders.length; i++) {
6801                         var display = ret.userFolders[i].name;
6802                         var value = ret.userFolders[i].id;
6803                         var selected = (ret.userFolders[i].selected != "") ? true : false;
6804                         var opt = new Option(display, value, selected);
6805                         opt.selected = selected;
6806                         user.options.add(opt);
6807                 }
6808         },
6809
6810         /**
6811          */
6812         startRequest : function(callback, args, forceAbort) {
6813                 if(this.currentRequestObject != null) {
6814                         if(this.forceAbort == true) {
6815                                 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6816                         }
6817                 }
6818                 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6819                 this._reset();
6820         },
6821
6822         requestInProgress : function() {
6823                 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6824         },
6825
6826         /**
6827          */
6828         updateFolderSubscriptions : function() {
6829                 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6830                 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6831                 hideOverlay();
6832         },
6833
6834         /**
6835          */
6836         updateFrameFolder : function() {
6837                 SUGAR.email2.folders.checkEmailAccounts();
6838         },
6839
6840         /**
6841          */
6842         updateUserPrefs : function(o) {
6843                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6844                 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6845         },
6846
6847         /**
6848          */
6849         uploadAttachmentSuccessful : function(o) {
6850                 // clear out field
6851                 document.getElementById('email_attachment').value = '';
6852
6853                 var ret = JSON.parse(o.responseText);
6854                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6855                 var overall = document.getElementById('addedFiles' + idx);
6856                 var index = overall.childNodes.length;
6857                 var out =
6858                         "<div id='email_attachment_bucket" + idx + index + "'>" +
6859                                 // remove button
6860                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6861                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6862                                         idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6863                                 // file icon
6864                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6865                                         "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6866                                 // hidden id field
6867                                 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6868                                 // file name
6869                                 ((ret.nameForDisplay != null) ? ret.nameForDisplay + "&nbsp;" : ret.name + "&nbsp;") +
6870                                 "<br/>" +
6871                         "</div>";
6872                 overall.innerHTML += out;
6873                 if(SUGAR.email2.util.isIe()) {
6874                         document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6875                 }
6876
6877                 // hide popup
6878                 SUGAR.email2.addFileDialog.hide();
6879                 // focus attachments
6880                 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6881         }
6882 };
6883
6884
6885 ///////////////////////////////////////////////////////////////////////////
6886 ////    PER MODULE CALLBACK OBJECTS
6887 AjaxObject.accounts = {
6888         saveOutboundCleanup : function(o) {
6889                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6890                 SUGAR.email2.accounts.outboundDialog.hide();
6891                 var id = o.responseText;
6892                 SUGAR.email2.accounts.newAddedOutboundId = id;
6893                 },
6894         saveDefaultOutboundCleanup: function(o){
6895
6896         },
6897         callbackEditOutbound : {
6898                 success : function(o)
6899                 {
6900                         var ret = JSON.parse(o.responseText);
6901                         // show overlay
6902                         SUGAR.email2.accounts.showAddSmtp();
6903
6904                         // fill values
6905                         document.getElementById("mail_id").value = ret.id;
6906                         document.getElementById("type").value = ret.type;
6907                         document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6908                         document.getElementById("mail_name").value = ret.name;
6909                         document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6910                         document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6911                         document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6912                         document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6913                         document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6914                         SUGAR.email2.accounts.smtp_authenticate_field_display();
6915                         document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6916
6917             if(ret.type == 'system-override') {
6918                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6919                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6920             }
6921             else {
6922                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6923                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6924             }
6925             SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6926
6927                 },
6928                 failure : AjaxObject.handleFailure,
6929                 timeout : AjaxObject.timeout,
6930                 scope   : AjaxObject
6931         },
6932         callbackDeleteOutbound : {
6933                 success : function(o) {
6934                     var ret = JSON.parse(o.responseText);
6935                     if(ret.is_error)
6936                     {
6937                         if(confirm(ret.error_message))
6938                 {
6939                     overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6940                     AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6941                 }
6942                 else
6943                     hideOverlay();
6944                     }
6945                     else
6946                     {
6947                              hideOverlay();
6948                              SUGAR.email2.accounts.refreshOuboundAccountTable();
6949                     }
6950                 },
6951
6952                 failure : AjaxObject.handleFailure,
6953                 timeout : AjaxObject.timeout,
6954                 scope   : AjaxObject
6955         },
6956
6957         callbackCheckMailProgress : {
6958            success : function(o) {
6959                if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6960                    SUGAR.email2.accounts.totalMsgCount = -1;
6961                }
6962
6963                //Check for server timeout / errors
6964                var ret = JSON.parse(o.responseText);
6965                var done = false;
6966
6967                if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6968                    hideOverlay();
6969                    overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6970                    SUGAR.email2.accounts.totalMsgCount = -1;
6971                //SUGAR.email2.folders.rebuildFolders();
6972                done = true;
6973                }
6974
6975                var currIeId = ret['ieid'];
6976
6977
6978                var serverCount = ret.count;
6979
6980                if (ret['status'] == 'done') {
6981                    for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
6982                        if (i == SUGAR.email2.accounts.ieIds.length - 1) {
6983                            //We are all done
6984                            done = true;
6985                            break;
6986                        } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
6987                            //Go to next account
6988                            currIeId = SUGAR.email2.accounts.ieIds[i+1];
6989                            ret.count = 0;
6990                            SUGAR.email2.accounts.totalMsgCount = -1;
6991                            break;
6992                        }
6993                    }
6994                }
6995                else if (ret.mbox && ret.totalcount && ret.count) {
6996                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
6997                    if (ret.count >= ret.totalcount) {
6998                        serverCount = 0;
6999                    }
7000                } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7001                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7002                } else {
7003                        hideOverlay();
7004                overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7005                SUGAR.email2.accounts.totalMsgCount = -1;
7006                done = true;
7007                    }
7008
7009                if (done) {
7010                    SUGAR.email2.accounts.totalMsgCount = -1;
7011                    hideOverlay();
7012                    SUGAR.email2.folders.rebuildFolders();
7013                    SE.listView.refreshGrid();
7014                } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7015                YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7016                AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7017                                 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=0&synch=" + ret.synch);
7018            } else {
7019                YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7020                    app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7021                    AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7022                    '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=" + serverCount +
7023                    '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7024                }
7025            },
7026            failure : AjaxObject.handleFailure,
7027        timeout : AjaxObject.timeout,
7028        scope   : AjaxObject
7029         }
7030 };
7031
7032 ///////////////////////////////////////////////////////////////////////////////
7033 ////    COMPOSE LAYOUT
7034 AjaxObject.composeLayout = {
7035         /**
7036          * Populates the record id
7037          */
7038         saveDraftCleanup : function(o) {
7039                 hideOverlay();
7040                 var ret = JSON.parse(o.responseText);
7041                 if(ret)
7042                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7043                 else if (o.responseText)
7044                   overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7045         }
7046 };
7047
7048 AjaxObject.composeLayout.callback = {
7049         saveDraft : {
7050                 success : AjaxObject.composeLayout.saveDraftCleanup,
7051                 failure : AjaxObject.handleFailure,
7052                 timeout : AjaxObject.timeout,
7053                 scope   : AjaxObject
7054         }
7055 };
7056
7057 AjaxObject.detailView = {
7058         /**
7059          * Pops-up a printable view of an email
7060          */
7061         displayPrintable : function(o) {
7062                 var ret = JSON.parse(o.responseText);
7063                 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7064                 // 2 below must be in global context
7065                 meta = ret.meta;
7066                 meta['panelId'] = SUGAR.email2.util.getPanelId();
7067                 email = ret.meta.email;
7068                 if (typeof(email.cc) == 'undefined') {
7069                   email.cc = "";
7070                 }
7071
7072                 var out = displayTemplate.exec({
7073                         'app_strings'   : app_strings,
7074                         'theme'                 : theme,
7075                         'idx'                   : 'Preview',
7076                         'meta'                  : meta,
7077                         'email'                 : meta.email
7078                 });
7079
7080                 // open popup window
7081                 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7082                     'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7083
7084                 popup.document.write(out);
7085                 popup.document.close();
7086         },
7087
7088         /**
7089          * Takes formatted response and creates a modal pop-over containing a title and content
7090          */
7091         displayView : function(o) {
7092                 var SED = SUGAR.email2.detailView;
7093                 var ret = JSON.parse(o.responseText);
7094
7095                 if(!SED.viewDialog) {
7096                         SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7097                                 modal:true,
7098                 visible:true,
7099                 fixedcenter:true,
7100                 constraintoviewport: true,
7101                                 shadow  : true
7102                         });
7103             SED.viewDialog.renderEvent.subscribe(function() {
7104                 var content = this.body.firstChild;
7105                 var viewH = YAHOO.util.Dom.getViewportHeight();
7106                 if (content) {
7107                         this.body.style.overflow = "auto";
7108                         this.body.style.width = "800px";
7109                         this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7110                 }
7111             }, SED.viewDialog);
7112                 } // end lazy load
7113                 SED.viewDialog.setHeader(ret.title);
7114                 SED.viewDialog.setBody(ret.html);
7115                 SED.viewDialog.render();
7116                 SED.viewDialog.show();
7117         },
7118
7119         /**
7120          * Generates a modal popup to populate with the contents of bean's full EditView
7121          */
7122         showQuickCreateForm : function(o) {
7123                 var SED = SUGAR.email2.detailView;
7124                 var ret = JSON.parse(o.responseText);
7125
7126                 if(!SED.quickCreateDialog) {
7127                         SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7128                                 modal:true,
7129                                 visible:true,
7130                 fixedcenter:true,
7131                 constraintoviewport: true,
7132                                 shadow  : true
7133                         });
7134
7135             SED.quickCreateDialog.renderEvent.subscribe(function() {
7136                 var viewH = YAHOO.util.Dom.getViewportHeight();
7137                 var contH = 0;
7138                 for (var i in this.body.childNodes) {
7139                         if (this.body.childNodes[i].clientHeight) {
7140                                 contH += this.body.childNodes[i].clientHeight;
7141                         } else if (this.body.childNodes[i].offsetHeight) {
7142                                 contH += this.body.childNodes[i].offsetHeight;
7143                         } // if
7144                 }
7145                         this.body.style.width = "800px";
7146                         this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7147                         this.body.style.overflow = "auto";
7148             }, SED.quickCreateDialog);
7149
7150             SED.quickCreateDialog.hideEvent.subscribe(function(){
7151                                 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7152                                 /*for(var qsField in qsFields){
7153                                         if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7154                                         Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7155                                 }*/
7156                         });
7157             SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7158                 } // end lazy load
7159                 if (ret.html) {
7160                         ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7161                 }
7162                 SED.quickCreateDialog.setBody(ret.html ? ret.html : "&nbsp;");
7163                 SED.quickCreateDialog.render();
7164                 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7165
7166                 SED.quickCreateDialog.ieId = ret.ieId;
7167                 SED.quickCreateDialog.uid = ret.uid;
7168         SED.quickCreateDialog.mbox = ret.mbox;
7169         SED.quickCreateDialog.qcmodule = ret.module;
7170
7171         SED.quickCreateDialog.show();
7172
7173                 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7174                 if (editForm) {
7175                   editForm.module.value = 'Emails';
7176                   var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7177                   var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7178                   var instId = ret.module + count;
7179                   SED.quickCreateEmailsToAdd = ret.emailAddress;
7180                   SED.quickCreateEmailCallback = function(instId, tableId) {
7181                           var eaw = SUGAR.EmailAddressWidget.instances[instId];
7182                           if (typeof(eaw) == "undefined")
7183                                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7184                                                 + instId + "','" + tableId + "');", 100);
7185                           eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7186                   }
7187                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7188                                         + instId + "','" + tableId + "');", 100);
7189                 }
7190         },
7191
7192         saveQuickCreateForm : function(o) {
7193             hideOverlay();
7194                 SUGAR.email2.detailView.quickCreateDialog.hide();
7195                 validate['EditView'] = [ ];
7196         },
7197
7198         saveQuickCreateFormAndReply : function(o) {
7199             hideOverlay();
7200             var ret = JSON.parse(o.responseText);
7201         SUGAR.email2.detailView.quickCreateDialog.hide();
7202         var qcd = SUGAR.email2.detailView.quickCreateDialog;
7203         var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7204         if (ret) {
7205             var emailID = ret.id;
7206             SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7207         } else {
7208             SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7209         }
7210         //Cean the validate cache to prevent errors on the next call
7211         validate['EditView'] = [ ];
7212     },
7213
7214         saveQuickCreateFormAndAddToAddressBook : function(o) {
7215            hideOverlay();
7216                 SUGAR.email2.detailView.quickCreateDialog.hide();
7217                 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7218                 validate['EditView'] = [ ];
7219         },
7220
7221         handleAssignmentDialogAssignAction : function() {
7222
7223
7224             var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7225
7226             var dist = 'direct';
7227             var users = false;
7228             var rules = false;
7229             var get = "";
7230             var found_teams = false;
7231             var warning_message = mod_strings.LBL_WARN_NO_USERS;
7232             if(!found_teams && assign_user_id == '' )
7233             {
7234                 alert(warning_message);
7235                 return;
7236             }
7237
7238             var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7239             var uids = "";
7240             for(i=0; i<emailUids.length; i++) {
7241                 if(uids != '') {
7242                     uids += app_strings.LBL_EMAIL_DELIMITER;
7243                 }
7244                 uids += emailUids[i];
7245             }
7246
7247             var row = SUGAR.email2.grid.getSelectedRows()[0];
7248             var data = SUGAR.email2.grid.getRecord(row).getData();
7249             var ieid = data.ieId;
7250             var mbox = data.mbox;
7251             AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7252             SUGAR.email2.contextMenus.assignToDialogue.hide();
7253             overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7254
7255         },
7256
7257         handleAssignmentDialogDeleteAction : function() {
7258                 // TO pass list of UIDS/emailIds
7259                 var uids = SUGAR.email2.listView.getUidsFromSelection();
7260                 var row = SUGAR.email2.grid.getSelections()[0];
7261                 var ieid = row.data.ieId;
7262             var mbox = row.data.mbox;
7263         AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7264         SUGAR.email2.contextMenus.assignmentDialog.hide();
7265                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7266
7267                 // AJAX Call
7268
7269         },
7270
7271         showEmailDetailView : function(o) {
7272         hideOverlay();
7273         var SED = SUGAR.email2.detailView;
7274                 var ret = JSON.parse(o.responseText);
7275
7276                 if(!SED.quickCreateDialog) {
7277                         SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7278                                 modal:true,
7279                                 visible:true,
7280                 //fixedcenter:true,
7281                 constraintoviewport: true,
7282                 draggable: true,
7283                                 autofillheight: "body",
7284                                 shadow  : true
7285                         });
7286                         SED.quickCreateDialog.renderEvent.subscribe(function() {
7287                 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7288                 var contH = 0;
7289                 for (var i in this.body.childNodes) {
7290                         if (this.body.childNodes[i].offsetHeight)
7291                                 contH += this.body.childNodes[i].offsetHeight;
7292                 }
7293                         this.body.style.overflow = "auto";
7294                         this.body.style.width = "800px";
7295                         this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7296                         this.center();
7297             }, SED.quickCreateDialog);
7298                 }
7299                 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7300                 SED.quickCreateDialog.setBody(ret.html);
7301                 SED.quickCreateDialog.render();
7302         SUGAR.util.evalScript(ret.html);
7303         SED.quickCreateDialog.show();
7304         },
7305
7306         showAssignmentDialogWithData : function(o) {
7307         var SEC = SUGAR.email2.contextMenus;
7308                 hideOverlay();
7309         var ret = JSON.parse(o.responseText);
7310         if (!SEC.assignmentDialog) {
7311                 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7312                         visible:false,
7313                 fixedcenter:true,
7314                 constraintoviewport: true,
7315                         modal   : true
7316                 });
7317                 SEC.assignmentDialog.setBody("");
7318                 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7319                 SEC.assignmentDialog.renderEvent.subscribe(function() {
7320                 var iev = YAHOO.util.Dom.get("Distribute");
7321                 if (iev) {
7322                         this.body.style.width = "700px";
7323                 }
7324             },  SEC.assignmentDialog);
7325                 SEC.assignmentDialog.render();
7326         }
7327         SEC.assignmentDialog.setBody(ret);
7328         SEC.assignmentDialog.render();
7329         validate = [];
7330         SEC.assignmentDialog.show();
7331         SUGAR.util.evalScript(ret);
7332         },
7333
7334         showImportForm : function(o) {
7335                 var SED = SUGAR.email2.detailView;
7336                 var ret = JSON.parse(o.responseText);
7337
7338         document.getElementById('quickCreateContent').innerHTML = "";
7339         hideOverlay();
7340         if (!ret) {
7341             return false;
7342         }
7343
7344         if(!SED.importDialog) {
7345             SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7346                 modal:true,
7347                 visible:false,
7348                 fixedcenter:true,
7349                 constraintoviewport: true,
7350                 buttons : [{
7351                         text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7352                                 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7353                 }]//,
7354                 //scroll : true
7355             });
7356             SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7357             SED.importDialog.setBody("");
7358             SED.importDialog.hideEvent.subscribe(function(){
7359                 for(var i in QSFieldsArray) {
7360                         if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7361                                 QSFieldsArray[i].destroy();
7362                                 delete QSFieldsArray[i];
7363                         }
7364                         if (QSProcessedFieldsArray[i]) {
7365                                 QSProcessedFieldsArray[i] = false;
7366                         } // if
7367                                 }
7368             });
7369             SED.importDialog.renderEvent.subscribe(function() {
7370                 var iev = YAHOO.util.Dom.get("ImportEditView");
7371                 if (iev) {
7372                         //this.body.style.height = (iev.clientHeight + 10) + "px";
7373                         this.body.style.width = "600px";
7374                 }
7375             }, SED.importDialog);
7376             SED.importDialog.render();
7377         } // end lazy load
7378         SED.importDialog.setBody(ret.html);
7379         SED.importDialog.ret = ret;
7380         SUGAR.util.evalScript(ret.html);
7381         SED.importDialog.render();
7382         validate = [];
7383         SED.importDialog.show();
7384         SED.importDialog.focusFirstButton();
7385     },
7386     getImportAction : function(ret) {
7387         if (!check_form('ImportEditView')) return false;
7388         if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7389                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7390                 return false;
7391         } // if
7392                 var get = "";
7393         var editView = document.getElementById('ImportEditView');
7394         if (editView.assigned_user_id != null) {
7395             get = get + "&user_id=" + editView.assigned_user_id.value
7396             //var user_id = editView.assigned_user_id.value;
7397         }
7398         var parent_id = editView.parent_id.value;
7399         var parent_type = editView.parent_type.value;
7400         var row = SUGAR.email2.grid.getSelectedRows()[0];
7401         row = SUGAR.email2.grid.getRecord(row);
7402         var data = row.getData();
7403         var ieId = data.ieId;
7404         var mbox = data.mbox;
7405         var serverDelete = editView.serverDelete.checked;
7406         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7407         var uids = "";
7408         for(i=0; i<emailUids.length; i++) {
7409             if(uids != '') {
7410                 uids += app_strings.LBL_EMAIL_DELIMITER;
7411             }
7412             uids += emailUids[i];
7413         }
7414
7415         var action = 'importEmail&uid=';
7416         if (ret.move) {
7417             action = 'moveEmails';
7418             action = action + '&sourceFolder=' + ret['srcFolder'];
7419             action = action + '&sourceIeId=' + ret['srcIeId'];
7420             action = action + '&destinationFolder=' + ret['dstFolder'];
7421             action = action + '&destinationIeId=' + ret['dstIeId'];
7422             action = action + '&emailUids=';
7423         }
7424         if (action.search(/importEmail/) != -1) {
7425             overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7426         } else {
7427             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7428         }
7429
7430         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7431         get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7432         SUGAR.email2.detailView.importDialog.hide();
7433         document.getElementById('importDialogContent').innerHTML = "";
7434
7435     },
7436     showRelateForm : function(o) {
7437         var SED = SUGAR.email2.detailView;
7438         var ret = JSON.parse(o.responseText);
7439         document.getElementById('quickCreateContent').innerHTML = "";
7440         hideOverlay();
7441         if (!ret) {
7442             return false;
7443         }
7444         dialog_loaded = true;
7445
7446         if(!SED.relateDialog) {
7447             SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7448                                 modal:true,
7449                                 visible:true,
7450                 fixedcenter:true,
7451                 width: '800px',
7452                 constraintoviewport: true,
7453                                 buttons : [{
7454                         text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7455                                         if (!check_form('RelateEditView')) return false;
7456                                         var get = "";
7457                         var editView = document.getElementById('RelateEditView');
7458                         var parent_id = editView.parent_id.value;
7459                         var parent_type = editView.parent_type.value;
7460                         var row = SUGAR.email2.grid.getSelectedRows()[0];
7461                         row  = SUGAR.email2.grid.getRecord(row);
7462                         var ieId = row.getData().ieId;
7463                         var mbox = row.getData().mbox;
7464                         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7465                         var uids = "";
7466                         for(i=0; i<emailUids.length; i++) {
7467                             if(uids != '') {
7468                                 uids += app_strings.LBL_EMAIL_DELIMITER;
7469                             }
7470                             uids += emailUids[i];
7471                         }
7472                         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7473                         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7474                             + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7475                         SED.relateDialog.hide();
7476                         document.getElementById('relateDialogContent').innerHTML = "";
7477                         }
7478                 }]
7479                         });
7480
7481             SED.relateDialog.hideEvent.subscribe(function(){
7482                 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7483                         QSFieldsArray['ImportEditView_parent_name'].destroy();
7484                         delete QSFieldsArray['ImportEditView_parent_name'];
7485                 } // if
7486                                 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7487                                         QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7488                                 } // if
7489             });
7490
7491             SED.relateDialog.renderEvent.subscribe(function() {
7492                 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7493                 var contH = 0;
7494                 for (var i in this.body.childNodes) {
7495                         if (this.body.childNodes[i].clientHeight)
7496                                 contH += this.body.childNodes[i].clientHeight;
7497                 }
7498             }, SED.relateDialog);
7499             SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7500                 } // end lazy load
7501
7502         SED.relateDialog.setBody(ret.html);
7503         SED.relateDialog.render();
7504         SUGAR.util.evalScript(ret.html);
7505         SED.relateDialog.show();
7506     }
7507 };
7508 /**
7509  * DetailView callbacks
7510  */
7511 AjaxObject.detailView.callback = {
7512         emailDetail : {
7513                 success : function(o) {
7514                         SUGAR.email2.o = o;
7515                         var ret = JSON.parse(o.responseText);
7516                         SUGAR.email2.detailView.consumeMetaDetail(ret);
7517                 },
7518                 argument: [targetDiv],
7519                 failure : AjaxObject.handleFailure,
7520                 timeout : 0,
7521                 scope   : AjaxObject
7522         },
7523         emailPreview : {
7524                 success : function(o) {
7525                         SUGAR.email2.o = o;
7526                         var ret = JSON.parse(o.responseText);
7527                         SUGAR.email2.detailView.consumeMetaPreview(ret);
7528                 },
7529                 failure : AjaxObject.handleFailure,
7530                 timeout : 0,
7531                 scope   : AjaxObject
7532         },
7533         viewPrint : {
7534                 success : AjaxObject.detailView.displayPrintable,
7535                 failure : AjaxObject.handleFailure,
7536                 timeout : AjaxObject.timeout,
7537                 scope   : AjaxObject
7538         },
7539         viewRaw : {
7540                 success : AjaxObject.detailView.displayView,
7541                 failure : AjaxObject.handleFailure,
7542                 timeout : AjaxObject.timeout,
7543                 scope   : AjaxObject
7544         }
7545 };
7546
7547
7548
7549
7550
7551 AjaxObject.folders = {
7552         /**
7553          * check-mail post actions
7554          */
7555         checkMailCleanup : function(o) {
7556                 hideOverlay();
7557                 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7558
7559                 // refresh focus ListView
7560                 SE.listView.refreshGrid();
7561                 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7562         },
7563
7564         /**
7565          */
7566         rebuildFolders : function(o) {
7567                 hideOverlay();
7568
7569                 var data = JSON.parse(o.responseText);
7570
7571                 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7572                 SUGAR.email2.folders.setSugarFolders();
7573         }
7574 };
7575 AjaxObject.folders.callback = {
7576         checkMail : {
7577                 success : AjaxObject.folders.checkMailCleanup,
7578                 failure : AjaxObject.handleFailure,
7579                 timeout : 600000, // 5 mins
7580                 scope   : AjaxObject
7581         }
7582 }
7583
7584 AjaxObject.rules = {
7585         loadRulesForSettings : function(o) {
7586                 document.getElementById("rulesListCell").innerHTML = o.responseText;
7587                 // assume we have the class we need
7588                 SUGAR.routing.getStrings();
7589                 SUGAR.routing.getDependentDropdowns();
7590         }
7591 };
7592 ////    END PER MODULE CALLBACK OBJECTS
7593 ///////////////////////////////////////////////////////////////////////////
7594
7595
7596 var callback = {
7597         success : AjaxObject.handleSuccess,
7598         failure : AjaxObject.handleFailure,
7599         timeout : AjaxObject.timeout,
7600         scope   : AjaxObject
7601 };
7602 var callbackAccount = {
7603         success : AjaxObject.ieSaveSuccess,
7604         failure : AjaxObject.handleFailure,
7605         timeout : AjaxObject.timeout,
7606         scope   : AjaxObject
7607 };
7608 var callbackAccountDelete = {
7609         success : AjaxObject.ieDeleteSuccess,
7610         failure : AjaxObject.handleFailure,
7611         timeout : AjaxObject.timeout,
7612         scope   : AjaxObject
7613 };
7614 var callbackOutboundTest = {
7615         success : AjaxObject.ieSendSuccess,
7616         failure : AjaxObject.handleFailure,
7617         timeout : AjaxObject.timeout,
7618         scope   : AjaxObject
7619 };
7620
7621
7622
7623 var callbackTeamInfoForSettings = {
7624 success : function (o) {
7625         var data = JSON.parse(o.responseText);
7626         document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7627 },
7628 failure : AjaxObject.handleFailure,
7629 timeout : AjaxObject.timeout,
7630 scope   : AjaxObject
7631
7632 };
7633
7634 var callbackStatusForImport = {
7635 success : function (o) {
7636         hideOverlay();
7637         if (o.responseText != "")  {
7638                 var statusString = "";
7639                 var data = JSON.parse(o.responseText);
7640                 for(i=0; i<data.length; i++) {
7641                         statusString = statusString + data[i] + '<br/>';
7642                 }
7643                 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7644         }
7645         SE.listView.refreshGrid();
7646
7647 },
7648 failure : AjaxObject.handleFailure,
7649 timeout : AjaxObject.timeout,
7650 scope   : AjaxObject
7651
7652 };
7653 var callbackComposeCache = {
7654         success : AjaxObject.composeCache,
7655         failure : AjaxObject.handleFailure,
7656         timeout : AjaxObject.timeout,
7657         scope   : AjaxObject
7658 };
7659 var callbackDelete = {
7660         success : AjaxObject.handleDeleteReturn,
7661         failure : AjaxObject.handleFailure,
7662         timeout : AjaxObject.timeout,
7663         scope   : AjaxObject
7664 };
7665 var callbackEmailDetailMultiple = {
7666         success : function(o) {
7667                 hideOverlay();
7668                 var retMulti = JSON.parse(o.responseText);
7669                 var ret = new Object();
7670
7671                 for(var i=0; i<retMulti.length; i++) {
7672                         ret = retMulti[i];
7673
7674                         SUGAR.email2._setDetailCache(ret);
7675                         SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7676                 }
7677         },
7678         failure : AjaxObject.handleFailure,
7679         timeout : 0,
7680         scope   : AjaxObject
7681 };
7682 var callbackListViewSortOrderChange = {
7683         success : AjaxObject.saveListViewSortOrderPart2,
7684         failure : AjaxObject.handleFailure,
7685         timeout : AjaxObject.timeout,
7686         scope   : AjaxObject,
7687         argument        : [ieId, ieName, focusFolder]
7688 };
7689 var callbackEmptyTrash = {
7690         success : function(o) {
7691                 hideOverlay();
7692                 AjaxObject.folderRenameCleanup;
7693         },
7694         failure : AjaxObject.handleFailure,
7695         timeout : AjaxObject.timeout,
7696         scope   : AjaxObject
7697 };
7698 var callbackClearCacheFiles = {
7699         success : function(o) {
7700                 hideOverlay();
7701         },
7702         failure : AjaxObject.handleFailure,
7703         timeout : AjaxObject.timeout,
7704         scope   : AjaxObject
7705 };
7706 var callbackFolderRename = {
7707         success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7708         failure : AjaxObject.handleFailure,
7709         timeout : AjaxObject.timeout,
7710         scope   : AjaxObject
7711 };
7712 var callbackFolderDelete = {
7713         success : function(o) {
7714                 var ret = JSON.parse(o.responseText);
7715                 if (ret.status) {
7716                     if (ret.folder_id) {
7717                         var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7718                         if(node)
7719                                 SUGAR.email2.tree.removeNode(node, true);
7720                     } else if (ret.ieId && ret.mbox) {
7721                         var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7722                         if(node)
7723                                 SUGAR.email2.tree.removeNode(node, true);
7724                     }
7725                         hideOverlay();
7726                         //SUGAR.email2.folders.loadSettingFolder();
7727                 } else {
7728                         hideOverlay();
7729                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7730                 } // else
7731         },
7732         failure : AjaxObject.handleFailure,
7733         timeout : AjaxObject.timeout,
7734         scope   : AjaxObject
7735 };
7736 var callbackFolderSave = {
7737         success : function(o) {
7738                 var ret = JSON.parse(o.responseText);
7739
7740                 switch(ret.action) {
7741                         case 'newFolderSave':
7742                                 SUGAR.email2.folders.rebuildFolders();
7743                         break;
7744                 }
7745         },
7746         failure : AjaxObject.handleFailure,
7747         timeout : AjaxObject.timeout,
7748         scope   : AjaxObject
7749 };
7750 var callbackFolderSubscriptions = {
7751         success : AjaxObject.updateFolderSubscriptions,
7752         failure : AjaxObject.handleFailure,
7753         timeout : AjaxObject.timeout,
7754         scope   : AjaxObject
7755 };
7756 var callbackFolderUpdate = {
7757         success : AjaxObject.updateFrameFolder,
7758         failure : AjaxObject.handleFailure,
7759         timeout : AjaxObject.timeout,
7760         scope   : AjaxObject
7761 };
7762 var callbackFolders = {
7763         success : AjaxObject.folders.rebuildFolders,
7764         //success : void(true),
7765         failure : AjaxObject.handleFailure,
7766         timeout : AjaxObject.timeout,
7767         scope   : AjaxObject
7768 };
7769 var callbackFullSync = {
7770         success : AjaxObject.fullSyncCleanup,
7771         failure : AjaxObject.handleFailure,
7772         timeout : 9999999999999,
7773         scope   : AjaxObject
7774 };
7775 var callbackGeneric = {
7776         success : function() {
7777                 hideOverlay();
7778         },
7779         failure : AjaxObject.handleFailure,
7780         timeout : AjaxObject.timeout,
7781         scope   : AjaxObject
7782 };
7783 var callbackIeAccountRetrieve = {
7784         success : function(o) {
7785                 // return JSON encoding
7786                 hideOverlay();
7787                 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7788                 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7789         },
7790         failure : AjaxObject.handleFailure,
7791         timeout : AjaxObject.timeout,
7792         scope   : AjaxObject
7793 };
7794 var callbackImportOneEmail = {
7795         success :  AjaxObject.detailView.showImportForm,
7796         failure : AjaxObject.handleFailure,
7797         timeout : AjaxObject.timeout,
7798         scope   : AjaxObject
7799 };
7800 var callbackRelateEmail = {
7801     success : AjaxObject.detailView.showRelateForm,
7802     failure : AjaxObject.handleFailure,
7803     timeout : AjaxObject.timeout,
7804     scope   : AjaxObject
7805 }
7806 var callbackEmailDetailView = {
7807     success : AjaxObject.detailView.showEmailDetailView,
7808     failure : AjaxObject.handleFailure,
7809     timeout : AjaxObject.timeout,
7810     scope   : AjaxObject
7811 }
7812 var callbackAssignmentDialog = {
7813         success :  AjaxObject.detailView.showAssignmentDialogWithData,
7814         failure : AjaxObject.handleFailure,
7815         timeout : AjaxObject.timeout,
7816         scope   : AjaxObject
7817 };
7818 var callbackAssignmentAction = {
7819         success :  function(o) {
7820                 SE.listView.refreshGrid();
7821                 hideOverlay();
7822                 if(o.responseText != '') {
7823                overlay('Assignment action result', o.responseText, 'alert');
7824             } // if
7825         } ,
7826         failure : AjaxObject.handleFailure,
7827         timeout : AjaxObject.timeout,
7828         scope   : AjaxObject
7829 };
7830 var callbackMoveEmails = {
7831         success :  function(o) {
7832             SE.listView.refreshGrid();
7833                 hideOverlay();
7834                 if(o.responseText != '') {
7835                overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7836             } // if
7837         } ,
7838         failure : AjaxObject.handleFailure,
7839         timeout : AjaxObject.timeout,
7840         scope   : AjaxObject
7841 };
7842 var callbackLoadAttachments = {
7843         success : AjaxObject.loadAttachments,
7844         failure : AjaxObject.handleFailure,
7845         timeout : AjaxObject.timeout,
7846         scope   : AjaxObject
7847 };
7848 var callbackLoadRules = {
7849         success : AjaxObject.rules.loadRulesForSettings,
7850         failure : AjaxObject.handleFailure,
7851         timeout : AjaxObject.timeout,
7852         scope   : AjaxObject
7853 };
7854 var callbackLoadSignature = {
7855         success : AjaxObject.loadSignature,
7856         failure : AjaxObject.handleFailure,
7857         timeout : AjaxObject.timeout,
7858         scope   : AjaxObject
7859 };
7860 var callbackDeleteSignature = {
7861         success : AjaxObject.handleDeleteSignature,
7862         failure : AjaxObject.handleFailure,
7863         timeout : AjaxObject.timeout,
7864         scope   : AjaxObject
7865 };
7866 /*var callbackMoveEmails = {
7867     success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7868     failure : AjaxObject.handleFailure,
7869     timeout : AjaxObject.timeout,
7870     scope   : AjaxObject
7871 }*/
7872 var callbackOutboundSave = {
7873         success : AjaxObject.accounts.saveOutboundCleanup,
7874         failure : AjaxObject.handleFailure,
7875         timeout : AjaxObject.timeout,
7876         scope   : AjaxObject
7877 };
7878 var callbackDefaultOutboundSave = {
7879         success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7880         failure : AjaxObject.handleFailure,
7881         timeout : AjaxObject.timeout,
7882         scope   : AjaxObject
7883 };
7884 var callbackQuickCreate = {
7885         success : AjaxObject.detailView.showQuickCreateForm,
7886         failure : AjaxObject.handleFailure,
7887         timeout : AjaxObject.timeout,
7888         scope   : AjaxObject
7889 };
7890 var callbackQuickCreateSave = {
7891         success : AjaxObject.detailView.saveQuickCreateForm,
7892         failure : AjaxObject.handleFailure,
7893         timeout : AjaxObject.timeout,
7894         scope   : AjaxObject
7895 };
7896 var callbackQuickCreateSaveAndAddToAddressBook = {
7897         success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7898         failure : AjaxObject.handleFailure,
7899         timeout : AjaxObject.timeout,
7900         scope   : AjaxObject
7901 };
7902 var callbackQuickCreateSaveAndReply = {
7903     success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7904     failure : AjaxObject.handleFailure,
7905     timeout : AjaxObject.timeout,
7906     scope   : AjaxObject
7907 }
7908 var callbackQuickCreateSaveAndReplyCase = {
7909     success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7910     failure : AjaxObject.handleFailure,
7911     timeout : AjaxObject.timeout,
7912     scope   : AjaxObject
7913 }
7914 var callbackRebuildShowAccountList = {
7915         success : AjaxObject.rebuildShowFolders,
7916         failure : AjaxObject.handleFailure,
7917         timeout : AjaxObject.timeout,
7918         scope   : AjaxObject
7919 };
7920
7921 var callbackRefreshSugarFolders = {
7922         success : function(o) {
7923                 var t = JSON.parse(o.responseText);
7924                 SUGAR.email2.folders.setSugarFoldersEnd(t);
7925         },
7926         failure : AjaxObject.handleFailure,
7927         timeout : AjaxObject.timeout,
7928         scope   : AjaxObject
7929 };
7930 var callbackReplyForward = {
7931         success : AjaxObject.handleReplyForward,
7932         finish : function(a, retryCount) {
7933                 if (typeof(retryCount) == 'undefined') {
7934                         retryCount = 0;
7935                 } else {
7936                         retryCount++;
7937                 }
7938                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7939                 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7940         try {
7941                         var html = t.getContent();
7942
7943             if (a.type != 'draft') {
7944                         if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7945                                 html += "&nbsp;<div><hr></div>" + a.description;
7946                         } else {
7947                                 html =  "&nbsp;<div><hr></div>" + a.description + html;
7948                         }
7949             }else {
7950                 html = a.description;
7951             }
7952
7953                         t.setContent(html);//
7954
7955                 } catch(e) {
7956                         if (retryCount < 5) {
7957                                 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7958                                 return;
7959                         }
7960                 }
7961                 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7962                 if (tabArray != null && tabArray.length > 0) {
7963                         for (i = 0 ; i < tabArray.length ; i++) {
7964                                 var tabObject = tabArray[i];
7965                                 if (tabObject.get("id") == ("composeTab" + idx)) {
7966                                         var tabLabel = a.name;
7967                                 if (tabLabel != null && tabLabel.length > 25) {
7968                                         tabLabel = tabLabel.substring(0, 25) + "...";
7969                                 } // if
7970                                         tabObject.get("labelEl").firstChild.data = tabLabel;
7971                                         break;
7972                                 }
7973                         }
7974                 }
7975
7976                 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
7977                 if (a.parent_name != null && a.parent_name != "") {
7978                         document.getElementById('data_parent_name' + idx).value = a.parent_name;
7979                 }
7980                 if (a.parent_type != null && a.parent_type != "") {
7981                         document.getElementById('data_parent_type' + idx).value = a.parent_type;
7982                 }
7983                 if (a.parent_id != null && a.parent_id != "") {
7984                         document.getElementById('data_parent_id' + idx).value = a.parent_id;
7985                 }
7986                 if (a.fromAccounts.status) {
7987                         var addressFrom = document.getElementById('addressFrom' + idx);
7988                 SUGAR.email2.util.emptySelectOptions(addressFrom);
7989                 var fromAccountOpts = a.fromAccounts.data;
7990                 for(i=0; i<fromAccountOpts.length; i++) {
7991                       var key = fromAccountOpts[i].value;
7992                       var display = fromAccountOpts[i].text;
7993                       var opt = new Option(display, key);
7994                       if (fromAccountOpts[i].selected) {
7995                         opt.selected = true;
7996                       }
7997                       addressFrom.options.add(opt);
7998                 }
7999                 } // if
8000                 hideOverlay();
8001
8002         },
8003         failure : AjaxObject.handleFailure,
8004         timeout : AjaxObject.timeout,
8005         scope   : AjaxObject,
8006         argument        : [sendType]
8007 };
8008 var callbackSendEmail = {
8009         success : AjaxObject.sendEmailCleanUp,
8010         failure : AjaxObject.handleFailure,
8011         timeout : AjaxObject.timeout,
8012         scope   : AjaxObject
8013 };
8014 var callbackSettings = {
8015         success : AjaxObject.updateUserPrefs,
8016         failure : AjaxObject.handleFailure,
8017         timeout : AjaxObject.timeout,
8018         scope   : AjaxObject
8019 };
8020 var callbackSettingsFolderRefresh = {
8021         success : AjaxObject.settingsFolderRefresh,
8022         failure : AjaxObject.handleFailure,
8023         timeout : AjaxObject.timeout,
8024         scope   : AjaxObject
8025 };
8026 var callbackLoadSettingFolder = {
8027         success : function(o) {
8028                 AjaxObject.settingsFolderRefresh(o);
8029                 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8030         },
8031         failure : AjaxObject.handleFailure,
8032         timeout : AjaxObject.timeout,
8033         scope   : AjaxObject
8034
8035 };
8036 var callbackUploadAttachment = {
8037         success : AjaxObject.uploadAttachmentSuccessful,
8038         upload  : AjaxObject.uploadAttachmentSuccessful,
8039         failure : AjaxObject.handleFailure,
8040         timeout : AjaxObject.timeout,
8041         scope   : AjaxObject
8042 };
8043 var callbackUserPrefs = {
8044         success : function(o) {
8045                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8046         },
8047         failure : AjaxObject.handleFailure,
8048         timeout : AjaxObject.timeout,
8049         scope   : AjaxObject
8050 };
8051
8052 var callbackContextmenus = {
8053         markUnread : {
8054                 success : AjaxObject.markEmailCleanup,
8055                 failure : AjaxObject.handleFailure,
8056                 timeout : AjaxObject.timeout,
8057                 scope   : AjaxObject
8058         }
8059 };
8060
8061 var callbackCheckEmail2 = {
8062         success : function(o) {
8063                 var ret = JSON.parse(o.responseText);
8064                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8065
8066
8067         },
8068         failure : AjaxObject.handleFailure,
8069         timeout : AjaxObject.timeout,
8070         scope   : AjaxObject
8071 }// End of File modules/Emails/javascript/ajax.js
8072                                 
8073 /*********************************************************************************
8074  * SugarCRM is a customer relationship management program developed by
8075  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8076  * 
8077  * This program is free software; you can redistribute it and/or modify it under
8078  * the terms of the GNU Affero General Public License version 3 as published by the
8079  * Free Software Foundation with the addition of the following permission added
8080  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8081  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8082  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8083  * 
8084  * This program is distributed in the hope that it will be useful, but WITHOUT
8085  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8086  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8087  * details.
8088  * 
8089  * You should have received a copy of the GNU Affero General Public License along with
8090  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8091  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8092  * 02110-1301 USA.
8093  * 
8094  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8095  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8096  * 
8097  * The interactive user interfaces in modified source and object code versions
8098  * of this program must display Appropriate Legal Notices, as required under
8099  * Section 5 of the GNU Affero General Public License version 3.
8100  * 
8101  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8102  * these Appropriate Legal Notices must retain the display of the "Powered by
8103  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8104  * technical reasons, the Appropriate Legal Notices must display the words
8105  * "Powered by SugarCRM".
8106  ********************************************************************************/
8107
8108 function gridInit() {
8109         if(SUGAR.email2.grid) {
8110                 SUGAR.email2.grid.destroy();
8111         }
8112         
8113         e2Grid = {
8114                 init : function() {
8115                 
8116                         var Ck = YAHOO.util.Cookie;
8117                         var widths = [ 10, 10, 150, 250, 175, 125 ];
8118
8119                         if (Ck.get("EmailGridWidths")) {
8120                                 for (var i=0; i < widths.length; i++) {
8121                                         widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8122                                 }
8123                         } else {
8124                                 for (var i=0; i < widths.length; i++) {
8125                                         Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8126                                 }
8127                         }
8128                         
8129                         // changes "F" to an icon
8130                         function flaggedIcon(cell, record, column, value) {
8131                                 if(value != "") {
8132                                         cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8133                                 }
8134                         }
8135                         // changes "A" to replied icon
8136                         function repliedIcon(cell, record, column, value) {
8137                                 if(value != "") {
8138                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8139                                 }
8140                         }
8141                 function attachIcon(cell, record, column, value) {
8142                                 if(value == "1") {
8143                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8144                                 }
8145                         }
8146
8147                         var colModel = 
8148                                 [
8149                                         {
8150                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>", 
8151                                                 width: 10, 
8152                                                 sortable: false, 
8153                                                 fixed: true,
8154                                                 resizeable: true,
8155                                                 formatter: attachIcon,
8156                                                 key: 'hasAttach'
8157                                         }, 
8158                                     {
8159                                                 label: "<span style='color: #f00; font-weight:bold;'>!</span>", 
8160                                                 width: widths[0], 
8161                                                 sortable: true, 
8162                                                 fixed: true,
8163                                                 resizeable: true,
8164                                                 formatter: flaggedIcon,
8165                                                 key: 'flagged'
8166                                         }, 
8167                                         {
8168                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>", 
8169                                                 width: widths[1], 
8170                                                 sortable: true, 
8171                                                 fixed: true,
8172                                                 resizeable: true,
8173                                                 formatter: repliedIcon,
8174                                                 key: 'status'
8175                                         },
8176                                         {
8177                                                 label: app_strings.LBL_EMAIL_FROM, 
8178                                                 width: widths[2],
8179                                                 sortable: true,
8180                                                 resizeable: true,
8181                                                 key: 'from'
8182                                         }, 
8183                                         {
8184                                                 label: app_strings.LBL_EMAIL_SUBJECT,
8185                                                 width: widths[3], 
8186                                                 sortable: true,
8187                                                 resizeable: true,
8188                                                 key: 'subject'
8189                                         }, 
8190                                         {
8191                                                 label: mod_strings.LBL_LIST_DATE,
8192                                                 width: widths[4], 
8193                                                 sortable: true,
8194                                                 resizeable: true,
8195                         key: 'date'
8196                                         }, 
8197                                         {
8198                                                 label: app_strings.LBL_EMAIL_TO,
8199                                                 width: widths[5], 
8200                                                 sortable: false,
8201                                                 resizeable: true,
8202                         key: 'to_addrs'
8203                                         }, 
8204                                         {
8205                                                 label: 'uid',
8206                                                 hidden: true,
8207                         key: 'uid'
8208                                         }, 
8209                                         {
8210                                                 label: 'mbox',
8211                                                 hidden: true,
8212                         key: 'mbox'
8213                                         }, 
8214                                         {
8215                                                 label: 'ieId',
8216                                                 hidden: true,
8217                         key: 'ieId'
8218                                         }, 
8219                                         {       
8220                                                 label: 'site_url',
8221                                                 hidden: true,
8222                         key: 'site_url'
8223                                         },
8224                                         {       label: 'seen',
8225                                                 hidden: true,
8226                         key: 'seen'
8227                                         },
8228                                         {       label: 'type',
8229                                                 hidden: true,
8230                         key: 'type'
8231                                         }
8232                                 ];
8233                         
8234                         var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8235                                 responseType: YAHOO.util.DataSource.TYPE_JSON,
8236                                 responseSchema: {
8237                                     resultsList: 'Email',
8238                             fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8239                             metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8240                                 }
8241                     });
8242                         var params = {
8243                                         to_pdf : "true",
8244                                         module : "Emails",
8245                                         action : "EmailUIAjax",
8246                                         emailUIAction : "getMessageList",
8247                                         mbox : "INBOX",
8248                                         ieId : "",
8249                                         forceRefresh : "false"
8250                         };
8251                         if(lazyLoadFolder != null) {
8252                                 params['mbox'] = lazyLoadFolder.folder;
8253                                 params['ieId'] = lazyLoadFolder.ieId;
8254                                 //Check if the folder is a Sugar Folder
8255                                 var test = new String(lazyLoadFolder.folder);
8256                                 if(test.match(/SUGAR\./)) {
8257                                         params['emailUIAction'] = 'getMessageListSugarFolders';
8258                                         params['mbox'] = test.substr(6);
8259                                 }
8260                         }
8261                         //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8262         
8263                         // create the Grid
8264                         var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8265                                 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8266                                 dynamicData: true,
8267                                 paginator: new YAHOO.widget.Paginator({ 
8268                                         rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),  
8269                                         containers : ["dt-pag-nav"],
8270                                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8271                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8272                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8273                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8274                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8275                                 }),
8276                                 initialRequest:SUGAR.util.paramsToUrl(params),
8277                                 width:  "800px",
8278                                 height: "400px"
8279                         });
8280
8281                         initRowDD();
8282
8283                         //Override Paging request construction
8284                         grid.set("generateRequest", function(oState, oSelf) {
8285                     oState = oState || {pagination:null, sortedBy:null};
8286                     var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8287                     var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8288                     var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8289                     var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8290                     // Build the request 
8291                     var ret = 
8292                             SUGAR.util.paramsToUrl(oSelf.params) + 
8293                             "&sort=" + sort +
8294                         "&dir=" + dir +
8295                         "&start=" + startIndex +
8296                         ((results !== null) ? "&limit=" + results : "");
8297                     return  ret;
8298                 });
8299                         
8300                         
8301                         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8302                                 oPayload = oPayload || { };
8303                                 
8304                                 oPayload.totalRecords = oResponse.meta.total;
8305                                 oPayload.unreadRecords = oResponse.meta.unread;
8306                                 
8307                         var tabObject = SE.innerLayout.get("tabs")[0];
8308                         var mboxTitle = "";
8309                         if (this.params.mbox != null) {
8310                                 mboxTitle = this.params.mbox;
8311                         }
8312                         var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8313                         tabObject.get("labelEl").firstChild.data = tabtext;
8314                         
8315                         if (SE.tree) {
8316                                 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8317                                 if (node) {
8318                                         node.data.unseen = oResponse.meta.unread;
8319                                         SE.accounts.renderTree();
8320                                 }
8321                         }
8322                                 return oPayload; 
8323                         }
8324                         
8325                         var resize = grid.resizeGrid = function () {
8326                                 SUGAR.email2.grid.set("width",  SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8327                                 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8328                         }
8329                         grid.convertDDRows = function() {
8330                                 var rowEl = this.getFirstTrEl();
8331                                 while (rowEl != null) {
8332                                         new this.DDRow(this, this.getRecord(rowEl), rowEl);
8333                                         rowEl = this.getNextTrEl(rowEl);
8334                                 }
8335                         }
8336                         
8337                         
8338                         grid.on("columnResizeEvent", function(o) {
8339                                 //Find the index of the column
8340                                 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8341                                 for (var i=0; i < colSet.length; i++) {
8342                                         if (o.column == colSet[i]) {
8343                                                 //Store it in the cookie
8344                                                 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8345                                         }
8346                                 }
8347                                 //this.resizeGrid();
8348                         }, null, grid); 
8349                         
8350                         grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8351                         grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);  
8352                         grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);  
8353                         grid.render();
8354                         SUGAR.email2.listViewLayout.on("render", resize);
8355                         resize();
8356                         
8357                         //Setup the default load parameters
8358                         SUGAR.email2.grid.params = params;
8359                         
8360                         grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8361                         dataModel.subscribe("requestEvent", grid.disable, grid, true);
8362                         dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8363                 }
8364         };
8365         e2Grid.init();
8366 };
8367
8368
8369 function initRowDD() {
8370         var sg = SUGAR.email2.grid,
8371         Dom = YAHOO.util.Dom;
8372         sg.DDRow = function(oDataTable, oRecord, elTr) {
8373                 if(oDataTable && oRecord && elTr) {
8374                         this.ddtable = oDataTable;
8375                 this.table = oDataTable.getTableEl();
8376                 this.row = oRecord;
8377                 this.rowEl = elTr;
8378                 this.newIndex = null;
8379                 this.init(elTr);
8380                 this.initFrame(); // Needed for DDProxy
8381                 this.invalidHandleTypes = {};
8382             }   
8383         };
8384         
8385         YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8386             _resizeProxy: function() {
8387                 this.constructor.superclass._resizeProxy.apply(this, arguments);
8388                 var dragEl = this.getDragEl(),
8389                     el = this.getEl();
8390                 var xy = Dom.getXY(el);
8391                 
8392                 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8393                 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8394                 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8395                 Dom.setStyle(dragEl, 'display', "");
8396             },
8397             
8398             startDrag: function(x, y) { 
8399                 //Check if we should be dragging a set of rows rather than just the one.
8400                 var selectedRows = this.ddtable.getSelectedRows();
8401                 var iSelected = false;
8402                 for (var i in selectedRows) {
8403                         if (this.rowEl.id == selectedRows[i]) {
8404                                 iSelected = true;
8405                                 break
8406                         }
8407                 }
8408                 if (iSelected) {
8409                         this.rows = [];
8410                         for (var i in selectedRows) {
8411                                 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8412                         }
8413                 } else {
8414                         this.rows = [this.row];
8415                         this.ddtable.unselectAllRows();
8416                         this.ddtable.selectRow(this.row);
8417                 }
8418                 
8419                 //Initialize the dragable proxy
8420                 var dragEl = this.getDragEl(); 
8421                 var clickEl = this.getEl(); 
8422                 Dom.setStyle(clickEl, "opacity", "0.25"); 
8423                 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>"; 
8424                 Dom.addClass(dragEl, "yui-dt-liner");
8425                 Dom.setStyle(dragEl, "opacity", "0.5"); 
8426                 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8427                 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); 
8428                     Dom.setStyle(dragEl, "border", "2px solid gray"); 
8429             },
8430             
8431             clickValidator: function(e) {
8432                 if (this.row.getData()[0] == " ")
8433                         return false;
8434                 var target = YAHOO.util.Event.getTarget(e);
8435                 return ( this.isValidHandleChild(target) && 
8436                                 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8437             },
8438             /**
8439              * This funciton checks that the target of the drag is a table row in this
8440              * DDGroup and simply moves the sourceEL to that location as a preview.
8441              */
8442             onDragOver: function(ev, id) {
8443                 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8444                 if (node && node != this.targetNode) {
8445                         this.targetNode = node;
8446                         SUGAR.email2.folders.unhighliteAll();
8447                         node.highlight();
8448                 }
8449             },
8450             
8451             onDragOut: function(e, id) {
8452                 if (this.targetNode) {
8453                         SUGAR.email2.folders.unhighliteAll();
8454                         this.targetNode = false;
8455                 }
8456             },
8457             endDrag: function() {
8458                 Dom.setStyle(this.getEl(), "opacity", "");
8459                 Dom.setStyle(this.getDragEl(), "display", "none"); 
8460                 if (this.targetNode) {
8461                         SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8462                 }
8463                 SUGAR.email2.folders.unhighliteAll();
8464                 this.rows = null;
8465             }
8466         });
8467 }
8468
8469 function AddressSearchGridInit() {
8470     function moduleIcon(elCell, oRecord, oColumn, oData) {
8471         elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8472     };
8473     function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8474         elCell.innerHTML =  '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8475     };
8476     var checkHeader = '<input type="checkbox" ';
8477     if (SUGAR.email2.util.isIe()) {
8478         checkHeader += 'style="top:-5px" ';
8479     }
8480     checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8481     var colModel = 
8482             [{
8483                 label: checkHeader,
8484             width: 30,
8485             formatter: selectionCheckBox,
8486             key: 'bean_id'
8487         },
8488             {
8489                 label: mod_strings.LBL_LIST_TYPE,
8490                 width: 25,
8491                 formatter: moduleIcon,
8492                 key: 'bean_module'
8493         },
8494             {
8495                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME, 
8496                 width: 180,
8497                 sortable: true,
8498                 key: 'name'
8499             }, 
8500             {
8501                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8502                 width: 300, 
8503                 sortable: true,
8504                 key: 'email'
8505             }];
8506     
8507     var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8508                 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8509         responseSchema: {
8510             resultsList: 'Person',
8511             fields: ['name', 'email', 'bean_id', 'bean_module'],
8512                     metaFields: {total: 'TotalCount'}
8513         },
8514         //enable sorting on the server accross all data
8515         remoteSort: true
8516     });
8517     dataModel.params = {
8518                 to_pdf          : true,
8519                 module          : "Emails",
8520                 action          : "EmailUIAjax",
8521                 emailUIAction:"getAddressSearchResults"
8522     }
8523     var rb = document.getElementById('hasRelatedBean').checked;
8524         if (rb) {
8525                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8526                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8527                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8528                 dataModel.params['related_bean_id'] = relatedBeanId;
8529                 dataModel.params['related_bean_type'] = relatedBeanType;
8530                 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8531         }
8532     SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8533     
8534     var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8535         MSG_EMPTY: "&nbsp;", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8536                 dynamicData: true,
8537                 paginator: new YAHOO.widget.Paginator({ 
8538                         rowsPerPage: 25,  
8539                         containers : ["dt-pag-nav-addressbook"],
8540                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8541                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8542                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8543                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8544                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8545                 }),
8546                 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8547                 width:  "560px",
8548                 height: "250px"
8549     });
8550         //Override Paging request construction
8551         grid.set("generateRequest", function(oState, oSelf) {
8552         oState = oState || {pagination:null, sortedBy:null};
8553         var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8554         var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8555         var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8556         var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8557         // Build the request 
8558         var ret = 
8559             SUGAR.util.paramsToUrl(oSelf.getDataSource().params) + 
8560             "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8561             ((results !== null) ? "&limit=" + results : "");
8562         return  ret;
8563     });
8564     
8565         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8566                 oPayload = oPayload || { };
8567                 oPayload.totalRecords = oResponse.meta.total;
8568                 return oPayload; 
8569         }
8570         
8571         grid.clickToggleSelect= function(args) {
8572                 var isIE = (args.event.target == null);
8573                 var targetElement = isIE ? args.event.srcElement : args.event.target;
8574                 if(targetElement.type == null || targetElement.type != 'checkbox') {
8575                         SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8576                 }
8577         }
8578         
8579         grid.reSelectRowsOnRender = function (){
8580             var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8581         for (var i = 0; i < rows.length; i++) 
8582         {
8583                 var emailAddress = rows[i].getData("email");
8584             var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8585             if(alreadyAdded)
8586             {
8587                 rows[i].setData("selected",  true);
8588                         SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8589             }
8590             else
8591             {
8592                 rows[i].setData("selected",  false);
8593                 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8594             }
8595         }
8596         }
8597         grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow); 
8598         grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow); 
8599         grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8600     grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8601     
8602     grid.render();
8603     dataModel.subscribe("requestEvent", grid.disable, grid, true);
8604     dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8605     
8606     grid.toggleSelectCheckbox = function(id,checked){
8607         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8608         row.setData("checked",checked);
8609     };
8610     grid.toggleSelect = function(id, checked) {
8611         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8612         checked = row.getData("selected");
8613         if (!checked)
8614         {
8615             SUGAR.email2.addressBook.grid.selectRow(row);
8616             SE.addressBook.insertContactRowToResultTable(id,null)
8617         } else 
8618         {
8619             SUGAR.email2.addressBook.grid.unselectRow(row);
8620             SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8621         }
8622         row.setData("selected", !checked);
8623     };
8624     
8625     grid.toggleSelectAll = function(checked) {
8626         rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8627         for (var i = 0; i < rows.length; i++) {
8628                         if (typeof(rows[i]) != "undefined")
8629                                 rows[i].setData("checked",  checked);
8630         }
8631         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8632         for (var i = 0; i < checkBoxes.length; i++) {
8633             checkBoxes[i].checked = checked;
8634         }
8635     };
8636     
8637     //Initialize the grid result table.
8638     AddressSearchResultsGridInit();
8639 }
8640
8641
8642
8643 /**
8644 *  Initalize the results table for the address book selection.
8645 *
8646 */
8647 function AddressSearchResultsGridInit()
8648 {
8649     
8650     /* Full name sort funciton to compare by last name if available */
8651     var fullNameSort = function(a, b, desc) {
8652         // Deal with empty values
8653         if(!YAHOO.lang.isValue(a))
8654             return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8655         else if(!YAHOO.lang.isValue(b))
8656             return -1;
8657
8658         var aNames = a.getData("name").split(' ');
8659         var bNames = b.getData("name").split(' ');
8660
8661         var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8662         var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8663
8664         return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8665
8666     };
8667     
8668     var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8669                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8670                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')]; 
8671               
8672     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})},
8673                      {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8674      
8675      var myDataSource = new YAHOO.util.DataSource([]); 
8676          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
8677          myDataSource.responseSchema = { 
8678                     fields: ["name","type","email_address","display_email_address","bean_id","idx"] 
8679                 };                                                                 
8680     
8681          var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8682                         width:  "350px",height: "250px", MSG_EMPTY: "&nbsp;"});
8683     
8684      var highlightEditableCell = function(oArgs) {
8685             var elCell = oArgs.target;
8686             if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8687                 this.highlightCell(elCell);
8688             }
8689         };
8690       
8691      gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8692      gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8693      gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8694      gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow); 
8695          gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow); 
8696      
8697      //Setup the context menus
8698      var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) { 
8699              var task = p_aArgs[1]; 
8700              if(task) 
8701              { 
8702                  var elRow = this.contextEventTarget; 
8703                  elRow = p_myDataTable.getTrEl(elRow); 
8704          
8705                  if(elRow) 
8706                  { 
8707                      switch(task.index) 
8708                      { 
8709                          case 0:     
8710                              var oRecord = p_myDataTable.getRecord(elRow); 
8711                              p_myDataTable.deleteRow(elRow);  
8712                              SUGAR.email2.addressBook.grid.reSelectRowsOnRender();    
8713                      } 
8714                  } 
8715              } 
8716          };
8717      var contextMenu = new YAHOO.widget.ContextMenu("contextmenu", 
8718                         {trigger:gridResults.getTbodyEl()}); 
8719          contextMenu.addItem(app_strings.LBL_EMAIL_DELETE); 
8720          contextMenu.render("addrSearchResultGrid"); 
8721          contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults); 
8722 }
8723 // End of File modules/Emails/javascript/grid.js
8724                                 
8725 /*********************************************************************************
8726  * SugarCRM is a customer relationship management program developed by
8727  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8728  * 
8729  * This program is free software; you can redistribute it and/or modify it under
8730  * the terms of the GNU Affero General Public License version 3 as published by the
8731  * Free Software Foundation with the addition of the following permission added
8732  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8733  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8734  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8735  * 
8736  * This program is distributed in the hope that it will be useful, but WITHOUT
8737  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8738  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8739  * details.
8740  * 
8741  * You should have received a copy of the GNU Affero General Public License along with
8742  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8743  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8744  * 02110-1301 USA.
8745  * 
8746  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8747  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8748  * 
8749  * The interactive user interfaces in modified source and object code versions
8750  * of this program must display Appropriate Legal Notices, as required under
8751  * Section 5 of the GNU Affero General Public License version 3.
8752  * 
8753  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8754  * these Appropriate Legal Notices must retain the display of the "Powered by
8755  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8756  * technical reasons, the Appropriate Legal Notices must display the words
8757  * "Powered by SugarCRM".
8758  ********************************************************************************/
8759
8760 /**
8761   Complex layout init
8762  */
8763 function complexLayoutInit() {
8764         var se = SUGAR.email2;
8765         var Dom = YAHOO.util.Dom;
8766         se.e2Layout = {
8767         getInnerLayout : function(rows) {
8768                 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8769                 parent: se.complexLayout,  
8770                         border:true,
8771                     hideOnLayout: true,
8772                     height: 400,
8773                                 units: [{
8774                                         position: "center",
8775                                     scroll:false, // grid should autoScroll itself
8776                                     split:true,
8777                                     body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8778                                 },{
8779                                         position: "bottom",
8780                                     scroll:true,
8781                                     collapse: false,
8782                                     resize: true,
8783                                     useShim:true,
8784                                     height:'250',
8785                                     body: "<div id='listBottom' />"
8786                                 },{
8787                                     position: "right",
8788                                     scroll:true,
8789                                     collapse: false,
8790                                     resize: true,
8791                                     useShim:true,
8792                                     width:'250',
8793                                     body: "<div id='listRight' />",
8794                                     titlebar: false //,header: "right"
8795                                 }]
8796             });
8797                 se.complexLayout.on("render", function(){
8798                         var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8799                                 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8800                                 SUGAR.email2.listViewLayout.set("height", height);
8801                                 SUGAR.email2.listViewLayout.render();
8802                 });
8803             se.listViewLayout.render();
8804             //CSS hack for now
8805             se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8806             var rp = se.listViewLayout.resizePreview = function() {
8807                 var pre = Dom.get("displayEmailFramePreview");
8808                 if (pre) {
8809                         var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8810                         pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8811                 }
8812             };
8813             se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8814             se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8815             se.e2Layout.setPreviewPanel(rows);
8816             se.previewLayout = se.listViewLayout;
8817             return se.listViewLayout;
8818         },
8819         
8820         getInnerLayout2Rows : function() {
8821             return this.getInnerLayout(true);
8822         },
8823         getInnerLayout2Columns : function() {
8824             return this.getInnerLayout(false);
8825         },
8826         
8827         init : function(){
8828             // initialize state manager, we will use cookies
8829 //                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8830                 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8831                 se.complexLayout = new YAHOO.widget.Layout("container", {
8832                         border:true,
8833                 hideOnLayout: true,
8834                 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8835                 width: Dom.getViewportWidth() - 40,
8836                 units: [{
8837                         position: "center",
8838                     scroll:false,
8839                     body: "<div id='emailtabs'></div>"
8840                 },
8841                 {
8842                         position: "left",
8843                         scroll: true,
8844                         body: "<div id='lefttabs'></div>",
8845                     collapse: true,
8846                     width: 210,
8847                     minWidth: 100,
8848                     resize:true,
8849                     useShim:true,
8850                     titlebar: true,
8851                     header: "&nbsp;"
8852                 },
8853                 {
8854                     header: Dom.get('footerLinks').innerHTML,
8855                                         position: 'bottom',
8856                                         id: 'mbfooter',
8857                                         height: 22,
8858                                         border: false
8859                 }]
8860             });
8861                 se.complexLayout.render();
8862                 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8863                         tp.addTab(new YAHOO.widget.Tab({ 
8864                                 label: "Inbox",
8865                                 scroll : true,
8866                                 content : "<div id='listViewDiv'/>",
8867                                 id : "center",
8868                                 active : true
8869                         }));
8870                 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8871                         tp.appendTo(centerEl);
8872                         //CSS hack for now
8873                         tp.get("element").style.borderRight = "1px solid #666"
8874                         
8875                         var listV =  this.getInnerLayout2Rows();
8876                         listV.set("height", tp.get("element").clientHeight - 25);
8877                         listV.render();
8878                 
8879             se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8880             var folderTab = new YAHOO.widget.Tab({ 
8881                                 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8882                                 scroll : true,
8883                                 content : "<div id='emailtree'/>",
8884                                 id : "tree",
8885                                 active : true
8886                         });
8887             folderTab.on("activeChange", function(o){ 
8888                 if (o.newValue) {
8889                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8890                 }
8891             });
8892             se.leftTabs.addTab(folderTab);
8893             
8894             var tabContent = SUGAR.util.getAndRemove("searchTab");
8895             var searchTab = new YAHOO.widget.Tab({ 
8896                                 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8897                                 scroll : true,
8898                                 content : tabContent.innerHTML,
8899                                 id : tabContent.id
8900                         });
8901             searchTab.on("activeChange", function(o){ 
8902                 if (o.newValue) 
8903                 {
8904                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8905                    //Setup the calendars if needed
8906                        Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_from", singleClick : true, step : 1, weekNumbers:false});
8907                        Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_to", singleClick : true, step : 1, weekNumbers:false});
8908                    
8909                        //Initalize sqs object for assigned user name 
8910                        se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');  
8911                        
8912                        //Attach event handler for when the relate module option is selected for the correct sqs object
8913                        var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8914                                                 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8915                        YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){ 
8916                            SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8917                        
8918                        //If enter key is pressed, perform search
8919                        var  addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8920                        for(var i=0; i < addKeyPressFields.length;i++)
8921                        {
8922                        YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8923                                 if (e.keyCode == 13) {
8924                                         YAHOO.util.Event.stopEvent(e);
8925                                         SUGAR.email2.search.searchAdvanced();
8926                                 }
8927                        });
8928                        }
8929                                    //Initiate quick search for the search tab.  Do this only when the tab is selected rather than onDomLoad for perf. gains.
8930                        enableQS(true);
8931                        //Clear parent values if selecting another parent type.
8932                        YAHOO.util.Event.addListener('data_parent_type_search','change', 
8933                            function(){ 
8934                                document.getElementById('data_parent_id_search').value =''; 
8935                                document.getElementById('data_parent_name_search').value =''; 
8936                            });
8937                 
8938                 }
8939             });
8940             se.leftTabs.addTab(searchTab);
8941             
8942             var resizeTabBody = function() {
8943                 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8944                                 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8945             }
8946             resizeTabBody();
8947             se.complexLayout.on("render", resizeTabBody);
8948             se.leftTabs.on("activeTabChange", resizeTabBody);
8949                         //hack to allow left pane scroll bar to fully show
8950                 var lefttabsDiv = document.getElementById('lefttabs');
8951                         var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8952                         var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8953                         lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8954           
8955         },
8956         initSQSObject: function(formName,fieldName)
8957         {
8958             var fullFieldName = formName + '_' + fieldName; //SQS Convention
8959             var resultName = fullFieldName + '_' + 'results';
8960             
8961             if (QSFieldsArray[fullFieldName] != null) 
8962             {
8963                 QSFieldsArray[fullFieldName].destroy();
8964                 delete QSFieldsArray[fullFieldName];
8965             }
8966             if (QSProcessedFieldsArray[fullFieldName])
8967             QSProcessedFieldsArray[fullFieldName] = false;
8968
8969             if( Dom.get(resultName) )
8970             {
8971                 var obj = document.getElementById(resultName);
8972                 obj.parentNode.removeChild(obj);
8973             }
8974         },
8975         setPreviewPanel: function(rows) {
8976                 if (rows) {
8977                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
8978                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
8979                 Dom.get("listRight").innerHTML = "";
8980                 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
8981             } else {
8982                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
8983                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
8984                 Dom.get("listBottom").innerHTML = "";
8985                 Dom.get("listRight").innerHTML = "<div id='_blank' />";
8986             }
8987         }
8988     };
8989         se.e2Layout.init();
8990 }
8991
8992 var myBufferedListenerObject = new Object();
8993 myBufferedListenerObject.refit = function() {
8994     if(SUGAR.email2.grid) {
8995         SUGAR.email2.grid.autoSize();
8996     }
8997 }
8998 // End of File modules/Emails/javascript/complexLayout.js
8999                                 
9000 /*********************************************************************************
9001  * SugarCRM is a customer relationship management program developed by
9002  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9003  * 
9004  * This program is free software; you can redistribute it and/or modify it under
9005  * the terms of the GNU Affero General Public License version 3 as published by the
9006  * Free Software Foundation with the addition of the following permission added
9007  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9008  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9009  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9010  * 
9011  * This program is distributed in the hope that it will be useful, but WITHOUT
9012  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9013  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9014  * details.
9015  * 
9016  * You should have received a copy of the GNU Affero General Public License along with
9017  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9018  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9019  * 02110-1301 USA.
9020  * 
9021  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9022  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9023  * 
9024  * The interactive user interfaces in modified source and object code versions
9025  * of this program must display Appropriate Legal Notices, as required under
9026  * Section 5 of the GNU Affero General Public License version 3.
9027  * 
9028  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9029  * these Appropriate Legal Notices must retain the display of the "Powered by
9030  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9031  * technical reasons, the Appropriate Legal Notices must display the words
9032  * "Powered by SugarCRM".
9033  ********************************************************************************/
9034
9035
9036 /******************************************************************************
9037  * Initialize Email 2.0 Application
9038  */
9039
9040 //Override Sugar Languge so quick creates work properly
9041
9042
9043 function email2init() {
9044
9045         //Init Tiny MCE
9046     // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9047     //             "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9048     if (!SUGAR.util.isTouchScreen()) {
9049          tinyMCE.init({
9050                  convert_urls : false,
9051          theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9052          width: tinyConfig.width,
9053          theme: tinyConfig.theme,
9054          theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9055          theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9056          theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9057          theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9058          plugins : tinyConfig.plugins,
9059          elements : tinyConfig.elements,
9060          language : tinyConfig.language,
9061          extended_valid_elements : tinyConfig.extended_valid_elements,
9062          mode: tinyConfig.mode,
9063          strict_loading_mode : true,
9064                  force_br_newlines : true,
9065          forced_root_block : ''
9066      });
9067     }
9068          //alert('loadedTiny');
9069
9070     // initialze message overlay
9071     SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9072             //iframe        : true,
9073             modal       : false,
9074             autoTabs    : true,
9075             width       : 300,
9076             height      : 120,
9077             shadow      : true
9078         }
9079     );
9080         // Hide Sugar menu
9081         if (SUGAR.themes.tempHideLeftCol)
9082         SUGAR.themes.tempHideLeftCol();
9083
9084         // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9085 //      YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9086
9087         // set defaults for YAHOO.util.DragDropManager
9088         YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9089
9090         SUGAR.email2.nextYear = new Date();
9091         SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9092
9093         
9094     // initialize and display UI framework (complexLayout.js)
9095     complexLayoutInit();
9096     
9097     // initialize and display grid (grid.js)
9098     gridInit();
9099     
9100     // initialize treeview for folders
9101         //onloadTreeinit();
9102         SUGAR.email2.folders.rebuildFolders(true);
9103         
9104         
9105     //Setup the Message Box overlay
9106     /*Ext.MessageBox.maxWidth = 350;
9107     Ext.MessageBox.minProgressWidth = 350;
9108
9109         ///////////////////////////////////////////////////////////////////////////
9110         ////    CONTEXT MENUS
9111         // detailView array
9112         SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9113 */
9114         var SEC = SUGAR.email2.contextMenus; 
9115         
9116         //Grid menu
9117         var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9118                 trigger: SUGAR.email2.grid.get("element"),
9119                 lazyload: true
9120         });
9121         emailMenu.subscribe("beforeShow", function() {
9122                 var oTarget = this.contextEventTarget;
9123                 if (typeof(oTarget) == "undefined")
9124                   return;
9125                 var grid = SUGAR.email2.grid;
9126                 var selectedRows = grid.getSelectedRows();
9127                 var multipleSelected = (selectedRows.length > 1) ? true: false;
9128                 if (!multipleSelected)
9129                 {
9130                         grid.unselectAllRows();
9131                         grid.selectRow(oTarget);
9132                         SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));    
9133                 }
9134                 else if(multipleSelected)
9135                 {
9136                     SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9137                 }
9138         });
9139         
9140         //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9141         //us to access individual elements easier by name rather than by index
9142         emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2,  'reply' : 3,'replyAll' : 4,'forward' : 5,
9143                                    'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9144         emailMenu.addItems([
9145         {
9146             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9147             id: 'showDetailView',
9148             onclick: { fn: SEC.showDetailView }
9149         },
9150         {
9151             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9152             onclick: { fn: SEC.openMultiple }
9153         },
9154         {
9155             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9156             onclick: { fn: SEC.archiveToSugar }
9157         },
9158         {
9159             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9160             id: 'reply',
9161             onclick: { fn: SEC.replyForwardEmailContext }
9162         },
9163         {
9164             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9165             id: 'replyAll',
9166             onclick: { fn: SEC.replyForwardEmailContext }
9167         },
9168         {
9169             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9170             id: 'forward',
9171             onclick: { fn: SEC.replyForwardEmailContext }
9172         },
9173         {
9174             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9175             id: 'delete',
9176             onclick: { fn: SEC.markDeleted }
9177         },
9178         {
9179             text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9180             id: 'print',
9181             onclick: { fn: SEC.viewPrintable }
9182         },                
9183         // Mark... submenu
9184         {
9185             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9186             submenu: {
9187                         id: "markEmailMenu",
9188                 itemdata : [
9189                     {
9190                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9191                         onclick: { fn: SEC.markUnread }
9192                     },
9193                     {
9194                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9195                         onclick: { fn: SEC.markRead }
9196                     },
9197                     {
9198                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9199                         onclick: { fn: SEC.markFlagged }
9200                     },
9201                     {
9202                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9203                         onclick: {  fn: SEC.markUnflagged }
9204                     }
9205                 ]
9206             }
9207          },
9208         {
9209             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9210                 id: 'assignTo',
9211                 onclick: { fn: SEC.assignEmailsTo }
9212          },
9213          {
9214             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9215             id: 'relateTo',
9216             onclick: { fn: SEC.relateTo }
9217          }
9218     ]);
9219         SEC.emailListContextMenu.render();
9220         
9221         //Handle the Tree folder menu trigger ourselves
9222         YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9223
9224         
9225         //Folder Menu
9226     SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9227                 trigger: "",
9228                 lazyload: true 
9229         });
9230     SEC.frameFoldersContextMenu.addItems([
9231                 {   text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9232                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9233                         onclick: {  fn: function() {
9234                         var node = SUGAR.email2.clickedFolderNode;
9235                         if (node.data.ieId) {
9236                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9237                     }}
9238                 },
9239                 {   text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9240                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9241                         onclick: {  fn: function() {
9242                         var node = SUGAR.email2.clickedFolderNode;
9243                         if (node.data.ieId) {
9244                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9245                     }}
9246                 },
9247                 {
9248                     text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9249                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9250                     onclick: {  fn: SUGAR.email2.folders.folderAdd }
9251                 },
9252                 {
9253                     text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9254                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9255                     onclick: {  fn: SUGAR.email2.folders.folderDelete }
9256                 },
9257                 {
9258                     text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9259                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9260                     onclick: {  fn: SUGAR.email2.folders.folderRename }
9261                  },
9262                  {
9263                     text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9264                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9265                     onclick: {  fn: SUGAR.email2.folders.emptyTrash }
9266                   },
9267                  {
9268                     text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9269                     onclick: {  fn: function() {
9270                         var node = SUGAR.email2.clickedFolderNode;
9271                         if (node.data.ieId) {
9272                             SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9273                     }}
9274                   } 
9275         ]);
9276     SEC.frameFoldersContextMenu.render();
9277     
9278     SEC.initContactsMenu = function() {
9279         // contacts
9280         SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9281                 trigger: "contacts",
9282                 lazyload: true
9283         });
9284         SEC.contactsContextMenu.addItems([
9285                 {
9286                         text: app_strings.LBL_EMAIL_MENU_REMOVE,
9287                         onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9288                 },
9289                 {
9290                         text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9291                         onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9292                 }
9293         ]);
9294         SEC.contactsContextMenu.subscribe("beforeShow", function() {
9295                 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9296                 if (oTarget && !grid.isSelected(oTarget)) {
9297                         grid.unselectAllRows();
9298                         grid.selectRow(oTarget);
9299                 }
9300         });
9301         SEC.contactsContextMenu.render();
9302         }
9303         
9304         
9305         // set auto-check timer
9306         SUGAR.email2.folders.startCheckTimer();
9307         // check if we're coming from an email-link click
9308         setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9309         
9310         YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9311         
9312         //Init fix for YUI 2.7.0 datatable sort.
9313         SUGAR.email2.addressBook.initFixForDatatableSort();
9314 }
9315
9316 function createTreePanel(treeData, params) {
9317         var tree = new YAHOO.widget.TreeView(params.id);
9318         var root = tree.getRoot();
9319         
9320         //if (treeData.nodes && treeData[0].id == "Home")
9321         //      treeData = treeData[0];
9322
9323         addChildNodes(root, treeData);
9324         
9325         return tree;
9326 }
9327
9328 function addChildNodes(parentNode, parentData) {
9329         var Ck = YAHOO.util.Cookie;
9330         var nextyear = SUGAR.email2.nextYear;
9331         var nodes = parentData.nodes || parentData.children;
9332         for (i in nodes) {
9333                 if (typeof(nodes[i]) == 'object') {
9334                         if (nodes[i].data) {
9335                                 nodes[i].data.href = '#';
9336                                 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9337                                 node.action = nodes[i].data.action;
9338                         } else {
9339                                 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9340                                         addChildNodes(parentNode, nodes[i]);
9341                                         return;
9342                                 }
9343                                 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9344                                 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9345                                 if (nodes[i].cls) {
9346                                         nodes[i].className = nodes[i].cls;
9347                                 }
9348                                 nodes[i].href = "#";
9349                                 if (nodes[i].text) nodes[i].label = nodes[i].text;
9350                                 //Override YUI child node creation
9351                                 if (nodes[i].children) {
9352                                         nodes[i].nodes = nodes[i].children;
9353                                         nodes[i].children = [ ];
9354                                 }
9355                                 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9356                         }
9357                         
9358                         if (typeof(nodes[i].nodes) == 'object') {
9359                                 addChildNodes(node, nodes[i]);
9360                         }
9361                 }
9362         }
9363 }
9364
9365 /**
9366  * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9367  */
9368 function email2treeinit(tree, treedata, treediv, params) {
9369         //ensure the tree data is not corrupt
9370         if (!treedata) {
9371            return;
9372         }
9373         if (SUGAR.email2.tree) {
9374                 SUGAR.email2.tree.destroy();
9375                 SUGAR.email2.tree = null;
9376         }
9377         
9378         var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9379                 id: 'emailtree'
9380         });
9381         
9382         tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9383         tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9384         tree.subscribe("expandComplete", function(node){
9385                 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9386                 for (var i in node.children) {
9387                         SE.accounts.setupDDTarget(node.children[i]);
9388                 }
9389         });
9390         tree.setCollapseAnim("TVSlideOut");
9391         tree.setExpandAnim("TVSlideIn");
9392         var root = tree.root;
9393         while (root.hasChildren()) {
9394                 var node = root.children[0];
9395                 node.destroy();
9396                 tree.removeNode(root.children[0], false);
9397         }
9398         addChildNodes(root, treedata);
9399         tree.render();
9400         SUGAR.email2.accounts.renderTree();
9401 }
9402
9403 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9404         SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9405 };
9406
9407
9408 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {    
9409     startDrag: function(x, y) {
9410                 var Dom = YAHOO.util.Dom;       
9411                 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9412                 
9413                 this.dragId = "";
9414                 var dragEl = this.getDragEl();  
9415         var clickEl = this.getEl(); 
9416         Dom.setStyle(clickEl, "color", "#AAA");
9417         Dom.setStyle(clickEl, "opacity", "0.25"); 
9418         dragEl.innerHTML = clickEl.innerHTML; 
9419          
9420         Dom.addClass(dragEl, "ygtvcell");
9421         Dom.addClass(dragEl, "ygtvcontent");
9422         Dom.addClass(dragEl, "folderDragProxy");
9423         Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9424         Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9425         Dom.setStyle(dragEl, "backgroundColor", "#FFF"); 
9426         Dom.setStyle(dragEl, "opacity", "0.5"); 
9427             Dom.setStyle(dragEl, "border", "1px solid #AAA");
9428     },
9429     
9430     onDragOver: function(ev, id) {
9431         var Dom = YAHOO.util.Dom;
9432         if (id != this.dragId)
9433         {
9434                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9435                 if(node.data.cls != "sugarFolder") {
9436                         SUGAR.email2.folders.unhighliteAll();
9437                         return;
9438                 }
9439                 this.dragId = id;
9440                 this.targetNode = node;
9441                 SUGAR.email2.folders.unhighliteAll();
9442                 node.highlight();
9443         }
9444     },
9445     
9446     onDragOut: function(e, id) {
9447         if (this.targetNode) {
9448                 SUGAR.email2.folders.unhighliteAll();
9449                 this.targetNode = false;
9450                 this.dragId = false;
9451         }
9452     },
9453     
9454     endDrag: function() { 
9455         YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9456         if (this.targetNode) {
9457                 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9458         }
9459     }
9460 });// End of File modules/Emails/javascript/init.js
9461                                 
9462 /*********************************************************************************
9463  * SugarCRM is a customer relationship management program developed by
9464  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9465  * 
9466  * This program is free software; you can redistribute it and/or modify it under
9467  * the terms of the GNU Affero General Public License version 3 as published by the
9468  * Free Software Foundation with the addition of the following permission added
9469  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9470  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9471  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9472  * 
9473  * This program is distributed in the hope that it will be useful, but WITHOUT
9474  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9475  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9476  * details.
9477  * 
9478  * You should have received a copy of the GNU Affero General Public License along with
9479  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9480  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9481  * 02110-1301 USA.
9482  * 
9483  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9484  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9485  * 
9486  * The interactive user interfaces in modified source and object code versions
9487  * of this program must display Appropriate Legal Notices, as required under
9488  * Section 5 of the GNU Affero General Public License version 3.
9489  * 
9490  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9491  * these Appropriate Legal Notices must retain the display of the "Powered by
9492  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9493  * technical reasons, the Appropriate Legal Notices must display the words
9494  * "Powered by SugarCRM".
9495  ********************************************************************************/
9496
9497 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9498 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9499 '       <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9500 '               <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9501 '               <input type="hidden" id="uid{idx}" name="uid" value="">' +
9502 '               <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9503 '               <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9504 '               <input type="hidden" id="type{idx}" name="type" value="">' +
9505 '               <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9506 '               <input type="hidden" id="composeType" name="composeType">' +
9507 '               <input type="hidden" id="fromAccount" name="fromAccount">' +
9508 '               <input type="hidden" id="sendSubject" name="sendSubject">' +
9509 '               <input type="hidden" id="sendDescription" name="sendDescription">' +
9510 '               <input type="hidden" id="sendTo" name="sendTo">' +
9511 '               <input type="hidden" id="sendBcc" name="sendBcc">' +
9512 '               <input type="hidden" id="sendCc" name="sendCc">' +
9513 '               <input type="hidden" id="setEditor" name="setEditor">' +
9514 '               <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9515 '               <input type="hidden" id="parent_id" name="parent_id">' +
9516 '               <input type="hidden" id="parent_type" name="parent_type">' +
9517 '               <input type="hidden" id="attachments" name="attachments">' +
9518 '               <input type="hidden" id="documents" name="documents">' +
9519 '               <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9520 '               <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9521 '               <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9522 '               <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9523 '                       <tr>' +
9524 '                               <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9525 '                                       <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>' +
9526 '                                       <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>' +
9527 '                                       <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>' +
9528 '                                       <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>' +
9529 '</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>' + 
9530 '&nbsp;</td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9531 '<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>' +
9532 '                       </td></tr></tbody></table></th>'     +
9533 '                       </tr>' +
9534 '                       <tr>' +
9535 '                               <td>' +
9536 '                                       <div style="margin:5px;">' +
9537 '                                       <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9538 '                                               <tr>' +
9539 '                                                       <td class="emailUILabel" NOWRAP >' +
9540 '                                                               {app_strings.LBL_EMAIL_FROM}:' +
9541 '                                                       </td>' +
9542 '                                                       <td class="emailUIField" NOWRAP>' +
9543 '                                                               <div>' +
9544 '                                                                       &nbsp;&nbsp;<select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9545 '                                                               </div>' +
9546 '                                                       </td>' +
9547 '                                               </tr>' +
9548 '                                               <tr>' +
9549 '                                                       <td class="emailUILabel" NOWRAP>' +
9550 '                                                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' + 
9551 '                                   {app_strings.LBL_EMAIL_TO}:' +
9552 '                               </button>' + 
9553 '                                                       </td>' +
9554 '                                                       <td class="emailUIField" NOWRAP>' +
9555 '                                                               <div class="ac_autocomplete">' +
9556 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9557 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}">&nbsp;</span></a> </span>' +
9558 '                                                                       <div class="ac_container" id="addressToAC{idx}"></div>' +
9559 '                                                               </div>' +
9560 '                                                       </td>' +
9561 '                                               </tr>' +
9562 '                                               <tr id="add_addr_options_tr{idx}">' +
9563 '                                                       <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>'+
9564 '                                               </tr>'+
9565 '                                               <tr class="yui-hidden" id="cc_tr{idx}">' +
9566 '                                                       <td class="emailUILabel" NOWRAP>' +
9567 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' + 
9568 '                                                               {app_strings.LBL_EMAIL_CC}:' +
9569 '                               </button>' + 
9570 '                                                       </td>' +
9571 '                                                       <td class="emailUIField" NOWRAP>' +
9572 '                                                               <div class="ac_autocomplete">' +
9573 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9574 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#"  style="display: none;">+<span id="DetailaddressCC{idx}">&nbsp;</span></a> </span>' + 
9575 '                                                                       <div class="ac_container" id="addressCcAC{idx}"></div>' +
9576 '                                                               </div>' +
9577 '                                                       </td>' +
9578 '                                               </tr>' +
9579 '                                               <tr class="yui-hidden" id="bcc_tr{idx}">' +
9580 '                                                       <td class="emailUILabel" NOWRAP>' +
9581 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' + 
9582 '                               {app_strings.LBL_EMAIL_BCC}:' +
9583 '                               </button>' + 
9584 '                                                       </td>' +
9585 '                                                       <td class="emailUIField" NOWRAP>' +
9586 '                                                               <div class="ac_autocomplete">' +
9587 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9588 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}">&nbsp;</span></a> </span>' +
9589 '                                                                       <div class="ac_container" id="addressBccAC{idx}"></div>' +
9590 '                                                               </div>' +
9591 '                                                       </td>' +
9592 '                                               </tr>' +
9593 '                                               <tr>' +
9594 '                                                       <td class="emailUILabel" NOWRAP width="1%">' +
9595 '                                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9596 '                                                       </td>' +
9597 '                                                       <td class="emailUIField" NOWRAP width="99%">' +
9598 '                                                               <div class="ac_autocomplete">' +
9599 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9600 '                                                               </div>' +
9601 '                                                       </td>' +
9602 '                                               </tr>' +
9603 '                                       </table>' +
9604 '                                       </div>' +
9605 '                               </td>'   +
9606 '                       </tr>' +
9607 '               </table>' +
9608 '               <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9609 '               <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9610 '                       <div style="padding:5px;">' +
9611 '                               <table cellpadding="2" cellspacing="0" border="0">' +
9612 '                                       <tr>' +
9613 '                                               <th>' +
9614 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9615 '                                                       <br />' +
9616 '                                                       &nbsp;' +
9617 '                                               </th>' +
9618 '                                       </tr>' +
9619 '                                       <tr>' +
9620 '                                               <td>' +
9621 '                                                       <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9622 '                                                       <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9623 '                                               </td>' +
9624 '                                       </tr>' +
9625 '                                       <tr>' +
9626 '                                               <td>' +
9627 '                                                       &nbsp;' +
9628 '                                                       <br />' +
9629 '                                                       &nbsp;' +
9630 '                                               </td>' +
9631 '                                       </tr>' +
9632 '                                       <tr>' +
9633 '                                               <th>' +
9634 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9635 '                                                       <br />' +
9636 '                                                       &nbsp;' +
9637 '                                               </th>' +
9638 '                                       </tr>' +
9639 '                                       <tr>' +
9640 '                                               <td>' +
9641 '                                                       <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9642 '                                                       <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>' +
9643 '                                               </td>' +
9644 '                                       </tr>' +
9645 '                                       <tr>' +
9646 '                                               <td>' +
9647 '                                                       &nbsp;' +
9648 '                                                       <br />' +
9649 '                                                       &nbsp;' +
9650 '                                               </td>' +
9651 '                                       </tr>' +
9652 '                                       <tr>' +
9653 '                                               <th>' +
9654 '                                                       <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9655 '                                                       <br />' +
9656 '                                                       &nbsp;' +
9657 '                                               </th>' +
9658 '                                       </tr>' +
9659 '                                       <tr>' +
9660 '                                               <td>' +
9661 '                                                       <div id="addedTemplateAttachments{idx}"></div>' +
9662 '                                               </td>' +
9663 '                                       </tr>' +
9664 '                               </table>' +
9665 '                       </div>' +
9666 '               </div>' +
9667 '       </form>' +
9668 '               <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9669 '             <div style="padding:5px;">' +
9670 '                       <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' + 
9671 '                               <table border="0" width="100%">' +
9672 '                                       <tr>' +
9673 '                                               <td NOWRAP style="padding:2px;">' +
9674 '                                                       <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9675 '                                               </td>' +
9676 '                                       </tr>' +
9677 '                                       <tr>' +
9678 '                                               <td NOWRAP style="padding:2px;">' +
9679 '                                                       <select name="email_template{idx}" id="email_template{idx}"  onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9680 '                                               </td>' +
9681 '                                       </tr>' +
9682 '                               </table>' +
9683 '                               <br />' +
9684 '                               <table border="0" width="100%">' +
9685 '                                       <tr>' +
9686 '                                               <td NOWRAP style="padding:2px;">' +
9687 '                                                       <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9688 '                                               </td>' +
9689 '                                       </tr>' +
9690 '                                       <tr>' +
9691 '                                               <td NOWRAP style="padding:2px;">' +
9692 '                                                       <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9693 '                                               </td>' +
9694 '                                       </tr>' +
9695 '                               </table>' +
9696 '                               <table border="0" width="100%">' +
9697 '                                       <tr>' +
9698 '                                               <td NOWRAP style="padding:2px;">' +
9699 '                                                       <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/>&nbsp;' +
9700 '                                                       <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9701 '                                               </td>' +
9702 '                                       </tr>' +
9703 '                               </table>' +
9704 '         </form>' +
9705 '                       </div> ' +
9706 '               </div>' +
9707 '</div>';
9708 // End of File modules/Emails/javascript/composeEmailTemplate.js
9709                                 
9710 /*********************************************************************************
9711  * SugarCRM is a customer relationship management program developed by
9712  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9713  * 
9714  * This program is free software; you can redistribute it and/or modify it under
9715  * the terms of the GNU Affero General Public License version 3 as published by the
9716  * Free Software Foundation with the addition of the following permission added
9717  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9718  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9719  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9720  * 
9721  * This program is distributed in the hope that it will be useful, but WITHOUT
9722  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9723  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9724  * details.
9725  * 
9726  * You should have received a copy of the GNU Affero General Public License along with
9727  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9728  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9729  * 02110-1301 USA.
9730  * 
9731  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9732  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9733  * 
9734  * The interactive user interfaces in modified source and object code versions
9735  * of this program must display Appropriate Legal Notices, as required under
9736  * Section 5 of the GNU Affero General Public License version 3.
9737  * 
9738  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9739  * these Appropriate Legal Notices must retain the display of the "Powered by
9740  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9741  * technical reasons, the Appropriate Legal Notices must display the words
9742  * "Powered by SugarCRM".
9743  ********************************************************************************/
9744
9745 SUGAR.email2.templates['displayOneEmail'] = 
9746 '<div class="emailDetailTable" style="height:100%">' +
9747 '<div id="viewMenuDiv{idx}"></div>' + 
9748 '<div width="100%" class="displayEmailValue">' +
9749 '                                       <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>' +
9750 '                                       <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>' +
9751 '                                       <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>' +
9752 '                                       <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>' +
9753 '                                       <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>' +
9754 '                                       <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>' +
9755 '                                       <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>' +
9756 '                                       <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>' +
9757 '                                       <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>' +
9758 '</div>' +
9759 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9760 '                               <tr>' +
9761 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9762 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9763 '                                       </td>' +
9764 '                                       <td width="99%" class="displayEmailValue">' +
9765 '                                               {email.from_addr}' +
9766 '                                       </td>' +
9767 '                               </tr>' +
9768 '                               <tr>' +
9769 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9770 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9771 '                                       </td>' +
9772 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9773 '                                               <b>{email.name}</b>' +
9774 '                                       </td>' +
9775 '                               </tr>' +
9776 '                               <tr>' +
9777 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9778 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9779 '                                       </td>' +
9780 '                                       <td class="displayEmailValue">' +
9781 '                                               {email.date_start} {email.time_start}' +
9782 '                                       </td>' +
9783 '                               </tr>' +
9784 '                               <tr>' +
9785 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9786 '                                               {app_strings.LBL_EMAIL_TO}:' +
9787 '                                       </td>' +
9788 '                                       <td class="displayEmailValue">' +
9789 '                                               {email.toaddrs}' +
9790 '                                       </td>' +
9791 '                               </tr>' +
9792 '                               <tr>{meta.cc}</tr>' +
9793 '                               <tr>{email.attachments}</tr>' +
9794 '                       </table>' +
9795 '                       <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>' +
9796 //'                           {email.description}' +
9797 '</div>'
9798 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9799                                 
9800 /*********************************************************************************
9801  * SugarCRM is a customer relationship management program developed by
9802  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9803  * 
9804  * This program is free software; you can redistribute it and/or modify it under
9805  * the terms of the GNU Affero General Public License version 3 as published by the
9806  * Free Software Foundation with the addition of the following permission added
9807  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9808  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9809  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9810  * 
9811  * This program is distributed in the hope that it will be useful, but WITHOUT
9812  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9813  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9814  * details.
9815  * 
9816  * You should have received a copy of the GNU Affero General Public License along with
9817  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9818  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9819  * 02110-1301 USA.
9820  * 
9821  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9822  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9823  * 
9824  * The interactive user interfaces in modified source and object code versions
9825  * of this program must display Appropriate Legal Notices, as required under
9826  * Section 5 of the GNU Affero General Public License version 3.
9827  * 
9828  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9829  * these Appropriate Legal Notices must retain the display of the "Powered by
9830  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9831  * technical reasons, the Appropriate Legal Notices must display the words
9832  * "Powered by SugarCRM".
9833  ********************************************************************************/
9834
9835 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9836 '<body onload="javascript:window.print();">' + 
9837 '<style>' + 
9838 'body {' + 
9839 '       margin: 0px;' + 
9840 '       font-family: helvetica, impact, sans-serif;' +
9841 '       font-size : 12pt;' +
9842 '} ' +
9843 'table {' +
9844 '       padding:10px;' +
9845 '}' +
9846 '</style>' +
9847 '<div>' +
9848 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9849 '       <tr>' +
9850 '               <td>' +
9851 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9852 '                               <tr>' +
9853 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9854 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9855 '                                       </td>' +
9856 '                                       <td width="99%" class="displayEmailValue">' +
9857 '                                               {email.from_name} &lt;{email.from_addr}&gt;' +
9858 '                                       </td>' +
9859 '                               </tr>' +
9860 '                               <tr>' +
9861 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9862 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9863 '                                       </td>' +
9864 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9865 '                                               <b>{email.name}</b>' +
9866 '                                       </td>' +
9867 '                               </tr>' +
9868 '                               <tr>' +
9869 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9870 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9871 '                                       </td>' +
9872 '                                       <td class="displayEmailValue">' +
9873 '                                               {email.date_start} {email.time_start}' +
9874 '                                       </td>' +
9875 '                               </tr>' +
9876 '                               <tr>' +
9877 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9878 '                                               {app_strings.LBL_EMAIL_TO}:' +
9879 '                                       </td>' +
9880 '                                       <td class="displayEmailValue">' +
9881 '                                               {email.toaddrs}' +
9882 '                                       </td>' +
9883 '                               </tr>' +
9884 '                               {email.cc}' +
9885 '                               {email.attachments}' +
9886 '                       </table>' +
9887 '               </td>' +
9888 '       </tr>' +
9889 '       <tr>' +
9890 '               <td>' +
9891 '                       <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9892 '                               <tr>' +
9893 '                                       <td style="border-top: 1px solid #333;">' +
9894 '                                               <div style="padding:5px;">' +
9895                                                         '{email.description}' +
9896 '                                               </div>' +
9897 '                                       </td>' +
9898 '                               </tr>' +
9899 '                       </table>' +
9900 '               </td>' +
9901 '       </tr>' +
9902 '</table>' +
9903 '</div>' +
9904 '</body></html>';
9905 // End of File modules/Emails/javascript/viewPrintable.js
9906                                 
9907 /*********************************************************************************
9908  * SugarCRM is a customer relationship management program developed by
9909  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9910  *
9911  * This program is free software; you can redistribute it and/or modify it under
9912  * the terms of the GNU Affero General Public License version 3 as published by the
9913  * Free Software Foundation with the addition of the following permission added
9914  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9915  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9916  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9917  *
9918  * This program is distributed in the hope that it will be useful, but WITHOUT
9919  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9920  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9921  * details.
9922  *
9923  * You should have received a copy of the GNU Affero General Public License along with
9924  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9925  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9926  * 02110-1301 USA.
9927  *
9928  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9929  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9930  *
9931  * The interactive user interfaces in modified source and object code versions
9932  * of this program must display Appropriate Legal Notices, as required under
9933  * Section 5 of the GNU Affero General Public License version 3.
9934  *
9935  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9936  * these Appropriate Legal Notices must retain the display of the "Powered by
9937  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9938  * technical reasons, the Appropriate Legal Notices must display the words
9939  * "Powered by SugarCRM".
9940  ********************************************************************************/
9941 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9942 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;}
9943 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');}
9944 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;}}
9945 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9946 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9947 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}
9948 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="";}}
9949 this.oldValue="";}});if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9950 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];}}}
9951 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]];}
9952 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
9953 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9954 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js
9955