]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/sugar_grp_emails.js
Release 6.2.1
[Github/sugarcrm.git] / include / javascript / sugar_grp_emails.js
1
2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
3
4 /**
5  * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6  * dragged element is inserted before the dragged-over element.
7  *
8  * @extends YAHOO.util.DDProxy
9  * @constructor
10  * @param {String} id the id of the linked element
11  * @param {String} sGroup the group of related DragDrop objects
12  */
13 function ygDDList(id, sGroup) {
14
15         if (id) {
16                 this.init(id, sGroup);
17                 this.initFrame();
18                 //this.logger = new ygLogger("ygDDList");
19         }
20
21         var s = this.getDragEl().style;
22         s.borderColor = "transparent";
23         s.backgroundColor = "#f6f5e5";
24         s.opacity = 0.76;
25         s.filter = "alpha(opacity=76)";
26 }
27
28 ygDDList.prototype = new YAHOO.util.DDProxy();
29
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
32
33 ygDDList.prototype.startDrag = function(x, y) {
34         //this.logger.debug(this.id + " startDrag");
35
36         var dragEl = this.getDragEl();
37         var clickEl = this.getEl();
38
39         dragEl.innerHTML = clickEl.innerHTML;
40         dragElObjects = dragEl.getElementsByTagName('object');
41
42         
43         dragEl.className = clickEl.className;
44         dragEl.style.color = clickEl.style.color;
45         dragEl.style.border = "1px solid #aaa";
46
47         // save the style of the object 
48         clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
49         
50         this.borderDiv = document.createElement('div'); // create a div to display border
51         this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52         this.borderDiv.style.border = '2px dashed #cccccc';
53         
54         for(i in clickEl.childNodes) { // hide contents of the target elements contents
55                 if(typeof clickEl.childNodes[i].style != 'undefined') {
56                         this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57                         clickEl.childNodes[i].style.display = 'none';
58                 }
59
60         }
61         clickEl.appendChild(this.borderDiv);
62 };
63
64 ygDDList.prototype.endDrag = function(e) {
65         // disable moving the linked element
66         var clickEl = this.getEl();
67
68         clickEl.removeChild(this.borderDiv); // remove border div
69         
70         for(i in clickEl.childNodes) { // show target elements contents
71                 if(typeof clickEl.childNodes[i].style != 'undefined') {
72                         clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
73                 }
74         }
75         
76         if(this.clickHeight) 
77             clickEl.style.height = this.clickHeight;
78         else 
79                 clickEl.style.height = '';
80         
81         if(this.clickBorder) 
82             clickEl.style.border = this.clickBorder;
83         else 
84                 clickEl.style.border = '';
85                 
86         dragEl = this.getDragEl();
87         dragEl.innerHTML = '';
88
89         this.afterEndDrag(e);
90 };
91
92 ygDDList.prototype.afterEndDrag = function(e) {
93
94 }
95
96 ygDDList.prototype.onDrag = function(e, id) {
97     
98 };
99
100 ygDDList.prototype.onDragOver = function(e, id) {
101         // this.logger.debug(this.id.toString() + " onDragOver " + id);
102         var el;
103         
104     if ("string" == typeof id) {
105         el = YAHOO.util.DDM.getElement(id);
106     } else { 
107         el = YAHOO.util.DDM.getBestMatch(id).getEl();
108     }
109     
110         dragEl = this.getDragEl();
111         elRegion = YAHOO.util.Dom.getRegion(el);
112             
113 //    this.logger.debug('id: ' + el.id);
114 //    this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 //    this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116         var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 //    this.logger.debug('mid: ' + mid);
118         
119 //    this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " <  " + mid);
120 //    this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
121         
122         if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123                 var el2 = this.getEl();
124                 var p = el.parentNode;
125                 p.insertBefore(el2, el);
126         }
127         if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128                 var el2 = this.getEl();
129                 var p = el.parentNode;
130                 p.insertBefore(el2, el.nextSibling);
131         }
132 };
133
134 ygDDList.prototype.onDragEnter = function(e, id) {
135         // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136         // this.getDragEl().style.border = "1px solid #449629";
137 };
138
139 ygDDList.prototype.onDragOut = function(e, id) {
140     // I need to know when we are over nothing
141         // this.getDragEl().style.border = "1px solid #964428";
142 }
143
144 /////////////////////////////////////////////////////////////////////////////
145
146 function ygDDListBoundary(id, sGroup) {
147         if (id) {
148                 this.init(id, sGroup);
149                 //this.logger = new ygLogger("ygDDListBoundary");
150                 this.isBoundary = true;
151         }
152 }
153
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
156                                 
157 /*********************************************************************************
158  * SugarCRM Community Edition is a customer relationship management program developed by
159  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
160  *
161  * This program is free software; you can redistribute it and/or modify it under
162  * the terms of the GNU Affero General Public License version 3 as published by the
163  * Free Software Foundation with the addition of the following permission added
164  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
167  *
168  * This program is distributed in the hope that it will be useful, but WITHOUT
169  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
171  * details.
172  *
173  * You should have received a copy of the GNU Affero General Public License along with
174  * this program; if not, see http://www.gnu.org/licenses or write to the Free
175  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
176  * 02110-1301 USA.
177  *
178  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
180  *
181  * The interactive user interfaces in modified source and object code versions
182  * of this program must display Appropriate Legal Notices, as required under
183  * Section 5 of the GNU Affero General Public License version 3.
184  *
185  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186  * these Appropriate Legal Notices must retain the display of the "Powered by
187  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188  * technical reasons, the Appropriate Legal Notices must display the words
189  * "Powered by SugarCRM".
190  ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span>&nbsp;</span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace('&#039;',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML='&nbsp;';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};addToValidate(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,'email',this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
216 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
217 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
218 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
219 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
220 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
221 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
222 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
223 if(SUGAR.isIE){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
224 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
225 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();// End of File include/SugarEmailAddress/SugarEmailAddress.js
226                                 
227 /*********************************************************************************
228  * SugarCRM Community Edition 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;if(SUGAR.isIE7&&e.tagName.toLowerCase()=='input')
299 {var properties=['class','style','name','type','valign','border','width','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}else{var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}
300 for(var i in properties)
301 {if(e[properties[i]])
302 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
303 newNode[properties[i]]=e[properties[i]];}}
304 if(recursive)
305 {for(var i in e.childNodes)
306 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
307 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
308 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
309                                 
310 /*********************************************************************************
311  * SugarCRM Community Edition is a customer relationship management program developed by
312  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
313  *
314  * This program is free software; you can redistribute it and/or modify it under
315  * the terms of the GNU Affero General Public License version 3 as published by the
316  * Free Software Foundation with the addition of the following permission added
317  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
318  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
319  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
320  *
321  * This program is distributed in the hope that it will be useful, but WITHOUT
322  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
323  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
324  * details.
325  *
326  * You should have received a copy of the GNU Affero General Public License along with
327  * this program; if not, see http://www.gnu.org/licenses or write to the Free
328  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
329  * 02110-1301 USA.
330  *
331  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
332  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
333  *
334  * The interactive user interfaces in modified source and object code versions
335  * of this program must display Appropriate Legal Notices, as required under
336  * Section 5 of the GNU Affero General Public License version 3.
337  *
338  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
339  * these Appropriate Legal Notices must retain the display of the "Powered by
340  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
341  * technical reasons, the Appropriate Legal Notices must display the words
342  * "Powered by SugarCRM".
343  ********************************************************************************/
344 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);}
345 return s;},init:function(){if(Rot13.map!=null)
346 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
347 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
348 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
349 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='';}
350 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='';}
351 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='';}}
352 return words;}
353 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName,ie_id)
354 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
355 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id:'';URL='index.php?'
356 +'module='+module_name
357 +'&to_pdf=1'
358 +'&action='+action
359 +'&target='+pageTarget
360 +'&target1='+pageTarget
361 +'&server_url='+mail_server
362 +'&email_user='+words[0]
363 +'&protocol='+protocol
364 +'&port='+port
365 +'&email_password='+words[1]
366 +'&mailbox='+words[2]
367 +'&ssl='+ssl
368 +'&ie_id='+ie_id
369 +'&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)
370 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
371 this.body.style.width=w}}
372 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
373 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();}
374 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'));}
375 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
376 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
377 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
378 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
379 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";}
380 out+=errors[i];}
381 alert(out);return false;}else{return true;}}
382 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?'
383 +'module='+module_name
384 +'&to_pdf=1'
385 +'&action='+action
386 +'&target='+pageTarget
387 +'&target1='+pageTarget
388 +'&server_url='+mail_server
389 +'&email_user='+words[0]
390 +'&protocol='+protocol
391 +'&port='+port
392 +'&email_password='+words[1]
393 +'&mailbox='+words[2]
394 +'&ssl='+ssl
395 +'&personal='+isPersonal
396 +'&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)
397 this.body.style.width=w}}
398 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();}
399 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;}}}
400 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';}}}
401 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='';}
402 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
403                                 
404 /*********************************************************************************
405  * SugarCRM Community Edition is a customer relationship management program developed by
406  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
407  * 
408  * This program is free software; you can redistribute it and/or modify it under
409  * the terms of the GNU Affero General Public License version 3 as published by the
410  * Free Software Foundation with the addition of the following permission added
411  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
412  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
413  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
414  * 
415  * This program is distributed in the hope that it will be useful, but WITHOUT
416  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
417  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
418  * details.
419  * 
420  * You should have received a copy of the GNU Affero General Public License along with
421  * this program; if not, see http://www.gnu.org/licenses or write to the Free
422  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
423  * 02110-1301 USA.
424  * 
425  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
426  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
427  * 
428  * The interactive user interfaces in modified source and object code versions
429  * of this program must display Appropriate Legal Notices, as required under
430  * Section 5 of the GNU Affero General Public License version 3.
431  * 
432  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
433  * these Appropriate Legal Notices must retain the display of the "Powered by
434  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
435  * technical reasons, the Appropriate Legal Notices must display the words
436  * "Powered by SugarCRM".
437  ********************************************************************************/
438
439 SUGAR.email2 = {
440     cache : new Object(),
441     o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
442     reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
443     templates : {},
444     tinyInstances : {
445         currentHtmleditor : ''
446     },
447
448     /**
449      * preserves hits from email server
450      */ 
451     _setDetailCache : function(ret) {
452         if(ret.meta) {
453             var compKey = ret.meta.mbox + ret.meta.uid;
454
455             if(!SUGAR.email2.cache[compKey]) {
456                 SUGAR.email2.cache[compKey] = ret;
457             }
458         }
459     },
460
461     autoSetLayout : function() {
462         var c = document.getElementById('container');
463         var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
464         //Ensure a minimum height.
465         tHeight = Math.max(tHeight, 550);
466         c.style.height = tHeight + "px";
467         SUGAR.email2.complexLayout.set('height', tHeight);
468         SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
469         SUGAR.email2.complexLayout.render();
470         SUGAR.email2.listViewLayout.resizePreview();        
471     }
472 };
473
474 /**
475  * Shows overlay progress message
476  */
477 function overlayModal(title, body) {
478     overlay(title, body);
479 }
480 function overlay(reqtitle, body, type, additconfig) {
481     var config = { };
482     if (typeof(additconfig) == "object") {
483         var config = additconfig;
484     }
485     config.type = type;
486     config.title = reqtitle;
487     config.msg = body;
488     YAHOO.SUGAR.MessageBox.show(config);
489 };
490
491 function hideOverlay() {
492         YAHOO.SUGAR.MessageBox.hide();
493 };
494 // End of File modules/Emails/javascript/EmailUIShared.js
495                                 
496 /*********************************************************************************
497  * SugarCRM Community Edition is a customer relationship management program developed by
498  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
499  * 
500  * This program is free software; you can redistribute it and/or modify it under
501  * the terms of the GNU Affero General Public License version 3 as published by the
502  * Free Software Foundation with the addition of the following permission added
503  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
504  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
505  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
506  * 
507  * This program is distributed in the hope that it will be useful, but WITHOUT
508  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
509  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
510  * details.
511  * 
512  * You should have received a copy of the GNU Affero General Public License along with
513  * this program; if not, see http://www.gnu.org/licenses or write to the Free
514  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
515  * 02110-1301 USA.
516  * 
517  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
518  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
519  * 
520  * The interactive user interfaces in modified source and object code versions
521  * of this program must display Appropriate Legal Notices, as required under
522  * Section 5 of the GNU Affero General Public License version 3.
523  * 
524  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
525  * these Appropriate Legal Notices must retain the display of the "Powered by
526  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
527  * technical reasons, the Appropriate Legal Notices must display the words
528  * "Powered by SugarCRM".
529  ********************************************************************************/
530
531
532 (function() {
533         var sw = YAHOO.SUGAR,
534                 Event = YAHOO.util.Event,
535                 Connect = YAHOO.util.Connect,
536             Dom = YAHOO.util.Dom
537             SE = SUGAR.email2;
538
539 ///////////////////////////////////////////////////////////////////////////////
540 ////    EMAIL ACCOUNTS
541 SE.accounts = {
542     outboundDialog : null,
543     inboundAccountEditDialog : null,
544     inboundAccountsSettingsTable : null,
545     outboundAccountsSettingsTable : null,
546     testOutboundDialog : null,
547     errorStyle : 'input-error',
548     normalStyle : '',
549     newAddedOutboundId : '',
550
551     /**
552      * makes async call to retrieve an outbound instance for editting
553      */
554      //EXT111
555     editOutbound : function(obi) {
556
557             AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
558
559     },
560     deleteOutbound : function(obi) {
561
562         if(obi.match(/^(add|line|sendmail)+/)) {
563             alert('Invalid Operation');
564         } else {
565                 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
566             AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
567         }
568     },
569     //EXT111
570     getReplyAddress : function() {
571         var primary = '';
572
573         for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
574             var addy = SE.userPrefs.current_user.emailAddresses[i];
575
576             if(addy.primary_address == "1") {
577                 primary = addy.email_address;
578             }
579
580             if(addy.reply_to == "1") {
581                 return addy.email_address;
582             }
583         }
584
585         return primary;
586     },
587
588     /**
589      * Called on "Accounts" tab activation event
590      */
591     lazyLoad : function() {
592
593         this._setupInboundAccountTable();
594         this._setupOutboundAccountTable();
595
596     },
597
598     _setupInboundAccountTable: function()
599     {
600         //Setup the inbound mail settings
601         if(!this.inboundAccountsSettingsTable)
602         {
603                   this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
604                                         var clckEvent = oColumn.key;
605                                         var imgSrc = "";
606                                         var is_group = oRecord.getData("is_group");
607                                         if(!is_group)
608                                         {
609                                         if(oColumn.key == 'edit')
610                                         {
611                                                 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
612                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
613                                         }
614                                         else if(oColumn.key == 'delete')
615                                         {
616                                                 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
617                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
618                                         }
619                                 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
620                                         }
621                    };
622
623                    this.showBoolean = function(el, oRecord, oColumn, oData)
624                    {
625                        var is_group = oRecord.getData("is_group");
626                        var bChecked = oData;
627                        bChecked = (bChecked) ? " checked" : "";
628                        if(!is_group)
629                        {
630                        el.innerHTML = "<input type=\"radio\"" + bChecked +
631                            " name=\"col" + oColumn.getId() + "-radio\"" +
632                            " class=\"yui-dt-radio\">";
633                        }
634                    };
635
636
637                 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
638                 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
639
640                 var typeHoverHelp = '&nbsp;<div id="rollover"><a href="#" class="rollover">'+
641                                     '<img border="0" src="themes/default/images/helpInline.gif">' +
642                                     '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
643
644
645                 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
646                                       {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
647                                       {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
648                                       {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
649                                       {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
650                                       {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
651                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
652                 this.ieDataSource = new YAHOO.util.DataSource(query);
653                         this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
654                         this.ieDataSource.responseSchema = {
655                                 resultsList: "account_list",
656                                 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
657                         };
658                 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
659                         this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
660
661                     var elCheckbox = oArgs.target;
662                     var oColumn = this.getColumn(elCheckbox);
663                         if(oColumn.key == 'is_active')
664                         {
665                                 var oRecord = this.getRecord(elCheckbox);
666                                 oRecord.setData("is_active",elCheckbox.checked);
667                                 var t_id = oRecord.getData('id');
668                         var isGroupFolder = oRecord.getData('has_groupfolder');
669
670                         if(isGroupFolder)
671                             SUGAR.email2.folders.updateSubscriptions();
672                         else
673                         SUGAR.email2.folders.setFolderSelection();
674
675                         }
676                 });
677                         var lastDefaultSelectedId = "";
678                 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
679
680                     var elRadio = oArgs.target;
681                     var oColumn = this.getColumn(elRadio);
682                         if(oColumn.key == 'is_default')
683                         {
684                                 var oRecord = this.getRecord(elRadio);
685                                 var t_id = oRecord.getData('id');
686                                 var t_isGroup = oRecord.getData('is_group');
687                                 if(t_id != lastDefaultSelectedId && !t_isGroup)
688                                 {
689                                                 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
690                                         lastDefaultSelectedId = t_id;
691                                         AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
692                                 }
693                                 else if(t_isGroup)
694                                    YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
695
696                         }
697                 });
698
699                         this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
700                         this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
701         }
702     },
703      _setupOutboundAccountTable: function()
704     {
705         if(!this.outboundAccountsSettingsTable)
706         {
707                 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
708                                         var clckEvent = oColumn.key;
709                                         var imgSrc = "";
710                                         var isEditable = oRecord.getData("is_editable");
711                                         var type = oRecord.getData("type");
712                                         if(isEditable)
713                                         {
714                                         if(oColumn.key == 'edit')
715                                         {
716                                                 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
717                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
718                                         }
719                                         else if(oColumn.key == 'delete' && type == 'user')
720                                         {
721                                                 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
722                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
723                                         }
724                                         if(imgSrc != '')
725                                     elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
726                                         }
727                 };
728
729                 //Custom formatter to display any error messages.
730                         this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
731
732                     if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
733                                             SUGAR.email2.composeLayout.outboundAccountErrors = {};
734
735                         var id = oRecord.getData('id');
736                                         var message = oRecord.getData("errors");
737                                         if(message != '')
738                                         {
739                                     elLiner.innerHTML = '<span class="required">' + message + '</span>';
740                                         //Add the id and message for all outbound accounts.
741                                         SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
742                                         }
743                                         else
744                                         {
745                                             if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
746                                             delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
747                                         }
748                 };
749                 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
750                 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
751
752                 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
753                                                                    {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
754                                                                    {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
755                                                                    {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
756
757                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
758                 this.obDataSource = new YAHOO.util.DataSource(query);
759                         this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
760                         this.obDataSource.responseSchema = {
761
762                                 resultsList: "outbound_account_list",
763                                 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
764                         };
765
766                 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
767
768
769                         this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
770                         this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
771                 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
772         }
773     },
774     /**
775      * Displays a modal diaglogue to edit outbound account settings
776      */
777     showEditInboundAccountDialogue : function(clear) {
778
779         if(!this.inboundAccountEditDialog) {
780                 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
781                 modal:true,
782                                 visible:true,
783                 fixedcenter:true,
784                 constraintoviewport: true,
785                 width   : "600px",
786                 shadow  : true
787             });
788                         EAD.showEvent.subscribe(function() {
789                 var el = this.element;
790                 var viewH = YAHOO.util.Dom.getViewportHeight();
791                 if (this.header && el && viewH - 50 < el.clientHeight) {
792                     var body = this.header.nextElementSibling;
793                                         body.style.overflow = "hidden";
794                     body.style.height = "100%";
795                 }
796             }, EAD);
797             EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
798                         Dom.removeClass("editAccountDialogue", "yui-hidden");
799
800         } // end lazy load
801
802         if(clear == undefined || clear == true)
803         {
804                 SE.accounts.clearInboundAccountEditScreen();
805                 //Set default protocol to IMAP when creating new records
806                 document.forms['ieAccount'].elements['protocol'].value = "imap";
807                 SE.accounts.setPortDefault();
808         }
809
810         //Check if we should display username/password fields for outbound account if errors were detected.
811         this.checkOutBoundSelection();
812
813         this.inboundAccountEditDialog.render();
814         this.inboundAccountEditDialog.show();
815         SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
816     },
817
818     /**
819     *  Set all fields on the outbound edit form to either enabled/disabled
820     *  except for the username/password.
821     *
822     */
823     toggleOutboundAccountDisabledFields: function(disable)
824     {
825         var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
826         for(var i=0;i<fields.length;i++)
827         {
828             document.getElementById(fields[i]).disabled = disable;
829         }
830         if(disable)
831             Dom.addClass("mail_smtpssl_row", "yui-hidden");
832         else
833             Dom.removeClass('mail_smtpssl_row', "yui-hidden");
834
835     },
836     /**
837     * Refresh the inbound accounts table.
838     */
839     refreshInboundAccountTable : function()
840     {
841             this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
842                 {
843                         success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
844                                 scope: this.inboundAccountsSettingsTable }
845                         );
846     },
847     /**
848     * Refresh the outbound accounts table.
849     */
850     refreshOuboundAccountTable : function()
851     {
852             this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
853                 {
854                         success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
855                                 scope: this.outboundAccountsSettingsTable }
856                         );
857     },
858     /**
859      * Displays a modal diaglogue to add a SMTP server
860      */
861     showAddSmtp : function() {
862         // lazy load dialogue
863         if(!this.outboundDialog) {
864                 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
865                 modal:true,
866                                 visible:true,
867                 fixedcenter:true,
868                 constraintoviewport: true,
869                 width   : "750px",
870                 shadow  : true
871             });
872             this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
873             this.outboundDialog.hideEvent.subscribe(function(){
874                 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
875                 var out = Dom.get("outbound_email");
876                 if (out && out.value == "SYSTEM_ADD")
877                 {
878                         out.value = out.options[0].value;
879                 }
880                 //Check if we should display username/password for system account.
881                 SE.accounts.checkOutBoundSelection();
882                 return true;
883             });
884
885             Dom.removeClass("outboundDialog", "yui-hidden");
886         } // end lazy load
887
888         // clear out form
889         var form = document.getElementById('outboundEmailForm');
890         for(i=0; i<form.elements.length; i++) {
891             if(form.elements[i].name == 'mail_smtpport') {
892                 form.elements[i].value = 25;
893             } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
894                 form.elements[i].value = '';
895             } else if(form.elements[i].type == 'checkbox') {
896                 form.elements[i].checked = false;
897             }
898         }
899         //Render the SMTP buttons
900         if ( !SUGAR.smtpButtonGroup ) {
901             SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
902             SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
903             {
904                 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
905                 document.getElementById('smtp_settings').style.display = '';
906                 form.mail_smtptype.value = e.newValue.get('value');
907             });
908             YAHOO.widget.Button.addHiddenFieldsToForm(form);
909         }
910         //Hide Username/Password
911         SUGAR.email2.accounts.smtp_authenticate_field_display();
912         //Unset readonly fields
913         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
914         SUGAR.email2.accounts.changeEmailScreenDisplay('other');
915                 this.outboundDialog.render();
916         this.outboundDialog.show();
917     },
918
919     /**
920      * Accounts' Advanced Settings view toggle
921      */
922     toggleAdv : function() {
923         var adv = document.getElementById("ie_adv");
924         if(adv.style.display == 'none') {
925             adv.style.display = "";
926         } else {
927             adv.style.display = 'none';
928         }
929     },
930
931         smtp_authenticate_field_display : function() {
932                 var smtpauth_req = document.getElementById("mail_smtpauth_req");
933                 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
934                 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
935         },
936         
937         smtp_setDefaultSMTPPort : function() {
938                 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
939     
940         if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
941             document.getElementById("mail_smtpport").value = '465';
942         }
943         if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
944             document.getElementById("mail_smtpport").value = '25';
945         }
946         },
947
948     /**
949      * Changes the display used in the outbound email SMTP dialog to match the
950      */
951     changeEmailScreenDisplay : function(smtptype, isSystemAccount)
952     {
953         document.getElementById("smtpButtonGroupTD").style.display = '';
954         document.getElementById("chooseEmailProviderTD").style.display = '';
955         document.getElementById("mailsettings1").style.display = '';
956         document.getElementById("mailsettings2").style.display = '';
957         document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
958         document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
959         document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
960         document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
961
962         switch (smtptype) {
963         case "yahoomail":
964             document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
965             document.getElementById("mail_smtpport").value = '465';
966             document.getElementById("mail_smtpauth_req").checked = true;
967             var ssl = document.getElementById("mail_smtpssl");
968             for(var j=0;j<ssl.options.length;j++) {
969                 if(ssl.options[j].text == 'SSL') {
970                     ssl.options[j].selected = true;
971                     break;
972                 }
973             }
974             document.getElementById("mailsettings1").style.display = 'none';
975             document.getElementById("mailsettings2").style.display = 'none';
976             document.getElementById("mail_smtppass_label").innerHTML =
977             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
978             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
979             break;
980         case "gmail":
981             document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
982             document.getElementById("mail_smtpport").value = '587';
983             document.getElementById("mail_smtpauth_req").checked = true;
984             var ssl = document.getElementById("mail_smtpssl");
985             for(var j=0;j<ssl.options.length;j++) {
986                 if(ssl.options[j].text == 'TLS') {
987                     ssl.options[j].selected = true;
988                     break;
989                 }
990             }
991             document.getElementById("mailsettings1").style.display = 'none';
992             document.getElementById("mailsettings2").style.display = 'none';
993             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
994             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
995             break;
996         case "exchange":
997             if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
998                     || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
999                 document.getElementById("mail_smtpserver").value = '';
1000             }
1001             document.getElementById("mail_smtpport").value = '25';
1002             document.getElementById("mail_smtpauth_req").checked = true;
1003             document.getElementById("mailsettings1").style.display = '';
1004             document.getElementById("mailsettings2").style.display = '';
1005             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1006             document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1007             document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1008             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1009             break;
1010         }
1011         if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1012         {
1013             document.getElementById("smtpButtonGroupTD").style.display = 'none';
1014             document.getElementById("chooseEmailProviderTD").style.display = 'none';
1015             document.getElementById("mailsettings2").style.display = 'none';
1016         }
1017
1018         SUGAR.email2.accounts.smtp_authenticate_field_display();
1019         SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1020     },
1021
1022     /**
1023     * Fill the gmail default values for inbound accounts.
1024     */
1025     fillInboundGmailDefaults: function () {
1026
1027         document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1028         document.forms['ieAccount'].elements['ssl'].checked = true;
1029         document.forms['ieAccount'].elements['protocol'].value = "imap";
1030         SUGAR.email2.accounts.setPortDefault();
1031         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1032     },
1033     /**
1034      * Sets Port field to selected protocol and SSL settings defaults
1035      */
1036     setPortDefault : function() {
1037         var prot = document.getElementById('protocol');
1038         var ssl  = document.getElementById('ssl');
1039         var port = document.getElementById('port');
1040         var stdPorts= new Array("110", "143", "993", "995");
1041         var stdBool    = new Boolean(false);
1042         var mailboxdiv = document.getElementById("mailboxdiv");
1043         var trashFolderdiv = document.getElementById("trashFolderdiv");
1044         var sentFolderdiv = document.getElementById("sentFolderdiv");
1045                 var monitoredFolder = document.getElementById("subscribeFolderButton");
1046         if(port.value == '') {
1047             stdBool.value = true;
1048         } else {
1049             for(i=0; i<stdPorts.length; i++) {
1050                 if(stdPorts[i] == port.value) {
1051                     stdBool.value = true;
1052                 }
1053             }
1054         }
1055
1056         if(stdBool.value == true) {
1057             if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1058                 port.value = "143";
1059             } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1060                 port.value = '993';
1061             } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1062                 port.value = '110';
1063             } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1064                 port.value = '995';
1065             }
1066         }
1067
1068         if (prot.value == 'imap') {
1069                 mailboxdiv.style.display = "";
1070                 trashFolderdiv.style.display = "";
1071                 sentFolderdiv.style.display = "";
1072                 monitoredFolder.style.display = "";
1073                 if (document.getElementById('mailbox').value == "") {
1074                         document.getElementById('mailbox').value = "INBOX";
1075                 }
1076         } else {
1077                 mailboxdiv.style.display = "none";
1078                 trashFolderdiv.style.display = "none";
1079                 sentFolderdiv.style.display = "none";
1080                         monitoredFolder.style.display = "none";
1081                 document.getElementById('mailbox').value = "";
1082         } // else
1083     },
1084
1085     /**
1086      * Draws/removes red boxes around required fields.
1087      */
1088     ieAccountError : function(style) {
1089         document.getElementById('server_url').className = style;
1090         document.getElementById('email_user').className = style;
1091         document.getElementById('email_password').className = style;
1092         document.getElementById('protocol').className = style;
1093         document.getElementById('port').className = style;
1094     },
1095
1096     checkOutBoundSelection: function() {
1097         var select = Dom.get('outbound_email');
1098         if (!select || select.selectedIndex == -1) { return; }
1099
1100         var v = select.options[select.selectedIndex].value;
1101
1102         if(v == '')
1103         {
1104                 select.options[select.selectedIndex].selected = false;
1105                 v = select.options[0].value;
1106         }
1107         else if (v == 'SYSTEM_ADD')
1108                 SUGAR.email2.accounts.showAddSmtp();
1109
1110         var foundError = false;
1111         var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1112                 for(i in errorAccounts)
1113                 {
1114                     if(v == i)
1115                     {
1116                         foundError = true;
1117                         break;
1118                     }
1119                 }
1120
1121                 //Should username/password fields for outbound account.
1122                 if(foundError)
1123                     this.toggleInboundOutboundFields(true);
1124                 else
1125                     this.toggleInboundOutboundFields(false);
1126
1127
1128
1129     },
1130     toggleInboundOutboundFields : function (display)
1131     {
1132         if(display)
1133         {
1134             Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1135                     Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1136         }
1137         else
1138         {
1139             Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1140                     Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1141         }
1142     },
1143     /**
1144      * rebuilds the select options for mailer options
1145      */
1146     rebuildMailerOptions : function() {
1147         var select = document.forms['ieAccount'].elements['outbound_email'];
1148         SE.util.emptySelectOptions(select);
1149
1150         //Get the available sugar mailers
1151         var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1152
1153         for(i=0;i<a_outbound.length;i++)
1154         {
1155                 var t_record = a_outbound[i];
1156                 var key = t_record.getData('id');
1157                 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1158
1159                 var opt = new Option(display, key);
1160                 select.options.add(opt);
1161                 if (key == SE.accounts.newAddedOutboundId) {
1162                         select.options.selectedIndex = i;
1163                 }
1164         }
1165
1166         select.options.add(new Option('',''));
1167         select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1168         //Hide/Show username password fields if necessary.
1169         SE.accounts.checkOutBoundSelection();
1170     },
1171     /**
1172      * Empties all the fields in the accounts edit view
1173      */
1174     clearInboundAccountEditScreen:function() {
1175
1176         document.getElementById('ie_id').value = '';
1177         document.getElementById('ie_name').value = '';
1178         document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1179         document.getElementById('ie_from_addr').value = this.getReplyAddress();
1180         document.getElementById('reply_to_addr').value = '';
1181         document.getElementById('server_url').value = '';
1182         document.getElementById('email_user').value = '';
1183         document.getElementById('email_password').value = '';
1184         document.getElementById('port').value = '';
1185         document.getElementById('inbound_mail_smtpuser').value = '';
1186         document.getElementById('inbound_mail_smtppass').value = '';
1187         document.ieAccount.protocol.options[0].selected = true;
1188         // handle SSL
1189         document.getElementById('ssl').checked = false;
1190         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1191     },
1192
1193     /**
1194      * Populates an account's fields in Settings->Accounts
1195      */
1196     fillIeAccount:function(jsonstr) {
1197         var o = JSON.parse(jsonstr);
1198
1199         document.getElementById('ie_id').value = o.id;
1200         document.getElementById('ie_name').value = o.name;
1201         if (o.stored_options != null) {
1202                 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1203                 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1204                 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1205                 if (o.stored_options.trashFolder != null) {
1206                         document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1207                 }
1208                 if (o.stored_options.sentFolder != null) {
1209                         document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1210                 }
1211         }
1212         document.getElementById('server_url').value = o.server_url;
1213         document.getElementById('email_user').value = o.email_user;
1214         document.getElementById('port').value = o.port;
1215         document.getElementById('group_id').value = o.group_id;
1216         document.getElementById('mailbox').value = o.mailbox;
1217
1218
1219         var i = 0;
1220
1221         // handle SSL
1222         if(typeof(o.service[2]) != 'undefined') {
1223             document.getElementById('ssl').checked = true;
1224         }
1225
1226         // handle protocol
1227         if(document.getElementById('protocol').value != o.protocol) {
1228             var prot = document.getElementById('protocol');
1229             for(i=0; i<prot.options.length; i++) {
1230                 if(prot.options[i].value == o.service[3]) {
1231                     prot.options[i].selected = true;
1232                     this.setPortDefault();
1233                 }
1234             }
1235         }
1236  // handle SMTP selection
1237         if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1238             var opts = document.getElementById('outbound_email').options;
1239             for(i=0; i<opts.length; i++) {
1240                 if(opts[i].value == o.stored_options.outbound_email) {
1241                     opts[i].selected = true;
1242                 }
1243             }
1244         }
1245     },
1246
1247     deleteIeAccount : function(IeAccountID,IeGroupID) {
1248         if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1249         {
1250             overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1251
1252             AjaxObject.target = 'frameFlex';
1253             AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1254             SUGAR.email2.accounts.refreshInboundAccountTable();
1255          }
1256      },
1257
1258        // Null check for Outbound Settings.
1259     checkOutboundSettings: function() {
1260         var errorMessage = '';
1261         var isError = false;
1262         if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1263             var mailName = document.getElementById('mail_name').value;
1264             var smtpServer = document.getElementById('mail_smtpserver').value;
1265             var smtpPort = document.getElementById('mail_smtpport').value;
1266
1267             var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1268             if(trim(mailName) == '') {
1269                 isError = true;
1270                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1271             }
1272             if(trim(smtpServer) == '') {
1273                 isError = true;
1274                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1275             }
1276             if(trim(smtpPort) == '') {
1277                 isError = true;
1278                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1279             }
1280             if(mailsmtpauthreq.checked) {
1281                 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1282                     isError = true;
1283                     errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1284                 }
1285             }
1286         }
1287         if(isError) {
1288             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1289             return false;
1290         } else {
1291             return true;
1292         }
1293     },
1294
1295     testOutboundSettings: function() {
1296         var errorMessage = '';
1297         var isError = false;
1298         var fromAddress = document.getElementById("outboundtest_from_address").value;
1299         if (trim(fromAddress) == "") {
1300             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1301             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1302             return false;
1303
1304         }
1305         else if (!isValidEmail(fromAddress)) {
1306             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1307             overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1308             return false;
1309         }
1310
1311         //Hide the dialogue and show an in progress indicator.
1312         SE.accounts.testOutboundDialog.hide();
1313         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1314
1315         //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1316         //nothing is sent in the request.
1317         var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1318         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1319
1320         YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1321         if(outboundType == 'system-override')
1322             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1323
1324         var data = "&emailUIAction=testOutbound&outboundtest_from_address=" +  fromAddress;
1325         AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1326
1327     },
1328
1329     testOutboundSettingsDialog: function() {
1330         //Ensure that all settings are correct before proceeding to send test email.
1331         if(!SE.accounts.checkOutboundSettings())
1332             return;
1333
1334         // lazy load dialogue
1335         if(!SE.accounts.testOutboundDialog) {
1336                 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1337                 modal:true,
1338                                 visible:true,
1339                 fixedcenter:true,
1340                 constraintoviewport: true,
1341                 width   : 600,
1342                 shadow  : true
1343             });
1344             SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1345             Dom.removeClass("testOutboundDialog", "yui-hidden");
1346         } // end lazy load
1347         SE.accounts.testOutboundDialog.render();
1348         SE.accounts.testOutboundDialog.show();
1349     },
1350
1351     /**
1352      * Saves Outbound email settings
1353      */
1354     saveOutboundSettings : function() {
1355         if(SE.accounts.checkOutboundSettings()) {
1356             //Enable the form fields for the post.
1357             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1358             YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1359             AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1360         } else {
1361             return false;
1362         }
1363     },
1364
1365     saveIeAccount : function() {
1366
1367         //Before saving check if there are any error messages associated with the outbound account.
1368         var outboundID = document.getElementById('outbound_email').value;
1369
1370         if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1371             'validateSMTPCreds':true}) )
1372         {
1373             document.getElementById('saveButton').disabled = true;
1374
1375             overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1376
1377             var formObject = document.getElementById('ieAccount');
1378             YAHOO.util.Connect.setForm(formObject);
1379
1380             AjaxObject._reset();
1381             AjaxObject.target = 'frameFlex';
1382             AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1383         }
1384     },
1385
1386     testSettings : function() {
1387         form = document.getElementById('ieAccount');
1388
1389         if(SE.accounts.checkIeCreds()) {
1390             ie_test_open_popup_with_submit("InboundEmail", "Popup", "Popup", 400, 300, trim(form.server_url.value), form.protocol.value, trim(form.port.value), trim(form.email_user.value), Rot13.write(form.email_password.value), trim(form.mailbox.value), form.ssl.checked, true, "ieAccount", form.ie_id.value);
1391         }
1392     },
1393
1394     getFoldersListForInboundAccountForEmail2 : function() {
1395         form = document.getElementById('ieAccount');
1396         if(SE.accounts.checkIeCreds()) {
1397                 var mailBoxValue = form.mailbox.value;
1398                 if (form.searchField.value.length > 0) {
1399                         mailBoxValue = "";
1400                 } // if
1401             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 );
1402         } // if
1403
1404     },
1405
1406     checkIeCreds : function(validateRules) {
1407         if(typeof(validateRules) == 'undefined')
1408             validateRules = {};
1409
1410         var errors = new Array();
1411         var out = new String();
1412
1413         var ie_name = Dom.get('ie_name').value;
1414         var fromAddress = Dom.get('ie_from_addr').value;
1415         var server_url = Dom.get('server_url').value;
1416         var email_user = Dom.get('email_user').value;
1417         var email_password = Dom.get('email_password').value;
1418         var protocol = Dom.get('protocol').value;
1419         var port = Dom.get('port').value;
1420         var oe = Dom.get('outbound_email');
1421         var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1422
1423         var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1424         var outboundPass = Dom.get('inbound_mail_smtppass').value;
1425
1426         //If the username and password were provided then ignore the error messge
1427
1428         var outboundCredentialsFound = false;
1429
1430         if(outboundUserName != "" && outboundPass != "")
1431             outboundCredentialsFound = true;
1432
1433         var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1434
1435         if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1436              && validateSMTPCreds)
1437         {
1438             if(trim(outboundUserName) == "") {
1439                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1440             }
1441             if(trim(outboundPass) == "") {
1442                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1443             }
1444         }
1445
1446         if(trim(ie_name) == "") {
1447             errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1448         }
1449
1450         if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1451         {
1452             if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1453                 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1454             }
1455         }
1456
1457
1458         if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1459              || trim(oe_value) == "SYSTEM_ADD") ) {
1460             errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1461         }
1462         if(trim(server_url) == "") {
1463             errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1464         }
1465         if(trim(email_user) == "") {
1466             errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1467         }
1468         if(protocol == "") {
1469             errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1470         }
1471         if (protocol == 'imap') {
1472                 var mailbox = document.getElementById('mailbox').value;
1473                 if (trim(mailbox) == "") {
1474                         errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1475                 } // if
1476                 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1477                         var trashFolder = document.getElementById('trashFolder').value;
1478                         if (trim(trashFolder) == "") {
1479                                 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1480                         } // if
1481                         } // if
1482         }
1483         if(port == "") {
1484             errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1485         }
1486
1487         if(errors.length > 0) {
1488             out = app_strings.LBL_EMAIL_ERROR_DESC;
1489             for(i=0; i<errors.length; i++) {
1490                 if(out != "") {
1491                     out += "\n";
1492                 }
1493                 out += errors[i];
1494             }
1495
1496             alert(out);
1497             return false;
1498         } else {
1499
1500             return true;
1501         }
1502     },
1503
1504     getIeAccount : function(ieId) {
1505         if(ieId == '')
1506             return;
1507
1508         overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1509                 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1510
1511         AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1512     },
1513
1514     /**
1515      * Iterates through TreeView nodes to apply styles dependent nature of node
1516      */
1517     renderTree:function() {
1518         SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1519         SE.tree.render();
1520     },
1521
1522     //Sets the style for any nodes that need it.
1523     setNodeStyle : function(node) {
1524         if (!node.data.origText) {
1525             node.data.origText = node.data.text;
1526         }
1527         //Set unread
1528         if (typeof(node.data.unseen) != 'undefined') {
1529                 if (node.data.unseen > 0) {
1530                                 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1531                         }
1532                         else {
1533                                 node.setUpLabel(node.data.origText);
1534                         }
1535         } else {
1536                 node.setUpLabel('<span>' + node.data.origText + '</span>');
1537         }
1538         SE.accounts.setupDDTarget(node);
1539     },
1540
1541     setupDDTarget : function(node) {
1542         if (node.ddTarget) {
1543                 node.ddTarget.removeFromGroup();
1544                 delete node.ddTarget;
1545         }
1546         var id = node.getElId();
1547         var num = id.substring(4);
1548         if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1549                         node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1550                         node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1551
1552                 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1553         }
1554         else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1555                 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1556         }
1557     },
1558
1559     /**
1560      * Async call to rebuild the folder list.  After a folder delete or account delete
1561      */
1562     rebuildFolderList : function() {
1563         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1564         AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1565     },
1566
1567     /**
1568      * Returns the number of remote accounts the user has active.
1569      */
1570     getAccountCount : function() {
1571         var tree = SE.tree;
1572         var count = 0;
1573         for(i=0; i<tree._nodes.length; i++) {
1574             var node = tree._nodes[i];
1575
1576             if(typeof(node) != 'undefined' && node.data.ieId) {
1577                 count++;
1578             }
1579         }
1580         return count;
1581     }
1582 };
1583 ////    END ACCOUNTS
1584 ///////////////////////////////////////////////////////////////////////////////
1585
1586
1587
1588
1589 ///////////////////////////////////////////////////////////////////////////////
1590 ////    CONTEXT MENU CALLS
1591 SE.contextMenus = {
1592
1593     assignToDialogue : null,
1594     /**
1595      * Archives from context menu
1596      * @param Array uids
1597      * @param string ieId
1598      * @param string folder
1599      */
1600     _archiveToSugar : function(uids, ieId, folder) {
1601         var ser = '';
1602
1603         for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1604             if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1605             ser += uids[i];
1606         }
1607         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1608     },
1609
1610     /**
1611      * Archives from context menu
1612      */
1613     archiveToSugar : function(menuItem) {
1614         SE.contextMenus.emailListContextMenu.hide();
1615
1616         var rows = SE.grid.getSelectedRows();
1617         var uids = [];
1618         /* iterate through available rows JIC a row is deleted - use first available */
1619         for(var i=0; i<rows.length; i++) {
1620             uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1621         }
1622         var data = SE.grid.getRecord(rows[0]).getData();
1623         SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1624     },
1625
1626     /**
1627      * Popup the printable version and start system's print function.
1628      */
1629     viewPrintable : function(menuItem) {
1630         var rows = SE.grid.getSelectedRows();
1631         var data = SE.grid.getRecord(rows[0]).getData();
1632         SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1633     },
1634
1635     /**
1636      * Marks email flagged on mail server
1637      */
1638     markRead : function(type, contextMenuId) {
1639         SE.contextMenus.markEmail('read');
1640     },
1641
1642     /**
1643      * Assign this emails to people based on assignment rules
1644      */
1645     assignEmailsTo : function(type, contextMenuId) {
1646         if(!SE.contextMenus.assignToDialogue)
1647         {
1648                 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1649                 modal:true,
1650                                 visible:false,
1651                 fixedcenter:true,
1652                 constraintoviewport: true,
1653                 width   : "600px",
1654                 shadow  : true
1655             });
1656             SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1657             enableQS(true);
1658         }
1659
1660         Dom.removeClass("assignToDiv", "yui-hidden");
1661         SE.contextMenus.assignToDialogue.render();
1662         SE.contextMenus.assignToDialogue.show();
1663     },
1664
1665     /**
1666      * Marks email flagged on mail server
1667      */
1668     markFlagged : function(contextMenuId) {
1669         SE.contextMenus.markEmail('flagged');
1670     },
1671
1672     /**
1673      * Marks email unflagged on mail server
1674      */
1675     markUnflagged : function(contextMenuId) {
1676         SE.contextMenus.markEmail('unflagged');
1677     },
1678
1679     /**
1680      * Marks email unread on mail server
1681      */
1682     markUnread : function() {
1683         SE.contextMenus.markEmail('unread');
1684     },
1685
1686     /**
1687      * Deletes an email from context menu
1688      */
1689     markDeleted : function() {
1690         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1691                 document.getElementById('_blank').innerHTML = "";
1692                 SE.contextMenus.markEmail('deleted');
1693         }
1694     },
1695
1696     /**
1697      * generic call API to apply a flag to emails on the server and on sugar
1698      * @param string type "read" | "unread" | "flagged" | "deleted"
1699      */
1700     markEmail : function(type) {
1701         SE.contextMenus.emailListContextMenu.hide();
1702
1703         //var dm = SE.grid.getStore();
1704         //var uids = SE.grid.getSelectedRowIds();
1705         //var indexes = SE.grid.getSelectedRowIndexes();
1706         var rows = SE.grid.getSelectedRows();
1707         if (rows.length == 0)
1708                 rows = [SE.contextMenus.currentRow];
1709         var ser = [ ];
1710
1711         for(var i=0; i<rows.length; i++) {
1712             ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1713         }
1714
1715         ser = YAHOO.lang.JSON.stringify(ser);
1716
1717         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1718         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1719
1720
1721         var count = 0;
1722
1723
1724         if(type == 'read' || type == 'deleted') {
1725             // mark read
1726             for(var j=0; j<rows.length; j++) {
1727                 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1728                     count = count + 1;
1729                     SE.grid.getRecord(rows[j]).setData("seen", "1");
1730                 }
1731             }
1732            //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1733             if(ieId){
1734             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1735             var unseenCount = node.data.unseen;
1736             if (isNaN(unseenCount)) {
1737                 unseenCount = 0;
1738             }
1739             var finalCount = parseInt(unseenCount) - count;
1740             node.data.unseen = finalCount;
1741
1742             SE.accounts.renderTree();
1743             }
1744         } else if(type == 'unread') {
1745             // mark unread
1746             for(var j=0; j<rows.length; j++) {
1747                 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1748                     count = count + 1;
1749                 }
1750             }
1751
1752             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1753             var unseenCount = node.data.unseen;
1754             if (isNaN(unseenCount)) {
1755                 unseenCount = 0;
1756             }
1757             var finalCount = parseInt(unseenCount) + count;
1758             node.data.unseen = finalCount;
1759             SE.accounts.renderTree();
1760         }
1761
1762         if (type == 'unread') {
1763                 for(var i=0; i<rows.length; i++) {
1764                     SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1765                 } // for
1766         }
1767
1768                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1769         AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1770     },
1771
1772     /**
1773      * refreshes the ListView to show changes to cache
1774      */
1775     markEmailCleanup : function() {
1776         SE.accounts.renderTree();
1777         hideOverlay();
1778         SE.listView.refreshGrid();
1779     },
1780
1781         showAssignmentDialog : function() {
1782                 if (SE.contextMenus.assignmentDialog == null) {
1783                         AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1784                 } else {
1785                         SE.contextMenus.assignmentDialog.show();
1786                 } // else
1787         },
1788
1789         /**
1790      * shows the import dialog with only relate visible.
1791      */
1792     relateTo : function() {
1793         SE.contextMenus.emailListContextMenu.hide();
1794
1795         var rows = SE.grid.getSelectedRows();
1796         var data = SE.grid.getRecord(rows[0]).getData();
1797         var ieId = data.ieId;
1798         var folder = data.mbox;
1799         var uids = [];
1800         /* iterate through available rows JIC a row is deleted - use first available */
1801         for(var i=0; i<rows.length; i++) {
1802             uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1803         }
1804         var ser = JSON.stringifyNoSecurity(uids);
1805
1806         AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1807     },
1808
1809         /**
1810      * shows the import dialog with only relate visible.
1811      */
1812     showDetailView : function() {
1813         SE.contextMenus.emailListContextMenu.hide();
1814         var rows = SE.grid.getSelectedRows();
1815         if (rows.length > 1) {
1816                 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1817                 return;
1818         }
1819         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1820         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1821         /* iterate through available rows JIC a row is deleted - use first available */
1822         var uid = SE.grid.getRecord(rows[0]).getData().uid;
1823         SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1824     },
1825
1826     /**
1827      *
1828      */
1829     showEmailDetailViewInPopup : function(ieId,uid, folder) {
1830         overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1831         AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1832     },
1833
1834     /**
1835      * Opens multiple messages from ListView context click
1836      */
1837     openMultiple : function() {
1838         SE.contextMenus.emailListContextMenu.hide();
1839
1840         var rows = SE.grid.getSelectedRows();
1841         var uids = SE.listView.getUidsFromSelection();
1842
1843         if(uids.length > 0) {
1844             var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1845             var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1846             SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1847         }
1848     },
1849
1850     /**
1851      * Replies/forwards email
1852      */
1853     replyForwardEmailContext : function() {
1854         SE.contextMenus.emailListContextMenu.hide();
1855
1856         var indexes = SE.grid.getSelectedRows();
1857         //var dm = SE.grid.getDataModel();
1858         var type = this.id;
1859
1860         for(var i=0; i<indexes.length; i++) {
1861             var row = SE.grid.getRecord(indexes[i]).getData();
1862             SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1863         }
1864     },
1865
1866     //show menu functions
1867     showEmailsListMenu : function(grid, row) {
1868
1869        var data = row.getData();
1870        var draft = (data.type == "draft");
1871        var menu = SE.contextMenus.emailListContextMenu;
1872        var folderNode;
1873
1874        if (SE.tree)
1875        {
1876                if (data.mbox == 'sugar::Emails')
1877                    folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1878                else
1879                    folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1880
1881                if (  folderNode != null && typeof(folderNode) != "undefined"  && typeof(folderNode.data) != "undefined"
1882                    && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1883                   ||  (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1884                        menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1885                else
1886                    menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1887        }
1888        else
1889            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1890
1891        menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1892        menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1893        menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1894        menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1895        menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1896
1897
1898        if (data.mbox == "sugar::Emails")
1899        {
1900            //Allow users to reassign imported emails
1901            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1902            menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1903            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1904            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1905        }
1906        else
1907        {
1908            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1909            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1910        }
1911     },
1912
1913     showFolderMenu : function(grid, rowIndex, event) {
1914        event.stopEvent();
1915        var coords = event.getXY();
1916        SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1917     }
1918 };
1919
1920 SE.contextMenus.dv = {
1921     archiveToSugar : function(contextMenuId) {
1922
1923         SE.contextMenus._archiveToSugar(uids, ieId, folder);
1924     },
1925
1926     replyForwardEmailContext : function(all) {
1927         SE.contextMenus.detailViewContextMenu.hide();
1928     }
1929
1930 };
1931
1932
1933
1934
1935
1936 ////    END SE.contextMenus
1937 ///////////////////////////////////////////////////////////////////////////////
1938
1939
1940
1941 ///////////////////////////////////////////////////////////////////////////////
1942 ////    DETAIL VIEW
1943 SE.detailView = {
1944     consumeMetaDetail : function(ret) {
1945         // handling if the Email drafts
1946         if(ret.type == 'draft') {
1947             SE.composeLayout.c0_composeDraft();
1948             return;
1949         }
1950
1951
1952         // cache contents browser-side
1953         SE._setDetailCache(ret);
1954
1955         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1956         // 2 below must be in global context
1957         meta = ret.meta;
1958         meta['panelId'] = SE.util.getPanelId();
1959
1960         email = ret.meta.email;
1961         var out = displayTemplate.exec({
1962             'app_strings' : app_strings,
1963             'theme' : theme,
1964             'idx' : targetDiv.id,
1965             'meta' : meta,
1966             'email' : meta.email,
1967             'linkBeans' : linkBeans
1968         });
1969         var tabLabel = meta.email.name;
1970         if (tabLabel != null && tabLabel.length > 25) {
1971                 tabLabel = tabLabel.substring(0, 25) + "...";
1972         } // if
1973         targetDiv.set("label", tabLabel);
1974         targetDiv.set("content", out);
1975
1976         var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1977         if (SUGAR.email2.util.isIe()) {
1978                 displayEmailFrameDiv.style.height = "390px";
1979         } else {
1980                 displayEmailFrameDiv.style.height = "410px";
1981         }
1982
1983         var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1984         displayFrame.contentWindow.document.write(email.description);
1985         displayFrame.contentWindow.document.close();
1986
1987         // hide archive links
1988         if(ret.meta.is_sugarEmail) {
1989                         document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1990             document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1991         } else {
1992             if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1993                 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1994         } // else
1995
1996     },
1997
1998     consumeMetaPreview : function(ret) {
1999         // cache contents browser-side
2000         SE._setDetailCache(ret);
2001
2002
2003
2004         var currrow = SE.grid.getLastSelectedRecord();
2005         currrow = SE.grid.getRecord(currrow);
2006         if (!currrow) {
2007             document.getElementById('_blank').innerHTML = '';
2008             return;
2009         }
2010         // handling if the Email drafts
2011         if(ret.type == 'draft'){
2012             if (currrow.getData().uid == ret.uid) {
2013                 SE.composeLayout.c0_composeDraft();
2014             }
2015             return;
2016         }
2017
2018         if (currrow.getData().uid != ret.meta.uid) {
2019            return;
2020         }
2021
2022         // remove loading sprite
2023         document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2024         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2025         meta = ret.meta;
2026         meta['panelId'] = SE.util.getPanelId();
2027         email = ret.meta.email;
2028
2029         document.getElementById('_blank').innerHTML = displayTemplate.exec({
2030             'app_strings' : app_strings,
2031             'theme' : theme,
2032             'idx' : 'Preview',
2033             'meta' : meta,
2034             'email' :meta.email,
2035             'linkBeans' : linkBeans
2036         });
2037        // document.getElementById('_blank').innerHTML = meta.email;
2038        /* displayTemplate.append('_blank', {
2039             'app_strings' : app_strings,
2040             'theme' : theme,
2041             'idx' : 'Preview',
2042             'meta' : meta,
2043             'email' :meta.email,
2044             'linkBeans' : linkBeans
2045         });*/
2046
2047         var displayFrame = document.getElementById('displayEmailFramePreview');
2048         displayFrame.contentWindow.document.write(email.description);
2049         displayFrame.contentWindow.document.close();
2050
2051         SE.listViewLayout.resizePreview();
2052
2053         // hide archive links
2054         if(ret.meta.is_sugarEmail) {
2055             document.getElementById("archiveEmailPreview").innerHTML = "&nbsp;";
2056             document.getElementById("btnEmailViewPreview").style.display = "none";
2057             document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2058         } else {
2059           //hide view relationship link
2060                  document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2061         }
2062     },
2063
2064     /**
2065      * wraps emailDelete() for single messages, comes from preview or tab
2066      */
2067     emailDeleteSingle : function(ieId, uid, mbox) {
2068         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2069             // find active panel and close if the user double clicked the email to view.
2070             var activeTabId = SE.util.getPanelId();
2071             if(activeTabId != 'Preview')
2072                 SE.innerLayout.get("activeTab").close();
2073
2074             document.getElementById('_blank').innerHTML = "";
2075                 var ser = [ ];
2076                         ser.push(uid);
2077                 uid = JSON.stringifyNoSecurity(ser);
2078             this.emailDelete(ieId, uid, mbox);
2079         }
2080     },
2081
2082     /**
2083      * Sends async call to delete a given message
2084      * @param
2085      */
2086     emailDelete : function(ieId, uid, mbox) {
2087        overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2088        AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2089            uid + "&ieId=" + ieId + "&folder=" + mbox);
2090     },
2091
2092     /**
2093      * retrieves one email to display in the preview pane.
2094      */
2095     getEmailPreview : function() {
2096         var row = SUGAR.email2.listView.currentRow;
2097         var data = row.getData();
2098             if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2099                var setRead = (data['seen'] == 0) ? true : false;
2100                    SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2101                    SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2102             }
2103     },
2104
2105     /**
2106      * Imports one email into Sugar
2107      */
2108     importEmail : function(ieId, uid, mbox) {
2109         SE.util.clearHiddenFieldValues('emailUIForm');
2110
2111         overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2112
2113         var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2114         AjaxObject.target = '';
2115         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2116     },
2117
2118     /**
2119      * Populates the frameFlex div with the contents of an email
2120      */
2121     populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2122         SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2123
2124         var mboxStr = new String(mbox);
2125         var compKey = mbox + uid;
2126
2127         if(setRead == true) {
2128                 SE.listView.boldUnreadRows()
2129                 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2130         }
2131
2132         if(destination == SE.innerLayout) {
2133                 /*
2134              * loading email into a tab, peer with ListView
2135              * targetDiv must remain in the global namespace as it is used by AjaxObject
2136              */
2137                 //Check if we already have a tab of the email open
2138                 var tabs = SE.innerLayout.get("tabs");
2139                 for (var t in tabs) {
2140                         if (tabs[t].id && tabs[t].id == uid) {
2141                                 SE.innerLayout.set("activeTab", tabs[t]);
2142                                 return;
2143                         }
2144                 }
2145
2146                 targetDiv = new YAHOO.SUGAR.ClosableTab({
2147                                 label: loadingSprite,
2148                                         scroll : true,
2149                                         content : "",
2150                                         active : true
2151                 }, SE.innerLayout);
2152                 targetDiv.id = uid;
2153                 SE.innerLayout.addTab(targetDiv);
2154
2155             // use cache if available
2156             if(SE.cache[compKey]) {
2157                 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2158             } else {
2159                 // open email as peer-tab to listView
2160                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2161                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2162             }
2163         } else {
2164             // loading email into preview pane
2165             document.getElementById('_blank').innerHTML = loadingSprite;
2166
2167             // use cache if available
2168             if(SE.cache[compKey]) {
2169                 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2170             } else {
2171                 AjaxObject.forceAbort = true;
2172                 // open in preview window
2173                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2174                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2175             }
2176         }
2177     },
2178
2179     requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2180     {
2181         if(mboxStr.substring(0,7) == 'sugar::') {
2182             // display an email from Sugar
2183             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2184         } else {
2185             // display an email from an email server
2186             document.getElementById('emailUIAction').value = 'getSingleMessage';
2187         }
2188         document.getElementById('mbox').value = mbox;
2189         document.getElementById('ieId').value = ieId;
2190         document.getElementById('uid').value = uid;
2191
2192         YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2193
2194         AjaxObject.forceAbort = true;
2195         AjaxObject.target = '_blank';
2196         AjaxObject.startRequest(callback, null);
2197     },
2198
2199     /**
2200      * Retrieves multiple emails for DetailView
2201      */
2202     populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2203         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2204         SE.util.clearHiddenFieldValues('emailUIForm');
2205
2206         var mboxStr = new String(mbox);
2207
2208         uids = SE.util.cleanUids(uids);
2209
2210         if(mboxStr.substring(0,7) == 'sugar::') {
2211             // display an email from Sugar
2212             document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2213             document.getElementById('uid').value = uids;
2214         } else {
2215             // display an email from an email server
2216             document.getElementById('emailUIAction').value = 'getMultipleMessages';
2217             document.getElementById('mbox').value = mbox;
2218             document.getElementById('ieId').value = ieId;
2219             document.getElementById('uid').value = uids;
2220         }
2221
2222         var formObject = document.getElementById('emailUIForm');
2223         YAHOO.util.Connect.setForm(formObject);
2224
2225         AjaxObject.target = 'frameFlex';
2226         AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2227
2228         if(setRead == true) {
2229             var c = uids.split(",");
2230             SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2231         }
2232     },
2233
2234     /**
2235      * Makes async call to get QuickCreate form
2236      * Renders a modal edit view for a given module
2237      */
2238     quickCreate : function(module, ieId, uid, mailbox) {
2239         var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2240
2241         if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2242             get += "&sugarEmail=true";
2243         }
2244
2245         AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2246     },
2247
2248     /**
2249      * Makes async call to save a quick create
2250      * @param bool
2251      */
2252     saveQuickCreate : function(action) {
2253         var qcd = SE.detailView.quickCreateDialog;
2254         if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2255                 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2256                 var theCallback = callbackQuickCreateSave;
2257                 var accountType = '&sugarEmail=true';
2258                 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2259                    accountType = '&ieId=' + qcd.ieId;
2260                 }
2261
2262             if (action == 'reply') {
2263                    theCallback = callbackQuickCreateSaveAndReply;
2264                 } else if (action == true) {
2265                     theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2266                 }
2267                 formObject.action.value = 'EmailUIAjax';
2268                 YAHOO.util.Connect.setForm(formObject);
2269                 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2270                 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2271                                        accountType + '&mbox=' + qcd.mbox);
2272         }
2273     },
2274
2275     /**
2276      * Code to show/hide long list of email address in DetailView
2277      */
2278     showCroppedEmailList : function(el) {
2279         el.style.display = 'none';
2280         el.previousSibling.style.display = 'inline'
2281     },
2282     showFullEmailList : function(el) {
2283         el.style.display = 'none';
2284         el.nextSibling.style.display = 'inline';
2285     },
2286
2287     /**
2288      * Shows the QuickCreate overlay
2289      * @param string ieId
2290      * @param string uid
2291      * @param string mailbox
2292      */
2293     showQuickCreate : function(ieId, uid, mailbox) {
2294         var panelId = SE.util.getPanelId();
2295         var context = document.getElementById("quickCreateSpan" + panelId);
2296
2297         if (!SE.detailView.cqMenus)
2298                 SE.detailView.cqMenus = {};
2299
2300         if (SE.detailView.cqMenus[context])
2301                 SE.detailView.cqMenus[context].destroy();
2302
2303             var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2304                 lazyload:true,
2305                 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2306         });
2307
2308             for (var i=0; i < this.qcmodules.length; i++) {
2309             var module = this.qcmodules[i];
2310             menu.addItem({
2311                 text:   app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2312                 modulename: module,
2313                 value: module,
2314                 onclick: { fn: function() {
2315                                 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2316                         }
2317                 }
2318             });
2319         }
2320
2321                 menu.render(document.body);
2322                 menu.show();
2323     },
2324
2325     /**
2326      * Displays the "View" submenu in the detailView
2327      * @param string ieId
2328      * @param string uid
2329      * @param string mailbox
2330      */
2331     showViewMenu : function(ieId, uid, mailbox) {
2332         var panelId = SE.util.getPanelId();
2333         var context = "btnEmailView" + panelId;
2334         if (!SE.detailView.viewMenus)
2335                 SE.detailView.viewMenus = {};
2336
2337         if (SE.detailView.viewMenus[context])
2338                 SE.detailView.viewMenus[context].destroy();
2339
2340             var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2341                 lazyload:true,
2342                 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2343                 clicktohide: true
2344         });
2345                 menu.addItems(
2346                                 (ieId == 'null' || ieId == null) ?
2347                         //No ieId - Sugar Email
2348                         [{
2349                                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2350                                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2351             }]
2352                         :
2353                         //IeID exists, on a remote server
2354                         [{
2355                 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2356                 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2357             },{
2358                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2359                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2360             }]
2361         );
2362                 menu.render(document.body);
2363                 menu.show();
2364
2365
2366         /*
2367         //#23108 jchi@07/17/2008
2368         menu.render('quickCreateSpan'+ panelId);*/
2369         //this.viewMenu = menu;
2370         //this.viewMenu.show(context);
2371     },
2372     /**
2373      * Makes async call to get an email's headers
2374      */
2375     viewHeaders : function(ieId, uid, mailbox) {
2376         var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2377         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2378     },
2379
2380     /**
2381      * Makes async call to get a printable version
2382      */
2383     viewPrintable : function(ieId, uid, mailbox) {
2384         if(mailbox == 'sugar::Emails') {
2385             // display an email from Sugar
2386             var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2387         } else {
2388             // display an email from an email server
2389             var emailUIAction = '&emailUIAction=getSingleMessage';
2390         }
2391
2392         var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2393         AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2394     },
2395
2396     /**
2397      * Makes async call to get an email's raw source
2398      */
2399     viewRaw : function(ieId, uid, mailbox) {
2400         var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2401         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2402     },
2403
2404     /**
2405      * Display all email addresses in detailview.
2406      */
2407     displayAllAddrs : function(el) {
2408         el.style.display = 'none';
2409         Dom.getNextSibling(el).style.display = 'inline';
2410     }
2411 };
2412 ////    END SE.detailView
2413 ///////////////////////////////////////////////////////////////////////////////
2414
2415
2416
2417 ///////////////////////////////////////////////////////////////////////////////
2418 ////    SE.folders
2419 SE.folders = {
2420     contextMenuFocus : new Object(),
2421
2422     /**
2423      * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2424      * SugarFolder ID - folder strings
2425      */
2426     _createFolderId : function(node) {
2427         var ret = '';
2428
2429         if(!node.data.id)
2430             return ret;
2431
2432         if(node.data.ieId) {
2433             /* we have a local Sugar folder */
2434             if(node.data.ieId == 'folder') {
2435                 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2436             } else if(node.data.ieId.match(SE.reGUID)) {
2437                 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2438             }
2439         } else {
2440             ret = node.data.id;
2441         }
2442
2443         return ret;
2444     },
2445
2446     addChildNode : function(parentNode, childNode) {
2447         var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2448         var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2449         var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2450
2451         if(childNode.nodes) {
2452             if(childNode.nodes.length > 0) {
2453                 for(j=0; j<childNode.nodes.length; j++) {
2454                     var newChildNode = childNode.nodes[j];
2455                     this.addChildNode(node, newChildNode);
2456                 }
2457             }
2458         }
2459     },
2460
2461     /**
2462      * Builds and returns a new TreeView Node
2463      * @param string name
2464      * @param string id
2465      * @param int is_group
2466      * @return object
2467      */
2468     buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2469         var node = new YAHOO.widget.TextNode(name, parentNode, true);
2470
2471         //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2472         node.expanded = expanded;
2473         node.data = new Object;
2474         node.data['id'] = id;
2475         node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2476         node.data['label'] = name;
2477         node.data['ieId'] = 'folder';
2478         node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2479         node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2480         node.data['unseen'] = unseen;
2481         return node;
2482     },
2483
2484     /**
2485      * ensures that a new folder has a valid name
2486      */
2487     checkFolderName : function(name) {
2488         if(name == "")
2489             return false;
2490
2491         this.folderAdd(name);
2492     },
2493
2494     /**
2495      * Pings email servers for new email - forces refresh of folder pane
2496      */
2497     checkEmailAccounts : function() {
2498         this.checkEmailAccountsSilent(true);
2499     },
2500
2501     checkEmailAccountsSilent : function(showOverlay) {
2502         if(typeof(SE.folders.checkingMail)) {
2503             clearTimeout(SE.folders.checkingMail);
2504         }
2505
2506         // don't stomp an on-going request
2507         if(AjaxObject.currentRequestObject.conn == null) {
2508             if(showOverlay) {
2509                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2510                       app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2511             }
2512             AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2513         } else {
2514             // wait 5 secs before trying again.
2515             SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2516         }
2517     },
2518
2519     /**
2520      * Starts check of all email Accounts using a loading bar for large POP accounts
2521      */
2522     startEmailAccountCheck : function() {
2523         // don't do two checks at the same time
2524        if(!AjaxObject.requestInProgress()) {
2525             overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2526             SE.accounts.ieIds = SE.folders.getIeIds();
2527             if (SE.accounts.ieIds.length > 0) {
2528                 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2529                                 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "&currentCount=0");
2530             } else {
2531                hideOverlay();
2532             }
2533         } else {
2534             // wait 5 secs before trying again.
2535             SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2536         }
2537     },
2538
2539     /**
2540      * Checks a single Account check based on passed ieId
2541      */
2542      startEmailCheckOneAccount : function(ieId, synch) {
2543             if (synch) {
2544                 synch = true;
2545             } else {
2546                 synch = false;
2547             }
2548             var mbox = "";
2549             var node = SE.clickedFolderNode;
2550             if (node && !synch) {
2551                 mbox = node.data.mbox;
2552             } // if
2553             overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2554             SE.accounts.ieIds = [ieId];
2555             AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2556                                 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "&currentCount=0&synch=" + synch);
2557       },
2558
2559
2560     /**
2561      * Empties trash for subscribed accounts
2562      */
2563     emptyTrash : function() {
2564         SE.contextMenus.frameFoldersContextMenu.hide();
2565         overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2566         AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2567     },
2568
2569     /**
2570      * Clears Cache files of the inboundemail account
2571      */
2572     clearCacheFiles : function(ieId) {
2573         SE.contextMenus.frameFoldersContextMenu.hide();
2574         overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2575         AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2576     },
2577
2578
2579     /**
2580      * Returns an array of all the active accounts in the folder view
2581      */
2582     getIeIds : function() {
2583          var ieIds = [];
2584          var root = SE.tree.getRoot();
2585          for(i=0; i < root.children.length; i++) {
2586            if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2587                         (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2588                ieIds.push(root.children[i].children[0].data.ieId);
2589            }
2590          }
2591          return ieIds;
2592      },
2593
2594     /**
2595      * loads folder lists in Settings->Folders
2596      */
2597     lazyLoadSettings : function() {
2598         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2599         AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2600     },
2601
2602     /**
2603      * After the add new folder is done via folders tab on seetings, this function should get called
2604      * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2605      */
2606     loadSettingFolder : function() {
2607         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2608         AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2609     },
2610
2611     /**
2612      * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2613      */
2614     removeSugarFolders : function() {
2615         var tree = SE.tree;
2616         var root = tree.getRoot();
2617         var folder = SE.util.findChildNode(root, "ieId", "folder");
2618         while(folder) {
2619             tree.removeNode(folder);
2620             folder = SE.util.findChildNode(root, "ieId", "folder");
2621         }
2622         if (!root.childrenRendered) {
2623                 root.childrenRendered = true;
2624         }
2625     },
2626
2627     rebuildFolders : function(silent) {
2628       if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2629        AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2630     },
2631
2632
2633
2634     /**
2635      * Updates TreeView with Sugar Folders
2636      */
2637     setSugarFolders : function(delay) {
2638         this.removeSugarFolders();
2639                 //AjaxObject.forceAbort = true;
2640                 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2641     },
2642
2643     /**
2644      * Takes async data object and creates the sugar folders in TreeView
2645      */
2646     setSugarFoldersEnd : function(o) {
2647         var root = SE.tree.getRoot();
2648         addChildNodes(root, {nodes: o});
2649         SE.accounts.renderTree();
2650         //If nothing is loaded in the grid, load "My Inbox"
2651         if (SE.grid.params.ieId == "undefined") {
2652                 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2653         }
2654     },
2655
2656     startCheckTimer : function() {
2657         if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2658             var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2659
2660             if(typeof(SE.folders.checkTimer) != 'undefined') {
2661                 clearTimeout(SE.folders.checkTimer);
2662             }
2663
2664             SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2665             if (!SE.userPrefs.emailSettings.firstAutoCheck)
2666             {
2667                 SE.userPrefs.emailSettings.firstAutoCheck = true;
2668                 SE.folders.checkEmailAccountsSilent(false);
2669             }
2670         }
2671     },
2672
2673     /**
2674      * makes an async call to save user preference and refresh folder view
2675      * @param object SELECT list object
2676      */
2677     setFolderSelection : function() {
2678         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2679
2680         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2681         var a_active_accnts = "";
2682         for(i=0;i<a_rs.length;i++)
2683         {
2684                 var t_record = a_rs[i];
2685                 var is_active = t_record.getData('is_active');
2686                 if(is_active)
2687                         a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2688         }
2689
2690         if(a_active_accnts == "")
2691                 a_active_accnts = "&ieIdShow[]=";
2692
2693         var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2694
2695         AjaxObject.startRequest(callbackFolders, urlStandard + query);
2696     },
2697
2698     /**
2699      * makes async call to save user preference for a given node's open state
2700      * @param object node YUI TextNode object
2701      */
2702     setOpenState : function(node) {
2703         SE.util.clearHiddenFieldValues('emailUIForm');
2704         var nodePath = node.data.id;
2705         var nodeParent = node.parent;
2706
2707         while(nodeParent != null) {
2708             // root node has no ID param
2709             if(nodeParent.data != null) {
2710                 nodePath = nodeParent.data.id + "::" + nodePath;
2711             }
2712
2713             var nodeParent = nodeParent.parent;
2714         }
2715
2716         document.getElementById('emailUIAction').value = 'setFolderOpenState';
2717         document.getElementById('focusFolder').value = nodePath;
2718
2719         if(node.expanded == true) {
2720             document.getElementById('focusFolderOpen').value = 'open';
2721         } else {
2722             document.getElementById('focusFolderOpen').value = 'closed';
2723         }
2724
2725         var formObject = document.getElementById('emailUIForm');
2726         YAHOO.util.Connect.setForm(formObject);
2727
2728         AjaxObject.startRequest(null, null);
2729     },
2730
2731     getNodeFromMboxPath : function(path) {
2732         var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2733         var a = JSON.parse(path);
2734
2735         var node = tree.getRoot();
2736
2737         var i = 0;
2738         while(i < a.length) {
2739             node = this.getChildNodeFromLabel(node, a[i]);
2740             i++;
2741         }
2742
2743         return node;
2744     },
2745
2746     getChildNodeFromLabel : function(node, nodeLabel) {
2747         for(i=0; i<node.children.length; i++) {
2748             if(node.children[i].data.id == nodeLabel) {
2749                 return node.children[i];
2750             }
2751         }
2752     },
2753
2754     /**
2755      * returns the node that presumably under the user's right-click
2756      */
2757     getNodeFromContextMenuFocus : function() {
2758         //// get the target(parent) node
2759         var tree = YAHOO.widget.TreeView.trees.frameFolders;
2760         var index = -1;
2761         var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2762
2763         // filter local folders
2764         if(target.className == 'localFolder' || target.className == 'groupInbox') {
2765             while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2766                 if(target.id == '') {
2767                     target = target.parentNode;
2768                 } else {
2769                     break;
2770                 }
2771             }
2772         }
2773
2774         var targetNode = document.getElementById(target.id);
2775         re = new RegExp(/ygtv[a-z]*(\d+)/i);
2776
2777         try {
2778             var matches = re.exec(targetNode.id);
2779         } catch(ex) {
2780             return document.getElementById(ygtvlabelel1);
2781         }
2782
2783         if(matches) {
2784             index = matches[1];
2785         } else {
2786             // usually parent node
2787             matches = re.exec(targetNode.parentNode.id);
2788
2789             if(matches) {
2790                 index = matches[1];
2791             }
2792         }
2793
2794         var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2795         parentNode.expand();
2796
2797         return parentNode;
2798     },
2799
2800     /**
2801      * Decrements the Unread Email count in folder text
2802      * @param string ieId ID to look for
2803      * @param string mailbox name
2804      * @param count how many to decrement
2805      */
2806     decrementUnreadCount : function(ieId, mbox, count) {
2807
2808         if(mbox == null)
2809             return;
2810
2811         if(mbox.indexOf("sugar::") === 0) {
2812             var node = this.getNodeFromId(ieId);
2813         } else {
2814             var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2815         }
2816         if(node) {
2817             var unseen = node.data.unseen;
2818             if(unseen > 0) {
2819                 var check = unseen - count;
2820                 var finalCount = (check >= 0) ? check : 0;
2821                 node.data.unseen = finalCount;
2822             }
2823             SE.accounts.renderTree();
2824         }
2825     },
2826
2827     /**
2828      * gets the TreeView node with a given ID/ieId
2829      * @param string id ID to look for
2830      * @return object Node
2831      */
2832     getNodeFromId : function(id) {
2833         SE.folders.focusNode = null;
2834         SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2835             if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2836                 SE.folders.focusNode = this;
2837                 return false;
2838             }
2839         }, null, [id]);
2840         return SE.folders.focusNode;
2841     },
2842
2843     /**
2844      * Uses ieId and mailbox to try to find a node in the tree
2845      */
2846     getNodeFromIeIdAndMailbox : function(id, mbox) {
2847                 SE.folders.focusNode = null;
2848         if (mbox == "sugar::Emails") {
2849                 mbox = id;
2850                 id = "folder";
2851         } // if
2852         SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2853                 if (varsarray instanceof Array) {
2854             if (this.data.ieId && this.data.ieId == varsarray[0]
2855                     && this.data.mbox == varsarray[1]) {
2856                 SE.folders.focusNode = this;
2857                 return false;
2858             } }
2859                 else {
2860                         if (this.data.ieId && this.data.ieId == varsarray) {
2861                                 SE.folders.focusNode = this;
2862                     return false;
2863                         }
2864                 }
2865         }, null, [id, mbox]);
2866         return SE.folders.focusNode;
2867     },
2868
2869     unhighliteAll : function() {
2870         SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2871     },
2872
2873     /**
2874      * Displays a short form
2875      */
2876     folderAdd : function() {
2877         SE.contextMenus.frameFoldersContextMenu.hide();
2878
2879         var node = SE.clickedFolderNode;
2880
2881         if(node != null && node.data) {
2882             overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2883                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2884                     'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2885         } else {
2886             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2887         }
2888     },
2889
2890     folderAddRegisterEnter : function() {
2891         this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2892                                                                                                                         {keys: YAHOO.util.KeyListener.KEY.ENTER},
2893                                                                                                                         this.buttons[1].handler);
2894
2895                 this.enterKeyListener.enable();
2896     },
2897
2898     folderRemoveRegisterEnter : function() {
2899         this.enterKeyListener.disable();
2900     },
2901
2902     folderAddXmlCall : function(name) {
2903         if (trim(name) == "") {
2904                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2905                 return false;
2906         }
2907         name = escape(name);
2908         var post = '';
2909         var type = 'sugar';
2910
2911         var parentNode = SE.clickedFolderNode;
2912
2913         this.contextMenuFocus = parentNode;
2914
2915         if(parentNode.data.ieId) {
2916             if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2917                 type = 'imap';
2918             }
2919         }
2920         if(type == 'imap') {
2921                 // make an IMAP folder
2922             post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2923             AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2924         } else if(type == 'sugar') {
2925             // make a Sugar folder
2926             if(SE.folders.isUniqueFolderName(name)) {
2927                 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2928                 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2929             } else {
2930                 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2931                 SE.folders.folderAdd();
2932                 return;
2933             }
2934         } else {
2935             alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2936         }
2937
2938         // hide add-folder diaglogue
2939         SE.e2overlay.hide();
2940     },
2941
2942     /**
2943      * Removes either an IMAP folder or a Sugar Folder
2944      */
2945     folderDelete : function() {
2946         SE.contextMenus.frameFoldersContextMenu.hide();
2947
2948         if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2949             var post = '';
2950             var parentNode = SE.clickedFolderNode;
2951
2952             if(parentNode != null && parentNode.data) {
2953                 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2954                     overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2955                     return;
2956                 }
2957
2958                 AjaxObject.target = 'frameFlex';
2959
2960                 if(parentNode.data.ieId != 'folder') {
2961                     // delete an IMAP folder
2962                     post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2963                 } else {
2964                     // delete a sugar folder
2965                     post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2966                 }
2967                 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2968                 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2969             } else {
2970                 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2971             }
2972         }
2973     },
2974
2975     /**
2976      * Rename folder form
2977      */
2978      //EXT111
2979     folderRename : function() {
2980         SE.contextMenus.frameFoldersContextMenu.hide();
2981         var node = SE.clickedFolderNode;
2982
2983         if(node != null) {
2984             if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2985                 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2986                 return;
2987             }
2988
2989                         overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2990                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2991                     'prompt',
2992                     {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2993         } else {
2994             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2995         }
2996     },
2997
2998     /**
2999      * fills an Object with key-value pairs of available folders
3000      */
3001     getAvailableFoldersObject : function() {
3002         var ret = new Object();
3003         var tree = SE.tree.root;
3004
3005         if(tree.children) {
3006             for(var i=0; i<tree.children.length; i++) {
3007                 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3008             }
3009         } else {
3010             ret['none'] = app_strings.LBL_NONE;
3011         }
3012
3013         return ret;
3014     },
3015
3016     /**
3017      * Fills in key-value pairs for dependent dropdowns
3018      * @param object ret Associative array
3019      * @param object node TreeView node in focus
3020      * @param string currentPath Built up path thus far
3021      * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3022      */
3023     getFolderFromChild : function(ret, node, currentPath, spacer) {
3024         if(node.data != null && node.depth > 0) {
3025             /* handle visual separtors differentiating b/t mailserver and local */
3026             if(node.data.ieId && node.data.ieId == 'folder') {
3027                 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3028             }
3029
3030             if(!ret.spacer0) {
3031                 ret['spacer0'] = spacer;
3032             } else if(ret.spacer0 != spacer) {
3033                 ret['spacer1'] = spacer
3034             }
3035
3036             var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3037             var depthMarker = currentPath;
3038             var retIndex = SE.folders._createFolderId(node);
3039             ret[retIndex] = depthMarker + theLabel;
3040         }
3041
3042         if(node.children != null) {
3043             if(theLabel) {
3044                 currentPath += theLabel + "/";
3045             }
3046
3047             for(var i=0; i<node.children.length; i++) {
3048                 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3049             }
3050         }
3051
3052         return ret;
3053     },
3054
3055     /**
3056      * Wrapper to refresh folders tree
3057      */
3058     getFolders : function() {
3059         SE.accounts.rebuildFolderList();
3060     },
3061
3062     /**
3063      * handles events around folder-rename input field changes
3064      * @param object YUI event object
3065      */
3066     handleEnter : function(e) {
3067         switch(e.browserEvent.type) {
3068             case 'click':
3069                 e.preventDefault(); // click in text field
3070             break;
3071
3072             case 'blur':
3073                 SE.folders.submitFolderRename(e);
3074             break;
3075
3076             case 'keypress':
3077                 var kc = e.browserEvent.keyCode;
3078                 switch(kc) {
3079                     case 13: // enter
3080                         e.preventDefault();
3081                         SE.folders.submitFolderRename(e);
3082                     break;
3083
3084                     case 27: // esc
3085                         e.preventDefault(e);
3086                         SE.folders.cancelFolderRename(e);
3087                     break;
3088                 }
3089             break;
3090         }
3091     },
3092     /**
3093     * Called when a node is clicked on in the folder tree
3094     * @param node, The node clicked on
3095     * @param e, The click event
3096     */
3097     handleClick : function(o) {
3098         var node = o.node;
3099         //If the click was on a sugar folder
3100         if (node.data.ieId == "folder") {
3101             SE.listView.populateListFrameSugarFolder(node, node.id, false);
3102         }
3103         else {
3104             SE.listView.populateListFrame(node, node.data.ieId, false);
3105         }
3106        //eval(node.data.click);
3107        //debugger;
3108     },
3109
3110     /**
3111     * Called when a node is right-clicked on in the folder tree
3112     */
3113     handleRightClick : function(e) {
3114         YAHOO.util.Event.preventDefault(e);
3115                 //Get the Tree Node
3116                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3117                 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3118
3119                 //If the click was on a sugar folder
3120         SE.clickedFolderNode = node;
3121         var inbound = (node.data.ieId && node.data.ieId != 'folder');
3122                 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3123                 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3124                 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3125                 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3126                 menu.getItem(3).cfg.setProperty("disabled", false);
3127                 menu.getItem(4).cfg.setProperty("disabled", false);
3128                 menu.getItem(5).cfg.setProperty("disabled", false);
3129                 menu.getItem(6).cfg.setProperty("disabled", true);
3130                 //Group folder
3131                 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3132                         menu.getItem(0).cfg.setProperty("disabled", true);
3133                         menu.getItem(1).cfg.setProperty("disabled", true);
3134                         menu.getItem(2).cfg.setProperty("disabled", true);
3135                         menu.getItem(3).cfg.setProperty("disabled", true);
3136                         menu.getItem(4).cfg.setProperty("disabled", true);
3137                 }
3138         if (node.data.protocol != null) {
3139                 menu.getItem(6).cfg.setProperty("disabled", false);
3140         }
3141                 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3142                                 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3143                         //Sent or Draft folders
3144                         menu.getItem(3).cfg.setProperty("disabled", true);
3145                         menu.getItem(4).cfg.setProperty("disabled", true);
3146                         menu.getItem(5).cfg.setProperty("disabled", true);
3147                 }
3148
3149                 //For group with auto inbound, disable everything.
3150                 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3151                 {
3152                     menu.getItem(0).cfg.setProperty("disabled", true);
3153                 menu.getItem(1).cfg.setProperty("disabled", true);
3154                 menu.getItem(2).cfg.setProperty("disabled", true);
3155                 menu.getItem(3).cfg.setProperty("disabled", true);
3156                 menu.getItem(4).cfg.setProperty("disabled", true);
3157                 menu.getItem(5).cfg.setProperty("disabled", true);
3158                 menu.getItem(6).cfg.setProperty("disabled", true);
3159                 }
3160
3161                 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3162                 menu.show();
3163     },
3164
3165     /**
3166     * Called when a row is dropped on a node
3167     */
3168     handleDrop : function(rows, targetFolder) {
3169         var rowData = rows[0].getData();
3170         if (rowData.mbox != targetFolder.data.mbox) {
3171             var srcIeId = rowData.ieId;
3172             var srcFolder = rowData.mbox;
3173             var destIeId = targetFolder.data.ieId;
3174             var destFolder = targetFolder.data.mbox;
3175             var uids = [];
3176             for(var i=0; i<rows.length; i++) {
3177                 uids[i] = rows[i].getData().uid;
3178             }
3179             SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3180         }
3181     },
3182
3183     /**
3184     * Called when something is dragged over a Folder Node
3185     */
3186     dragOver : function(dragObject) {
3187        return true;
3188     },
3189
3190     /**
3191      * Determines if a folder name is unique to the folder tree
3192      * @param string name
3193      */
3194     isUniqueFolderName : function(name) {
3195         uniqueFolder = true;
3196         var root = SE.tree.getRoot();
3197         SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3198             if (this.attributes && this.attributes.ieId == "folder") {
3199                 if (this.attributes.text == name) {
3200                     uniqueFolder = false;
3201                     return false;
3202                 }
3203             }
3204         }, null, [name]);
3205         return uniqueFolder;
3206     },
3207
3208     /**
3209      * Makes async call to rename folder in focus
3210      * @param object e Event Object
3211      */
3212     submitFolderRename : function(newName) {
3213         if (trim(newName) == "") {
3214                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3215                 return false;
3216         }
3217                 newName = escape(newName);
3218         var node = SE.clickedFolderNode;
3219         var origName = node.data.text
3220         //Ignore no change
3221         if (newName == origName) {
3222             return true;
3223         }
3224         if(SE.folders.isUniqueFolderName(newName)) {
3225             overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3226             if (node.data.ieId == "folder") {
3227                 //Sugar Folder
3228                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3229             }
3230             else {
3231                 //IMAP folder or POP mailbox
3232                 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3233                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3234                     + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3235             }
3236             return true;
3237         } else {
3238             alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3239             return false;
3240         }
3241     },
3242
3243     moveFolder : function(folderId, parentFolderId) {
3244         if (folderId != parentFolderId)
3245         {
3246                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3247                     + folderId + "&newParentId=" + parentFolderId);
3248         }
3249     },
3250
3251     /**
3252      * makes async call to do a full synchronization of all accounts
3253      */
3254     synchronizeAccounts : function() {
3255         if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3256             overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3257             AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3258         }
3259     },
3260
3261     /**
3262      * Updates user's folder subscriptsion (Sugar only)
3263      * @param object SELECT DOM object in focus
3264      * @param string type of Folder selection
3265      */
3266     updateSubscriptions : function() {
3267         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3268
3269         var active = "";
3270
3271         select = document.getElementById('userFolders');
3272
3273         for(i=0; i<select.options.length; i++) {
3274             var opt = select.options[i];
3275              if(opt.selected && opt.value != "") {
3276                  if(active != "") {
3277                      active += "::";
3278                  }
3279                  active += opt.value;
3280              }
3281         }
3282
3283         //Add the group folder ids.
3284         var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3285         for(i=0; i<group_folders.length; i++)
3286         {
3287             active += ("::" + group_folders[i]);
3288         }
3289
3290         AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3291     },
3292     /**
3293      * Updates user's group folder subscriptsion (Sugar only)
3294      * @param ieID The group folder to add to the tree view
3295      */
3296     retrieveGroupFolderSubscriptions : function() {
3297
3298         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3299         var activeGroupFolders = "";
3300         var activeGroupIds = [];
3301         for(i=0;i<a_rs.length;i++)
3302         {
3303                 var t_record = a_rs[i];
3304                 var is_active = t_record.getData('is_active');
3305                 var isGroupFolder = t_record.getData('has_groupfolder');
3306                 var ieID = t_record.getData('id');
3307                 if( isGroupFolder )
3308                 {
3309                     if(is_active)
3310                       activeGroupIds.push(ieID);
3311                 }
3312         }
3313
3314         return activeGroupIds;
3315     }
3316
3317 };
3318
3319 SE.folders.checkEmail2 = function() {
3320     AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3321 }
3322 ////    END FOLDERS OBJECT
3323 ///////////////////////////////////////////////////////////////////////////////
3324
3325
3326 ///////////////////////////////////////////////////////////////////////////////
3327 ////    SE.keys
3328 /**
3329  * Keypress Event capture and processing
3330  */
3331 SE.keys = {
3332     overall : function(e) {
3333         switch(e.charCode) {
3334             case 119: // "w"
3335                 if(e.ctrlKey || e.altKey) {
3336                     var focusRegion = SE.innerLayout.regions.center;
3337                     if(focusRegion.activePanel.closable == true) {
3338                         focusRegion.remove(focusRegion.activePanel);
3339                     }
3340                 }
3341             break;
3342         }
3343     }
3344 };
3345 ////    END SE.keys
3346 ///////////////////////////////////////////////////////////////////////////////
3347
3348
3349 ///////////////////////////////////////////////////////////////////////////////
3350 ////    SE.listView
3351 /**
3352  * ListView object methods and attributes
3353  */
3354 SE.listView = {
3355     currentRowId : -1,
3356
3357     /**
3358      * Fills the ListView pane with detected messages.
3359      */
3360     populateListFrame : function(node, ieId, forceRefresh) {
3361         SE.innerLayout.selectTab(0);
3362                 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3363
3364         Dom.get('_blank').innerHTML = "";
3365         SE.grid.params['emailUIAction'] = 'getMessageList';
3366         SE.grid.params['mbox'] = node.data.mbox;
3367         SE.grid.params['ieId'] = ieId;
3368         forcePreview = true; // loads the preview pane with first item in grid
3369         SE.listView.refreshGrid();
3370     },
3371
3372     /**
3373      * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3374      */
3375     populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3376         SE.innerLayout.selectTab(0);
3377         Dom.get('_blank').innerHTML = "";
3378         SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3379         SE.grid.params['ieId'] = node.data.id;
3380         SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3381         SE.listView.refreshGrid();
3382     },
3383
3384     /**Mac
3385      * Sets sort order as user preference
3386      * @param
3387      */
3388     saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3389         ieId = ieIdPassed;
3390         ieName = ieNamePassed;
3391         focusFolder = focusFolderPassed;
3392
3393         SE.util.clearHiddenFieldValues('emailUIForm');
3394         var previousSort = document.getElementById('sortBy').value;
3395
3396         document.getElementById('sortBy').value = sortBy;
3397         document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3398         document.getElementById('focusFolder').value = focusFolder;
3399         document.getElementById('ieId').value = ieId;
3400
3401         if(sortBy == previousSort) {
3402             document.getElementById('reverse').value = '1';
3403         }
3404
3405         var formObject = document.getElementById('emailUIForm');
3406         YAHOO.util.Connect.setForm(formObject);
3407
3408         AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3409     },
3410
3411
3412     /**
3413      * Enables click/arrow select of grid items which then populate the preview pane.
3414      */
3415     selectFirstRow : function() {
3416         SE.grid.selModel.selectFirstRow();
3417     },
3418
3419     selectLastRow : function() {
3420         SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3421     },
3422
3423     setEmailListStyles : function() {
3424         SE.listView.boldUnreadRows();
3425         return;
3426         var ds = SE.grid.getStore();
3427         if (SE.grid.getSelections().length == 0) {
3428             document.getElementById('_blank').innerHTML = '';
3429         }
3430
3431         var acctMbox = '';
3432         if(typeof(ds.baseParams.mbox) != 'undefined') {
3433             acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3434             var cm = SE.grid.getColumnModel();
3435             if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3436                 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3437                 //SE.grid.render();
3438             } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3439                 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3440                 //SE.grid.render();
3441             }
3442         }
3443         var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3444         SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3445
3446
3447         // 4/20/2007 added to hide overlay after search
3448         //hideOverlay();
3449         if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3450             var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3451             var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3452             if (node) node.data.unseen = unread;
3453         }
3454         SE.accounts.renderTree();
3455
3456
3457         // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3458         if(forcePreview && ds.totalCount > 0) {
3459             SE.detailView.getEmailPreview();
3460             forcePreview = false;
3461         }
3462     },
3463
3464     /**
3465      * Removes a row if found via its UID
3466      */
3467     removeRowByUid : function(uid) {
3468         uid = new String(uid);
3469         uids = uid.split(',');
3470         var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3471
3472         for(j=0; j<uids.length; j++) {
3473             var theUid = uids[j];
3474             for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3475                 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3476                         SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3477                 }
3478             } // for
3479         }
3480     },
3481
3482     displaySelectedEmails : function(rows) {
3483         var dm = SE.grid.getDataModel();
3484         var uids = '';
3485
3486         for(i=0; i<rows.length; i++) {
3487             var rowIndex = rows[i].rowIndex;
3488             var metadata = dm.data[rowIndex];
3489
3490             if(uids != "") {
3491                 uids += ",";
3492             }
3493             uids += metadata[5];
3494
3495             // unbold unseen email
3496             this.unboldRow(rowIndex);
3497         }
3498
3499         SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3500     },
3501
3502     /**
3503      * exception handler for data load failures
3504      */
3505     loadException : function(dataModel, ex, response) {
3506         //debugger;
3507     },
3508
3509     /**
3510      * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3511      * @param string sourceIeId Email's source I-E id
3512      * @param string sourceFolder Email's current folder
3513      * @param destinationIeId Destination I-E id
3514      * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3515      *
3516      * @param array emailUids Array of email's UIDs
3517      */
3518     moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3519         if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3520             overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3521         } else {
3522             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3523             // remove rows from visibility
3524             for(row in selectedRows) {
3525                 //SE.grid.getStore().remove(row);
3526             }
3527
3528             var baseUrl =    '&sourceIeId=' + sourceIeId +
3529                             '&sourceFolder=' + sourceFolder +
3530                             '&destinationIeId=' + destinationIeId +
3531                             '&destinationFolder=' + destinationFolder;
3532             var uids = '';
3533
3534             for(i=0; i<emailUids.length; i++) {
3535                 if(uids != '') {
3536                     uids += app_strings.LBL_EMAIL_DELIMITER;
3537                 }
3538                 uids += emailUids[i];
3539             }
3540             if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3541                 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3542             } else {
3543                 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3544             }
3545         }
3546     },
3547
3548     /**
3549      * Unbolds text in the grid view to denote read status
3550      */
3551     markRead : function(index, record) {
3552         // unbold unseen email
3553         var row = SE.grid.getRecord(record);
3554         row.getData().seen = 1;
3555         SE.grid.getTrEl(record).style.fontWeight = "normal";
3556     },
3557
3558     /**
3559      * grid row output, bolding unread emails
3560      */
3561     boldUnreadRows : function() {
3562         // bold unread emails
3563         var trEl = SE.grid.getFirstTrEl();
3564         while(trEl != null) {
3565                 if(SE.grid.getRecord(trEl).getData().seen == "0")
3566                         trEl.style.fontWeight = "bold";
3567                 else
3568                         trEl.style.fontWeight = "";
3569                 trEl = SE.grid.getNextTrEl(trEl);
3570         }
3571     },
3572
3573     /**
3574      * Show preview for an email if 1 and only 1 is selected
3575      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3576      */
3577     handleRowSelect : function(e) {
3578         if(e.selectedRows.length == 1) {
3579             SE.detailView.getEmailPreview();
3580         }
3581     },
3582
3583     handleDrop : function(e, dd, targetId, e2) {
3584         switch(targetId) {
3585             case 'htmleditordiv':
3586                 var rows = SE.grid.getSelectedRows();
3587                 if(rows.length > 0) {
3588                     SE.listView.displaySelectedEmails(rows);
3589                 }
3590             break;
3591
3592             default:
3593                 var targetElId = new String(targetId);
3594                 var targetIndex = targetElId.replace('ygtvlabelel',"");
3595                 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3596                 var dm = SE.grid.getDataModel();
3597                 var emailUids = new Array();
3598                 var destinationIeId = targetNode.data.ieId;
3599                 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3600
3601
3602                 var rows = SE.grid.getSelectedRows();
3603                 // iterate through dragged rows
3604                 for(i=0; i<rows.length; i++) {
3605                     //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3606                     var rowIndex = rows[i].rowIndex;
3607                     var dataModelRow = dm.data[rowIndex];
3608                     var sourceIeId = dataModelRow[7];
3609                     var sourceFolder = dataModelRow[6];
3610                     emailUids[i] = dataModelRow[5];
3611                 }
3612
3613                 // event wrapped call - need FQ
3614                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3615                 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3616             break;
3617         }
3618     },
3619
3620     /**
3621      * Hack-around to get double-click and single clicks to work on the grid
3622      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3623      */
3624     handleClick : function(o) {
3625         SUGAR.email2.grid.clearTextSelection();
3626
3627         var el = SUGAR.email2.grid.getSelectedRows();
3628
3629         //Load an email preview only if a single record is selected.  For multiple selections do nothing.
3630         if ( el.length == 1)
3631         {
3632            var rowId = el[0];
3633            SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3634            SUGAR.email2.listView.currentRowIndex = rowId;
3635            clearTimeout(SUGAR.email2.detailView.previewTimer);
3636            SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3637         }
3638     },
3639
3640     /**
3641      * Custom handler for double-click/enter
3642      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3643      */
3644     getEmail : function(e) {
3645         var rows = SE.grid.getSelectedRows();
3646         var row = SE.grid.getRecord(rows[0]).getData();
3647
3648         clearTimeout(SE.detailView.previewTimer);
3649         document.getElementById("_blank").innerHTML = "";
3650
3651         if(row.type != "draft") {
3652             SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3653         } else {
3654             // circumventing yui-ext tab generation, let callback handler build new view
3655             SE.util.clearHiddenFieldValues('emailUIForm');
3656             //function(uid, mbox, ieId, setRead, destination) {
3657             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3658             document.getElementById('uid').value = row.uid; // uid;
3659             document.getElementById('mbox').value = row.mbox; // mbox;
3660             document.getElementById('ieId').value = row.ieId; // ieId;
3661
3662             YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3663             AjaxObject.target = '_blank';
3664             AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3665         }
3666     },
3667
3668     /**
3669      * Retrieves a row if found via its UID
3670      * @param string
3671      * @return int
3672      */
3673     getRowIndexByUid : function(uid) {
3674         uid = new String(uid);
3675         uids = uid.split(',');
3676
3677         for(j=0; j<uids.length; j++) {
3678             var theUid = uids[j];
3679
3680             for(i=0; i<SE.grid.getStore().data.length; i++) {
3681                 if(SE.grid.getStore().data[i].id == theUid) {
3682                     return i;
3683                 }
3684             }
3685         }
3686     },
3687
3688     /**
3689      * Returns the UID's of the seleted rows
3690      *
3691      */
3692      getUidsFromSelection : function() {
3693          var rows = SE.grid.getSelectedRows();
3694          var uids = [];
3695          /* iterate through available rows JIC a row is deleted - use first available */
3696          for(var i=0; i<rows.length; i++) {
3697                  uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3698          }
3699          return uids;
3700      },
3701
3702     refreshGrid : function() {
3703         SE.grid.getDataSource().sendRequest(
3704             SUGAR.util.paramsToUrl(SE.grid.params),
3705                 SE.grid.onDataReturnInitializeTable,
3706                 SE.grid
3707         );
3708     }
3709
3710 };
3711 ////    END SE.listView
3712 ///////////////////////////////////////////////////////////////////////////////
3713
3714 ///////////////////////////////////////////////////////////////////////////////
3715 ////    SEARCH
3716 SE.search = {
3717     /**
3718      * sends search criteria
3719      * @param reference element search field
3720      */
3721     search : function(el) {
3722         var searchCriteria = new String(el.value);
3723
3724         if(searchCriteria == '') {
3725             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3726             return false;
3727         }
3728
3729         var safeCriteria = escape(searchCriteria);
3730
3731         var accountListSearch = document.getElementById('accountListSearch');
3732         //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3733
3734         SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3735         SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3736         SE.grid.getStore().baseParams['subject'] = safeCriteria;
3737         SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3738         SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3739
3740     },
3741
3742     /**
3743      * sends advanced search criteria
3744      */
3745     searchAdvanced : function() {
3746         var formObject = document.getElementById('advancedSearchForm');
3747         var search = false;
3748
3749         //Set assigned user id to blank if name is not present.
3750         if (formObject.elements['assigned_user_name'].value == "")
3751             formObject.elements['assigned_user_id'].value = "";
3752
3753         for(i=0; i<formObject.elements.length; i++) {
3754             if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3755                 search = true;
3756             }
3757             if(formObject.elements[i].type == 'text') {
3758                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3759             }
3760             if(formObject.elements[i].type == 'hidden') {
3761                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3762             }
3763              if(formObject.elements[i].type == 'select-one') {
3764                 var el = formObject.elements[i];
3765                 var v = el.options[el.selectedIndex].value;
3766
3767                 if(v != "")
3768                     SE.grid.params[el.name] = v;
3769                 else
3770                 {
3771                     //Clear previous search results if necessary
3772                     if(typeof( SE.grid.params[el.name]) != 'undefined')
3773                         delete SE.grid.params[el.name]
3774                 }
3775              }
3776         }
3777
3778         if (search)
3779         {
3780             if(! this.validateSearchFormInput() )
3781                 return;
3782
3783                 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3784                 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3785                 var accountListSearch = document.getElementById('accountListSearch');
3786                 SE.listView.refreshGrid();
3787         } else {
3788             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3789         }
3790     },
3791
3792     /**
3793     *  Validates the search form inputs to ensure all parameters are valid
3794     *  @return bool
3795     */
3796     validateSearchFormInput: function()
3797     {
3798         addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3799         addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3800         var dateCheck = check_form('advancedSearchForm');
3801
3802         //If the parent type is selected ensure the user selected a parent_id.
3803         if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3804             return true;
3805         else
3806             return false;
3807     },
3808     /**
3809     *   Toggles the advanced options, either hidding or showing the selection.
3810     */
3811     toggleAdvancedOptions: function()
3812     {
3813         var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3814
3815         for(var i=0;i<el.length;i++)
3816         {
3817             if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3818                 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3819             else
3820                 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3821         }
3822     },
3823     /**
3824      * clears adv search form fields
3825      */
3826     searchClearAdvanced : function() {
3827         var form = document.getElementById('advancedSearchForm');
3828
3829         for(i=0; i<form.elements.length; i++) {
3830             if(form.elements[i].type != 'button') {
3831                 form.elements[i].value = '';
3832             }
3833         }
3834     }
3835 };
3836 ////    END SE.search
3837 //////////////////////////////////////////////////////////////////////////////
3838
3839
3840 //////////////////////////////////////////////////////////////////////////////
3841 ////    SE.settings
3842 SE.settings = {
3843     /******************************************************************************
3844      * USER SIGNATURES calls stolen from Users module
3845      *****************************************************************************/
3846     createSignature : function(record, the_user_id) {
3847         var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3848         if(record != "") {
3849             URL += "&record="+record;
3850         }
3851         if(the_user_id != "") {
3852             URL += "&the_user_id="+the_user_id;
3853         }
3854         var windowName = 'email_signature';
3855         var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3856
3857         var win = window.open(URL, windowName, windowFeatures);
3858         if(win && win.focus) {
3859             // put the focus on the popup if the browser supports the focus() method
3860             win.focus();
3861         }
3862     },
3863
3864     deleteSignature : function() {
3865         if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3866             overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3867                 var singature_id = document.getElementById('signature_id').value;
3868                 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3869         } // if
3870     },
3871
3872     saveOptionsGeneral :  function(displayMessage) {
3873         var formObject = document.getElementById('formEmailSettingsGeneral');
3874         if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3875                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3876                 return false;
3877         } // if
3878         YAHOO.util.Connect.setForm(formObject);
3879         SE.composeLayout.emailTemplates = null;
3880
3881         AjaxObject.target = 'frameFlex';
3882         AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3883
3884         if(displayMessage)
3885             alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3886
3887         SE.settings.settingsDialog.hide();
3888     },
3889
3890     /**
3891      * Shows settings container screen
3892      */
3893     showSettings : function() {
3894         if(!SE.settings.settingsDialog) {
3895                 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3896                 modal:true,
3897                 visible:false,
3898                 fixedcenter:true,
3899                 draggable: false,
3900                 width:"800px",
3901                                 constraintoviewport: true
3902             });
3903                         dlg.showEvent.subscribe( function (){
3904                                 var el = this.element;
3905                                 var viewH = YAHOO.util.Dom.getViewportHeight();
3906                 if (this.header && el && viewH - 50 < el.clientHeight) {
3907                     var body = this.header.nextElementSibling;
3908                                         body.style.overflow = "auto";
3909                     body.style.height = (viewH - 50) + "px";
3910                 }
3911             }, dlg);
3912                 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3913                 dlg.setBody('<div id="settingsTabDiv"/>');
3914                 dlg.beforeRenderEvent.subscribe(function() {
3915                         var dd = new YAHOO.util.DDProxy(dlg.element);
3916                         dd.setHandleElId(dlg.header);
3917                         dd.on('endDragEvent', function() {
3918                                 dlg.show();
3919                         });
3920                 }, dlg, true);
3921                 dlg.render();
3922
3923                 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3924                         var tabContent = Dom.get("tab_general");
3925                 tp.addTab(new YAHOO.widget.Tab({
3926                                 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3927                                 scroll : true,
3928                                 content :  tabContent.innerHTML,
3929                                 id : "generalSettings",
3930                                 active : true
3931                         }));
3932                 tabContent.parentNode.removeChild(tabContent);
3933                 tabContent = Dom.get("tab_accounts");
3934                 var accountTab = new YAHOO.widget.Tab({
3935                                 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3936                                 scroll : true,
3937                                 content : tabContent.innerHTML,
3938                                 id : "accountSettings"
3939                         });
3940                 tp.addTab(accountTab);
3941                 tabContent.parentNode.removeChild(tabContent);
3942
3943                         tp.appendTo(dlg.body);
3944         }
3945
3946         SE.settings.settingsDialog.show();
3947         SE.folders.lazyLoadSettings();
3948         SE.accounts.lazyLoad();
3949     },
3950
3951
3952     lazyLoadRules : function() {
3953         if(false/*!SE.settings.rules*/) {
3954             AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3955         }
3956
3957     }
3958 };
3959 ////    END SE.settings
3960 ///////////////////////////////////////////////////////////////////////////////
3961 })();
3962
3963 /******************************************************************************
3964  * UTILITIES
3965  *****************************************************************************/
3966 function removeHiddenNodes(nodes, grid) {
3967     var el;
3968         for(var i = nodes.length - 1; i > -1; i--) {
3969         el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3970         if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3971                 nodes.splice(i,1);
3972        }
3973     }
3974 }
3975
3976 function strpad(val) {
3977     return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3978 };
3979
3980 function refreshTodos() {
3981     SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3982     AjaxObject.target = 'todo';
3983     AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3984 };
3985
3986 /******************************************************************************
3987  * MUST STAY IN GLOBAL NAMESPACE
3988  *****************************************************************************/
3989 function refresh_signature_list(signature_id, signature_name) {
3990     var field=document.getElementById('signature_id');
3991     var bfound=0;
3992     for (var i=0; i < field.options.length; i++) {
3993             if (field.options[i].value == signature_id) {
3994                 if (field.options[i].selected==false) {
3995                     field.options[i].selected=true;
3996                 }
3997                 bfound=1;
3998             }
3999     }
4000     //add item to selection list.
4001     if (bfound == 0) {
4002         var newElement=document.createElement('option');
4003         newElement.text=signature_name;
4004         newElement.value=signature_id;
4005         field.options.add(newElement);
4006         newElement.selected=true;
4007     }
4008
4009     //enable the edit button.
4010     var field1=document.getElementById('edit_sig');
4011     field1.style.visibility="inherit";
4012     var deleteButt = document.getElementById('delete_sig');
4013     deleteButt.style.visibility="inherit";
4014 };
4015
4016 function setDefaultSigId(id) {
4017     var checkbox = document.getElementById("signature_default");
4018     var default_sig = document.getElementById("signatureDefault");
4019
4020     if(checkbox.checked) {
4021         default_sig.value = id;
4022     } else {
4023         default_sig.value = "";
4024     }
4025 };
4026
4027 function setSigEditButtonVisibility() {
4028     var field = document.getElementById('signature_id');
4029     var editButt = document.getElementById('edit_sig');
4030     var deleteButt = document.getElementById('delete_sig');
4031     if(field.value != '') {
4032         editButt.style.visibility = "inherit";
4033         deleteButt.style.visibility = "inherit";
4034     } else {
4035         editButt.style.visibility = "hidden";
4036         deleteButt.style.visibility = "hidden";
4037     }
4038 }// End of File modules/Emails/javascript/EmailUI.js
4039                                 
4040 /*********************************************************************************
4041  * SugarCRM Community Edition is a customer relationship management program developed by
4042  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4043  * 
4044  * This program is free software; you can redistribute it and/or modify it under
4045  * the terms of the GNU Affero General Public License version 3 as published by the
4046  * Free Software Foundation with the addition of the following permission added
4047  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4048  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4049  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4050  * 
4051  * This program is distributed in the hope that it will be useful, but WITHOUT
4052  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4053  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
4054  * details.
4055  * 
4056  * You should have received a copy of the GNU Affero General Public License along with
4057  * this program; if not, see http://www.gnu.org/licenses or write to the Free
4058  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4059  * 02110-1301 USA.
4060  * 
4061  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4062  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4063  * 
4064  * The interactive user interfaces in modified source and object code versions
4065  * of this program must display Appropriate Legal Notices, as required under
4066  * Section 5 of the GNU Affero General Public License version 3.
4067  * 
4068  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4069  * these Appropriate Legal Notices must retain the display of the "Powered by
4070  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4071  * technical reasons, the Appropriate Legal Notices must display the words
4072  * "Powered by SugarCRM".
4073  ********************************************************************************/
4074
4075  (function() {
4076         var sw = YAHOO.SUGAR,
4077                 Event = YAHOO.util.Event,
4078                 Connect = YAHOO.util.Connect,
4079             Dom = YAHOO.util.Dom
4080             SE = SUGAR.email2;
4081
4082 ///////////////////////////////////////////////////////////////////////////////
4083 ////    ADDRESS BOOK
4084 SE.addressBook = {
4085     _contactCache : new Array(), // cache of contacts
4086     _dd : new Array(), // filtered list, same format as _contactCache
4087     _ddLists : new Array(), // list of Lists
4088     _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4089     _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4090     clickBubble : true, // hack to get around onclick event bubbling
4091         relatedBeanId : '',
4092         relatedBeanType : '',
4093         idx : 0,
4094
4095     itemSpacing : 'white-space:nowrap; padding:2px;',
4096     reGUID : SE.reGUID,
4097
4098
4099
4100     /**
4101     *  YUI bug fix 2527707.  Causes nested datatable's in <tables> to cause 404 errors whens earching.
4102     */
4103     initFixForDatatableSort: function () {
4104         //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4105         YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4106             var oColumn = this._oColumnSet.getColumn(column);
4107
4108             if(!oColumn) {
4109                 // Validate TD element
4110                 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4111                 if(elCell) {
4112                     oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4113                 }
4114                 // Validate TH element
4115                 else {
4116                     elCell = this.getThEl(column);
4117                     if(elCell) {
4118                         // Find by TH el ID
4119                         var allColumns = this._oColumnSet.flat;
4120                         for(var i=0, len=allColumns.length; i<len; i++) {
4121                             if(allColumns[i].getThEl().id === elCell.id) {
4122                                 oColumn = allColumns[i];
4123                             }
4124                         }
4125                     }
4126                 }
4127             }
4128
4129             return oColumn;
4130         };
4131     },
4132
4133     cancelEdit : function() {
4134         if(this.editContactDialog)
4135             this.editContactDialog.hide();
4136         if(this.editMailingListDialog)
4137             this.editMailingListDialog.hide();
4138     },
4139
4140     /**
4141      * Clears filter form
4142      */
4143     clear : function() {
4144         var t = document.getElementById('contactsFilter');
4145         t.value = '';
4146         this.filter(t);
4147     },
4148
4149     /**
4150      * handle context-menu Compose-to call
4151      * @param string type 'contacts' or 'lists'
4152      */
4153     composeTo : function(type, waited) {
4154         var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4155         if (activePanel.substring(0, 10) != "composeTab") {
4156             SE.composeLayout.c0_composeNewEmail();
4157             setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4158                 SE.contextMenus.contactsContextMenu.hide();
4159             return;
4160         }
4161         var idx = activePanel.substring(10);
4162         var rows = [ ];
4163         var id = '';
4164         // determine if we have a selection to work with
4165         if(type == 'contacts') {
4166             var ids = SE.contactView.getSelectedRows();
4167             for (var i in ids) {
4168                 rows[i] = SE.contactView.getRecord(ids[i]);
4169             }
4170             removeHiddenNodes(rows, SE.contactView);
4171         }
4172                 else { return; }
4173
4174         if(rows.length > 0) {
4175             SE.composeLayout.handleDrop(
4176                 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4177                 null, rows, 'addressTO' + idx );
4178         } else {
4179             alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4180         }
4181     },
4182
4183     editContact : function() {
4184         SE.contextMenus.contactsContextMenu.hide();
4185         var element = SE.contactView.getSelectedNodes()[0];
4186         var elementId = "";
4187         if (element.className.indexOf('address-contact') > -1) {
4188             elementId = element.id;
4189         } else if (element.className.indexOf('address-exp-contact') > -1) {
4190             elementId = element.id.substring(2);
4191         }
4192     },
4193
4194
4195     /**
4196      * Filters contact entries based on user input
4197      */
4198     filter : function(inputEl) {
4199         var ret = new Object();
4200         var re = new RegExp(inputEl.value, "gi");
4201
4202         for(var i in this._contactCache) {
4203             if(this._contactCache[i].name.match(re)) {
4204                 ret[i] = this._contactCache[i];
4205             }
4206         }
4207
4208         this.buildContactList(ret);
4209     },
4210
4211     fullForm : function(id, module) {
4212         document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4213     },
4214
4215     /**
4216      * returns a formatted email address from the addressBook cache
4217      */
4218     getFormattedAddress : function(id) {
4219         var o = this._contactCache[id];
4220         var primaryEmail = '';
4221
4222         for(var i=0; i<o.email.length; i++) {
4223             var currentEmail = o.email[i].email_address;
4224
4225             if(o.email[i].primary_address == 1) {
4226                 primaryEmail = o.email[i].email_address;
4227             }
4228         }
4229
4230         var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4231         var name = new String(o.name);
4232         var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/&#039;/gi,'\'');
4233         var ret = finalName + " <" + finalEmail.replace(/&#039;/gi,'\'') + ">";
4234
4235         return ret;
4236     },
4237
4238     /**
4239      * Sets up async call to query for matching contacts, users, etc.
4240      */
4241     searchContacts : function() {
4242         var fn = document.getElementById('input_searchField').value;
4243         var pe = document.getElementById('input_searchPerson').value;
4244
4245         var rb = document.getElementById('hasRelatedBean').checked;
4246         if (rb) {
4247                         var idx = this.idx;
4248                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4249                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4250                 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4251                 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4252         } else {
4253                 this.addressBookDataModel.params['related_bean_id'] = '';
4254         }
4255
4256         this.addressBookDataModel.params['search_field'] = fn;
4257         this.addressBookDataModel.params['person'] = pe;
4258         this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4259         this.grid._oDataSource = this.addressBookDataModel;
4260         this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params),  this.grid.onDataReturnInitializeTable, this.grid);
4261     },
4262
4263     /**
4264      * Clear Search Crieteria For Addressbook
4265      */
4266     clearAddressBookSearch : function() {
4267         document.getElementById('input_searchField').value = "";
4268         document.getElementById('input_searchPerson').selectedIndex = 0;
4269     },
4270
4271     /**
4272      * Opens modal select window to add contacts to addressbook
4273      */
4274     selectContactsDialogue : function(destId) {
4275         if(!this.contactsDialogue) {
4276                 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4277                 modal:true,
4278                 visible:false,
4279                 draggable: false,
4280                 constraintoviewport: true,
4281                 width   : 980,
4282                 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4283                            {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4284             });
4285                 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4286
4287                 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4288                 dlg.setBody(body.innerHTML);
4289                 dlg.renderEvent.subscribe(function() {
4290                 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4291                 if (iev && !SUGAR.isIE) {
4292                         this.body.style.width = "950px";
4293                 }
4294             }, dlg);
4295
4296
4297                 dlg.beforeRenderEvent.subscribe(function() {
4298                         var dd = new YAHOO.util.DDProxy(dlg.element);
4299                         dd.setHandleElId(dlg.header);
4300                         dd.on('endDragEvent', function() {
4301                                 dlg.show();
4302                         });
4303                 }, dlg, true);
4304                 dlg.render();
4305
4306                 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4307
4308                 var tabContent = SUGAR.util.getAndRemove("searchForm");
4309                 tp.addTab(new YAHOO.widget.Tab({
4310                                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4311                                 scroll : true,
4312                                 content : tabContent.innerHTML,
4313                                 id : "addressSearchTab",
4314                                 active : true
4315                         }));
4316
4317                 var addListenerFields = ['input_searchPerson','input_searchField' ]
4318                 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4319                         if (e.keyCode == 13) {
4320                                 YAHOO.util.Event.stopEvent(e);
4321                                 SUGAR.email2.addressBook.searchContacts();
4322                         }
4323                 });
4324
4325                 this.contactsDialogue.render();
4326                 dlg.center();
4327         }
4328         //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4329         if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4330             var idx = 0;
4331         else
4332         {
4333             var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4334             var idx = activePanel.substring(10);
4335         }
4336         SE.addressBook.idx = idx;
4337
4338                 var relatedBeanId;
4339         if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4340                 document.getElementById('relatedBeanColumn').style.display = '';
4341                 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4342                         var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4343                         relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4344                         document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4345                         SE.addressBook.relatedBeanType = relatedBeanType;
4346             } else {
4347                 document.getElementById('relatedBeanColumn').style.display = 'none';
4348                 document.getElementById('hasRelatedBean').checked = false;
4349             }
4350
4351             if (!SE.addressBook.grid)
4352             {
4353                 if (hasRelatedBeanId) {
4354                         document.getElementById('hasRelatedBean').checked = true;
4355                 }
4356                 AddressSearchGridInit();
4357                         SE.addressBook.relatedBeanId = relatedBeanId;
4358             }
4359             else
4360             {
4361                 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4362                 {
4363                         SE.addressBook.relatedBeanId = relatedBeanId;
4364                         document.getElementById('hasRelatedBean').checked = true;
4365                 }
4366                 if (document.getElementById('hasRelatedBean').checked == true)
4367                 {
4368                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4369                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4370                 } else {
4371                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4372                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4373                 }
4374                 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4375                         SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4376                 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params),  SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4377             }
4378
4379             //Remove any lingering rows in the result set table if the module was closed.
4380             SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4381             //Repopulate
4382             SE.addressBook.populateResulstTableEmailAddresses();
4383
4384         this.contactsDialogue.show();
4385     },
4386     /**
4387     *  Clear all email addresses from result table.
4388     *
4389     */
4390     clearAllEmailAddressFieldsFromResultTable: function () {
4391         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4392         //Unhighlight any rows currently selected if the emails were cleared.
4393         SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4394         SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4395     },
4396     /**
4397     *  Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4398     *  results table.  This function is called when the address book is displayed.
4399     */
4400     populateResulstTableEmailAddresses: function () {
4401
4402         var idx = SE.addressBook.idx;
4403         var emailFields = ['to','cc','bcc'];
4404
4405         for(var k=0;k<emailFields.length;k++)
4406         {
4407             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4408             var allEmails = document.getElementById(elKey).value;
4409             if(allEmails == '')
4410                 continue;
4411
4412             var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4413
4414                 for (var i=0; i<formatedEmails.length; i++)
4415                 {
4416                     var t_name = formatedEmails[i].name;
4417                     var t_emailAddr = formatedEmails[i].email_address;
4418                     var displayEmail = t_name + ' <' + t_emailAddr + '>';
4419                     if(t_name == '')
4420                         t_name = displayEmail = t_emailAddr;
4421
4422                     var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4423                 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4424                     'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4425                 }
4426         }
4427     },
4428
4429     /**
4430     * Checks all entries in the result table against a particular email address, returning true
4431     * if the email address is found, false otherwise.
4432     */
4433     doesEmailAdddressExistInResultTable: function(emailAddress)
4434     {
4435         if(trim(emailAddress) == '')
4436             return false;
4437
4438         var emailAddressFound = false;
4439         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4440         for (var i=0; i < contacts.length; i++)
4441         {
4442             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4443             //If we are adding to cc or bcc fields, make them visible.
4444             if(data.email_address == emailAddress)
4445             {
4446                 emailAddressFound = true;
4447                 break;
4448             }
4449         }
4450
4451         return emailAddressFound;
4452     },
4453     /**
4454     *  Takes all email addresses that the users wishes to add from the address book and populates the To
4455     *  fields on the compose tab.
4456     */
4457     populateEmailAddressFieldsFromResultTable: function()
4458     {
4459         //Clear the fields first, all email addresses are stored in the address book
4460         var idx = SE.addressBook.idx;
4461         var emailFields = ['to','cc','bcc'];
4462         for(var k=0;k<emailFields.length;k++)
4463         {
4464             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4465             document.getElementById(elKey).value = "";
4466         }
4467
4468         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4469         for (var i=0; i < contacts.length; i++)
4470         {
4471             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4472
4473             var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4474             //If we are adding to cc or bcc fields, make them visible.
4475             if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4476                 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4477             //Construct the target id
4478             var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4479
4480             var target = document.getElementById(target_id);
4481             target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4482         }
4483
4484         //Delete all rows from the result set table
4485         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4486
4487         //Hide the dialogue
4488         SE.addressBook.contactsDialogue.hide()
4489     },
4490     /**
4491     *  Insert contacts into the result table.
4492     */
4493     insertContactToResultTable : function(event,address_type) {
4494
4495         var contactsDialogue = SE.addressBook.contactsDialogue;
4496         var contacts = SE.addressBook.grid.getSelectedRows();
4497
4498         var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4499         for (var i = 0; i < rows.length; i++)
4500         {
4501                         if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4502                         {
4503                             var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4504                 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4505                 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4506                 rows[i].setData("selected",true);
4507                         }
4508         }
4509         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4510         for (var i = 0; i < checkBoxes.length; i++) {
4511             checkBoxes[i].checked = false;
4512         }
4513     },
4514     /**
4515     *
4516     */
4517     insertContactRowToResultTable : function(rowId, addressType) {
4518         var data = SE.addressBook.grid.getRecord(rowId).getData();
4519         if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4520                 return;
4521         var name = data.name.replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
4522         var ea = name + ' <' + data.email.replace(/&#039;/gi,'\'') + '>';
4523         if(addressType == null)
4524             addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4525         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});
4526     },
4527     /**
4528     * Remove a row from the gridsResult table.
4529     */
4530     removeRowFromGridResults : function(rowId,emailAddress)
4531     {
4532         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4533         for (var i=0; i < contacts.length; i++)
4534         {
4535             var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4536             var data = rec.getData();
4537             if(data.email_address == emailAddress)
4538             {
4539                 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4540                 break;
4541             }
4542         }
4543
4544        SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4545     },
4546     /**
4547     * Translates between the addressType To|Cc|Bcc labels/keys.
4548     */
4549     translateAddresType: function(addressType,fromKey)
4550     {
4551         var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4552         var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4553         var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4554         var mappingObject = {};
4555
4556         if(fromKey)
4557             mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4558         else
4559         {
4560             mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4561             mappingObject[displayCc] = 'cc';
4562             mappingObject[displayBcc] = 'bcc';
4563         }
4564
4565         return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4566
4567     },
4568     /**
4569     *
4570     */
4571     toggleSearchRowIcon : function(rowId,show)
4572     {
4573         if(show)
4574         {
4575             var idToShow = rowId + '_add_img';
4576             var idToHide = rowId + '_rm_img';
4577         }
4578         else
4579         {
4580             var idToShow = rowId + '_rm_img';
4581             var idToHide = rowId + '_add_img';
4582         }
4583
4584
4585         Dom.addClass(idToHide, "yui-hidden");
4586         Dom.removeClass(idToShow, "yui-hidden");
4587     },
4588     /**
4589     * Determine if an entry has already been added to the grid results table to prevent duplicates.
4590     */
4591     doesGridResultsEntryExist: function(emailAddrs)
4592     {
4593
4594         var contactExists = false;
4595         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4596         for (var i=0; i < contacts.length; i++)
4597         {
4598             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4599             if(data.email_address == emailAddrs)
4600             {
4601                 contactExists = true;
4602                 break;
4603             }
4604         }
4605         return contactExists;
4606     },
4607
4608     /**
4609      * adds an email address to a string, but first checks if it exists
4610      * @param string concat The string we are appending email addresses to
4611      * @param string addr Email address to add
4612      * @return string
4613      */
4614     smartAddEmailAddressToComposeField : function(concat, addr) {
4615         var re = new RegExp(addr);
4616
4617         if(!concat.match(re)) {
4618             if(concat != "") {
4619                 concat += "; " + addr;
4620             } else {
4621                 concat = addr;
4622             }
4623         }
4624
4625         return concat;
4626     }
4627 };
4628 ////    END ADDRESS BOOK
4629 ///////////////////////////////////////////////////////////////////////////////
4630
4631
4632
4633 ///////////////////////////////////////////////////////////////////////////////
4634 ////    AUTOCOMPLETE
4635 /**
4636  * Auto-complete object
4637  */
4638 SE.autoComplete = {
4639     config : {
4640         delimChar : [";", ","],
4641         useShadow :    false,
4642         useIFrame : false,
4643         typeAhead : true,
4644         prehighlightClassName : "yui-ac-prehighlight",
4645         queryDelay : 0
4646     },
4647     instances : new Array(),
4648
4649     /**
4650      * Parses an addressBook entry looking for primary address.  If not found, it will return the last found address.
4651      * @param object Contact from AddressBook
4652      * @return string
4653      */
4654     getPrimaryAddress : function(contact) {
4655         var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4656
4657         for(var eIndex in contact.email) {
4658             address = contact.email[eIndex].email_address;
4659             if(contact.email[eIndex].primary_address == 1) {
4660                 return contact.email[eIndex].email_address;
4661             }
4662         }
4663         return address;
4664     },
4665
4666
4667     /**
4668      * initializes autocomplete widgets for a given compose view
4669      * @param int idx
4670      */
4671     init : function(idx) {
4672         var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4673             "queryMatchContains" : false,
4674             "queryMatchSubset" : true
4675         });
4676
4677         this.instances[idx] = {
4678             to : null,
4679             cc : null,
4680             bcc : null
4681         };
4682
4683
4684         // instantiate the autoComplete widgets
4685         this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4686         this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4687         this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4688
4689         // enable hiding of interfering textareas
4690         this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4691         this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4692         this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4693
4694         // enable reshowing of hidden textareas
4695         this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4696         this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4697         this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4698
4699         // enable refreshes of contact lists
4700         this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4701         this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4702         this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4703     },
4704
4705     refreshDataSource : function(sType, aArgs) {
4706         var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4707         var idx;
4708         var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4709
4710         if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4711             idx = textBoxId.substr(9);
4712         } else {
4713             idx = textBoxId.substr(10);
4714         }
4715
4716         SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4717         SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4718         SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4719     },
4720
4721     /**
4722      * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4723      */
4724     returnDataSource : function(contacts) {
4725         var ret = new Array();
4726         for(var id in contacts) {
4727             if (contacts[id].name) {
4728                     var primary = this.getPrimaryAddress(contacts[id]);
4729
4730                     ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4731                     //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4732
4733                     for(var emailIndex in contacts[id].email) {
4734                         ret[ret.length] = contacts[id].email[emailIndex].email_address;
4735                     }
4736             }
4737         }
4738
4739         return ret;
4740     },
4741
4742     /**
4743      * Hides address textareas to prevent autocomplete dropdown from being obscured
4744      */
4745     toggleTextareaHide : function(sType, aArgs) {
4746         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4747         var type = "";
4748         var idx = -1;
4749
4750         if(textBoxId.indexOf("addressTO") > -1) {
4751             type = "to";
4752         } else if(textBoxId.indexOf("addressCC") > -1) {
4753             type = "cc";
4754         }
4755         idx = textBoxId.substr(9);
4756
4757         // follow through if not BCC
4758         if(type != "") {
4759             var cc = document.getElementById("addressCC" + idx);
4760             var bcc = document.getElementById("addressBCC" + idx);
4761
4762             switch(type) {
4763                 case "to":
4764                     cc.style.visibility = 'hidden';
4765                 case "cc":
4766                     bcc.style.visibility = 'hidden';
4767                 break;
4768             }
4769         }
4770     },
4771
4772     /**
4773      * Redisplays the textareas after an address is commited
4774      */
4775     toggleTextareaShow : function(sType, aArgs) {
4776         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4777         var type = "";
4778         var idx = -1;
4779
4780         if(textBoxId.indexOf("addressTO") > -1) {
4781             type = "to";
4782         } else if(textBoxId.indexOf("addressCC") > -1) {
4783             type = "cc";
4784         }
4785         idx = textBoxId.substr(9);
4786
4787         // follow through if not BCC
4788         if(type != "") {
4789             document.getElementById("addressCC" + idx).style.visibility = 'visible';
4790             document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4791         }
4792     }
4793 };
4794
4795 ////    END AUTOCOMPLETE
4796 ///////////////////////////////////////////////////////////////////////////////
4797
4798 ///////////////////////////////////////////////////////////////////////////////
4799 ////    COMPOSE & SEND
4800 /**
4801  * expands the options sidebar
4802  */
4803 SE.composeLayout = {
4804     currentInstanceId : 0,
4805     ccHidden : true,
4806     bccHidden : true,
4807     outboundAccountErrors : null,
4808     loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4809
4810     showAddressDetails : function(e) {
4811         var linkElement = document.getElementById("More"+e.id);
4812         var spanElement = document.getElementById("Detail"+e.id);
4813         var emailAddressList = e.value;
4814         if(e.value.length > 96)
4815         {
4816                 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4817             var displayArray = [];
4818                 for (var i=0; i<resultArray.length; i++)
4819                 {
4820                     var t_name = resultArray[i].name;
4821                     var t_emailAddr = resultArray[i].email_address;
4822                     if(t_name == '')
4823                        displayArray.push('<br/>&lt;' + t_emailAddr + '&gt;');
4824                     else
4825                        displayArray.push(t_name + '<br/>&lt;' + t_emailAddr + '&gt;');
4826                 }
4827
4828             var result = displayArray.join('<br/>');
4829                 // Display
4830             linkElement.style.display = "inline";
4831             linkElement.style.height="10px";
4832             linkElement.style.overflow="visible";
4833             spanElement.innerHTML = result;
4834         }
4835         else
4836                 linkElement.style.display = "none";
4837
4838         },
4839
4840    /**
4841     *  Given a string of email address, return an array containing the name portion (if available)
4842     *  and email portion.
4843     */
4844     _getEmailArrayFromString : function (emailAddressList){
4845
4846         var reg = /@.*?;/g;
4847         while ((results = reg.exec(emailAddressList)) != null)
4848         {
4849             orignial = results[0];
4850             parsedResult = results[0].replace(';', ':::::');
4851             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4852         }
4853
4854         reg = /@.*?,/g;
4855         while ((results = reg.exec(emailAddressList)) != null)
4856         {
4857             orignial = results[0];
4858             parsedResult = results[0].replace(',', ':::::');
4859             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4860         }
4861         //Administrator <johndoe@som.com>  ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4862         var emailArr = emailAddressList.split(":::::");
4863         var resultsArray = [];
4864         var newArr = [];
4865         for (var i=0; i<emailArr.length; i++)
4866         {
4867             var rposition = emailArr[i].indexOf('<');
4868             var lposition = emailArr[i].indexOf('>');
4869
4870             if(trim(emailArr[i]) != '')
4871             {
4872                 if(rposition != -1 && lposition != -1)
4873                 {
4874                     var t_name = emailArr[i].substr(0, rposition-1);
4875                     var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4876                     resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4877                 }
4878                 else
4879                 {
4880                     resultsArray.push({'name':'', 'email_address': emailArr[i]});
4881                 }
4882             }
4883         }
4884         return resultsArray;
4885     },
4886     ///////////////////////////////////////////////////////////////////////////
4887     ////    COMPOSE FLOW
4888     /**
4889      * Prepare bucket DIV and yui-ext tab panels
4890      */
4891     _0_yui : function() {
4892         var idx = this.currentInstanceId;
4893
4894         var composeTab = new YAHOO.SUGAR.ClosableTab({
4895                         label: mod_strings.LNK_NEW_SEND_EMAIL,
4896                                 scroll : true,
4897                                 content : "<div id='htmleditordiv" + idx + "'/>",
4898                                 id : "composeTab" + idx,
4899                                 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4900                                 active : true
4901         }, SE.innerLayout);
4902         SE.innerLayout.addTab(composeTab);
4903
4904         // get template engine with template
4905         if (!SE.composeLayout.composeTemplate) {
4906                 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4907         }
4908
4909         // create Tab inner layout
4910         var composePanel =  this.getComposeLayout();
4911         composePanel.getUnitByPosition("right").collapse();
4912         composePanel.autoSize();
4913
4914     },
4915         /**
4916      * Generate the quick compose layout
4917          * @method getQuickComposeLayout
4918          * @param {Pannel} parentPanel Parent pannel
4919          * @param {Object} o Options
4920          * @return {} none
4921          **/
4922     getQuickComposeLayout : function (parentPanel,o) {
4923          var idx = SE.composeLayout.currentInstanceId;
4924
4925          //Before rendering the parent pannel we need to initalize the grid layout
4926          parentPanel.beforeRenderEvent.subscribe(function() {
4927
4928                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4929                         SE.composeLayout._createComposeLayout(idx);
4930                         SE.composeLayout[idx].set('height', 350);
4931                         SE.composeLayout[idx].render();
4932            });
4933         });
4934
4935          //Wait until the Compose Layout has rendered, then add the
4936          //options tab and perform the tiny initialization.
4937          parentPanel.renderEvent.subscribe(function() {
4938
4939                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4940                 SE.composeLayout._initComposeOptionTabs(idx);
4941                 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4942                 //Initialize tinyMCE
4943                 if (!SUGAR.util.isTouchScreen())
4944                     SE.composeLayout._1_tiny();
4945                 //Init templates and address book
4946                 SE.composeLayout._2_final();
4947
4948             SE.composeLayout.quickCreateComposePackage(o);
4949
4950                 });
4951          });
4952
4953             //Check if we have the div override for the shortcut bar
4954         if(typeof o.menu_id != 'undefined') {
4955                    parentPanel.render(o.menu_id);
4956             } else {
4957                    parentPanel.render(document.body);
4958             }
4959
4960         return SE.composeLayout[idx];
4961     },
4962     /**
4963      * Fill in all fields into the quick compose layout.
4964          * @method quickCreateComposePackage
4965          * @param {Object} o Options
4966          * @return {} none
4967          **/
4968     quickCreateComposePackage: function(o)
4969     {
4970         //If we have a compose package fill in defaults.
4971         if (typeof(o.composePackage) != 'undefined')
4972         {
4973             composePackage = o.composePackage; //Set the compose data object
4974             //Hijack this method called by composePackage as it's not need for quick creates.
4975             SE.composeLayout.c0_composeNewEmail = function(){};
4976             SE.composeLayout.composePackage(); //Fill in defaults.
4977         }
4978     },
4979     getComposeLayout : function() {
4980         var idx = SE.composeLayout.currentInstanceId;
4981
4982         this._createComposeLayout(idx);
4983         SE.composeLayout[idx].render();
4984         this._initComposeOptionTabs(idx);
4985
4986         return SE.composeLayout[idx];
4987         },
4988
4989         /**
4990         *       Create the layout manager for the compose window.
4991         */
4992         _createComposeLayout : function(idx)
4993         {
4994                 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
4995                 parent: SE.complexLayout,
4996                 border:true,
4997             hideOnLayout: true,
4998             height: 400,
4999                         units: [{
5000                                         position: "center",
5001                         animate: false,
5002                         scroll: false,
5003                         split:true,
5004                         body:
5005                                 SE.composeLayout.composeTemplate.exec({
5006                                 'app_strings':app_strings,
5007                                 'mod_strings':mod_strings,
5008                                 'theme': theme,
5009                                 'linkbeans_options' : linkBeans,
5010                                 'idx' : SE.composeLayout.currentInstanceId
5011                                 })
5012                     },{
5013                         position: "right",
5014                                     scroll:true,
5015                                     collapse: true,
5016                                     collapsed: true,
5017                                     resize: true,
5018                                     border:true,
5019                                     animate: false,
5020                                     width:'230',
5021                                     body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5022                                     titlebar: true,
5023                                     split: true,
5024                                     header: app_strings.LBL_EMAIL_OPTIONS
5025                     }]
5026                 });
5027         },
5028
5029         /**
5030         *  Create compose tab which will populate the 'right' container in the compose window.
5031         */
5032         _initComposeOptionTabs : function(idx)
5033         {
5034                 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5035                 var tab = new YAHOO.widget.Tab({
5036                                 label: app_strings.LBL_EMAIL_ATTACHMENT,
5037                                 scroll : true,
5038                                 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5039                                 id : "divAttachments" + idx,
5040                                 active : true
5041                         });
5042
5043                 tab.layout = SE.composeLayout[idx];
5044
5045            tab.on("activeChange", function(o){
5046                         if (o.newValue) {
5047                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5048                         }
5049                 });
5050
5051                 cTabs.addTab(tab);
5052
5053                 tab = new YAHOO.widget.Tab({
5054                                 label: app_strings.LBL_EMAIL_OPTIONS,
5055                                 scroll : true,
5056                                 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5057                                 id : "divOptions" + idx,
5058                                 active : false
5059                         });
5060
5061                 tab.layout = SE.composeLayout[idx];
5062                 tab.on("activeChange", function(o){
5063                         if (o.newValue) {
5064                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5065                         }
5066                 });
5067                 cTabs.addTab(tab);
5068
5069                 SE.composeLayout[idx].autoSize = function() {
5070                         var pEl = this.get("element").parentNode.parentNode.parentNode;
5071                         this.set("height", pEl.clientHeight-30);
5072                         this.render();
5073                 }
5074
5075                 SE.composeLayout[idx].rightTabs = cTabs;
5076     },
5077     isParentTypeValid : function(idx) {
5078                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5079                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5080                 if (trim(parentTypeValue) == ""){
5081                         alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5082                         return false;
5083                 } // if
5084                 return true;
5085     },
5086
5087     isParentTypeAndNameValid : function(idx) {
5088                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5089                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5090                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5091                 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5092                         (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5093                                 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5094                         return false;
5095                 } // if
5096                 return true;
5097     },
5098
5099     callopenpopupForEmail2 : function(idx,options) {
5100
5101         var formName = 'emailCompose' + idx;
5102
5103         if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5104             formName = options.form_name;
5105
5106                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5107                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5108                 if (!SE.composeLayout.isParentTypeValid(idx)) {
5109                         return;
5110                 } // if
5111                 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5112                 {
5113                         call_back_function:"SE.composeLayout.popupAddEmail",
5114                         form_name:formName,
5115                         field_to_name_array:{
5116                                 id:'data_parent_id' + idx,
5117                                 name:'data_parent_name' + idx,
5118                                 email1:'email1'}
5119                 });
5120         },
5121
5122         popupAddEmail : function(o)
5123         {
5124                 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5125                 var data = o.name_to_value_array;
5126                 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5127                         && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5128         {
5129                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5130                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5131         }
5132                 set_return(o);
5133         },
5134     /**
5135      * Prepare TinyMCE
5136      */
5137     _1_tiny : function() {
5138         var idx = SE.composeLayout.currentInstanceId;
5139         var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5140         SE.tinyInstances[elId] = { };
5141         SE.tinyInstances[elId].ready = false;
5142         var t = tinyMCE.getInstanceById(elId);
5143
5144         if(typeof(t) == 'undefined')  {
5145             tinyMCE.execCommand('mceAddControl', false, elId);
5146             YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5147                 SE.composeLayout.resizeEditor(idx);
5148                 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
5149             }, this);
5150         }
5151     },
5152
5153     resizeEditor : function(idx)
5154     {
5155         var cof = Dom.get('composeOverFrame' + idx);
5156         var head = Dom.get('composeHeaderTable' + idx);
5157         var targetHeight = cof.clientHeight - head.clientHeight;
5158         var instance =  tinyMCE.get(SE.tinyInstances.currentHtmleditor);
5159
5160         var parentEl = Dom.get(instance.editorId + '_parent');
5161         var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5162         var contentEl  = instance.contentAreaContainer;
5163         var iFrame = contentEl.firstChild;
5164         var tinMceToolbarOffset = 18;
5165         iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset)  + "px";
5166     },
5167
5168     /**
5169      * Initializes d&d, auto-complete, email templates
5170      */
5171     _2_final : function() {
5172         var idx = SE.composeLayout.currentInstanceId;
5173
5174         if(this.emailTemplates) {
5175             this.setComposeOptions(idx);
5176         } else {
5177             //populate email template cache
5178             AjaxObject.target = '';
5179             AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5180         }
5181
5182         // handle drop targets for addressBook
5183        var to =  new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5184        var cc =  new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5185        var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5186        to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5187
5188         // auto-complete setup
5189         SE.autoComplete.init(idx);
5190
5191         // set focus on to:
5192         document.getElementById("addressTO" + idx).focus();
5193     },
5194
5195         /**
5196      * hide tinyMCE tool bar if send email as plaintext is checked
5197      */
5198     renderTinyMCEToolBar : function (idx, hide) {
5199         if (hide) {
5200                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5201         } else {
5202                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5203         }
5204     },
5205
5206     c1_composeEmail : function(isReplyForward, retry) {
5207         if (!retry) {
5208             this._0_yui();
5209         }
5210         if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5211             setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5212         } else {
5213                 this._1_tiny();
5214                 this._2_final();
5215
5216                 if(isReplyForward) {
5217                     this.replyForwardEmailStage2();
5218                 }
5219         }
5220     },
5221
5222     /**
5223      * takes draft info and prepopulates
5224      */
5225     c0_composeDraft : function() {
5226         this.getNewInstanceId();
5227         inCompose = true;
5228         document.getElementById('_blank').innerHTML = '';
5229         var idx = SE.composeLayout.currentInstanceId;
5230                 SE.composeLayout.draftObject = new Object();
5231                 SE.composeLayout.draftObject.id = idx;
5232                 SE.composeLayout.draftObject.isDraft = true;
5233         SE.composeLayout.currentInstanceId = idx;
5234         SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5235         SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5236         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5237
5238         SE.composeLayout._0_yui();
5239         SE.composeLayout._1_tiny();
5240
5241         // final touches
5242         SE.composeLayout._2_final();
5243
5244         /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5245         setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5246     },
5247
5248     /**
5249      * Strip & Prep editor hidden fields
5250      */
5251     c0_composeNewEmail : function() {
5252         this.getNewInstanceId();
5253         this.c1_composeEmail(false);
5254     },
5255
5256     /**
5257      * Sends async request to get the compose view.
5258      * Requests come from "reply" or "forwards"
5259      */
5260     c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5261         SE.composeLayout.replyForwardObj = new Object();
5262         SE.composeLayout.replyForwardObj.ieId = ieId;
5263         SE.composeLayout.replyForwardObj.uid = uid;
5264         SE.composeLayout.replyForwardObj.mbox = mbox;
5265         SE.composeLayout.replyForwardObj.type = type;
5266
5267         if(mbox == 'sugar::Emails') {
5268             SE.composeLayout.replyForwardObj.sugarEmail = true;
5269         }
5270
5271         SE.composeLayout.getNewInstanceId();
5272         SE.composeLayout.c1_composeEmail(true);
5273     },
5274     ////    END COMPOSE FLOW
5275     ///////////////////////////////////////////////////////////////////////////
5276
5277     /**
5278      * Called when a contact, email, or mailinglist is dropped
5279      * into one of the compose fields.
5280      */
5281     handleDrop : function (source, event, data, target) {
5282         var nodes;
5283         if (!target) {
5284             target = event.getTarget();
5285             if (data.single) {
5286                 data.nodes = [data.nodes];
5287             }
5288             nodes = data.nodes;
5289         } else {
5290             target = document.getElementById(target);
5291             nodes = data;
5292         }
5293
5294         if (target.id.indexOf('address') > -1) {
5295             // dropped onto email to/cc/bcc field
5296             for(var i in nodes) {
5297                 var node = nodes[i].getData();
5298                 var email = "";
5299                 if (node[1].indexOf('contact') > -1) {
5300                     email = SE.addressBook.getFormattedAddress(node[0]);
5301                 } else if (node[1].indexOf('address-email') > -1){
5302                     email = node[3].replace(/&nbsp;/gi, '');
5303                     email = email.replace('&lt;', '<').replace('&gt;', '>');
5304                     var tr = source.getTrEl(nodes[i]);
5305                     while (tr && !Dom.hasClass(tr, "address-contact")) {
5306                         tr = source.getPreviousTrEl(tr);
5307                     }
5308                     var CID = source.getRecord(tr).getData()[0];
5309                     var o = SE.addressBook._contactCache[CID];
5310                     var name = new String(o.name);
5311                     var finalName = name.replace(/(<([^>]+)>)/ig, "");
5312                     email = finalName + email;
5313                 }
5314                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5315             }
5316         }
5317     },
5318
5319
5320     /*/////////////////////////////////////////////////////////////////////////////
5321     ///    EMAIL TEMPLATE CODE
5322      */
5323     applyEmailTemplate : function (idx, id) {
5324
5325         //bug #20680
5326         var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5327                 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5328                 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5329                 
5330                 //bug #6224
5331                 var to_addr = document.getElementById('addressTO'+idx);
5332                 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1) 
5333                 {
5334                         box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5335                         box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5336                 }
5337                 
5338                 // id is selected index of email template drop-down
5339                 if(id == '' || id == "0") {
5340                         YAHOO.SUGAR.MessageBox.show({
5341                    title:box_title,
5342                    msg: box_none_msg,
5343                    type: 'confirm',
5344                    fn: function(btn){
5345                                 if(btn=='no'){return;};
5346                                 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5347                    modal:true,
5348                    scope:this
5349                });
5350                return;
5351                 }
5352
5353                 YAHOO.SUGAR.MessageBox.show({
5354            title:box_title,
5355            msg: box_msg,
5356            type: 'confirm',
5357            fn: function(btn){
5358                         if(btn=='no'){return;};
5359                         SUGAR.email2.composeLayout.processResult(idx, id);},
5360            modal:true,
5361            scope:this
5362        });
5363     },
5364
5365     processNoneResult : function(idx, id) {
5366         var tiny = SE.util.getTiny('htmleditor' + idx);
5367         var tinyHTML = tiny.getContent();
5368         var openTag = '<div><span><span>';
5369         var htmllow = tinyHTML.toLowerCase();
5370         var start = htmllow.indexOf(openTag);
5371                 if (start > -1) {
5372                 tinyHTML = tinyHTML.substr(start);
5373                 tiny.setContent(tinyHTML);
5374                 } else {
5375                 tiny.setContent('');
5376                 }
5377     },
5378
5379         processResult : function(idx , id){
5380         call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5381
5382         // get attachments if any
5383         AjaxObject.target = '';
5384         AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5385     },
5386
5387     appendEmailTemplateJSON : function() {
5388         var idx = SE.composeLayout.currentInstanceId; // post increment
5389
5390         // query based on template, contact_id0,related_to
5391         //jchi 09/10/2008 refix #7743
5392         if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5393             document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5394         }
5395
5396         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,'"');
5397
5398         // cn: bug 14361 - text-only templates don't fill compose screen
5399         if(text == '') {
5400             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/>");
5401         }
5402
5403         var tiny = SE.util.getTiny('htmleditor' + idx);
5404         var tinyHTML = tiny.getContent();
5405         var openTag = '<div><span><span>';
5406         var closeTag = '</span></span></div>';
5407         var htmllow = tinyHTML.toLowerCase();
5408         var start = htmllow.indexOf(openTag);
5409                 if (start > -1) {
5410                 var htmlPart2 = tinyHTML.substr(start);
5411                 tinyHTML = text + htmlPart2;
5412                 tiny.setContent(tinyHTML);
5413                 } else {
5414                 tiny.setContent(text);
5415                 }
5416     },
5417
5418     /**
5419      * Writes out the signature in the email editor
5420      */
5421     setSignature : function(idx) {
5422         if (!tinyMCE)
5423             return false;
5424         var hide = document.getElementById('setEditor' + idx).checked;
5425         SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5426         //wait for signatures to load before trying to set them
5427         if (!SE.composeLayout.signatures) {
5428             setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5429                         return;
5430         }
5431
5432         if(idx) {
5433             var sel = document.getElementById('signatures' + idx);
5434         } else {
5435             var sel = document.getElementById('signature_id');
5436             idx = SE.tinyInstances.currentHtmleditor;
5437         }
5438
5439         //Ensure that the tinyMCE html has been rendered.
5440         if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5441             setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5442                     return;
5443                 }
5444
5445         var signature = '';
5446
5447         try {
5448             signature = sel.options[sel.selectedIndex].value;
5449         } catch(e) {
5450
5451         }
5452
5453         var openTag = '<div><span><span>';
5454         var closeTag = '</span></span></div>';
5455         var t = SE.util.getTiny('htmleditor' + idx);
5456         //IE 6 Hack
5457         if(typeof(t) != 'undefined')
5458         {
5459             t.contentDocument = t.contentWindow.document;
5460             var html = t.getContent();
5461         }
5462         else
5463             var html = '';
5464
5465         var htmllow = html.toLowerCase();
5466         var start = htmllow.indexOf(openTag);
5467         var end = htmllow.indexOf(closeTag) + closeTag.length;
5468
5469         // selected "none" - remove signature from email
5470         if(signature == '') {
5471             if (start > -1) {
5472                 var htmlPart1 = html.substr(0, start);
5473                 var htmlPart2 = html.substr(end, html.length);
5474
5475                 html = htmlPart1 + htmlPart2;
5476                 t.setContent(html);
5477             }
5478             SE.signatures.lastAttemptedLoad = '';
5479             return false;
5480         }
5481
5482         if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5483             SE.signatures.lastAttemptedLoad = '';
5484
5485         SE.signatures.lastAttemptedLoad = signature;
5486
5487         if(typeof(SE.signatures[signature]) == 'undefined') {
5488             //lazy load
5489             SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5490             SE.signatures.targetInstance = (idx) ? idx : "";
5491             AjaxObject.target = '';
5492             AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5493         } else {
5494             var newSignature = this.prepareSignature(SE.signatures[signature]);
5495
5496             // clear out old signature
5497             if(SE.signatures.lastAttemptedLoad && start > -1) {
5498                 var htmlPart1 = html.substr(0, start);
5499                 var htmlPart2 = html.substr(end, html.length);
5500
5501                 html = htmlPart1 + htmlPart2;
5502             }
5503
5504             // [pre|ap]pend
5505                         start = html.indexOf('<div><hr></div>');
5506             if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5507                                 var htmlPart1 = html.substr(0, start);
5508                                 var htmlPart2 = html.substr(start, html.length);
5509                 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5510             } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5511                 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5512             } else {
5513                 var newHtml = html + openTag + newSignature + closeTag;
5514             }
5515             //tinyMCE.setContent(newHtml);
5516             t.setContent(newHtml);
5517         }
5518     },
5519
5520     prepareSignature : function(str) {
5521         var signature = new String(str);
5522
5523         signature = signature.replace(/&lt;/gi, '<');
5524         signature = signature.replace(/&gt;/gi, '>');
5525
5526         return signature;
5527     },
5528
5529
5530     showAttachmentPanel : function(idx) {
5531         var east = SE.composeLayout[idx].getUnitByPosition("right");
5532         var tabs = SE.composeLayout[idx].rightTabs;
5533         east.expand();
5534         tabs.set("activeTab", tabs.getTab(0));
5535     },
5536
5537     /**
5538      * expands sidebar and displays options panel
5539      */
5540     showOptionsPanel : function(idx) {
5541         var east = SE.composeLayout[idx].getUnitByPosition("right");
5542         var tabs = SE.composeLayout[idx].rightTabs;
5543         east.expand();
5544         tabs.set("activeTab", tabs.getTab(1));
5545     },
5546
5547     /**
5548      * Selects the Contacts tab
5549      */
5550     showContactsPanel : function() {
5551         SE.complexLayout.regions.west.showPanel("contactsTab");
5552     },
5553
5554     /**
5555      * Generates fields for Select Document
5556      */
5557     addDocumentField : function(idx) {
5558         var basket = document.getElementById('addedDocuments' + idx);
5559         if(basket) {
5560             var index = (basket.childNodes.length / 7) - 1;
5561             if(index < 0)
5562                 index = 0;
5563         } else {
5564             index = 0;
5565         }
5566
5567         var test = document.getElementById('documentId' + idx + index);
5568
5569         while(test != null) {
5570             index++;
5571             test = document.getElementById('documentId' + idx + index);
5572         }
5573
5574         var documentCup = document.createElement("div");
5575         documentCup.id = 'documentCup' + idx + index;
5576         documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5577                 // document id field
5578                 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5579                 // document name field
5580                 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5581                 // select button
5582                 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5583                     "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5584                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5585                 // remove button
5586                 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5587                     "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5588                  "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5589                 "<br/>";
5590
5591         basket.appendChild(documentCup);
5592         //basket.innerHTML += out;
5593         return index;
5594     },
5595
5596     /**
5597      * Makes async call to save a draft of the email
5598      * @param int Instance index
5599      */
5600     saveDraft : function(tinyInstance) {
5601         this.sendEmail(tinyInstance, true);
5602     },
5603
5604     selectDocument : function(target) {
5605         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5606         windowName = 'selectDocument';
5607         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5608
5609         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5610         if(window.focus) {
5611             // put the focus on the popup if the browser supports the focus() method
5612             win.focus();
5613         }
5614     },
5615
5616     /**
5617      * Modal popup for file attachment dialogue
5618      */
5619     addFileField : function() {
5620         if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5621             SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5622                 modal:true,
5623                 visible:false,
5624                 fixedcenter:true,
5625                 constraintoviewport: true,
5626                 scroll: true,
5627                 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5628                         fn:function(){SE.addFileDialog.hide();}
5629                 })
5630             });
5631             SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5632             SE.addFileDialog.render();
5633            // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5634         }
5635         Dom.removeClass("addFileDialog", "yui-hidden");
5636
5637         SE.addFileDialog.show();
5638     },
5639
5640     /**
5641      * Async upload of file to temp dir
5642      */
5643     uploadAttachment : function() {
5644         if(document.getElementById('email_attachment').value != "") {
5645             var formObject = document.getElementById('uploadAttachment');
5646             YAHOO.util.Connect.setForm(formObject, true, true);
5647             AjaxObject.target = '';
5648             AjaxObject.startRequest(callbackUploadAttachment, null);
5649         } else {
5650             alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5651         }
5652     },
5653
5654     /**
5655      * Adds a SugarDocument to an outbound email.  Action occurs in a popup window displaying a ListView from the Documents module
5656      * @param string target in focus compose layout
5657      */
5658     setDocument : function(idx, target, documentId, documentName, docRevId) {
5659         // fields are named/id'd [fieldName][instanceId][index]
5660         var addedDocs = document.getElementById("addedDocuments" + idx);
5661         var docId = document.getElementById('documentId' + idx + target);
5662         var docName = document.getElementById('documentName' + idx + target);
5663         var docRevisionId = document.getElementById('document' + idx + target);
5664         docId.value = documentId;
5665         docName.value = documentName;
5666         docRevisionId.value = docRevId;
5667     },
5668
5669     /**
5670      * Removes the bucket div containing the document input fields
5671      */
5672     deleteDocumentField : function(documentCup) {
5673         var f0 = document.getElementById(documentCup);
5674         f0.parentNode.removeChild(f0);
5675     },
5676
5677     /**
5678      * Removes a Template Attachment field
5679      * @param int
5680      * @param int
5681      */
5682     deleteTemplateAttachmentField : function(idx, index) {
5683         // create not-in-array values for removal filtering
5684         var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5685
5686         if(r != "") {
5687             r += "::";
5688         }
5689
5690         r += document.getElementById('templateAttachmentId' + idx + index).value;
5691         document.getElementById("templateAttachmentsRemove" + idx).value = r;
5692
5693         var target = 'templateAttachmentCup' + idx + index;
5694         d =  document.getElementById(target);
5695         d.parentNode.removeChild(d);
5696     },
5697
5698     /**
5699      * Async removal of uploaded temp file
5700      * @param string index Should be a concatenation of idx and index
5701      * @param string
5702      */
5703     deleteUploadAttachment : function(index, file) {
5704         var d = document.getElementById('email_attachment_bucket' + index);
5705         d.parentNode.removeChild(d);
5706
5707         // make async call to delete cached file
5708         AjaxObject.target = '';
5709         AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5710     },
5711
5712     /**
5713      * Attaches files coming from Email Templates
5714      */
5715     addTemplateAttachmentField : function(idx) {
5716         // expose title
5717         document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5718
5719         var basket = document.getElementById('addedTemplateAttachments' + idx);
5720
5721         if(basket) {
5722             var index = basket.childNodes.length;
5723             if(index < 0)
5724                 index = 0;
5725         } else {
5726             index = 0;
5727         }
5728
5729         var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5730                                 // remove button
5731                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5732                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5733                                         idx + "\",\"" + index + "\");'/>" +
5734                                 // file icon
5735                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5736                                 // templateAttachment field
5737                                 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5738                                 // docId field
5739                                 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5740                                 // file name
5741                                 "<span id='templateAttachmentName"  + idx + index + "'" + ">&nbsp;</span>" +
5742                                 "<br id='br" + index + "></br>" +
5743                                 "<br id='brdoc" + index + "></br>" +
5744                         "</div>";
5745                 basket.innerHTML = basket.innerHTML + out;
5746
5747         return index;
5748     },
5749
5750     /**
5751      * Sends one email via async call
5752      * @param int idx Editor instance ID
5753      * @param bool isDraft
5754      */
5755     sendEmail : function(idx, isDraft) {
5756
5757         //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5758         var obAccountID = document.getElementById('addressFrom' + idx).value;
5759
5760         if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5761         {
5762             overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5763             return false;
5764         }
5765
5766
5767         var form = document.getElementById('emailCompose' + idx);
5768         var composeOptionsFormName = "composeOptionsForm" + idx;
5769         var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5770         var html = t.getContent();
5771         var subj = document.getElementById('emailSubject' + idx).value;
5772         var to = trim(document.getElementById('addressTO' + idx).value);
5773         var cc = trim(document.getElementById('addressCC' + idx).value);
5774         var bcc = trim(document.getElementById('addressBCC' + idx).value);
5775         var email_id = document.getElementById('email_id' + idx).value;
5776         var composeType = document.getElementById('composeType').value;
5777         var parent_type = document.getElementById("parent_type").value;
5778         var parent_id = document.getElementById("parent_id").value;
5779
5780         var el_uid = document.getElementById("uid");
5781         var uid = (el_uid == null) ? '' : el_uid.value;
5782
5783         var el_ieId = document.getElementById("ieId");
5784         var ieId = (el_ieId == null) ? '' : el_ieId.value;
5785
5786         var el_mbox = document.getElementById("mbox");
5787         var mbox = (el_mbox == null) ? '' : el_mbox.value;
5788
5789         if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5790                         alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5791                 return false;
5792         }
5793
5794         if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5795                 return;
5796         } // if
5797                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5798                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5799         parent_id = parentIdValue;
5800         parent_type = parentTypeValue;
5801
5802         var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5803         // baseline viability check
5804
5805         if(to == "" && cc == '' && bcc == '' && !isDraft) {
5806             alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5807             return false;
5808         } else if(subj == '' && !isDraft) {
5809             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5810                 return false;
5811             } else {
5812                 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5813             }
5814         } else if(html == '' && !isDraft) {
5815             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5816                 return false;
5817             }
5818         }
5819
5820         SE.util.clearHiddenFieldValues('emailCompose' + idx);
5821                 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5822                 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5823         overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5824         html = html.replace(/&lt;/ig, "sugarLessThan");
5825         html = html.replace(/&gt;/ig, "sugarGreaterThan");
5826
5827         form.sendDescription.value = html;
5828         form.sendSubject.value = subj;
5829         form.sendTo.value = to;
5830         form.sendCc.value = cc;
5831         form.sendBcc.value = bcc;
5832         form.email_id.value = email_id;
5833         form.composeType.value = composeType;
5834         form.composeLayoutId.value = 'composeLayout' + idx;
5835         form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5836         form.saveToSugar.value = 1;
5837         form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5838         form.parent_type.value = parent_type;
5839         form.parent_id.value = parent_id;
5840         form.uid.value = uid;
5841         form.ieId.value = ieId;
5842         form.mbox.value = mbox;
5843
5844         // email attachments
5845         var addedFiles = document.getElementById('addedFiles' + idx);
5846         if(addedFiles) {
5847             for(i=0; i<addedFiles.childNodes.length; i++) {
5848                 var bucket = addedFiles.childNodes[i];
5849
5850                 for(j=0; j<bucket.childNodes.length; j++) {
5851                     var node = bucket.childNodes[j];
5852                     var nName = new String(node.name);
5853
5854                     if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5855                         if(form.attachments.value != '') {
5856                             form.attachments.value += "::";
5857                         }
5858                         form.attachments.value += node.value;
5859                     }
5860                 }
5861             }
5862         }
5863
5864         // sugar documents
5865         var addedDocs = document.getElementById('addedDocuments' + idx);
5866         if(addedDocs) {
5867             for(i=0; i<addedDocs.childNodes.length; i++) {
5868                 var cNode = addedDocs.childNodes[i];
5869                 for(j=0; j<cNode.childNodes.length; j++) {
5870                     var node = cNode.childNodes[j];
5871                     var nName = new String(node.name);
5872                     if(node.type == 'hidden' && nName.match(/documentId/)) {
5873                         if(form.documents.value != '') {
5874                             form.documents.value += "::";
5875                         }
5876                         form.documents.value += node.value;
5877                     }
5878                 }
5879             }
5880         }
5881
5882         // template attachments
5883         var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5884         if(addedTemplateAttachments) {
5885             for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5886                 var cNode = addedTemplateAttachments.childNodes[i];
5887                 for(j=0; j<cNode.childNodes.length; j++) {
5888                     var node = cNode.childNodes[j];
5889                     var nName = new String(node.name);
5890                     if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5891                         if(form.templateAttachments.value != "") {
5892                             form.templateAttachments.value += "::";
5893                         }
5894                         form.templateAttachments.value += node.value;
5895                     }
5896                 }
5897             }
5898         }
5899
5900         // remove attachments
5901         form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5902
5903         YAHOO.util.Connect.setForm(form);
5904
5905         AjaxObject.target = 'frameFlex';
5906
5907         // sending a draft email
5908         if(!isDraft && in_draft) {
5909             // remove row
5910             SE.listView.removeRowByUid(email_id);
5911         }
5912
5913         var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5914         var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5915
5916         AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5917     },
5918
5919     /**
5920      * Handles clicking the email address link from a given view
5921      */
5922     composePackage : function() {
5923         if(composePackage != null) {
5924             SE.composeLayout.c0_composeNewEmail();
5925
5926
5927             if(composePackage.to_email_addrs) {
5928                 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5929             } // if
5930             if (composePackage.subject != null && composePackage.subject.length > 0) {
5931                 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5932             }
5933
5934             //If no parent fields are set in the composePackage, ensure they are cleared.
5935             var parentFields = ['parent_type','parent_name','parent_id'];
5936             for(var i=0;i<parentFields.length;i++)
5937             {
5938                 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5939                     composePackage[parentFields[i]] = "";
5940             }
5941
5942             document.getElementById("parent_type").value = composePackage.parent_type;
5943             document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5944             document.getElementById("parent_id").value = composePackage.parent_id;
5945             document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5946             document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5947
5948             if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5949                 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5950             } // if
5951             if (composePackage.body != null && composePackage.body.length > 0) {
5952                         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5953                         SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5954                         setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5955             } // if
5956             if (composePackage.attachments != null) {
5957                                 SE.composeLayout.loadAttachments(composePackage.attachments);
5958             } // if
5959
5960             if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5961                                 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5962                         SE.util.emptySelectOptions(addressFrom);
5963                         var fromAccountOpts = composePackage.fromAccounts.data;
5964                         for(i=0; i<fromAccountOpts.length; i++) {
5965                               var key = fromAccountOpts[i].value;
5966                               var display = fromAccountOpts[i].text;
5967                               var opt = new Option(display, key);
5968                               if (fromAccountOpts[i].selected) {
5969                                 opt.selected = true;
5970                               }
5971                               addressFrom.options.add(opt);
5972                         }
5973
5974             } // if
5975         } // if
5976     },
5977
5978     setContentOnThisTiny : function() {
5979         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5980         var tinyHTML = tiny.getContent();
5981         composePackage.body = decodeURI(encodeURI(composePackage.body));
5982         // cn: bug 14361 - text-only templates don't fill compose screen
5983         if(composePackage.body == '') {
5984             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,'"');
5985         } // if
5986         //Flag determines if we should clear the tiny contents or just append
5987         if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5988             SE.composeLayout.tinyHTML = '';
5989         else
5990             SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
5991
5992          tiny.setContent(SE.composeLayout.tinyHTML);
5993          //Indicate that the contents has been loaded successfully.
5994          SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5995     },
5996     /**
5997      * Confirms closure of a compose screen if "x" is clicked
5998      */
5999     confirmClose : function(panel) {
6000         if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6001             SE.composeLayout.closeCompose(panel.id);
6002             return true;
6003         } else {
6004             return false;
6005         }
6006     },
6007
6008     /**
6009      * forces close of a compose screen
6010      */
6011     forceCloseCompose : function(id) {
6012         SE.composeLayout.closeCompose(id);
6013
6014         // handle flow back to originating view
6015         if(composePackage) {
6016             // check if it's a module we need to return to
6017             if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6018                 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6019                     var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6020                     window.location = url;
6021                 }
6022             }
6023         }
6024     },
6025
6026     /**
6027      * closes the editor that just sent email
6028      * @param string id ID of composeLayout tab
6029      */
6030     closeCompose : function(id) {
6031         // destroy tinyMCE instance
6032         var idx = id.substr(13, id.length);
6033         var instanceId = "htmleditor" + idx;
6034         tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6035
6036         // nullify DOM and namespace values.
6037         inCompose = false;
6038         SE.composeLayout[idx] = null;
6039         SE.tinyInstances[instanceId] = null;
6040         var tabsArray = SE.innerLayout.get("tabs");
6041         for (i = 0 ; i < tabsArray.length ; i++) {
6042                 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6043                         tabsArray[i].close();
6044                         break;
6045                 }
6046         }
6047         //SE.innerLayout.getTab(idx).close();
6048     },
6049
6050     /**
6051     *  Enable the quick search for the compose relate field or search tab
6052     */
6053     enableQuickSearchRelate: function(idx,overides){
6054
6055         if(typeof overides != 'undefined')
6056         {
6057             var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6058             var newModule = document.getElementById(newModuleID).value;
6059             var formName = overides['formName'];
6060             var fieldName = overides['fieldName'];
6061             var fieldId = overides['fieldId'];
6062             var fullName = formName + "_" + fieldName;
6063             var postBlurFunction = null;
6064         }
6065         else
6066         {
6067             var newModule = document.getElementById('data_parent_type'+idx).value;
6068             var formName = 'emailCompose'+idx;
6069             var fieldName = 'data_parent_name'+idx;
6070             var fieldId = 'data_parent_id'+idx;
6071             var fullName = formName + "_" + fieldName;
6072             var postBlurFunction = "SE.composeLayout.qsAddAddress";
6073         }
6074
6075         if(typeof sqs_objects == 'undefined')
6076             window['sqs_objects'] = new Array;
6077
6078         window['sqs_objects'][fullName] = {
6079             form:formName,
6080                         method:"query",
6081                         modules:[newModule],
6082                         group:"or",
6083             field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6084             conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6085                         post_onblur_function: postBlurFunction,
6086             order:"name","limit":"30","no_match_text":"No Match"};
6087
6088
6089         if(typeof QSProcessedFieldsArray != 'undefined')
6090                 QSProcessedFieldsArray[fullName] = false;
6091         if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6092                 QSFieldsArray[fullName].destroy();
6093                 delete QSFieldsArray[fullName];
6094         }
6095         if (Dom.get(fullName + "_results")) {
6096                 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6097         }
6098
6099         enableQS(false);
6100     },
6101
6102         qsAddAddress : function(o) {
6103         if (o.name != "" && o.email1 != "")
6104         {
6105                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6106                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6107         }
6108     },
6109     /**
6110      * Returns a new instance ID, 0-index
6111      */
6112     getNewInstanceId : function() {
6113         this.currentInstanceId = this.currentInstanceId + 1;
6114         return this.currentInstanceId;
6115     },
6116
6117     /**
6118      * 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.
6119      */
6120     loadAttachments : function(result) {
6121         var idx = SE.composeLayout.currentInstanceId;
6122
6123         if(typeof(result) == 'object') {
6124                 //jchi #20680. Clean the former template attachments;
6125                 var basket = document.getElementById('addedTemplateAttachments' + idx);
6126                         if(basket.innerHTML != ''){
6127                                 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6128                                         if (btn != 'yes'){
6129                                                 basket.innerHTML = '';
6130                                         }
6131                                 });
6132                         }
6133             for(i in result) {
6134                 if(typeof result[i] == 'object') {
6135                     var index = SE.composeLayout.addTemplateAttachmentField(idx);
6136                     var bean = result[i];
6137                     document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6138                     document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6139                 }
6140             }
6141         }
6142     },
6143
6144     /**
6145      * fills drop-down values for email templates and signatures
6146      */
6147     setComposeOptions : function(idx) {
6148         // send from accounts
6149         var addressFrom = document.getElementById('addressFrom' + idx);
6150
6151         if (addressFrom.options.length <= 0) {
6152                 SE.util.emptySelectOptions(addressFrom);
6153                 var fromAccountOpts = SE.composeLayout.fromAccounts;
6154                 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6155                       var key = fromAccountOpts[id].value;
6156                       var display = fromAccountOpts[id].text;
6157                       var is_default = false;
6158                       if(key == SUGAR.default_inbound_accnt_id)
6159                         is_default = true;
6160                       var opt = new Option(display, key);
6161                       addressFrom.options.add(opt);
6162                       addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6163                 }
6164         }
6165
6166         // email templates
6167         var et = document.getElementById('email_template' + idx);
6168         SE.util.emptySelectOptions(et);
6169
6170         for(var key in this.emailTemplates) { // iterate through assoc array
6171             var display = this.emailTemplates[key];
6172             var opt = new Option(display, key);
6173             et.options.add(opt);
6174         }
6175
6176         // signatures
6177         var sigs = document.getElementById('signatures' + idx);
6178         SE.util.emptySelectOptions(sigs);
6179
6180         for(var key in this.signatures) { // iterate through assoc array
6181             var display = this.signatures[key];
6182             var opt = new Option(display, key);
6183
6184             if(key == SE.userPrefs.signatures.signature_default) {
6185                 opt.selected = true;
6186             }
6187
6188             sigs.options.add(opt);
6189         }
6190
6191         // html/plain email?
6192         var htmlEmail = document.getElementById('setEditor' + idx);
6193         if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6194             htmlEmail.checked = true;
6195         } else {
6196                 htmlEmail.checked = false;
6197         }
6198
6199         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6200     },
6201
6202     /**
6203      * After compose screen is rendered, async call to get email body from Sugar
6204      */
6205     replyForwardEmailStage2 : function() {
6206         SE.util.clearHiddenFieldValues('emailUIForm');
6207         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6208
6209         var ieId = SE.composeLayout.replyForwardObj.ieId;
6210         var uid = SE.composeLayout.replyForwardObj.uid;
6211         var mbox = SE.composeLayout.replyForwardObj.mbox;
6212         var type = SE.composeLayout.replyForwardObj.type;
6213         var idx = SE.composeLayout.currentInstanceId;
6214
6215         var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6216
6217         document.getElementById('emailSubject' + idx).value = type;
6218         document.getElementById('emailUIAction').value = 'composeEmail';
6219         document.getElementById('composeType').value = type;
6220         document.getElementById('ieId').value = ieId;
6221         document.getElementById('uid').value = uid;
6222         document.getElementById('mbox').value = mbox;
6223                 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6224         var formObject = document.getElementById('emailUIForm');
6225         YAHOO.util.Connect.setForm(formObject);
6226
6227         var sendType = type;
6228         AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6229     },
6230
6231     /**
6232     *  Show the hidden cc or bcc fields
6233     */
6234     showHiddenAddress: function(addrType,idx){
6235
6236         Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6237         Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6238                 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6239                 this[addrType+'Hidden'+idx] = false;
6240
6241                 //After bcc or cc is added, move options below last addr field
6242                 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6243
6244                 //If both cc and bcc hidden, remove the empty row containing text.
6245                 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6246                            && ( this['ccHidden'+idx]  == false && this['bccHidden'+idx] == false) )
6247                         Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6248
6249                 SE.composeLayout.resizeEditor(idx);
6250     },
6251     /**
6252     *  Hide the cc and bcc fields if they were shown.
6253     */
6254     hideHiddenAddresses: function(idx){
6255
6256         var addrTypes = ['cc','bcc'];
6257         for(var i = 0;i<addrTypes.length;i++)
6258         {
6259             Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6260             Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6261             this[addrTypes[i] + 'Hidden'+idx] = true
6262         }
6263
6264         Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6265         Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6266         Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6267     }
6268 };
6269
6270 ////    END SE.composeLayout
6271 ///////////////////////////////////////////////////////////////////////////////
6272 ///////////////////////////////////////////////////////////////////////////////
6273 ////    SE.util
6274 SE.util = {
6275     /**
6276      * Cleans serialized UID lists of duplicates
6277      * @param string
6278      * @return string
6279      */
6280     cleanUids : function(str) {
6281         var seen = new Object();
6282         var clean = "";
6283         var arr = new String(str).split(",");
6284
6285         for(var i=0; i<arr.length; i++) {
6286             if(seen[arr[i]]) {
6287                 continue;
6288             }
6289
6290             clean += (clean != "") ? "," : "";
6291             clean += arr[i];
6292             seen[arr[i]] = true;
6293         }
6294
6295         return clean;
6296     },
6297
6298     /**
6299      * Clears hidden field values
6300      * @param string id ID of form element to clear
6301      */
6302     clearHiddenFieldValues : function(id) {
6303         var form = document.getElementById(id);
6304
6305         for(i=0; i<form.elements.length; i++) {
6306             if(form.elements[i].type == 'hidden') {
6307                 var e = form.elements[i];
6308                 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6309                     e.value = '';
6310                 }
6311             }
6312         }
6313     },
6314
6315     /**
6316      * Reduces a SELECT drop-down to 0 items to prepare for new ones
6317      */
6318     emptySelectOptions : function(el) {
6319         if(el) {
6320             for(i=el.childNodes.length - 1; i >= 0; i--) {
6321                 if(el.childNodes[i]) {
6322                     el.removeChild(el.childNodes[i]);
6323                 }
6324             }
6325         }
6326     },
6327
6328     /**
6329      * Returns the MBOX path in the manner php_imap expects:
6330      * ie: INBOX.DEBUG.test
6331      * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6332      */
6333     generateMboxPath : function(str) {
6334         var ex = str.split("::");
6335
6336         /* we have a serialized MBOX path */
6337         if(ex.length > 1) {
6338             var start = false;
6339             var ret = '';
6340             for(var i=0; i<ex.length; i++) {
6341                 if(ex[i] == 'INBOX') {
6342                     start = true;
6343                 }
6344
6345                 if(start == true) {
6346                     if(ret != "") {
6347                         ret += ".";
6348                     }
6349                     ret += ex[i];
6350                 }
6351             }
6352         } else {
6353             /* we have a Sugar folder GUID - do nothing */
6354             return str;
6355         }
6356
6357         return ret;
6358     },
6359
6360     /**
6361      * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6362      * @param HTMLElement el
6363      * @return string GUID of found element or empty on failure
6364      */
6365     getGuidFromElement : function(el) {
6366         var GUID = '';
6367         var iterations = 4;
6368         var passedEl = el;
6369
6370         // upwards
6371         for(var i=0; i<iterations; i++) {
6372             if(el) {
6373                 if(el.id.match(SE.reGUID)) {
6374                     return el.id;
6375                 } else {
6376                     el = el.parentNode;
6377                 }
6378             }
6379         }
6380
6381         return GUID;
6382     },
6383
6384     /**
6385      * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6386      * @return string
6387      */
6388     getPanelId : function() {
6389         return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6390     },
6391
6392     /**
6393      * wrapper to handle weirdness with IE
6394      * @param string instanceId
6395      * @return tinyMCE Controller object
6396      */
6397     getTiny : function(instanceId) {
6398         if(instanceId == '') {
6399             return null;
6400         }
6401
6402         var t = tinyMCE.getInstanceById(instanceId);
6403
6404         if(this.isIe()) {
6405             this.sleep(200);
6406             YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6407         }
6408         return t;
6409     },
6410
6411     /**
6412      * Simple check for MSIE browser
6413      * @return bool
6414      */
6415     isIe : function() {
6416         var nav = new String(navigator.appVersion);
6417         if(nav.match(/MSIE/)) {
6418             return true;
6419         }
6420         return false;
6421     },
6422
6423     /**
6424      * Recursively removes an element from the DOM
6425      * @param HTMLElement
6426      */
6427     removeElementRecursive : function(el) {
6428         this.emptySelectOptions(el);
6429     },
6430
6431     /**
6432      * Fakes a sleep
6433      * @param int
6434      */
6435     sleep : function(secs) {
6436         setTimeout("void(0);", secs);
6437     },
6438
6439     /**
6440      * Converts a <select> element to an Ext.form.combobox
6441      */
6442      convertSelect : function(select) {
6443        alert('in convertSelect');
6444        if (typeof(select) == "string") {
6445            select = document.getElementById(select);
6446        }
6447      },
6448
6449      findChildNode : function (parent, property, value) {
6450          for (i in parent.children) {
6451                  var child = parent.children[i];
6452                  if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6453                          return child;
6454                  var searchChild = SE.util.findChildNode(child, property, value);
6455                  if (searchChild)
6456                          return searchChild;
6457          }
6458          return false;
6459      },
6460
6461      cascadeNodes : function (parent, fn, scope, args) {
6462          for (i in parent.children) {
6463                  var child = parent.children[i];
6464                  var s = scope ? scope : child;
6465                  var a = args ? args : child;
6466                  fn.call(s, a);
6467                  SE.util.cascadeNodes(child, fn, scope, args);
6468          }
6469      }
6470 };
6471
6472
6473 ////    END UTIL
6474 ///////////////////////////////////////////////////////////////////////////////
6475
6476
6477 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6478                                 
6479 /*********************************************************************************
6480  * SugarCRM Community Edition is a customer relationship management program developed by
6481  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6482  * 
6483  * This program is free software; you can redistribute it and/or modify it under
6484  * the terms of the GNU Affero General Public License version 3 as published by the
6485  * Free Software Foundation with the addition of the following permission added
6486  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6487  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6488  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6489  * 
6490  * This program is distributed in the hope that it will be useful, but WITHOUT
6491  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6492  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
6493  * details.
6494  * 
6495  * You should have received a copy of the GNU Affero General Public License along with
6496  * this program; if not, see http://www.gnu.org/licenses or write to the Free
6497  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6498  * 02110-1301 USA.
6499  * 
6500  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6501  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6502  * 
6503  * The interactive user interfaces in modified source and object code versions
6504  * of this program must display Appropriate Legal Notices, as required under
6505  * Section 5 of the GNU Affero General Public License version 3.
6506  * 
6507  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6508  * these Appropriate Legal Notices must retain the display of the "Powered by
6509  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6510  * technical reasons, the Appropriate Legal Notices must display the words
6511  * "Powered by SugarCRM".
6512  ********************************************************************************/
6513
6514
6515 if (typeof console == "undefined")
6516         console = { log: function(o) {alert(o)} };
6517
6518 var AjaxObject = {
6519         ret : '',
6520         currentRequestObject : null,
6521         //timeout : 30000, // 30 second timeout default
6522         timeout : 9999999999, // 30 second timeout default
6523         forceAbort : false,
6524         trail : new Array(),
6525
6526         /**
6527          */
6528         _reset : function() {
6529                 this.timeout = 30000;
6530                 this.forceAbort = false;
6531         },
6532
6533         folderRenameCleanup : function() {
6534                 SUGAR.email2.folders.setSugarFolders();
6535         },
6536
6537         fullSyncCleanup : function(o) {
6538                 this.folders.checkMailCleanup(o);
6539                 SUGAR.email2.settings.settingsDialog.hide();
6540         },
6541
6542         /**
6543          */
6544         composeCache : function(o) {
6545                 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6546                 // get email templates and user signatures
6547                 var ret = JSON.parse(o.responseText);
6548
6549                 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6550                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6551                 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6552
6553                 SUGAR.email2.composeLayout.setComposeOptions(idx);
6554
6555                 //Set the error array so we can notify the user when they try to hit send if any errors
6556                 //are present.  We will also notify them now (after hitting compose button).
6557                 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6558
6559
6560                 //if error element is returning an array, then check the length to make sure we have error messages
6561                 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6562                         //add error messages for display
6563                         for(i in ret.errorArray)
6564                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6565                 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6566                         //if error element is returning an object, and the object value is not empty or null, then display error message
6567                         for(i in ret.errorArray)
6568                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6569                 }
6570
6571                 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6572                 if(SUGAR.isIE) {
6573                         var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6574                         if(overlayPanel) {
6575                           overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6576                         }
6577                 }
6578         },
6579
6580
6581         handleDeleteSignature : function(o) {
6582                 hideOverlay();
6583                 var ret = JSON.parse(o.responseText);
6584                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6585         var field = document.getElementById('signature_id');
6586                 SUGAR.email2.util.emptySelectOptions(field);
6587
6588                 for(var i in ret.signatures) { // iterate through assoc array
6589                         var opt = new Option(ret.signatures[i], i);
6590                         field.options.add(opt);
6591                 }
6592                 setSigEditButtonVisibility();
6593         },
6594
6595         /**
6596          */
6597         handleDeleteReturn : function(o) {
6598                 // force refresh ListView
6599                 hideOverlay();
6600                 if(document.getElementById('focusEmailMbox')) {
6601                         YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6602                 }
6603
6604                 // need to display success message before calling next async call?
6605                 document.getElementById(this.target).innerHTML = o.responseText;
6606         },
6607
6608         /**
6609          */
6610     handleFailure : function(o) {
6611                 // Failure handler
6612                 overlay('Exception occurred...', o.statusText, 'alert');
6613                 if(document.getElementById('saveButton')) {
6614                         document.getElementById('saveButton').disabled = false;
6615                 }
6616         },
6617
6618         handleReplyForward : 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.from;
6626                 document.getElementById('uid' + idx).value = a.uid;
6627                 if(a.cc) {
6628                         document.getElementById('addressCC' + idx).value = a.cc;
6629                         SE.composeLayout.showHiddenAddress('cc', idx);
6630                 }
6631
6632                 if(a.type) {
6633                         document.getElementById('type' + idx).value = a.type;
6634                 }
6635
6636                 // apply attachment values
6637                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6638
6639                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6640         },
6641
6642         handleReplyForwardForDraft : function(o) {
6643                 var a = JSON.parse(o.responseText);
6644                 globalA = a;
6645                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6646
6647                 document.getElementById('email_id' + idx).value = a.uid;
6648                 document.getElementById('emailSubject' + idx).value = a.name;
6649                 document.getElementById('addressTO' + idx).value = a.to;
6650
6651                 if(a.cc) {
6652                         document.getElementById('addressCC' + idx).value = a.cc;
6653                         SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6654                 }
6655
6656                 if(a.bcc) {
6657                         document.getElementById('addressBCC' + idx).value = a.bcc;
6658                         SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6659                 }
6660
6661
6662                 if(a.type) {
6663                         document.getElementById('type' + idx).value = a.type;
6664                 }
6665
6666
6667                 // apply attachment values
6668                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6669
6670                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6671         },
6672
6673         /**
6674          */
6675         handleSuccess : function(o) {
6676                 document.getElementById(this.target).innerHTML = o.responseText;
6677                 hideOverlay();
6678         },
6679
6680         /**
6681          */
6682         ieDeleteSuccess : function(o) {
6683                 hideOverlay();
6684
6685                 var ret = JSON.parse(o.responseText);
6686
6687                 SUGAR.email2.accounts.refreshInboundAccountTable();
6688                 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6689                 SUGAR.email2.accounts.rebuildFolderList();
6690
6691         },
6692
6693         /**
6694          */
6695         ieSaveSuccess : function(o) {
6696                 document.getElementById('saveButton').disabled = false;
6697                 var a = JSON.parse(o.responseText);
6698                 if (a) {
6699                         if(a.error) {
6700                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6701                                 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6702                         } else {
6703                                 resp = JSON.parse(o.responseText);
6704                                 SUGAR.email2.accounts.refreshInboundAccountTable();
6705                                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6706                                 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6707                                 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6708                         }
6709                 } else {
6710                      hideOverlay();
6711                      overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6712                 }
6713
6714         },
6715
6716         /**
6717          */
6718         loadAttachments : function(o) {
6719                 var result = JSON.parse(o.responseText);
6720
6721                 SUGAR.email2.composeLayout.loadAttachments(result);
6722         },
6723
6724         /**
6725          */
6726         loadSignature : function(o) {
6727                 var ret = JSON.parse(o.responseText);
6728                 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6729                 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6730         },
6731
6732         /**
6733          * Follow up to mark email read|unread|flagged
6734          */
6735         markEmailCleanup : function(o) {
6736                 var ret = JSON.parse(o.responseText);
6737                 if (!ret['status']) {
6738                 hideOverlay();
6739                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6740                 } else {
6741                         SUGAR.email2.contextMenus.markEmailCleanup();
6742                 } // else
6743         },
6744
6745         /**
6746          */
6747         rebuildShowFolders : function(o) {
6748                 var t = JSON.parse(o.responseText);
6749                 var show = document.getElementById('ieAccountListShow');
6750
6751                 SUGAR.email2.util.emptySelectOptions(show);
6752
6753                 for(i=0; i<t.length; i++) { // iterate through assoc array
6754                         var opt = new Option(t[i].text, t[i].value, t[i].selected);
6755                         opt.selected = t[i].selected;
6756                         show.options.add(opt);
6757                 }
6758
6759                 SUGAR.email2.accounts.renderTree();
6760         },
6761         /**
6762          */
6763         saveListViewSortOrderPart2 : function() {
6764                 // create the JSON string the func expects
6765                 focusFolderPath = '[ "Home", "' + ieName + '"';
6766
6767                 var f = new String(focusFolder);
6768                 var fEx = f.split('.');
6769
6770                 for(i=0; i<fEx.length; i++) {
6771                         focusFolderPath += ', "' + fEx[i] +'"'
6772                 }
6773
6774                 focusFolderPath += ']';
6775
6776                 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6777                 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6778         },
6779
6780         /**
6781          *
6782          */
6783         sendEmailCleanUp : function(o) {
6784                 hideOverlay();
6785                 var ret = JSON.parse(o.responseText);
6786                 if (ret) {
6787                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6788                   //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6789                 } else if (o.responseText) {
6790                   overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6791                 }
6792
6793                 if (typeof(SE.grid) != 'undefined')
6794                         SE.listView.refreshGrid();
6795                 //Disabled while address book is disabled
6796
6797                 //If this call back was initiated by quick compose from a Detail View page, refresh the
6798                 //history subpanel.  If it was initiated by quickcreate from shortcut bar, then
6799                 //close the shortcut bar menu
6800                 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6801                         if(action_sugar_grp1 == 'DetailView') {
6802                                 showSubPanel('history',null,true);
6803                         } else if(action_sugar_grp1 == 'quickcreate') {
6804                                 closeEmailOverlay();
6805                         }
6806                 }
6807
6808         },
6809
6810         ieSendSuccess : function(o) {
6811                 hideOverlay();
6812                 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6813         },
6814
6815         /**
6816          */
6817         settingsFolderRefresh : function(o) {
6818                 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6819                 var ret = JSON.parse(o.responseText);
6820                 var user = document.getElementById('userFolders');
6821
6822                 SUGAR.email2.util.emptySelectOptions(user);
6823
6824                 for(i=0; i<ret.userFolders.length; i++) {
6825                         var display = ret.userFolders[i].name;
6826                         var value = ret.userFolders[i].id;
6827                         var selected = (ret.userFolders[i].selected != "") ? true : false;
6828                         var opt = new Option(display, value, selected);
6829                         opt.selected = selected;
6830                         user.options.add(opt);
6831                 }
6832         },
6833
6834         /**
6835          */
6836         startRequest : function(callback, args, forceAbort) {
6837                 if(this.currentRequestObject != null) {
6838                         if(this.forceAbort == true) {
6839                                 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6840                         }
6841                 }
6842                 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6843                 this._reset();
6844         },
6845
6846         requestInProgress : function() {
6847                 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6848         },
6849
6850         /**
6851          */
6852         updateFolderSubscriptions : function() {
6853                 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6854                 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6855                 hideOverlay();
6856         },
6857
6858         /**
6859          */
6860         updateFrameFolder : function() {
6861                 SUGAR.email2.folders.checkEmailAccounts();
6862         },
6863
6864         /**
6865          */
6866         updateUserPrefs : function(o) {
6867                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6868                 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6869         },
6870
6871         /**
6872          */
6873         uploadAttachmentSuccessful : function(o) {
6874                 // clear out field
6875                 document.getElementById('email_attachment').value = '';
6876
6877                 var ret = JSON.parse(o.responseText);
6878                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6879                 var overall = document.getElementById('addedFiles' + idx);
6880                 var index = overall.childNodes.length;
6881                 var out =
6882                         "<div id='email_attachment_bucket" + idx + index + "'>" +
6883                                 // remove button
6884                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6885                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6886                                         idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6887                                 // file icon
6888                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6889                                         "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6890                                 // hidden id field
6891                                 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6892                                 // file name
6893                                 ((ret.nameForDisplay != null) ? ret.nameForDisplay + "&nbsp;" : ret.name + "&nbsp;") +
6894                                 "<br/>" +
6895                         "</div>";
6896                 overall.innerHTML += out;
6897                 if(SUGAR.email2.util.isIe()) {
6898                         document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6899                 }
6900
6901                 // hide popup
6902                 SUGAR.email2.addFileDialog.hide();
6903                 // focus attachments
6904                 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6905         }
6906 };
6907
6908
6909 ///////////////////////////////////////////////////////////////////////////
6910 ////    PER MODULE CALLBACK OBJECTS
6911 AjaxObject.accounts = {
6912         saveOutboundCleanup : function(o) {
6913                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6914                 SUGAR.email2.accounts.outboundDialog.hide();
6915                 var id = o.responseText;
6916                 SUGAR.email2.accounts.newAddedOutboundId = id;
6917                 },
6918         saveDefaultOutboundCleanup: function(o){
6919
6920         },
6921         callbackEditOutbound : {
6922                 success : function(o)
6923                 {
6924                         var ret = JSON.parse(o.responseText);
6925                         // show overlay
6926                         SUGAR.email2.accounts.showAddSmtp();
6927
6928                         // fill values
6929                         document.getElementById("mail_id").value = ret.id;
6930                         document.getElementById("type").value = ret.type;
6931                         document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6932                         document.getElementById("mail_name").value = ret.name;
6933                         document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6934                         document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6935                         document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6936                         document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6937                         document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6938                         SUGAR.email2.accounts.smtp_authenticate_field_display();
6939                         document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6940
6941             if(ret.type == 'system-override') {
6942                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6943                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6944             }
6945             else {
6946                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6947                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6948             }
6949             SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6950
6951                 },
6952                 failure : AjaxObject.handleFailure,
6953                 timeout : AjaxObject.timeout,
6954                 scope   : AjaxObject
6955         },
6956         callbackDeleteOutbound : {
6957                 success : function(o) {
6958                     var ret = JSON.parse(o.responseText);
6959                     if(ret.is_error)
6960                     {
6961                         if(confirm(ret.error_message))
6962                 {
6963                     overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6964                     AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6965                 }
6966                 else
6967                     hideOverlay();
6968                     }
6969                     else
6970                     {
6971                              hideOverlay();
6972                              SUGAR.email2.accounts.refreshOuboundAccountTable();
6973                     }
6974                 },
6975
6976                 failure : AjaxObject.handleFailure,
6977                 timeout : AjaxObject.timeout,
6978                 scope   : AjaxObject
6979         },
6980
6981         callbackCheckMailProgress : {
6982            success : function(o) {
6983                if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6984                    SUGAR.email2.accounts.totalMsgCount = -1;
6985                }
6986
6987                //Check for server timeout / errors
6988                var ret = JSON.parse(o.responseText);
6989                var done = false;
6990
6991                if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6992                    hideOverlay();
6993                    overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6994                    SUGAR.email2.accounts.totalMsgCount = -1;
6995                //SUGAR.email2.folders.rebuildFolders();
6996                done = true;
6997                }
6998
6999                var currIeId = ret['ieid'];
7000
7001
7002                var serverCount = ret.count;
7003
7004                if (ret['status'] == 'done') {
7005                    for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7006                        if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7007                            //We are all done
7008                            done = true;
7009                            break;
7010                        } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7011                            //Go to next account
7012                            currIeId = SUGAR.email2.accounts.ieIds[i+1];
7013                            ret.count = 0;
7014                            SUGAR.email2.accounts.totalMsgCount = -1;
7015                            break;
7016                        }
7017                    }
7018                }
7019                else if (ret.mbox && ret.totalcount && ret.count) {
7020                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7021                    if (ret.count >= ret.totalcount) {
7022                        serverCount = 0;
7023                    }
7024                } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7025                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7026                } else {
7027                        hideOverlay();
7028                overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7029                SUGAR.email2.accounts.totalMsgCount = -1;
7030                done = true;
7031                    }
7032
7033                if (done) {
7034                    SUGAR.email2.accounts.totalMsgCount = -1;
7035                    hideOverlay();
7036                    SUGAR.email2.folders.rebuildFolders();
7037                    SE.listView.refreshGrid();
7038                } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7039                YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7040                AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7041                                 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=0&synch=" + ret.synch);
7042            } else {
7043                YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7044                    app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7045                    AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7046                    '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=" + serverCount +
7047                    '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7048                }
7049            },
7050            failure : AjaxObject.handleFailure,
7051        timeout : AjaxObject.timeout,
7052        scope   : AjaxObject
7053         }
7054 };
7055
7056 ///////////////////////////////////////////////////////////////////////////////
7057 ////    COMPOSE LAYOUT
7058 AjaxObject.composeLayout = {
7059         /**
7060          * Populates the record id
7061          */
7062         saveDraftCleanup : function(o) {
7063                 hideOverlay();
7064                 var ret = JSON.parse(o.responseText);
7065                 if(ret)
7066                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7067                 else if (o.responseText)
7068                   overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7069         }
7070 };
7071
7072 AjaxObject.composeLayout.callback = {
7073         saveDraft : {
7074                 success : AjaxObject.composeLayout.saveDraftCleanup,
7075                 failure : AjaxObject.handleFailure,
7076                 timeout : AjaxObject.timeout,
7077                 scope   : AjaxObject
7078         }
7079 };
7080
7081 AjaxObject.detailView = {
7082         /**
7083          * Pops-up a printable view of an email
7084          */
7085         displayPrintable : function(o) {
7086                 var ret = JSON.parse(o.responseText);
7087                 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7088                 // 2 below must be in global context
7089                 meta = ret.meta;
7090                 meta['panelId'] = SUGAR.email2.util.getPanelId();
7091                 email = ret.meta.email;
7092                 if (typeof(email.cc) == 'undefined') {
7093                   email.cc = "";
7094                 }
7095
7096                 var out = displayTemplate.exec({
7097                         'app_strings'   : app_strings,
7098                         'theme'                 : theme,
7099                         'idx'                   : 'Preview',
7100                         'meta'                  : meta,
7101                         'email'                 : meta.email
7102                 });
7103
7104                 // open popup window
7105                 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7106                     'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7107
7108                 popup.document.write(out);
7109                 popup.document.close();
7110         },
7111
7112         /**
7113          * Takes formatted response and creates a modal pop-over containing a title and content
7114          */
7115         displayView : function(o) {
7116                 var SED = SUGAR.email2.detailView;
7117                 var ret = JSON.parse(o.responseText);
7118
7119                 if(!SED.viewDialog) {
7120                         SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7121                                 modal:true,
7122                 visible:true,
7123                 fixedcenter:true,
7124                 constraintoviewport: true,
7125                                 shadow  : true
7126                         });
7127             SED.viewDialog.renderEvent.subscribe(function() {
7128                 var content = this.body.firstChild;
7129                 var viewH = YAHOO.util.Dom.getViewportHeight();
7130                 if (content) {
7131                         this.body.style.overflow = "auto";
7132                         this.body.style.width = "800px";
7133                         this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7134                 }
7135             }, SED.viewDialog);
7136                 } // end lazy load
7137                 SED.viewDialog.setHeader(ret.title);
7138                 SED.viewDialog.setBody(ret.html);
7139                 SED.viewDialog.render();
7140                 SED.viewDialog.show();
7141         },
7142
7143         /**
7144          * Generates a modal popup to populate with the contents of bean's full EditView
7145          */
7146         showQuickCreateForm : function(o) {
7147                 var SED = SUGAR.email2.detailView;
7148                 var ret = JSON.parse(o.responseText);
7149
7150                 if(!SED.quickCreateDialog) {
7151                         SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7152                                 modal:true,
7153                                 visible:true,
7154                 fixedcenter:true,
7155                 constraintoviewport: true,
7156                                 shadow  : true
7157                         });
7158
7159             SED.quickCreateDialog.renderEvent.subscribe(function() {
7160                 var viewH = YAHOO.util.Dom.getViewportHeight();
7161                 var contH = 0;
7162                 for (var i in this.body.childNodes) {
7163                         if (this.body.childNodes[i].clientHeight) {
7164                                 contH += this.body.childNodes[i].clientHeight;
7165                         } else if (this.body.childNodes[i].offsetHeight) {
7166                                 contH += this.body.childNodes[i].offsetHeight;
7167                         } // if
7168                 }
7169                         this.body.style.width = "800px";
7170                         this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7171                         this.body.style.overflow = "auto";
7172             }, SED.quickCreateDialog);
7173
7174             SED.quickCreateDialog.hideEvent.subscribe(function(){
7175                                 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7176                                 /*for(var qsField in qsFields){
7177                                         if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7178                                         Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7179                                 }*/
7180                         });
7181             SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7182                 } // end lazy load
7183                 if (ret.html) {
7184                         ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7185                 }
7186                 SED.quickCreateDialog.setBody(ret.html ? ret.html : "&nbsp;");
7187                 SED.quickCreateDialog.render();
7188                 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7189
7190                 SED.quickCreateDialog.ieId = ret.ieId;
7191                 SED.quickCreateDialog.uid = ret.uid;
7192         SED.quickCreateDialog.mbox = ret.mbox;
7193         SED.quickCreateDialog.qcmodule = ret.module;
7194
7195         SED.quickCreateDialog.show();
7196
7197                 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7198                 if (editForm) {
7199                   editForm.module.value = 'Emails';
7200                   var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7201                   var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7202                   var instId = ret.module + count;
7203                   SED.quickCreateEmailsToAdd = ret.emailAddress;
7204                   SED.quickCreateEmailCallback = function(instId, tableId) {
7205                           var eaw = SUGAR.EmailAddressWidget.instances[instId];
7206                           if (typeof(eaw) == "undefined")
7207                                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7208                                                 + instId + "','" + tableId + "');", 100);
7209                           eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7210                   }
7211                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7212                                         + instId + "','" + tableId + "');", 100);
7213                 }
7214         },
7215
7216         saveQuickCreateForm : function(o) {
7217             hideOverlay();
7218                 SUGAR.email2.detailView.quickCreateDialog.hide();
7219                 validate['EditView'] = [ ];
7220         },
7221
7222         saveQuickCreateFormAndReply : function(o) {
7223             hideOverlay();
7224             var ret = JSON.parse(o.responseText);
7225         SUGAR.email2.detailView.quickCreateDialog.hide();
7226         var qcd = SUGAR.email2.detailView.quickCreateDialog;
7227         var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7228         if (ret) {
7229             var emailID = ret.id;
7230             SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7231         } else {
7232             SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7233         }
7234         //Cean the validate cache to prevent errors on the next call
7235         validate['EditView'] = [ ];
7236     },
7237
7238         saveQuickCreateFormAndAddToAddressBook : function(o) {
7239            hideOverlay();
7240                 SUGAR.email2.detailView.quickCreateDialog.hide();
7241                 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7242                 validate['EditView'] = [ ];
7243         },
7244
7245         handleAssignmentDialogAssignAction : function() {
7246
7247
7248             var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7249
7250             var dist = 'direct';
7251             var users = false;
7252             var rules = false;
7253             var get = "";
7254             var found_teams = false;
7255             var warning_message = mod_strings.LBL_WARN_NO_USERS;
7256             if(!found_teams && assign_user_id == '' )
7257             {
7258                 alert(warning_message);
7259                 return;
7260             }
7261
7262             var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7263             var uids = "";
7264             for(i=0; i<emailUids.length; i++) {
7265                 if(uids != '') {
7266                     uids += app_strings.LBL_EMAIL_DELIMITER;
7267                 }
7268                 uids += emailUids[i];
7269             }
7270
7271             var row = SUGAR.email2.grid.getSelectedRows()[0];
7272             var data = SUGAR.email2.grid.getRecord(row).getData();
7273             var ieid = data.ieId;
7274             var mbox = data.mbox;
7275             AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7276             SUGAR.email2.contextMenus.assignToDialogue.hide();
7277             overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7278
7279         },
7280
7281         handleAssignmentDialogDeleteAction : function() {
7282                 // TO pass list of UIDS/emailIds
7283                 var uids = SUGAR.email2.listView.getUidsFromSelection();
7284                 var row = SUGAR.email2.grid.getSelections()[0];
7285                 var ieid = row.data.ieId;
7286             var mbox = row.data.mbox;
7287         AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7288         SUGAR.email2.contextMenus.assignmentDialog.hide();
7289                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7290
7291                 // AJAX Call
7292
7293         },
7294
7295         showEmailDetailView : function(o) {
7296         hideOverlay();
7297         var SED = SUGAR.email2.detailView;
7298                 var ret = JSON.parse(o.responseText);
7299
7300                 if(!SED.quickCreateDialog) {
7301                         SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7302                                 modal:true,
7303                                 visible:true,
7304                 //fixedcenter:true,
7305                 constraintoviewport: true,
7306                 draggable: true,
7307                                 autofillheight: "body",
7308                                 shadow  : true
7309                         });
7310                         SED.quickCreateDialog.renderEvent.subscribe(function() {
7311                 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7312                 var contH = 0;
7313                 for (var i in this.body.childNodes) {
7314                         if (this.body.childNodes[i].offsetHeight)
7315                                 contH += this.body.childNodes[i].offsetHeight;
7316                 }
7317                         this.body.style.overflow = "auto";
7318                         this.body.style.width = "800px";
7319                         this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7320                         this.center();
7321             }, SED.quickCreateDialog);
7322                 }
7323                 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7324                 SED.quickCreateDialog.setBody(ret.html);
7325                 SED.quickCreateDialog.render();
7326         SUGAR.util.evalScript(ret.html);
7327         SED.quickCreateDialog.show();
7328         },
7329
7330         showAssignmentDialogWithData : function(o) {
7331         var SEC = SUGAR.email2.contextMenus;
7332                 hideOverlay();
7333         var ret = JSON.parse(o.responseText);
7334         if (!SEC.assignmentDialog) {
7335                 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7336                         visible:false,
7337                 fixedcenter:true,
7338                 constraintoviewport: true,
7339                         modal   : true
7340                 });
7341                 SEC.assignmentDialog.setBody("");
7342                 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7343                 SEC.assignmentDialog.renderEvent.subscribe(function() {
7344                 var iev = YAHOO.util.Dom.get("Distribute");
7345                 if (iev) {
7346                         this.body.style.width = "700px";
7347                 }
7348             },  SEC.assignmentDialog);
7349                 SEC.assignmentDialog.render();
7350         }
7351         SEC.assignmentDialog.setBody(ret);
7352         SEC.assignmentDialog.render();
7353         validate = [];
7354         SEC.assignmentDialog.show();
7355         SUGAR.util.evalScript(ret);
7356         },
7357
7358         showImportForm : function(o) {
7359                 var SED = SUGAR.email2.detailView;
7360                 var ret = JSON.parse(o.responseText);
7361
7362         document.getElementById('quickCreateContent').innerHTML = "";
7363         hideOverlay();
7364         if (!ret) {
7365             return false;
7366         }
7367
7368         if(!SED.importDialog) {
7369             SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7370                 modal:true,
7371                 visible:false,
7372                 fixedcenter:true,
7373                 constraintoviewport: true,
7374                 buttons : [{
7375                         text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7376                                 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7377                 }]//,
7378                 //scroll : true
7379             });
7380             SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7381             SED.importDialog.setBody("");
7382             SED.importDialog.hideEvent.subscribe(function(){
7383                 for(var i in QSFieldsArray) {
7384                         if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7385                                 QSFieldsArray[i].destroy();
7386                                 delete QSFieldsArray[i];
7387                         }
7388                         if (QSProcessedFieldsArray[i]) {
7389                                 QSProcessedFieldsArray[i] = false;
7390                         } // if
7391                                 }
7392             });
7393             SED.importDialog.renderEvent.subscribe(function() {
7394                 var iev = YAHOO.util.Dom.get("ImportEditView");
7395                 if (iev) {
7396                         //this.body.style.height = (iev.clientHeight + 10) + "px";
7397                         this.body.style.width = "600px";
7398                 }
7399             }, SED.importDialog);
7400             SED.importDialog.render();
7401         } // end lazy load
7402         SED.importDialog.setBody(ret.html);
7403         SED.importDialog.ret = ret;
7404         SUGAR.util.evalScript(ret.html);
7405         SED.importDialog.render();
7406         validate = [];
7407         SED.importDialog.show();
7408         SED.importDialog.focusFirstButton();
7409     },
7410     getImportAction : function(ret) {
7411         if (!check_form('ImportEditView')) return false;
7412         if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7413                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7414                 return false;
7415         } // if
7416                 var get = "";
7417         var editView = document.getElementById('ImportEditView');
7418         if (editView.assigned_user_id != null) {
7419             get = get + "&user_id=" + editView.assigned_user_id.value
7420             //var user_id = editView.assigned_user_id.value;
7421         }
7422         var parent_id = editView.parent_id.value;
7423         var parent_type = editView.parent_type.value;
7424         var row = SUGAR.email2.grid.getSelectedRows()[0];
7425         row = SUGAR.email2.grid.getRecord(row);
7426         var data = row.getData();
7427         var ieId = data.ieId;
7428         var mbox = data.mbox;
7429         var serverDelete = editView.serverDelete.checked;
7430         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7431         var uids = "";
7432         for(i=0; i<emailUids.length; i++) {
7433             if(uids != '') {
7434                 uids += app_strings.LBL_EMAIL_DELIMITER;
7435             }
7436             uids += emailUids[i];
7437         }
7438
7439         var action = 'importEmail&uid=';
7440         if (ret.move) {
7441             action = 'moveEmails';
7442             action = action + '&sourceFolder=' + ret['srcFolder'];
7443             action = action + '&sourceIeId=' + ret['srcIeId'];
7444             action = action + '&destinationFolder=' + ret['dstFolder'];
7445             action = action + '&destinationIeId=' + ret['dstIeId'];
7446             action = action + '&emailUids=';
7447         }
7448         if (action.search(/importEmail/) != -1) {
7449             overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7450         } else {
7451             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7452         }
7453
7454         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7455         get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7456         SUGAR.email2.detailView.importDialog.hide();
7457         document.getElementById('importDialogContent').innerHTML = "";
7458
7459     },
7460     showRelateForm : function(o) {
7461         var SED = SUGAR.email2.detailView;
7462         var ret = JSON.parse(o.responseText);
7463         document.getElementById('quickCreateContent').innerHTML = "";
7464         hideOverlay();
7465         if (!ret) {
7466             return false;
7467         }
7468         dialog_loaded = true;
7469
7470         if(!SED.relateDialog) {
7471             SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7472                                 modal:true,
7473                                 visible:true,
7474                 fixedcenter:true,
7475                 width: '800px',
7476                 constraintoviewport: true,
7477                                 buttons : [{
7478                         text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7479                                         if (!check_form('RelateEditView')) return false;
7480                                         var get = "";
7481                         var editView = document.getElementById('RelateEditView');
7482                         var parent_id = editView.parent_id.value;
7483                         var parent_type = editView.parent_type.value;
7484                         var row = SUGAR.email2.grid.getSelectedRows()[0];
7485                         row  = SUGAR.email2.grid.getRecord(row);
7486                         var ieId = row.getData().ieId;
7487                         var mbox = row.getData().mbox;
7488                         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7489                         var uids = "";
7490                         for(i=0; i<emailUids.length; i++) {
7491                             if(uids != '') {
7492                                 uids += app_strings.LBL_EMAIL_DELIMITER;
7493                             }
7494                             uids += emailUids[i];
7495                         }
7496                         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7497                         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7498                             + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7499                         SED.relateDialog.hide();
7500                         document.getElementById('relateDialogContent').innerHTML = "";
7501                         }
7502                 }]
7503                         });
7504
7505             SED.relateDialog.hideEvent.subscribe(function(){
7506                 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7507                         QSFieldsArray['ImportEditView_parent_name'].destroy();
7508                         delete QSFieldsArray['ImportEditView_parent_name'];
7509                 } // if
7510                                 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7511                                         QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7512                                 } // if
7513             });
7514
7515             SED.relateDialog.renderEvent.subscribe(function() {
7516                 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7517                 var contH = 0;
7518                 for (var i in this.body.childNodes) {
7519                         if (this.body.childNodes[i].clientHeight)
7520                                 contH += this.body.childNodes[i].clientHeight;
7521                 }
7522             }, SED.relateDialog);
7523             SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7524                 } // end lazy load
7525
7526         SED.relateDialog.setBody(ret.html);
7527         SED.relateDialog.render();
7528         SUGAR.util.evalScript(ret.html);
7529         SED.relateDialog.show();
7530     }
7531 };
7532 /**
7533  * DetailView callbacks
7534  */
7535 AjaxObject.detailView.callback = {
7536         emailDetail : {
7537                 success : function(o) {
7538                         SUGAR.email2.o = o;
7539                         var ret = JSON.parse(o.responseText);
7540                         SUGAR.email2.detailView.consumeMetaDetail(ret);
7541                 },
7542                 argument: [targetDiv],
7543                 failure : AjaxObject.handleFailure,
7544                 timeout : 0,
7545                 scope   : AjaxObject
7546         },
7547         emailPreview : {
7548                 success : function(o) {
7549                         SUGAR.email2.o = o;
7550                         var ret = JSON.parse(o.responseText);
7551                         SUGAR.email2.detailView.consumeMetaPreview(ret);
7552                 },
7553                 failure : AjaxObject.handleFailure,
7554                 timeout : 0,
7555                 scope   : AjaxObject
7556         },
7557         viewPrint : {
7558                 success : AjaxObject.detailView.displayPrintable,
7559                 failure : AjaxObject.handleFailure,
7560                 timeout : AjaxObject.timeout,
7561                 scope   : AjaxObject
7562         },
7563         viewRaw : {
7564                 success : AjaxObject.detailView.displayView,
7565                 failure : AjaxObject.handleFailure,
7566                 timeout : AjaxObject.timeout,
7567                 scope   : AjaxObject
7568         }
7569 };
7570
7571
7572
7573
7574
7575 AjaxObject.folders = {
7576         /**
7577          * check-mail post actions
7578          */
7579         checkMailCleanup : function(o) {
7580                 hideOverlay();
7581                 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7582
7583                 // refresh focus ListView
7584                 SE.listView.refreshGrid();
7585                 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7586         },
7587
7588         /**
7589          */
7590         rebuildFolders : function(o) {
7591                 hideOverlay();
7592
7593                 var data = JSON.parse(o.responseText);
7594
7595                 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7596                 SUGAR.email2.folders.setSugarFolders();
7597         }
7598 };
7599 AjaxObject.folders.callback = {
7600         checkMail : {
7601                 success : AjaxObject.folders.checkMailCleanup,
7602                 failure : AjaxObject.handleFailure,
7603                 timeout : 600000, // 5 mins
7604                 scope   : AjaxObject
7605         }
7606 }
7607
7608 AjaxObject.rules = {
7609         loadRulesForSettings : function(o) {
7610                 document.getElementById("rulesListCell").innerHTML = o.responseText;
7611                 // assume we have the class we need
7612                 SUGAR.routing.getStrings();
7613                 SUGAR.routing.getDependentDropdowns();
7614         }
7615 };
7616 ////    END PER MODULE CALLBACK OBJECTS
7617 ///////////////////////////////////////////////////////////////////////////
7618
7619
7620 var callback = {
7621         success : AjaxObject.handleSuccess,
7622         failure : AjaxObject.handleFailure,
7623         timeout : AjaxObject.timeout,
7624         scope   : AjaxObject
7625 };
7626 var callbackAccount = {
7627         success : AjaxObject.ieSaveSuccess,
7628         failure : AjaxObject.handleFailure,
7629         timeout : AjaxObject.timeout,
7630         scope   : AjaxObject
7631 };
7632 var callbackAccountDelete = {
7633         success : AjaxObject.ieDeleteSuccess,
7634         failure : AjaxObject.handleFailure,
7635         timeout : AjaxObject.timeout,
7636         scope   : AjaxObject
7637 };
7638 var callbackOutboundTest = {
7639         success : AjaxObject.ieSendSuccess,
7640         failure : AjaxObject.handleFailure,
7641         timeout : AjaxObject.timeout,
7642         scope   : AjaxObject
7643 };
7644
7645
7646
7647 var callbackTeamInfoForSettings = {
7648 success : function (o) {
7649         var data = JSON.parse(o.responseText);
7650         document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7651 },
7652 failure : AjaxObject.handleFailure,
7653 timeout : AjaxObject.timeout,
7654 scope   : AjaxObject
7655
7656 };
7657
7658 var callbackStatusForImport = {
7659 success : function (o) {
7660         hideOverlay();
7661         if (o.responseText != "")  {
7662                 var statusString = "";
7663                 var data = JSON.parse(o.responseText);
7664                 for(i=0; i<data.length; i++) {
7665                         statusString = statusString + data[i] + '<br/>';
7666                 }
7667                 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7668         }
7669         SE.listView.refreshGrid();
7670
7671 },
7672 failure : AjaxObject.handleFailure,
7673 timeout : AjaxObject.timeout,
7674 scope   : AjaxObject
7675
7676 };
7677 var callbackComposeCache = {
7678         success : AjaxObject.composeCache,
7679         failure : AjaxObject.handleFailure,
7680         timeout : AjaxObject.timeout,
7681         scope   : AjaxObject
7682 };
7683 var callbackDelete = {
7684         success : AjaxObject.handleDeleteReturn,
7685         failure : AjaxObject.handleFailure,
7686         timeout : AjaxObject.timeout,
7687         scope   : AjaxObject
7688 };
7689 var callbackEmailDetailMultiple = {
7690         success : function(o) {
7691                 hideOverlay();
7692                 var retMulti = JSON.parse(o.responseText);
7693                 var ret = new Object();
7694
7695                 for(var i=0; i<retMulti.length; i++) {
7696                         ret = retMulti[i];
7697
7698                         SUGAR.email2._setDetailCache(ret);
7699                         SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7700                 }
7701         },
7702         failure : AjaxObject.handleFailure,
7703         timeout : 0,
7704         scope   : AjaxObject
7705 };
7706 var callbackListViewSortOrderChange = {
7707         success : AjaxObject.saveListViewSortOrderPart2,
7708         failure : AjaxObject.handleFailure,
7709         timeout : AjaxObject.timeout,
7710         scope   : AjaxObject,
7711         argument        : [ieId, ieName, focusFolder]
7712 };
7713 var callbackEmptyTrash = {
7714         success : function(o) {
7715                 hideOverlay();
7716                 AjaxObject.folderRenameCleanup;
7717         },
7718         failure : AjaxObject.handleFailure,
7719         timeout : AjaxObject.timeout,
7720         scope   : AjaxObject
7721 };
7722 var callbackClearCacheFiles = {
7723         success : function(o) {
7724                 hideOverlay();
7725         },
7726         failure : AjaxObject.handleFailure,
7727         timeout : AjaxObject.timeout,
7728         scope   : AjaxObject
7729 };
7730 var callbackFolderRename = {
7731         success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7732         failure : AjaxObject.handleFailure,
7733         timeout : AjaxObject.timeout,
7734         scope   : AjaxObject
7735 };
7736 var callbackFolderDelete = {
7737         success : function(o) {
7738                 var ret = JSON.parse(o.responseText);
7739                 if (ret.status) {
7740                     if (ret.folder_id) {
7741                         var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7742                         if(node)
7743                                 SUGAR.email2.tree.removeNode(node, true);
7744                     } else if (ret.ieId && ret.mbox) {
7745                         var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7746                         if(node)
7747                                 SUGAR.email2.tree.removeNode(node, true);
7748                     }
7749                         hideOverlay();
7750                         //SUGAR.email2.folders.loadSettingFolder();
7751                 } else {
7752                         hideOverlay();
7753                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7754                 } // else
7755         },
7756         failure : AjaxObject.handleFailure,
7757         timeout : AjaxObject.timeout,
7758         scope   : AjaxObject
7759 };
7760 var callbackFolderSave = {
7761         success : function(o) {
7762                 var ret = JSON.parse(o.responseText);
7763
7764                 switch(ret.action) {
7765                         case 'newFolderSave':
7766                                 SUGAR.email2.folders.rebuildFolders();
7767                         break;
7768                 }
7769         },
7770         failure : AjaxObject.handleFailure,
7771         timeout : AjaxObject.timeout,
7772         scope   : AjaxObject
7773 };
7774 var callbackFolderSubscriptions = {
7775         success : AjaxObject.updateFolderSubscriptions,
7776         failure : AjaxObject.handleFailure,
7777         timeout : AjaxObject.timeout,
7778         scope   : AjaxObject
7779 };
7780 var callbackFolderUpdate = {
7781         success : AjaxObject.updateFrameFolder,
7782         failure : AjaxObject.handleFailure,
7783         timeout : AjaxObject.timeout,
7784         scope   : AjaxObject
7785 };
7786 var callbackFolders = {
7787         success : AjaxObject.folders.rebuildFolders,
7788         //success : void(true),
7789         failure : AjaxObject.handleFailure,
7790         timeout : AjaxObject.timeout,
7791         scope   : AjaxObject
7792 };
7793 var callbackFullSync = {
7794         success : AjaxObject.fullSyncCleanup,
7795         failure : AjaxObject.handleFailure,
7796         timeout : 9999999999999,
7797         scope   : AjaxObject
7798 };
7799 var callbackGeneric = {
7800         success : function() {
7801                 hideOverlay();
7802         },
7803         failure : AjaxObject.handleFailure,
7804         timeout : AjaxObject.timeout,
7805         scope   : AjaxObject
7806 };
7807 var callbackIeAccountRetrieve = {
7808         success : function(o) {
7809                 // return JSON encoding
7810                 hideOverlay();
7811                 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7812                 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7813         },
7814         failure : AjaxObject.handleFailure,
7815         timeout : AjaxObject.timeout,
7816         scope   : AjaxObject
7817 };
7818 var callbackImportOneEmail = {
7819         success :  AjaxObject.detailView.showImportForm,
7820         failure : AjaxObject.handleFailure,
7821         timeout : AjaxObject.timeout,
7822         scope   : AjaxObject
7823 };
7824 var callbackRelateEmail = {
7825     success : AjaxObject.detailView.showRelateForm,
7826     failure : AjaxObject.handleFailure,
7827     timeout : AjaxObject.timeout,
7828     scope   : AjaxObject
7829 }
7830 var callbackEmailDetailView = {
7831     success : AjaxObject.detailView.showEmailDetailView,
7832     failure : AjaxObject.handleFailure,
7833     timeout : AjaxObject.timeout,
7834     scope   : AjaxObject
7835 }
7836 var callbackAssignmentDialog = {
7837         success :  AjaxObject.detailView.showAssignmentDialogWithData,
7838         failure : AjaxObject.handleFailure,
7839         timeout : AjaxObject.timeout,
7840         scope   : AjaxObject
7841 };
7842 var callbackAssignmentAction = {
7843         success :  function(o) {
7844                 SE.listView.refreshGrid();
7845                 hideOverlay();
7846                 if(o.responseText != '') {
7847                overlay('Assignment action result', o.responseText, 'alert');
7848             } // if
7849         } ,
7850         failure : AjaxObject.handleFailure,
7851         timeout : AjaxObject.timeout,
7852         scope   : AjaxObject
7853 };
7854 var callbackMoveEmails = {
7855         success :  function(o) {
7856             SE.listView.refreshGrid();
7857                 hideOverlay();
7858                 if(o.responseText != '') {
7859                overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7860             } // if
7861         } ,
7862         failure : AjaxObject.handleFailure,
7863         timeout : AjaxObject.timeout,
7864         scope   : AjaxObject
7865 };
7866 var callbackLoadAttachments = {
7867         success : AjaxObject.loadAttachments,
7868         failure : AjaxObject.handleFailure,
7869         timeout : AjaxObject.timeout,
7870         scope   : AjaxObject
7871 };
7872 var callbackLoadRules = {
7873         success : AjaxObject.rules.loadRulesForSettings,
7874         failure : AjaxObject.handleFailure,
7875         timeout : AjaxObject.timeout,
7876         scope   : AjaxObject
7877 };
7878 var callbackLoadSignature = {
7879         success : AjaxObject.loadSignature,
7880         failure : AjaxObject.handleFailure,
7881         timeout : AjaxObject.timeout,
7882         scope   : AjaxObject
7883 };
7884 var callbackDeleteSignature = {
7885         success : AjaxObject.handleDeleteSignature,
7886         failure : AjaxObject.handleFailure,
7887         timeout : AjaxObject.timeout,
7888         scope   : AjaxObject
7889 };
7890 /*var callbackMoveEmails = {
7891     success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7892     failure : AjaxObject.handleFailure,
7893     timeout : AjaxObject.timeout,
7894     scope   : AjaxObject
7895 }*/
7896 var callbackOutboundSave = {
7897         success : AjaxObject.accounts.saveOutboundCleanup,
7898         failure : AjaxObject.handleFailure,
7899         timeout : AjaxObject.timeout,
7900         scope   : AjaxObject
7901 };
7902 var callbackDefaultOutboundSave = {
7903         success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7904         failure : AjaxObject.handleFailure,
7905         timeout : AjaxObject.timeout,
7906         scope   : AjaxObject
7907 };
7908 var callbackQuickCreate = {
7909         success : AjaxObject.detailView.showQuickCreateForm,
7910         failure : AjaxObject.handleFailure,
7911         timeout : AjaxObject.timeout,
7912         scope   : AjaxObject
7913 };
7914 var callbackQuickCreateSave = {
7915         success : AjaxObject.detailView.saveQuickCreateForm,
7916         failure : AjaxObject.handleFailure,
7917         timeout : AjaxObject.timeout,
7918         scope   : AjaxObject
7919 };
7920 var callbackQuickCreateSaveAndAddToAddressBook = {
7921         success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7922         failure : AjaxObject.handleFailure,
7923         timeout : AjaxObject.timeout,
7924         scope   : AjaxObject
7925 };
7926 var callbackQuickCreateSaveAndReply = {
7927     success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7928     failure : AjaxObject.handleFailure,
7929     timeout : AjaxObject.timeout,
7930     scope   : AjaxObject
7931 }
7932 var callbackQuickCreateSaveAndReplyCase = {
7933     success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7934     failure : AjaxObject.handleFailure,
7935     timeout : AjaxObject.timeout,
7936     scope   : AjaxObject
7937 }
7938 var callbackRebuildShowAccountList = {
7939         success : AjaxObject.rebuildShowFolders,
7940         failure : AjaxObject.handleFailure,
7941         timeout : AjaxObject.timeout,
7942         scope   : AjaxObject
7943 };
7944
7945 var callbackRefreshSugarFolders = {
7946         success : function(o) {
7947                 var t = JSON.parse(o.responseText);
7948                 SUGAR.email2.folders.setSugarFoldersEnd(t);
7949         },
7950         failure : AjaxObject.handleFailure,
7951         timeout : AjaxObject.timeout,
7952         scope   : AjaxObject
7953 };
7954 var callbackReplyForward = {
7955         success : AjaxObject.handleReplyForward,
7956         finish : function(a, retryCount) {
7957                 if (typeof(retryCount) == 'undefined') {
7958                         retryCount = 0;
7959                 } else {
7960                         retryCount++;
7961                 }
7962                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7963                 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7964         try {
7965                         var html = t.getContent();
7966
7967             if (a.type != 'draft') {
7968                         if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7969                                 html += "&nbsp;<div><hr></div>" + a.description;
7970                         } else {
7971                                 html =  "&nbsp;<div><hr></div>" + a.description + html;
7972                         }
7973             }else {
7974                 html = a.description;
7975             }
7976
7977                         t.setContent(html);//
7978
7979                 } catch(e) {
7980                         if (retryCount < 5) {
7981                                 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7982                                 return;
7983                         }
7984                 }
7985                 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7986                 if (tabArray != null && tabArray.length > 0) {
7987                         for (i = 0 ; i < tabArray.length ; i++) {
7988                                 var tabObject = tabArray[i];
7989                                 if (tabObject.get("id") == ("composeTab" + idx)) {
7990                                         var tabLabel = a.name;
7991                                 if (tabLabel != null && tabLabel.length > 25) {
7992                                         tabLabel = tabLabel.substring(0, 25) + "...";
7993                                 } // if
7994                                         tabObject.get("labelEl").firstChild.data = tabLabel;
7995                                         break;
7996                                 }
7997                         }
7998                 }
7999
8000                 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8001                 if (a.parent_name != null && a.parent_name != "") {
8002                         document.getElementById('data_parent_name' + idx).value = a.parent_name;
8003                 }
8004                 if (a.parent_type != null && a.parent_type != "") {
8005                         document.getElementById('data_parent_type' + idx).value = a.parent_type;
8006                 }
8007                 if (a.parent_id != null && a.parent_id != "") {
8008                         document.getElementById('data_parent_id' + idx).value = a.parent_id;
8009                 }
8010                 if (a.fromAccounts.status) {
8011                         var addressFrom = document.getElementById('addressFrom' + idx);
8012                 SUGAR.email2.util.emptySelectOptions(addressFrom);
8013                 var fromAccountOpts = a.fromAccounts.data;
8014                 for(i=0; i<fromAccountOpts.length; i++) {
8015                       var key = fromAccountOpts[i].value;
8016                       var display = fromAccountOpts[i].text;
8017                       var opt = new Option(display, key);
8018                       if (fromAccountOpts[i].selected) {
8019                         opt.selected = true;
8020                       }
8021                       addressFrom.options.add(opt);
8022                 }
8023                 } // if
8024                 hideOverlay();
8025
8026         },
8027         failure : AjaxObject.handleFailure,
8028         timeout : AjaxObject.timeout,
8029         scope   : AjaxObject,
8030         argument        : [sendType]
8031 };
8032 var callbackSendEmail = {
8033         success : AjaxObject.sendEmailCleanUp,
8034         failure : AjaxObject.handleFailure,
8035         timeout : AjaxObject.timeout,
8036         scope   : AjaxObject
8037 };
8038 var callbackSettings = {
8039         success : AjaxObject.updateUserPrefs,
8040         failure : AjaxObject.handleFailure,
8041         timeout : AjaxObject.timeout,
8042         scope   : AjaxObject
8043 };
8044 var callbackSettingsFolderRefresh = {
8045         success : AjaxObject.settingsFolderRefresh,
8046         failure : AjaxObject.handleFailure,
8047         timeout : AjaxObject.timeout,
8048         scope   : AjaxObject
8049 };
8050 var callbackLoadSettingFolder = {
8051         success : function(o) {
8052                 AjaxObject.settingsFolderRefresh(o);
8053                 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8054         },
8055         failure : AjaxObject.handleFailure,
8056         timeout : AjaxObject.timeout,
8057         scope   : AjaxObject
8058
8059 };
8060 var callbackUploadAttachment = {
8061         success : AjaxObject.uploadAttachmentSuccessful,
8062         upload  : AjaxObject.uploadAttachmentSuccessful,
8063         failure : AjaxObject.handleFailure,
8064         timeout : AjaxObject.timeout,
8065         scope   : AjaxObject
8066 };
8067 var callbackUserPrefs = {
8068         success : function(o) {
8069                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8070         },
8071         failure : AjaxObject.handleFailure,
8072         timeout : AjaxObject.timeout,
8073         scope   : AjaxObject
8074 };
8075
8076 var callbackContextmenus = {
8077         markUnread : {
8078                 success : AjaxObject.markEmailCleanup,
8079                 failure : AjaxObject.handleFailure,
8080                 timeout : AjaxObject.timeout,
8081                 scope   : AjaxObject
8082         }
8083 };
8084
8085 var callbackCheckEmail2 = {
8086         success : function(o) {
8087                 var ret = JSON.parse(o.responseText);
8088                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8089
8090
8091         },
8092         failure : AjaxObject.handleFailure,
8093         timeout : AjaxObject.timeout,
8094         scope   : AjaxObject
8095 }// End of File modules/Emails/javascript/ajax.js
8096                                 
8097 /*********************************************************************************
8098  * SugarCRM Community Edition is a customer relationship management program developed by
8099  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8100  * 
8101  * This program is free software; you can redistribute it and/or modify it under
8102  * the terms of the GNU Affero General Public License version 3 as published by the
8103  * Free Software Foundation with the addition of the following permission added
8104  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8105  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8106  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8107  * 
8108  * This program is distributed in the hope that it will be useful, but WITHOUT
8109  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8110  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8111  * details.
8112  * 
8113  * You should have received a copy of the GNU Affero General Public License along with
8114  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8115  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8116  * 02110-1301 USA.
8117  * 
8118  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8119  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8120  * 
8121  * The interactive user interfaces in modified source and object code versions
8122  * of this program must display Appropriate Legal Notices, as required under
8123  * Section 5 of the GNU Affero General Public License version 3.
8124  * 
8125  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8126  * these Appropriate Legal Notices must retain the display of the "Powered by
8127  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8128  * technical reasons, the Appropriate Legal Notices must display the words
8129  * "Powered by SugarCRM".
8130  ********************************************************************************/
8131
8132 function gridInit() {
8133         if(SUGAR.email2.grid) {
8134                 SUGAR.email2.grid.destroy();
8135         }
8136         
8137         e2Grid = {
8138                 init : function() {
8139                 
8140                         var Ck = YAHOO.util.Cookie;
8141                         var widths = [ 10, 10, 150, 250, 175, 125 ];
8142
8143                         if (Ck.get("EmailGridWidths")) {
8144                                 for (var i=0; i < widths.length; i++) {
8145                                         widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8146                                 }
8147                         } else {
8148                                 for (var i=0; i < widths.length; i++) {
8149                                         Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8150                                 }
8151                         }
8152                         
8153                         // changes "F" to an icon
8154                         function flaggedIcon(cell, record, column, value) {
8155                                 if(value != "") {
8156                                         cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8157                                 }
8158                         }
8159                         // changes "A" to replied icon
8160                         function repliedIcon(cell, record, column, value) {
8161                                 if(value != "") {
8162                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8163                                 }
8164                         }
8165                 function attachIcon(cell, record, column, value) {
8166                                 if(value == "1") {
8167                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8168                                 }
8169                         }
8170
8171                         var colModel = 
8172                                 [
8173                                         {
8174                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>", 
8175                                                 width: 10, 
8176                                                 sortable: false, 
8177                                                 fixed: true,
8178                                                 resizeable: true,
8179                                                 formatter: attachIcon,
8180                                                 key: 'hasAttach'
8181                                         }, 
8182                                     {
8183                                                 label: "<span style='color: #f00; font-weight:bold;'>!</span>", 
8184                                                 width: widths[0], 
8185                                                 sortable: true, 
8186                                                 fixed: true,
8187                                                 resizeable: true,
8188                                                 formatter: flaggedIcon,
8189                                                 key: 'flagged'
8190                                         }, 
8191                                         {
8192                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>", 
8193                                                 width: widths[1], 
8194                                                 sortable: true, 
8195                                                 fixed: true,
8196                                                 resizeable: true,
8197                                                 formatter: repliedIcon,
8198                                                 key: 'status'
8199                                         },
8200                                         {
8201                                                 label: app_strings.LBL_EMAIL_FROM, 
8202                                                 width: widths[2],
8203                                                 sortable: true,
8204                                                 resizeable: true,
8205                                                 key: 'from'
8206                                         }, 
8207                                         {
8208                                                 label: app_strings.LBL_EMAIL_SUBJECT,
8209                                                 width: widths[3], 
8210                                                 sortable: true,
8211                                                 resizeable: true,
8212                                                 key: 'subject'
8213                                         }, 
8214                                         {
8215                                                 label: mod_strings.LBL_LIST_DATE,
8216                                                 width: widths[4], 
8217                                                 sortable: true,
8218                                                 resizeable: true,
8219                         key: 'date'
8220                                         }, 
8221                                         {
8222                                                 label: app_strings.LBL_EMAIL_TO,
8223                                                 width: widths[5], 
8224                                                 sortable: false,
8225                                                 resizeable: true,
8226                         key: 'to_addrs'
8227                                         }, 
8228                                         {
8229                                                 label: 'uid',
8230                                                 hidden: true,
8231                         key: 'uid'
8232                                         }, 
8233                                         {
8234                                                 label: 'mbox',
8235                                                 hidden: true,
8236                         key: 'mbox'
8237                                         }, 
8238                                         {
8239                                                 label: 'ieId',
8240                                                 hidden: true,
8241                         key: 'ieId'
8242                                         }, 
8243                                         {       
8244                                                 label: 'site_url',
8245                                                 hidden: true,
8246                         key: 'site_url'
8247                                         },
8248                                         {       label: 'seen',
8249                                                 hidden: true,
8250                         key: 'seen'
8251                                         },
8252                                         {       label: 'type',
8253                                                 hidden: true,
8254                         key: 'type'
8255                                         }
8256                                 ];
8257                         
8258                         var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8259                                 responseType: YAHOO.util.DataSource.TYPE_JSON,
8260                                 responseSchema: {
8261                                     resultsList: 'Email',
8262                             fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8263                             metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8264                                 }
8265                     });
8266                         var params = {
8267                                         to_pdf : "true",
8268                                         module : "Emails",
8269                                         action : "EmailUIAjax",
8270                                         emailUIAction : "getMessageList",
8271                                         mbox : "INBOX",
8272                                         ieId : "",
8273                                         forceRefresh : "false"
8274                         };
8275                         if(lazyLoadFolder != null) {
8276                                 params['mbox'] = lazyLoadFolder.folder;
8277                                 params['ieId'] = lazyLoadFolder.ieId;
8278                                 //Check if the folder is a Sugar Folder
8279                                 var test = new String(lazyLoadFolder.folder);
8280                                 if(test.match(/SUGAR\./)) {
8281                                         params['emailUIAction'] = 'getMessageListSugarFolders';
8282                                         params['mbox'] = test.substr(6);
8283                                 }
8284                         }
8285                         //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8286         
8287                         // create the Grid
8288                         var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8289                                 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8290                                 dynamicData: true,
8291                                 paginator: new YAHOO.widget.Paginator({ 
8292                                         rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),  
8293                                         containers : ["dt-pag-nav"],
8294                                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8295                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8296                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8297                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8298                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8299                                 }),
8300                                 initialRequest:SUGAR.util.paramsToUrl(params),
8301                                 width:  "800px",
8302                                 height: "400px"
8303                         });
8304
8305                         initRowDD();
8306
8307                         //Override Paging request construction
8308                         grid.set("generateRequest", function(oState, oSelf) {
8309                     oState = oState || {pagination:null, sortedBy:null};
8310                     var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8311                     var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8312                     var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8313                     var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8314                     // Build the request 
8315                     var ret = 
8316                             SUGAR.util.paramsToUrl(oSelf.params) + 
8317                             "&sort=" + sort +
8318                         "&dir=" + dir +
8319                         "&start=" + startIndex +
8320                         ((results !== null) ? "&limit=" + results : "");
8321                     return  ret;
8322                 });
8323                         
8324                         
8325                         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8326                                 oPayload = oPayload || { };
8327                                 
8328                                 oPayload.totalRecords = oResponse.meta.total;
8329                                 oPayload.unreadRecords = oResponse.meta.unread;
8330                                 
8331                         var tabObject = SE.innerLayout.get("tabs")[0];
8332                         var mboxTitle = "";
8333                         if (this.params.mbox != null) {
8334                                 mboxTitle = this.params.mbox;
8335                         }
8336                         var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8337                         tabObject.get("labelEl").firstChild.data = tabtext;
8338                         
8339                         if (SE.tree) {
8340                                 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8341                                 if (node) {
8342                                         node.data.unseen = oResponse.meta.unread;
8343                                         SE.accounts.renderTree();
8344                                 }
8345                         }
8346                                 return oPayload; 
8347                         }
8348                         
8349                         var resize = grid.resizeGrid = function () {
8350                                 SUGAR.email2.grid.set("width",  SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8351                                 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8352                         }
8353                         grid.convertDDRows = function() {
8354                                 var rowEl = this.getFirstTrEl();
8355                                 while (rowEl != null) {
8356                                         new this.DDRow(this, this.getRecord(rowEl), rowEl);
8357                                         rowEl = this.getNextTrEl(rowEl);
8358                                 }
8359                         }
8360                         
8361                         
8362                         grid.on("columnResizeEvent", function(o) {
8363                                 //Find the index of the column
8364                                 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8365                                 for (var i=0; i < colSet.length; i++) {
8366                                         if (o.column == colSet[i]) {
8367                                                 //Store it in the cookie
8368                                                 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8369                                         }
8370                                 }
8371                                 //this.resizeGrid();
8372                         }, null, grid); 
8373                         
8374                         grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8375                         grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);  
8376                         grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);  
8377                         grid.render();
8378                         SUGAR.email2.listViewLayout.on("render", resize);
8379                         resize();
8380                         
8381                         //Setup the default load parameters
8382                         SUGAR.email2.grid.params = params;
8383                         
8384                         grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8385                         dataModel.subscribe("requestEvent", grid.disable, grid, true);
8386                         dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8387                 }
8388         };
8389         e2Grid.init();
8390 };
8391
8392
8393 function initRowDD() {
8394         var sg = SUGAR.email2.grid,
8395         Dom = YAHOO.util.Dom;
8396         sg.DDRow = function(oDataTable, oRecord, elTr) {
8397                 if(oDataTable && oRecord && elTr) {
8398                         this.ddtable = oDataTable;
8399                 this.table = oDataTable.getTableEl();
8400                 this.row = oRecord;
8401                 this.rowEl = elTr;
8402                 this.newIndex = null;
8403                 this.init(elTr);
8404                 this.initFrame(); // Needed for DDProxy
8405                 this.invalidHandleTypes = {};
8406             }   
8407         };
8408         
8409         YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8410             _resizeProxy: function() {
8411                 this.constructor.superclass._resizeProxy.apply(this, arguments);
8412                 var dragEl = this.getDragEl(),
8413                     el = this.getEl();
8414                 var xy = Dom.getXY(el);
8415                 
8416                 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8417                 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8418                 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8419                 Dom.setStyle(dragEl, 'display', "");
8420             },
8421             
8422             startDrag: function(x, y) { 
8423                 //Check if we should be dragging a set of rows rather than just the one.
8424                 var selectedRows = this.ddtable.getSelectedRows();
8425                 var iSelected = false;
8426                 for (var i in selectedRows) {
8427                         if (this.rowEl.id == selectedRows[i]) {
8428                                 iSelected = true;
8429                                 break
8430                         }
8431                 }
8432                 if (iSelected) {
8433                         this.rows = [];
8434                         for (var i in selectedRows) {
8435                                 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8436                         }
8437                 } else {
8438                         this.rows = [this.row];
8439                         this.ddtable.unselectAllRows();
8440                         this.ddtable.selectRow(this.row);
8441                 }
8442                 
8443                 //Initialize the dragable proxy
8444                 var dragEl = this.getDragEl(); 
8445                 var clickEl = this.getEl(); 
8446                 Dom.setStyle(clickEl, "opacity", "0.25"); 
8447                 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>"; 
8448                 Dom.addClass(dragEl, "yui-dt-liner");
8449                 Dom.setStyle(dragEl, "opacity", "0.5"); 
8450                 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8451                 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); 
8452                     Dom.setStyle(dragEl, "border", "2px solid gray"); 
8453             },
8454             
8455             clickValidator: function(e) {
8456                 if (this.row.getData()[0] == " ")
8457                         return false;
8458                 var target = YAHOO.util.Event.getTarget(e);
8459                 return ( this.isValidHandleChild(target) && 
8460                                 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8461             },
8462             /**
8463              * This funciton checks that the target of the drag is a table row in this
8464              * DDGroup and simply moves the sourceEL to that location as a preview.
8465              */
8466             onDragOver: function(ev, id) {
8467                 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8468                 if (node && node != this.targetNode) {
8469                         this.targetNode = node;
8470                         SUGAR.email2.folders.unhighliteAll();
8471                         node.highlight();
8472                 }
8473             },
8474             
8475             onDragOut: function(e, id) {
8476                 if (this.targetNode) {
8477                         SUGAR.email2.folders.unhighliteAll();
8478                         this.targetNode = false;
8479                 }
8480             },
8481             endDrag: function() {
8482                 Dom.setStyle(this.getEl(), "opacity", "");
8483                 Dom.setStyle(this.getDragEl(), "display", "none"); 
8484                 if (this.targetNode) {
8485                         SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8486                 }
8487                 SUGAR.email2.folders.unhighliteAll();
8488                 this.rows = null;
8489             }
8490         });
8491 }
8492
8493 function AddressSearchGridInit() {
8494     function moduleIcon(elCell, oRecord, oColumn, oData) {
8495         elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8496     };
8497     function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8498         elCell.innerHTML =  '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8499     };
8500     var checkHeader = '<input type="checkbox" ';
8501     if (SUGAR.email2.util.isIe()) {
8502         checkHeader += 'style="top:-5px" ';
8503     }
8504     checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8505     var colModel = 
8506             [{
8507                 label: checkHeader,
8508             width: 30,
8509             formatter: selectionCheckBox,
8510             key: 'bean_id'
8511         },
8512             {
8513                 label: mod_strings.LBL_LIST_TYPE,
8514                 width: 25,
8515                 formatter: moduleIcon,
8516                 key: 'bean_module'
8517         },
8518             {
8519                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME, 
8520                 width: 180,
8521                 sortable: true,
8522                 key: 'name'
8523             }, 
8524             {
8525                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8526                 width: 300, 
8527                 sortable: true,
8528                 key: 'email'
8529             }];
8530     
8531     var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8532                 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8533         responseSchema: {
8534             resultsList: 'Person',
8535             fields: ['name', 'email', 'bean_id', 'bean_module'],
8536                     metaFields: {total: 'TotalCount'}
8537         },
8538         //enable sorting on the server accross all data
8539         remoteSort: true
8540     });
8541     dataModel.params = {
8542                 to_pdf          : true,
8543                 module          : "Emails",
8544                 action          : "EmailUIAjax",
8545                 emailUIAction:"getAddressSearchResults"
8546     }
8547     var rb = document.getElementById('hasRelatedBean').checked;
8548         if (rb) {
8549                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8550                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8551                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8552                 dataModel.params['related_bean_id'] = relatedBeanId;
8553                 dataModel.params['related_bean_type'] = relatedBeanType;
8554                 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8555         }
8556     SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8557     
8558     var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8559         MSG_EMPTY: "&nbsp;", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8560                 dynamicData: true,
8561                 paginator: new YAHOO.widget.Paginator({ 
8562                         rowsPerPage: 25,  
8563                         containers : ["dt-pag-nav-addressbook"],
8564                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8565                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8566                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8567                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8568                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8569                 }),
8570                 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8571                 width:  "560px",
8572                 height: "250px"
8573     });
8574         //Override Paging request construction
8575         grid.set("generateRequest", function(oState, oSelf) {
8576         oState = oState || {pagination:null, sortedBy:null};
8577         var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8578         var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8579         var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8580         var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8581         // Build the request 
8582         var ret = 
8583             SUGAR.util.paramsToUrl(oSelf.getDataSource().params) + 
8584             "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8585             ((results !== null) ? "&limit=" + results : "");
8586         return  ret;
8587     });
8588     
8589         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8590                 oPayload = oPayload || { };
8591                 oPayload.totalRecords = oResponse.meta.total;
8592                 return oPayload; 
8593         }
8594         
8595         grid.clickToggleSelect= function(args) {
8596                 var isIE = (args.event.target == null);
8597                 var targetElement = isIE ? args.event.srcElement : args.event.target;
8598                 if(targetElement.type == null || targetElement.type != 'checkbox') {
8599                         SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8600                 }
8601         }
8602         
8603         grid.reSelectRowsOnRender = function (){
8604             var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8605         for (var i = 0; i < rows.length; i++) 
8606         {
8607                 var emailAddress = rows[i].getData("email");
8608             var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8609             if(alreadyAdded)
8610             {
8611                 rows[i].setData("selected",  true);
8612                         SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8613             }
8614             else
8615             {
8616                 rows[i].setData("selected",  false);
8617                 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8618             }
8619         }
8620         }
8621         grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow); 
8622         grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow); 
8623         grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8624     grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8625     
8626     grid.render();
8627     dataModel.subscribe("requestEvent", grid.disable, grid, true);
8628     dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8629     
8630     grid.toggleSelectCheckbox = function(id,checked){
8631         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8632         row.setData("checked",checked);
8633     };
8634     grid.toggleSelect = function(id, checked) {
8635         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8636         checked = row.getData("selected");
8637         if (!checked)
8638         {
8639             SUGAR.email2.addressBook.grid.selectRow(row);
8640             SE.addressBook.insertContactRowToResultTable(id,null)
8641         } else 
8642         {
8643             SUGAR.email2.addressBook.grid.unselectRow(row);
8644             SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8645         }
8646         row.setData("selected", !checked);
8647     };
8648     
8649     grid.toggleSelectAll = function(checked) {
8650         rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8651         for (var i = 0; i < rows.length; i++) {
8652                         if (typeof(rows[i]) != "undefined")
8653                                 rows[i].setData("checked",  checked);
8654         }
8655         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8656         for (var i = 0; i < checkBoxes.length; i++) {
8657             checkBoxes[i].checked = checked;
8658         }
8659     };
8660     
8661     //Initialize the grid result table.
8662     AddressSearchResultsGridInit();
8663 }
8664
8665
8666
8667 /**
8668 *  Initalize the results table for the address book selection.
8669 *
8670 */
8671 function AddressSearchResultsGridInit()
8672 {
8673     
8674     /* Full name sort funciton to compare by last name if available */
8675     var fullNameSort = function(a, b, desc) {
8676         // Deal with empty values
8677         if(!YAHOO.lang.isValue(a))
8678             return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8679         else if(!YAHOO.lang.isValue(b))
8680             return -1;
8681
8682         var aNames = a.getData("name").split(' ');
8683         var bNames = b.getData("name").split(' ');
8684
8685         var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8686         var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8687
8688         return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8689
8690     };
8691     
8692     var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8693                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8694                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')]; 
8695               
8696     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})},
8697                      {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8698      
8699      var myDataSource = new YAHOO.util.DataSource([]); 
8700          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
8701          myDataSource.responseSchema = { 
8702                     fields: ["name","type","email_address","display_email_address","bean_id","idx"] 
8703                 };                                                                 
8704     
8705          var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8706                         width:  "350px",height: "250px", MSG_EMPTY: "&nbsp;"});
8707     
8708      var highlightEditableCell = function(oArgs) {
8709             var elCell = oArgs.target;
8710             if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8711                 this.highlightCell(elCell);
8712             }
8713         };
8714       
8715      gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8716      gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8717      gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8718      gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow); 
8719          gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow); 
8720      
8721      //Setup the context menus
8722      var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) { 
8723              var task = p_aArgs[1]; 
8724              if(task) 
8725              { 
8726                  var elRow = this.contextEventTarget; 
8727                  elRow = p_myDataTable.getTrEl(elRow); 
8728          
8729                  if(elRow) 
8730                  { 
8731                      switch(task.index) 
8732                      { 
8733                          case 0:     
8734                              var oRecord = p_myDataTable.getRecord(elRow); 
8735                              p_myDataTable.deleteRow(elRow);  
8736                              SUGAR.email2.addressBook.grid.reSelectRowsOnRender();    
8737                      } 
8738                  } 
8739              } 
8740          };
8741      var contextMenu = new YAHOO.widget.ContextMenu("contextmenu", 
8742                         {trigger:gridResults.getTbodyEl()}); 
8743          contextMenu.addItem(app_strings.LBL_EMAIL_DELETE); 
8744          contextMenu.render("addrSearchResultGrid"); 
8745          contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults); 
8746 }
8747 // End of File modules/Emails/javascript/grid.js
8748                                 
8749 /*********************************************************************************
8750  * SugarCRM Community Edition is a customer relationship management program developed by
8751  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8752  * 
8753  * This program is free software; you can redistribute it and/or modify it under
8754  * the terms of the GNU Affero General Public License version 3 as published by the
8755  * Free Software Foundation with the addition of the following permission added
8756  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8757  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8758  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8759  * 
8760  * This program is distributed in the hope that it will be useful, but WITHOUT
8761  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8762  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8763  * details.
8764  * 
8765  * You should have received a copy of the GNU Affero General Public License along with
8766  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8767  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8768  * 02110-1301 USA.
8769  * 
8770  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8771  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8772  * 
8773  * The interactive user interfaces in modified source and object code versions
8774  * of this program must display Appropriate Legal Notices, as required under
8775  * Section 5 of the GNU Affero General Public License version 3.
8776  * 
8777  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8778  * these Appropriate Legal Notices must retain the display of the "Powered by
8779  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8780  * technical reasons, the Appropriate Legal Notices must display the words
8781  * "Powered by SugarCRM".
8782  ********************************************************************************/
8783
8784 /**
8785   Complex layout init
8786  */
8787 function complexLayoutInit() {
8788         var se = SUGAR.email2;
8789         var Dom = YAHOO.util.Dom;
8790         se.e2Layout = {
8791         getInnerLayout : function(rows) {
8792                 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8793                 parent: se.complexLayout,  
8794                         border:true,
8795                     hideOnLayout: true,
8796                     height: 400,
8797                                 units: [{
8798                                         position: "center",
8799                                     scroll:false, // grid should autoScroll itself
8800                                     split:true,
8801                                     body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8802                                 },{
8803                                         position: "bottom",
8804                                     scroll:true,
8805                                     collapse: false,
8806                                     resize: true,
8807                                     useShim:true,
8808                                     height:'250',
8809                                     body: "<div id='listBottom' />"
8810                                 },{
8811                                     position: "right",
8812                                     scroll:true,
8813                                     collapse: false,
8814                                     resize: true,
8815                                     useShim:true,
8816                                     width:'250',
8817                                     body: "<div id='listRight' />",
8818                                     titlebar: false //,header: "right"
8819                                 }]
8820             });
8821                 se.complexLayout.on("render", function(){
8822                         var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8823                                 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8824                                 SUGAR.email2.listViewLayout.set("height", height);
8825                                 SUGAR.email2.listViewLayout.render();
8826                 });
8827             se.listViewLayout.render();
8828             //CSS hack for now
8829             se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8830             var rp = se.listViewLayout.resizePreview = function() {
8831                 var pre = Dom.get("displayEmailFramePreview");
8832                 if (pre) {
8833                         var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8834                         pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8835                 }
8836             };
8837             se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8838             se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8839             se.e2Layout.setPreviewPanel(rows);
8840             se.previewLayout = se.listViewLayout;
8841             return se.listViewLayout;
8842         },
8843         
8844         getInnerLayout2Rows : function() {
8845             return this.getInnerLayout(true);
8846         },
8847         getInnerLayout2Columns : function() {
8848             return this.getInnerLayout(false);
8849         },
8850         
8851         init : function(){
8852             // initialize state manager, we will use cookies
8853 //                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8854                 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8855                 se.complexLayout = new YAHOO.widget.Layout("container", {
8856                         border:true,
8857                 hideOnLayout: true,
8858                 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8859                 width: Dom.getViewportWidth() - 40,
8860                 units: [{
8861                         position: "center",
8862                     scroll:false,
8863                     body: "<div id='emailtabs'></div>"
8864                 },
8865                 {
8866                         position: "left",
8867                         scroll: true,
8868                         body: "<div id='lefttabs'></div>",
8869                     collapse: true,
8870                     width: 210,
8871                     minWidth: 100,
8872                     resize:true,
8873                     useShim:true,
8874                     titlebar: true,
8875                     header: "&nbsp;"
8876                 },
8877                 {
8878                     header: Dom.get('footerLinks').innerHTML,
8879                                         position: 'bottom',
8880                                         id: 'mbfooter',
8881                                         height: 22,
8882                                         border: false
8883                 }]
8884             });
8885                 se.complexLayout.render();
8886                 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8887                         tp.addTab(new YAHOO.widget.Tab({ 
8888                                 label: "Inbox",
8889                                 scroll : true,
8890                                 content : "<div id='listViewDiv'/>",
8891                                 id : "center",
8892                                 active : true
8893                         }));
8894                 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8895                         tp.appendTo(centerEl);
8896                         //CSS hack for now
8897                         tp.get("element").style.borderRight = "1px solid #666"
8898                         
8899                         var listV =  this.getInnerLayout2Rows();
8900                         listV.set("height", tp.get("element").clientHeight - 25);
8901                         listV.render();
8902                 
8903             se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8904             var folderTab = new YAHOO.widget.Tab({ 
8905                                 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8906                                 scroll : true,
8907                                 content : "<div id='emailtree'/>",
8908                                 id : "tree",
8909                                 active : true
8910                         });
8911             folderTab.on("activeChange", function(o){ 
8912                 if (o.newValue) {
8913                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8914                 }
8915             });
8916             se.leftTabs.addTab(folderTab);
8917             
8918             var tabContent = SUGAR.util.getAndRemove("searchTab");
8919             var searchTab = new YAHOO.widget.Tab({ 
8920                                 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8921                                 scroll : true,
8922                                 content : tabContent.innerHTML,
8923                                 id : tabContent.id
8924                         });
8925             searchTab.on("activeChange", function(o){ 
8926                 if (o.newValue) 
8927                 {
8928                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8929                    //Setup the calendars if needed
8930                        Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
8931                        Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
8932                    
8933                        //Initalize sqs object for assigned user name 
8934                        se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');  
8935                        
8936                        //Attach event handler for when the relate module option is selected for the correct sqs object
8937                        var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8938                                                 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8939                        YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){ 
8940                            SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8941                        
8942                        //If enter key is pressed, perform search
8943                        var  addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8944                        for(var i=0; i < addKeyPressFields.length;i++)
8945                        {
8946                        YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8947                                 if (e.keyCode == 13) {
8948                                         YAHOO.util.Event.stopEvent(e);
8949                                         SUGAR.email2.search.searchAdvanced();
8950                                 }
8951                        });
8952                        }
8953                                    //Initiate quick search for the search tab.  Do this only when the tab is selected rather than onDomLoad for perf. gains.
8954                        enableQS(true);
8955                        //Clear parent values if selecting another parent type.
8956                        YAHOO.util.Event.addListener('data_parent_type_search','change', 
8957                            function(){ 
8958                                document.getElementById('data_parent_id_search').value =''; 
8959                                document.getElementById('data_parent_name_search').value =''; 
8960                            });
8961                 
8962                 }
8963             });
8964             se.leftTabs.addTab(searchTab);
8965             
8966             var resizeTabBody = function() {
8967                 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8968                                 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8969             }
8970             resizeTabBody();
8971             se.complexLayout.on("render", resizeTabBody);
8972             se.leftTabs.on("activeTabChange", resizeTabBody);
8973                         //hack to allow left pane scroll bar to fully show
8974                 var lefttabsDiv = document.getElementById('lefttabs');
8975                         var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8976                         var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8977                         lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8978           
8979         },
8980         initSQSObject: function(formName,fieldName)
8981         {
8982             var fullFieldName = formName + '_' + fieldName; //SQS Convention
8983             var resultName = fullFieldName + '_' + 'results';
8984             
8985             if (QSFieldsArray[fullFieldName] != null) 
8986             {
8987                 QSFieldsArray[fullFieldName].destroy();
8988                 delete QSFieldsArray[fullFieldName];
8989             }
8990             if (QSProcessedFieldsArray[fullFieldName])
8991             QSProcessedFieldsArray[fullFieldName] = false;
8992
8993             if( Dom.get(resultName) )
8994             {
8995                 var obj = document.getElementById(resultName);
8996                 obj.parentNode.removeChild(obj);
8997             }
8998         },
8999         setPreviewPanel: function(rows) {
9000                 if (rows) {
9001                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9002                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9003                 Dom.get("listRight").innerHTML = "";
9004                 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9005             } else {
9006                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9007                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9008                 Dom.get("listBottom").innerHTML = "";
9009                 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9010             }
9011         }
9012     };
9013         se.e2Layout.init();
9014 }
9015
9016 var myBufferedListenerObject = new Object();
9017 myBufferedListenerObject.refit = function() {
9018     if(SUGAR.email2.grid) {
9019         SUGAR.email2.grid.autoSize();
9020     }
9021 }
9022 // End of File modules/Emails/javascript/complexLayout.js
9023                                 
9024 /*********************************************************************************
9025  * SugarCRM Community Edition is a customer relationship management program developed by
9026  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9027  * 
9028  * This program is free software; you can redistribute it and/or modify it under
9029  * the terms of the GNU Affero General Public License version 3 as published by the
9030  * Free Software Foundation with the addition of the following permission added
9031  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9032  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9033  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9034  * 
9035  * This program is distributed in the hope that it will be useful, but WITHOUT
9036  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9037  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9038  * details.
9039  * 
9040  * You should have received a copy of the GNU Affero General Public License along with
9041  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9042  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9043  * 02110-1301 USA.
9044  * 
9045  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9046  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9047  * 
9048  * The interactive user interfaces in modified source and object code versions
9049  * of this program must display Appropriate Legal Notices, as required under
9050  * Section 5 of the GNU Affero General Public License version 3.
9051  * 
9052  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9053  * these Appropriate Legal Notices must retain the display of the "Powered by
9054  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9055  * technical reasons, the Appropriate Legal Notices must display the words
9056  * "Powered by SugarCRM".
9057  ********************************************************************************/
9058
9059
9060 /******************************************************************************
9061  * Initialize Email 2.0 Application
9062  */
9063
9064 //Override Sugar Languge so quick creates work properly
9065
9066
9067 function email2init() {
9068
9069         //Init Tiny MCE
9070     // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9071     //             "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9072     if (!SUGAR.util.isTouchScreen()) {
9073          tinyMCE.init({
9074                  convert_urls : false,
9075          theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9076          width: tinyConfig.width,
9077          theme: tinyConfig.theme,
9078          theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9079          theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9080          theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9081          theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9082          plugins : tinyConfig.plugins,
9083          elements : tinyConfig.elements,
9084          language : tinyConfig.language,
9085          extended_valid_elements : tinyConfig.extended_valid_elements,
9086          mode: tinyConfig.mode,
9087          strict_loading_mode : true,
9088                  force_br_newlines : true,
9089          forced_root_block : '',
9090          directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
9091      });
9092     }
9093
9094     // initialze message overlay
9095     SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9096             //iframe        : true,
9097             modal       : false,
9098             autoTabs    : true,
9099             width       : 300,
9100             height      : 120,
9101             shadow      : true
9102         }
9103     );
9104         // Hide Sugar menu
9105         if (SUGAR.themes.tempHideLeftCol)
9106         SUGAR.themes.tempHideLeftCol();
9107
9108         // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9109 //      YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9110
9111         // set defaults for YAHOO.util.DragDropManager
9112         YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9113
9114         SUGAR.email2.nextYear = new Date();
9115         SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9116
9117         
9118     // initialize and display UI framework (complexLayout.js)
9119     complexLayoutInit();
9120     
9121     // initialize and display grid (grid.js)
9122     gridInit();
9123     
9124     // initialize treeview for folders
9125         //onloadTreeinit();
9126         SUGAR.email2.folders.rebuildFolders(true);
9127         
9128         
9129     //Setup the Message Box overlay
9130     /*Ext.MessageBox.maxWidth = 350;
9131     Ext.MessageBox.minProgressWidth = 350;
9132
9133         ///////////////////////////////////////////////////////////////////////////
9134         ////    CONTEXT MENUS
9135         // detailView array
9136         SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9137 */
9138         var SEC = SUGAR.email2.contextMenus; 
9139         
9140         //Grid menu
9141         var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9142                 trigger: SUGAR.email2.grid.get("element"),
9143                 lazyload: true
9144         });
9145         emailMenu.subscribe("beforeShow", function() {
9146                 var oTarget = this.contextEventTarget;
9147                 if (typeof(oTarget) == "undefined")
9148                   return;
9149                 var grid = SUGAR.email2.grid;
9150                 var selectedRows = grid.getSelectedRows();
9151                 var multipleSelected = (selectedRows.length > 1) ? true: false;
9152                 if (!multipleSelected)
9153                 {
9154                         grid.unselectAllRows();
9155                         grid.selectRow(oTarget);
9156                         SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));    
9157                 }
9158                 else if(multipleSelected)
9159                 {
9160                     SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9161                 }
9162         });
9163         
9164         //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9165         //us to access individual elements easier by name rather than by index
9166         emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2,  'reply' : 3,'replyAll' : 4,'forward' : 5,
9167                                    'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9168         emailMenu.addItems([
9169         {
9170             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9171             id: 'showDetailView',
9172             onclick: { fn: SEC.showDetailView }
9173         },
9174         {
9175             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9176             onclick: { fn: SEC.openMultiple }
9177         },
9178         {
9179             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9180             onclick: { fn: SEC.archiveToSugar }
9181         },
9182         {
9183             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9184             id: 'reply',
9185             onclick: { fn: SEC.replyForwardEmailContext }
9186         },
9187         {
9188             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9189             id: 'replyAll',
9190             onclick: { fn: SEC.replyForwardEmailContext }
9191         },
9192         {
9193             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9194             id: 'forward',
9195             onclick: { fn: SEC.replyForwardEmailContext }
9196         },
9197         {
9198             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9199             id: 'delete',
9200             onclick: { fn: SEC.markDeleted }
9201         },
9202         {
9203             text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9204             id: 'print',
9205             onclick: { fn: SEC.viewPrintable }
9206         },                
9207         // Mark... submenu
9208         {
9209             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9210             submenu: {
9211                         id: "markEmailMenu",
9212                 itemdata : [
9213                     {
9214                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9215                         onclick: { fn: SEC.markUnread }
9216                     },
9217                     {
9218                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9219                         onclick: { fn: SEC.markRead }
9220                     },
9221                     {
9222                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9223                         onclick: { fn: SEC.markFlagged }
9224                     },
9225                     {
9226                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9227                         onclick: {  fn: SEC.markUnflagged }
9228                     }
9229                 ]
9230             }
9231          },
9232         {
9233             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9234                 id: 'assignTo',
9235                 onclick: { fn: SEC.assignEmailsTo }
9236          },
9237          {
9238             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9239             id: 'relateTo',
9240             onclick: { fn: SEC.relateTo }
9241          }
9242     ]);
9243         SEC.emailListContextMenu.render();
9244         
9245         //Handle the Tree folder menu trigger ourselves
9246         YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9247
9248         
9249         //Folder Menu
9250     SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9251                 trigger: "",
9252                 lazyload: true 
9253         });
9254     SEC.frameFoldersContextMenu.addItems([
9255                 {   text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9256                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9257                         onclick: {  fn: function() {
9258                         var node = SUGAR.email2.clickedFolderNode;
9259                         if (node.data.ieId) {
9260                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9261                     }}
9262                 },
9263                 {   text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9264                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9265                         onclick: {  fn: function() {
9266                         var node = SUGAR.email2.clickedFolderNode;
9267                         if (node.data.ieId) {
9268                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9269                     }}
9270                 },
9271                 {
9272                     text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9273                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9274                     onclick: {  fn: SUGAR.email2.folders.folderAdd }
9275                 },
9276                 {
9277                     text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9278                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9279                     onclick: {  fn: SUGAR.email2.folders.folderDelete }
9280                 },
9281                 {
9282                     text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9283                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9284                     onclick: {  fn: SUGAR.email2.folders.folderRename }
9285                  },
9286                  {
9287                     text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9288                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9289                     onclick: {  fn: SUGAR.email2.folders.emptyTrash }
9290                   },
9291                  {
9292                     text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9293                     onclick: {  fn: function() {
9294                         var node = SUGAR.email2.clickedFolderNode;
9295                         if (node.data.ieId) {
9296                             SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9297                     }}
9298                   } 
9299         ]);
9300     SEC.frameFoldersContextMenu.render();
9301     
9302     SEC.initContactsMenu = function() {
9303         // contacts
9304         SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9305                 trigger: "contacts",
9306                 lazyload: true
9307         });
9308         SEC.contactsContextMenu.addItems([
9309                 {
9310                         text: app_strings.LBL_EMAIL_MENU_REMOVE,
9311                         onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9312                 },
9313                 {
9314                         text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9315                         onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9316                 }
9317         ]);
9318         SEC.contactsContextMenu.subscribe("beforeShow", function() {
9319                 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9320                 if (oTarget && !grid.isSelected(oTarget)) {
9321                         grid.unselectAllRows();
9322                         grid.selectRow(oTarget);
9323                 }
9324         });
9325         SEC.contactsContextMenu.render();
9326         }
9327         
9328         
9329         // set auto-check timer
9330         SUGAR.email2.folders.startCheckTimer();
9331         // check if we're coming from an email-link click
9332         setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9333         
9334         YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9335         
9336         //Init fix for YUI 2.7.0 datatable sort.
9337         SUGAR.email2.addressBook.initFixForDatatableSort();
9338 }
9339
9340 function createTreePanel(treeData, params) {
9341         var tree = new YAHOO.widget.TreeView(params.id);
9342         var root = tree.getRoot();
9343         
9344         //if (treeData.nodes && treeData[0].id == "Home")
9345         //      treeData = treeData[0];
9346
9347         addChildNodes(root, treeData);
9348         
9349         return tree;
9350 }
9351
9352 function addChildNodes(parentNode, parentData) {
9353         var Ck = YAHOO.util.Cookie;
9354         var nextyear = SUGAR.email2.nextYear;
9355         var nodes = parentData.nodes || parentData.children;
9356         for (i in nodes) {
9357                 if (typeof(nodes[i]) == 'object') {
9358                         if (nodes[i].data) {
9359                                 nodes[i].data.href = '#';
9360                                 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9361                                 node.action = nodes[i].data.action;
9362                         } else {
9363                                 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9364                                         addChildNodes(parentNode, nodes[i]);
9365                                         return;
9366                                 }
9367                                 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9368                                 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9369                                 if (nodes[i].cls) {
9370                                         nodes[i].className = nodes[i].cls;
9371                                 }
9372                                 nodes[i].href = "#";
9373                                 if (nodes[i].text) nodes[i].label = nodes[i].text;
9374                                 //Override YUI child node creation
9375                                 if (nodes[i].children) {
9376                                         nodes[i].nodes = nodes[i].children;
9377                                         nodes[i].children = [ ];
9378                                 }
9379                                 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9380                         }
9381                         
9382                         if (typeof(nodes[i].nodes) == 'object') {
9383                                 addChildNodes(node, nodes[i]);
9384                         }
9385                 }
9386         }
9387 }
9388
9389 /**
9390  * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9391  */
9392 function email2treeinit(tree, treedata, treediv, params) {
9393         //ensure the tree data is not corrupt
9394         if (!treedata) {
9395            return;
9396         }
9397         if (SUGAR.email2.tree) {
9398                 SUGAR.email2.tree.destroy();
9399                 SUGAR.email2.tree = null;
9400         }
9401         
9402         var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9403                 id: 'emailtree'
9404         });
9405         
9406         tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9407         tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9408         tree.subscribe("expandComplete", function(node){
9409                 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9410                 for (var i in node.children) {
9411                         SE.accounts.setupDDTarget(node.children[i]);
9412                 }
9413         });
9414         tree.setCollapseAnim("TVSlideOut");
9415         tree.setExpandAnim("TVSlideIn");
9416         var root = tree.root;
9417         while (root.hasChildren()) {
9418                 var node = root.children[0];
9419                 node.destroy();
9420                 tree.removeNode(root.children[0], false);
9421         }
9422         addChildNodes(root, treedata);
9423         tree.render();
9424         SUGAR.email2.accounts.renderTree();
9425 }
9426
9427 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9428         SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9429 };
9430
9431
9432 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {    
9433     startDrag: function(x, y) {
9434                 var Dom = YAHOO.util.Dom;       
9435                 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9436                 
9437                 this.dragId = "";
9438                 var dragEl = this.getDragEl();  
9439         var clickEl = this.getEl(); 
9440         Dom.setStyle(clickEl, "color", "#AAA");
9441         Dom.setStyle(clickEl, "opacity", "0.25"); 
9442         dragEl.innerHTML = clickEl.innerHTML; 
9443          
9444         Dom.addClass(dragEl, "ygtvcell");
9445         Dom.addClass(dragEl, "ygtvcontent");
9446         Dom.addClass(dragEl, "folderDragProxy");
9447         Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9448         Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9449         Dom.setStyle(dragEl, "backgroundColor", "#FFF"); 
9450         Dom.setStyle(dragEl, "opacity", "0.5"); 
9451             Dom.setStyle(dragEl, "border", "1px solid #AAA");
9452     },
9453     
9454     onDragOver: function(ev, id) {
9455         var Dom = YAHOO.util.Dom;
9456         if (id != this.dragId)
9457         {
9458                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9459                 if(node.data.cls != "sugarFolder") {
9460                         SUGAR.email2.folders.unhighliteAll();
9461                         return;
9462                 }
9463                 this.dragId = id;
9464                 this.targetNode = node;
9465                 SUGAR.email2.folders.unhighliteAll();
9466                 node.highlight();
9467         }
9468     },
9469     
9470     onDragOut: function(e, id) {
9471         if (this.targetNode) {
9472                 SUGAR.email2.folders.unhighliteAll();
9473                 this.targetNode = false;
9474                 this.dragId = false;
9475         }
9476     },
9477     
9478     endDrag: function() { 
9479         YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9480         if (this.targetNode) {
9481                 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9482         }
9483     }
9484 });// End of File modules/Emails/javascript/init.js
9485                                 
9486 /*********************************************************************************
9487  * SugarCRM Community Edition is a customer relationship management program developed by
9488  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9489  * 
9490  * This program is free software; you can redistribute it and/or modify it under
9491  * the terms of the GNU Affero General Public License version 3 as published by the
9492  * Free Software Foundation with the addition of the following permission added
9493  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9494  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9495  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9496  * 
9497  * This program is distributed in the hope that it will be useful, but WITHOUT
9498  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9499  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9500  * details.
9501  * 
9502  * You should have received a copy of the GNU Affero General Public License along with
9503  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9504  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9505  * 02110-1301 USA.
9506  * 
9507  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9508  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9509  * 
9510  * The interactive user interfaces in modified source and object code versions
9511  * of this program must display Appropriate Legal Notices, as required under
9512  * Section 5 of the GNU Affero General Public License version 3.
9513  * 
9514  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9515  * these Appropriate Legal Notices must retain the display of the "Powered by
9516  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9517  * technical reasons, the Appropriate Legal Notices must display the words
9518  * "Powered by SugarCRM".
9519  ********************************************************************************/
9520
9521 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9522 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9523 '       <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9524 '               <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9525 '               <input type="hidden" id="uid{idx}" name="uid" value="">' +
9526 '               <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9527 '               <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9528 '               <input type="hidden" id="type{idx}" name="type" value="">' +
9529 '               <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9530 '               <input type="hidden" id="composeType" name="composeType">' +
9531 '               <input type="hidden" id="fromAccount" name="fromAccount">' +
9532 '               <input type="hidden" id="sendSubject" name="sendSubject">' +
9533 '               <input type="hidden" id="sendDescription" name="sendDescription">' +
9534 '               <input type="hidden" id="sendTo" name="sendTo">' +
9535 '               <input type="hidden" id="sendBcc" name="sendBcc">' +
9536 '               <input type="hidden" id="sendCc" name="sendCc">' +
9537 '               <input type="hidden" id="setEditor" name="setEditor">' +
9538 '               <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9539 '               <input type="hidden" id="parent_id" name="parent_id">' +
9540 '               <input type="hidden" id="parent_type" name="parent_type">' +
9541 '               <input type="hidden" id="attachments" name="attachments">' +
9542 '               <input type="hidden" id="documents" name="documents">' +
9543 '               <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9544 '               <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9545 '               <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9546 '               <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9547 '                       <tr>' +
9548 '                               <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9549 '                                       <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>' +
9550 '                                       <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>' +
9551 '                                       <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>' +
9552 '                                       <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>' +
9553 '</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>' + 
9554 '&nbsp;</td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9555 '<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>' +
9556 '                       </td></tr></tbody></table></th>'     +
9557 '                       </tr>' +
9558 '                       <tr>' +
9559 '                               <td>' +
9560 '                                       <div style="margin:5px;">' +
9561 '                                       <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9562 '                                               <tr>' +
9563 '                                                       <td class="emailUILabel" NOWRAP >' +
9564 '                                                               {app_strings.LBL_EMAIL_FROM}:' +
9565 '                                                       </td>' +
9566 '                                                       <td class="emailUIField" NOWRAP>' +
9567 '                                                               <div>' +
9568 '                                                                       &nbsp;&nbsp;<select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9569 '                                                               </div>' +
9570 '                                                       </td>' +
9571 '                                               </tr>' +
9572 '                                               <tr>' +
9573 '                                                       <td class="emailUILabel" NOWRAP>' +
9574 '                                                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' + 
9575 '                                   {app_strings.LBL_EMAIL_TO}:' +
9576 '                               </button>' + 
9577 '                                                       </td>' +
9578 '                                                       <td class="emailUIField" NOWRAP>' +
9579 '                                                               <div class="ac_autocomplete">' +
9580 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9581 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}">&nbsp;</span></a> </span>' +
9582 '                                                                       <div class="ac_container" id="addressToAC{idx}"></div>' +
9583 '                                                               </div>' +
9584 '                                                       </td>' +
9585 '                                               </tr>' +
9586 '                                               <tr id="add_addr_options_tr{idx}">' +
9587 '                                                       <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>'+
9588 '                                               </tr>'+
9589 '                                               <tr class="yui-hidden" id="cc_tr{idx}">' +
9590 '                                                       <td class="emailUILabel" NOWRAP>' +
9591 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' + 
9592 '                                                               {app_strings.LBL_EMAIL_CC}:' +
9593 '                               </button>' + 
9594 '                                                       </td>' +
9595 '                                                       <td class="emailUIField" NOWRAP>' +
9596 '                                                               <div class="ac_autocomplete">' +
9597 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9598 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#"  style="display: none;">+<span id="DetailaddressCC{idx}">&nbsp;</span></a> </span>' + 
9599 '                                                                       <div class="ac_container" id="addressCcAC{idx}"></div>' +
9600 '                                                               </div>' +
9601 '                                                       </td>' +
9602 '                                               </tr>' +
9603 '                                               <tr class="yui-hidden" id="bcc_tr{idx}">' +
9604 '                                                       <td class="emailUILabel" NOWRAP>' +
9605 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' + 
9606 '                               {app_strings.LBL_EMAIL_BCC}:' +
9607 '                               </button>' + 
9608 '                                                       </td>' +
9609 '                                                       <td class="emailUIField" NOWRAP>' +
9610 '                                                               <div class="ac_autocomplete">' +
9611 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9612 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}">&nbsp;</span></a> </span>' +
9613 '                                                                       <div class="ac_container" id="addressBccAC{idx}"></div>' +
9614 '                                                               </div>' +
9615 '                                                       </td>' +
9616 '                                               </tr>' +
9617 '                                               <tr>' +
9618 '                                                       <td class="emailUILabel" NOWRAP width="1%">' +
9619 '                                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9620 '                                                       </td>' +
9621 '                                                       <td class="emailUIField" NOWRAP width="99%">' +
9622 '                                                               <div class="ac_autocomplete">' +
9623 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9624 '                                                               </div>' +
9625 '                                                       </td>' +
9626 '                                               </tr>' +
9627 '                                       </table>' +
9628 '                                       </div>' +
9629 '                               </td>'   +
9630 '                       </tr>' +
9631 '               </table>' +
9632 '               <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9633 '               <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9634 '                       <div style="padding:5px;">' +
9635 '                               <table cellpadding="2" cellspacing="0" border="0">' +
9636 '                                       <tr>' +
9637 '                                               <th>' +
9638 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9639 '                                                       <br />' +
9640 '                                                       &nbsp;' +
9641 '                                               </th>' +
9642 '                                       </tr>' +
9643 '                                       <tr>' +
9644 '                                               <td>' +
9645 '                                                       <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9646 '                                                       <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9647 '                                               </td>' +
9648 '                                       </tr>' +
9649 '                                       <tr>' +
9650 '                                               <td>' +
9651 '                                                       &nbsp;' +
9652 '                                                       <br />' +
9653 '                                                       &nbsp;' +
9654 '                                               </td>' +
9655 '                                       </tr>' +
9656 '                                       <tr>' +
9657 '                                               <th>' +
9658 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9659 '                                                       <br />' +
9660 '                                                       &nbsp;' +
9661 '                                               </th>' +
9662 '                                       </tr>' +
9663 '                                       <tr>' +
9664 '                                               <td>' +
9665 '                                                       <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9666 '                                                       <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>' +
9667 '                                               </td>' +
9668 '                                       </tr>' +
9669 '                                       <tr>' +
9670 '                                               <td>' +
9671 '                                                       &nbsp;' +
9672 '                                                       <br />' +
9673 '                                                       &nbsp;' +
9674 '                                               </td>' +
9675 '                                       </tr>' +
9676 '                                       <tr>' +
9677 '                                               <th>' +
9678 '                                                       <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9679 '                                                       <br />' +
9680 '                                                       &nbsp;' +
9681 '                                               </th>' +
9682 '                                       </tr>' +
9683 '                                       <tr>' +
9684 '                                               <td>' +
9685 '                                                       <div id="addedTemplateAttachments{idx}"></div>' +
9686 '                                               </td>' +
9687 '                                       </tr>' +
9688 '                               </table>' +
9689 '                       </div>' +
9690 '               </div>' +
9691 '       </form>' +
9692 '               <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9693 '             <div style="padding:5px;">' +
9694 '                       <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' + 
9695 '                               <table border="0" width="100%">' +
9696 '                                       <tr>' +
9697 '                                               <td NOWRAP style="padding:2px;">' +
9698 '                                                       <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9699 '                                               </td>' +
9700 '                                       </tr>' +
9701 '                                       <tr>' +
9702 '                                               <td NOWRAP style="padding:2px;">' +
9703 '                                                       <select name="email_template{idx}" id="email_template{idx}"  onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9704 '                                               </td>' +
9705 '                                       </tr>' +
9706 '                               </table>' +
9707 '                               <br />' +
9708 '                               <table border="0" width="100%">' +
9709 '                                       <tr>' +
9710 '                                               <td NOWRAP style="padding:2px;">' +
9711 '                                                       <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9712 '                                               </td>' +
9713 '                                       </tr>' +
9714 '                                       <tr>' +
9715 '                                               <td NOWRAP style="padding:2px;">' +
9716 '                                                       <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9717 '                                               </td>' +
9718 '                                       </tr>' +
9719 '                               </table>' +
9720 '                               <table border="0" width="100%">' +
9721 '                                       <tr>' +
9722 '                                               <td NOWRAP style="padding:2px;">' +
9723 '                                                       <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/>&nbsp;' +
9724 '                                                       <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9725 '                                               </td>' +
9726 '                                       </tr>' +
9727 '                               </table>' +
9728 '         </form>' +
9729 '                       </div> ' +
9730 '               </div>' +
9731 '</div>';
9732 // End of File modules/Emails/javascript/composeEmailTemplate.js
9733                                 
9734 /*********************************************************************************
9735  * SugarCRM Community Edition is a customer relationship management program developed by
9736  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9737  * 
9738  * This program is free software; you can redistribute it and/or modify it under
9739  * the terms of the GNU Affero General Public License version 3 as published by the
9740  * Free Software Foundation with the addition of the following permission added
9741  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9742  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9743  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9744  * 
9745  * This program is distributed in the hope that it will be useful, but WITHOUT
9746  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9747  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9748  * details.
9749  * 
9750  * You should have received a copy of the GNU Affero General Public License along with
9751  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9752  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9753  * 02110-1301 USA.
9754  * 
9755  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9756  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9757  * 
9758  * The interactive user interfaces in modified source and object code versions
9759  * of this program must display Appropriate Legal Notices, as required under
9760  * Section 5 of the GNU Affero General Public License version 3.
9761  * 
9762  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9763  * these Appropriate Legal Notices must retain the display of the "Powered by
9764  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9765  * technical reasons, the Appropriate Legal Notices must display the words
9766  * "Powered by SugarCRM".
9767  ********************************************************************************/
9768
9769 SUGAR.email2.templates['displayOneEmail'] = 
9770 '<div class="emailDetailTable" style="height:100%">' +
9771 '<div id="viewMenuDiv{idx}"></div>' + 
9772 '<div width="100%" class="displayEmailValue">' +
9773 '                                       <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>' +
9774 '                                       <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>' +
9775 '                                       <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>' +
9776 '                                       <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>' +
9777 '                                       <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>' +
9778 '                                       <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>' +
9779 '                                       <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>' +
9780 '                                       <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>' +
9781 '                                       <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>' +
9782 '</div>' +
9783 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9784 '                               <tr>' +
9785 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9786 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9787 '                                       </td>' +
9788 '                                       <td width="99%" class="displayEmailValue">' +
9789 '                                               {email.from_addr}' +
9790 '                                       </td>' +
9791 '                               </tr>' +
9792 '                               <tr>' +
9793 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9794 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9795 '                                       </td>' +
9796 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9797 '                                               <b>{email.name}</b>' +
9798 '                                       </td>' +
9799 '                               </tr>' +
9800 '                               <tr>' +
9801 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9802 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9803 '                                       </td>' +
9804 '                                       <td class="displayEmailValue">' +
9805 '                                               {email.date_start} {email.time_start}' +
9806 '                                       </td>' +
9807 '                               </tr>' +
9808 '                               <tr>' +
9809 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9810 '                                               {app_strings.LBL_EMAIL_TO}:' +
9811 '                                       </td>' +
9812 '                                       <td class="displayEmailValue">' +
9813 '                                               {email.toaddrs}' +
9814 '                                       </td>' +
9815 '                               </tr>' +
9816 '                               <tr>{meta.cc}</tr>' +
9817 '                               <tr>{email.attachments}</tr>' +
9818 '                       </table>' +
9819 '                       <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>' +
9820 //'                           {email.description}' +
9821 '</div>'
9822 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9823                                 
9824 /*********************************************************************************
9825  * SugarCRM Community Edition is a customer relationship management program developed by
9826  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9827  * 
9828  * This program is free software; you can redistribute it and/or modify it under
9829  * the terms of the GNU Affero General Public License version 3 as published by the
9830  * Free Software Foundation with the addition of the following permission added
9831  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9832  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9833  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9834  * 
9835  * This program is distributed in the hope that it will be useful, but WITHOUT
9836  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9837  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9838  * details.
9839  * 
9840  * You should have received a copy of the GNU Affero General Public License along with
9841  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9842  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9843  * 02110-1301 USA.
9844  * 
9845  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9846  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9847  * 
9848  * The interactive user interfaces in modified source and object code versions
9849  * of this program must display Appropriate Legal Notices, as required under
9850  * Section 5 of the GNU Affero General Public License version 3.
9851  * 
9852  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9853  * these Appropriate Legal Notices must retain the display of the "Powered by
9854  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9855  * technical reasons, the Appropriate Legal Notices must display the words
9856  * "Powered by SugarCRM".
9857  ********************************************************************************/
9858
9859 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9860 '<body onload="javascript:window.print();">' + 
9861 '<style>' + 
9862 'body {' + 
9863 '       margin: 0px;' + 
9864 '       font-family: helvetica, impact, sans-serif;' +
9865 '       font-size : 12pt;' +
9866 '} ' +
9867 'table {' +
9868 '       padding:10px;' +
9869 '}' +
9870 '</style>' +
9871 '<div>' +
9872 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9873 '       <tr>' +
9874 '               <td>' +
9875 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9876 '                               <tr>' +
9877 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9878 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9879 '                                       </td>' +
9880 '                                       <td width="99%" class="displayEmailValue">' +
9881 '                                               {email.from_name} &lt;{email.from_addr}&gt;' +
9882 '                                       </td>' +
9883 '                               </tr>' +
9884 '                               <tr>' +
9885 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9886 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9887 '                                       </td>' +
9888 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9889 '                                               <b>{email.name}</b>' +
9890 '                                       </td>' +
9891 '                               </tr>' +
9892 '                               <tr>' +
9893 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9894 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9895 '                                       </td>' +
9896 '                                       <td class="displayEmailValue">' +
9897 '                                               {email.date_start} {email.time_start}' +
9898 '                                       </td>' +
9899 '                               </tr>' +
9900 '                               <tr>' +
9901 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9902 '                                               {app_strings.LBL_EMAIL_TO}:' +
9903 '                                       </td>' +
9904 '                                       <td class="displayEmailValue">' +
9905 '                                               {email.toaddrs}' +
9906 '                                       </td>' +
9907 '                               </tr>' +
9908 '                               {email.cc}' +
9909 '                               {email.attachments}' +
9910 '                       </table>' +
9911 '               </td>' +
9912 '       </tr>' +
9913 '       <tr>' +
9914 '               <td>' +
9915 '                       <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9916 '                               <tr>' +
9917 '                                       <td style="border-top: 1px solid #333;">' +
9918 '                                               <div style="padding:5px;">' +
9919                                                         '{email.description}' +
9920 '                                               </div>' +
9921 '                                       </td>' +
9922 '                               </tr>' +
9923 '                       </table>' +
9924 '               </td>' +
9925 '       </tr>' +
9926 '</table>' +
9927 '</div>' +
9928 '</body></html>';
9929 // End of File modules/Emails/javascript/viewPrintable.js
9930                                 
9931 /*********************************************************************************
9932  * SugarCRM Community Edition is a customer relationship management program developed by
9933  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9934  *
9935  * This program is free software; you can redistribute it and/or modify it under
9936  * the terms of the GNU Affero General Public License version 3 as published by the
9937  * Free Software Foundation with the addition of the following permission added
9938  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9939  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9940  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9941  *
9942  * This program is distributed in the hope that it will be useful, but WITHOUT
9943  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9944  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9945  * details.
9946  *
9947  * You should have received a copy of the GNU Affero General Public License along with
9948  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9949  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9950  * 02110-1301 USA.
9951  *
9952  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9953  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9954  *
9955  * The interactive user interfaces in modified source and object code versions
9956  * of this program must display Appropriate Legal Notices, as required under
9957  * Section 5 of the GNU Affero General Public License version 3.
9958  *
9959  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9960  * these Appropriate Legal Notices must retain the display of the "Powered by
9961  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9962  * technical reasons, the Appropriate Legal Notices must display the words
9963  * "Powered by SugarCRM".
9964  ********************************************************************************/
9965 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9966 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;}
9967 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');}
9968 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;}}
9969 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9970 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9971 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}
9972 if(!loaded){QSProcessedFieldsArray[qs_index_id]=true;qsFields[qsField].form_id=form_id;var sqs=sqs_objects[qs_index_id];var resultDiv=document.createElement('div');resultDiv.id=combo_id+"_results";Dom.insertAfter(resultDiv,qsFields[qsField]);var fields=qs_obj.field_list.slice();fields[fields.length]="module";var ds=new YAHOO.util.DataSource("index.php?",{responseType:YAHOO.util.XHRDataSource.TYPE_JSON,responseSchema:{resultsList:'fields',total:'totalCount',fields:fields,metaNode:"fields",metaFields:{total:'totalCount',fields:"fields"}},connMethodPost:true});var forceSelect=!((qsFields[qsField].form&&typeof(qsFields[qsField].form)=='object'&&qsFields[qsField].form.name=='search_form')||qsFields[qsField].className.match('sqsNoAutofill')!=null);var search=new YAHOO.widget.AutoComplete(qsFields[qsField],resultDiv,ds,{typeAhead:forceSelect,forceSelection:forceSelect,fields:fields,sqs:sqs,animSpeed:0.25,qs_obj:qs_obj,inputElement:qsFields[qsField],generateRequest:function(sQuery){var out=SUGAR.util.paramsToUrl({to_pdf:'true',module:'Home',action:'quicksearchQuery',data:encodeURIComponent(YAHOO.lang.JSON.stringify(this.sqs)),query:sQuery});return out;},setFields:function(data,filter){this.updateFields(data,filter);},updateFields:function(data,filter){for(var i in this.fields){for(var key in this.qs_obj.field_list){if(this.fields[i]==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&this.qs_obj.populate_list[key].match(filter)){var displayValue=data[i].replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value=displayValue;}}}},clearFields:function(){for(var key in this.qs_obj.field_list){if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]){document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";}}
9973 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
9974 {search.clearFields=function(){};search.setFields=function(data,filter)
9975 {var label_str='';var label_data_str='';var current_label_data_str='';var label_data_hash=new Array();for(var i in this.fields){for(var key in this.qs_obj.field_list){if(this.fields[i]==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&document.getElementById(this.qs_obj.populate_list[key]+'_label')&&this.qs_obj.populate_list[key].match(filter)){var displayValue=data[i].replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');var data_label=document.getElementById(this.qs_obj.populate_list[key]+'_label').innerHTML.replace(/\n/gi,'');label_and_data=data_label+' '+displayValue;if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&!label_data_hash[data_label])
9976 {label_str+=data_label+' \n';label_data_str+=label_and_data+'\n';label_data_hash[data_label]=true;current_label_data_str+=data_label+' '+document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value+'\n';}}}}
9977 if(label_str!=current_label_data_str&&current_label_data_str!=label_data_str){module_key=(typeof document.forms[form_id].elements['module']!='undefined')?document.forms[form_id].elements['module'].value:'app_strings';warning_label=SUGAR.language.translate(module_key,'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM')+'\n\n'+label_data_str;if(!confirm(warning_label))
9978 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
9979 {if(this.inputElement.id=='shipping_account_name')
9980 {filter=Dom.get('shipping_checkbox').checked?/(account_id|office_phone)/:filter;}else if(this.inputElement.id=='billing_account_name'){filter=Dom.get('shipping_checkbox').checked?filter:/(account_id|office_phone|billing)/;}}else if(Dom.get('alt_checkbox')){filter=Dom.get('alt_checkbox').checked?filter:/^(?!alt)/;}
9981 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
9982 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9983 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];}}}
9984 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]];}
9985 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});search.typeAheadEvent.subscribe(function(e,args){this.getInputEl().value=this.getInputEl().value.replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
9986 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9987 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js
9988