1 /*********************************************************************************
2 * SugarCRM Community Edition is a customer relationship management program developed by
3 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5 * This program is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU Affero General Public License version 3 as published by the
7 * Free Software Foundation with the addition of the following permission added
8 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
17 * You should have received a copy of the GNU Affero General Public License along with
18 * this program; if not, see http://www.gnu.org/licenses or write to the Free
19 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
23 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25 * The interactive user interfaces in modified source and object code versions
26 * of this program must display Appropriate Legal Notices, as required under
27 * Section 5 of the GNU Affero General Public License version 3.
29 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
30 * these Appropriate Legal Notices must retain the display of the "Powered by
31 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
32 * technical reasons, the Appropriate Legal Notices must display the words
33 * "Powered by SugarCRM".
34 ********************************************************************************/
38 var flexContentOld = "";
39 var forcePreview = false;
40 var inCompose = false;
42 /* globals for Callback functions */
43 var email; // AjaxObject.showEmailPreview
47 var meta; // AjaxObject.showEmailPreview
50 var urlBase = 'index.php';
51 var urlStandard = 'sugar_body_only=true&to_pdf=true&module=Emails&action=EmailUIAjax';
53 var lazyLoadFolder = null;// End of File modules/Emails/javascript/vars.js
55 /*********************************************************************************
56 * SugarCRM Community Edition is a customer relationship management program developed by
57 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
59 * This program is free software; you can redistribute it and/or modify it under
60 * the terms of the GNU Affero General Public License version 3 as published by the
61 * Free Software Foundation with the addition of the following permission added
62 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
63 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
64 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
66 * This program is distributed in the hope that it will be useful, but WITHOUT
67 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
68 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
71 * You should have received a copy of the GNU Affero General Public License along with
72 * this program; if not, see http://www.gnu.org/licenses or write to the Free
73 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
76 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
77 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
79 * The interactive user interfaces in modified source and object code versions
80 * of this program must display Appropriate Legal Notices, as required under
81 * Section 5 of the GNU Affero General Public License version 3.
83 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
84 * these Appropriate Legal Notices must retain the display of the "Powered by
85 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
86 * technical reasons, the Appropriate Legal Notices must display the words
87 * "Powered by SugarCRM".
88 ********************************************************************************/
89 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)
90 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_","_")]);}
91 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
92 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;}
93 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();}
94 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';}
95 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='';}
96 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',100);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',100);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
97 this.js_more();this.js_more();}
98 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
99 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
100 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);}}}
101 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
102 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&¤tNode.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';}
103 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);}}
104 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);}}}
105 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++;}}}
106 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
107 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='';}}
109 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;}
111 if(!has_primary){return false;}
113 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);}}}
114 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;}}}}
115 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;}
116 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();}}}}
117 if(noAdd){enableQS(false);}
118 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);}}}
120 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
121 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=='';}
123 SUGAR.collection.safe_clone=function(e,recursive)
124 {if(e.nodeName=="#text")
125 {return document.createTextNode(e.data);}
126 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];if(SUGAR.isIE7&&e.tagName.toLowerCase()=='input')
127 {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'];}
128 for(var i in properties)
129 {if(e[properties[i]])
130 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
131 newNode[properties[i]]=e[properties[i]];}}
133 {for(var i in e.childNodes)
134 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
135 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
137 // End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
139 /*********************************************************************************
140 * SugarCRM Community Edition is a customer relationship management program developed by
141 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
143 * This program is free software; you can redistribute it and/or modify it under
144 * the terms of the GNU Affero General Public License version 3 as published by the
145 * Free Software Foundation with the addition of the following permission added
146 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
147 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
148 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
150 * This program is distributed in the hope that it will be useful, but WITHOUT
151 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
152 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
155 * You should have received a copy of the GNU Affero General Public License along with
156 * this program; if not, see http://www.gnu.org/licenses or write to the Free
157 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
160 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
161 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
163 * The interactive user interfaces in modified source and object code versions
164 * of this program must display Appropriate Legal Notices, as required under
165 * Section 5 of the GNU Affero General Public License version 3.
167 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
168 * these Appropriate Legal Notices must retain the display of the "Powered by
169 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
170 * technical reasons, the Appropriate Legal Notices must display the words
171 * "Powered by SugarCRM".
172 ********************************************************************************/
175 cache : new Object(),
176 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
177 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
180 currentHtmleditor : ''
184 * preserves hits from email server
186 _setDetailCache : function(ret) {
188 var compKey = ret.meta.mbox + ret.meta.uid;
190 if(!SUGAR.email2.cache[compKey]) {
191 SUGAR.email2.cache[compKey] = ret;
196 autoSetLayout : function() {
197 var c = document.getElementById('container');
198 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
199 //Ensure a minimum height.
200 tHeight = Math.max(tHeight, 550);
201 c.style.height = tHeight + "px";
202 SUGAR.email2.complexLayout.set('height', tHeight);
203 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
204 SUGAR.email2.complexLayout.render();
205 SUGAR.email2.listViewLayout.resizePreview();
210 * Shows overlay progress message
212 function overlayModal(title, body) {
213 overlay(title, body);
215 function overlay(reqtitle, body, type, additconfig) {
217 if (typeof(additconfig) == "object") {
218 var config = additconfig;
221 config.title = reqtitle;
223 YAHOO.SUGAR.MessageBox.show(config);
226 function hideOverlay() {
227 YAHOO.SUGAR.MessageBox.hide();
229 // End of File modules/Emails/javascript/EmailUIShared.js
231 /*********************************************************************************
232 * SugarCRM Community Edition is a customer relationship management program developed by
233 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
235 * This program is free software; you can redistribute it and/or modify it under
236 * the terms of the GNU Affero General Public License version 3 as published by the
237 * Free Software Foundation with the addition of the following permission added
238 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
239 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
240 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
242 * This program is distributed in the hope that it will be useful, but WITHOUT
243 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
244 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
247 * You should have received a copy of the GNU Affero General Public License along with
248 * this program; if not, see http://www.gnu.org/licenses or write to the Free
249 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
252 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
253 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
255 * The interactive user interfaces in modified source and object code versions
256 * of this program must display Appropriate Legal Notices, as required under
257 * Section 5 of the GNU Affero General Public License version 3.
259 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
260 * these Appropriate Legal Notices must retain the display of the "Powered by
261 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
262 * technical reasons, the Appropriate Legal Notices must display the words
263 * "Powered by SugarCRM".
264 ********************************************************************************/
267 if (typeof console == "undefined")
268 console = { log: function(o) {alert(o)} };
272 currentRequestObject : null,
273 //timeout : 30000, // 30 second timeout default
274 timeout : 9999999999, // 30 second timeout default
280 _reset : function() {
281 this.timeout = 30000;
282 this.forceAbort = false;
285 folderRenameCleanup : function() {
286 SUGAR.email2.folders.setSugarFolders();
289 fullSyncCleanup : function(o) {
290 this.folders.checkMailCleanup(o);
291 SUGAR.email2.settings.settingsDialog.hide();
296 composeCache : function(o) {
297 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
298 // get email templates and user signatures
299 var ret = YAHOO.lang.JSON.parse(o.responseText);
301 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
302 SUGAR.email2.composeLayout.signatures = ret.signatures;
303 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
305 SUGAR.email2.composeLayout.setComposeOptions(idx);
307 //Set the error array so we can notify the user when they try to hit send if any errors
308 //are present. We will also notify them now (after hitting compose button).
309 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
312 //if error element is returning an array, then check the length to make sure we have error messages
313 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
314 //add error messages for display
315 for(i in ret.errorArray)
316 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
317 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
318 //if error element is returning an object, and the object value is not empty or null, then display error message
319 for(i in ret.errorArray)
320 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
323 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
325 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
327 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
333 handleDeleteSignature : function(o) {
335 var ret = YAHOO.lang.JSON.parse(o.responseText);
336 SUGAR.email2.composeLayout.signatures = ret.signatures;
337 var field = document.getElementById('signature_id');
338 SUGAR.email2.util.emptySelectOptions(field);
340 for(var i in ret.signatures) { // iterate through assoc array
341 var opt = new Option(ret.signatures[i], i);
342 field.options.add(opt);
344 setSigEditButtonVisibility();
349 handleDeleteReturn : function(o) {
350 // force refresh ListView
352 if(document.getElementById('focusEmailMbox')) {
353 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
356 // need to display success message before calling next async call?
357 document.getElementById(this.target).innerHTML = o.responseText;
362 handleFailure : function(o) {
364 overlay('Exception occurred...', o.statusText, 'alert');
365 if(document.getElementById('saveButton')) {
366 document.getElementById('saveButton').disabled = false;
370 handleReplyForward : function(o) {
371 var a = YAHOO.lang.JSON.parse(o.responseText);
373 var idx = SUGAR.email2.composeLayout.currentInstanceId;
375 document.getElementById('email_id' + idx).value = a.uid;
376 document.getElementById('emailSubject' + idx).value = a.name;
377 document.getElementById('addressTO' + idx).value = a.from;
378 document.getElementById('uid' + idx).value = a.uid;
380 document.getElementById('addressCC' + idx).value = a.cc;
381 SE.composeLayout.showHiddenAddress('cc', idx);
385 document.getElementById('type' + idx).value = a.type;
388 // apply attachment values
389 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
391 setTimeout("callbackReplyForward.finish(globalA);", 500);
394 handleReplyForwardForDraft : function(o) {
395 var a = YAHOO.lang.JSON.parse(o.responseText);
397 var idx = SUGAR.email2.composeLayout.currentInstanceId;
399 document.getElementById('email_id' + idx).value = a.uid;
400 document.getElementById('emailSubject' + idx).value = a.name;
401 document.getElementById('addressTO' + idx).value = a.to;
404 document.getElementById('addressCC' + idx).value = a.cc;
405 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
409 document.getElementById('addressBCC' + idx).value = a.bcc;
410 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
415 document.getElementById('type' + idx).value = a.type;
419 // apply attachment values
420 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
422 setTimeout("callbackReplyForward.finish(globalA);", 500);
427 handleSuccess : function(o) {
428 document.getElementById(this.target).innerHTML = o.responseText;
434 ieDeleteSuccess : function(o) {
437 SUGAR.email2.accounts.refreshInboundAccountTable();
438 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
439 SUGAR.email2.accounts.rebuildFolderList();
444 ieSaveSuccess : function(o) {
445 document.getElementById('saveButton').disabled = false;
446 var a = YAHOO.lang.JSON.parse(o.responseText);
449 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
450 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
452 resp = YAHOO.lang.JSON.parse(o.responseText);
453 SUGAR.email2.accounts.refreshInboundAccountTable();
454 SUGAR.email2.accounts.refreshOuboundAccountTable();
455 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
456 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
460 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
467 loadAttachments : function(o) {
468 var result = YAHOO.lang.JSON.parse(o.responseText);
470 SUGAR.email2.composeLayout.loadAttachments(result);
475 loadSignature : function(o) {
476 var ret = YAHOO.lang.JSON.parse(o.responseText);
477 SUGAR.email2.signatures[ret.id] = ret.signature_html;
478 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
482 * Follow up to mark email read|unread|flagged
484 markEmailCleanup : function(o) {
485 var ret = YAHOO.lang.JSON.parse(o.responseText);
486 if (!ret['status']) {
488 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
490 SUGAR.email2.contextMenus.markEmailCleanup();
496 rebuildShowFolders : function(o) {
497 var t = YAHOO.lang.JSON.parse(o.responseText);
498 var show = document.getElementById('ieAccountListShow');
500 SUGAR.email2.util.emptySelectOptions(show);
502 for(i=0; i<t.length; i++) { // iterate through assoc array
503 var opt = new Option(t[i].text, t[i].value, t[i].selected);
504 opt.selected = t[i].selected;
505 show.options.add(opt);
508 SUGAR.email2.accounts.renderTree();
512 saveListViewSortOrderPart2 : function() {
513 // create the JSON string the func expects
514 focusFolderPath = '[ "Home", "' + ieName + '"';
516 var f = new String(focusFolder);
517 var fEx = f.split('.');
519 for(i=0; i<fEx.length; i++) {
520 focusFolderPath += ', "' + fEx[i] +'"'
523 focusFolderPath += ']';
525 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
526 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
532 sendEmailCleanUp : function(o) {
537 ret = YAHOO.lang.JSON.parse(o.responseText);
538 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
539 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
541 if (o.responseText) {
542 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
544 // Else we have an error here.
547 if (typeof(SE.grid) != 'undefined')
548 SE.listView.refreshGrid();
549 //Disabled while address book is disabled
551 //If this call back was initiated by quick compose from a Detail View page, refresh the
552 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
553 //close the shortcut bar menu
554 if ( (typeof(action_sugar_grp1) != 'undefined')) {
555 if(action_sugar_grp1 == 'DetailView') {
556 showSubPanel('history',null,true);
557 } else if(action_sugar_grp1 == 'quickcreate') {
564 ieSendSuccess : function(o) {
566 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
571 settingsFolderRefresh : function(o) {
572 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
573 var ret = YAHOO.lang.JSON.parse(o.responseText);
574 var user = document.getElementById('userFolders');
576 SUGAR.email2.util.emptySelectOptions(user);
578 for(i=0; i<ret.userFolders.length; i++) {
579 var display = ret.userFolders[i].name;
580 var value = ret.userFolders[i].id;
581 var selected = (ret.userFolders[i].selected != "") ? true : false;
582 var opt = new Option(display, value, selected);
583 opt.selected = selected;
584 user.options.add(opt);
590 startRequest : function(callback, args, forceAbort) {
591 if(this.currentRequestObject != null) {
592 if(this.forceAbort == true) {
593 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
596 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
600 requestInProgress : function() {
601 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
606 updateFolderSubscriptions : function() {
607 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
608 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
614 updateFrameFolder : function() {
615 SUGAR.email2.folders.checkEmailAccounts();
620 updateUserPrefs : function(o) {
621 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
622 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
627 uploadAttachmentSuccessful : function(o) {
629 document.getElementById('email_attachment').value = '';
631 var ret = YAHOO.lang.JSON.parse(o.responseText);
632 var idx = SUGAR.email2.composeLayout.currentInstanceId;
633 var overall = document.getElementById('addedFiles' + idx);
634 var index = overall.childNodes.length;
636 "<div id='email_attachment_bucket" + idx + index + "'>" +
638 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
639 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
640 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
642 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
643 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
645 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
647 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
650 overall.innerHTML += out;
651 if(SUGAR.email2.util.isIe()) {
652 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
656 SUGAR.email2.addFileDialog.hide();
658 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
663 ///////////////////////////////////////////////////////////////////////////
664 //// PER MODULE CALLBACK OBJECTS
665 AjaxObject.accounts = {
666 saveOutboundCleanup : function(o) {
667 SUGAR.email2.accounts.refreshOuboundAccountTable();
668 SUGAR.email2.accounts.outboundDialog.hide();
669 var id = o.responseText;
670 SUGAR.email2.accounts.newAddedOutboundId = id;
672 saveDefaultOutboundCleanup: function(o){
675 callbackEditOutbound : {
676 success : function(o)
678 var ret = YAHOO.lang.JSON.parse(o.responseText);
680 SUGAR.email2.accounts.showAddSmtp();
683 document.getElementById("mail_id").value = ret.id;
684 document.getElementById("type").value = ret.type;
685 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
686 document.getElementById("mail_name").value = ret.name;
687 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
688 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
689 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
690 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
691 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
692 SUGAR.email2.accounts.smtp_authenticate_field_display();
693 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
695 if(ret.type == 'system-override') {
696 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
697 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
700 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
701 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
703 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
706 failure : AjaxObject.handleFailure,
707 timeout : AjaxObject.timeout,
710 callbackDeleteOutbound : {
711 success : function(o) {
712 var ret = YAHOO.lang.JSON.parse(o.responseText);
715 if(confirm(ret.error_message))
717 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
718 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
726 SUGAR.email2.accounts.refreshOuboundAccountTable();
730 failure : AjaxObject.handleFailure,
731 timeout : AjaxObject.timeout,
735 callbackCheckMailProgress : {
736 success : function(o) {
737 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
738 SUGAR.email2.accounts.totalMsgCount = -1;
741 //Check for server timeout / errors
742 var ret = YAHOO.lang.JSON.parse(o.responseText);
745 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
747 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
748 SUGAR.email2.accounts.totalMsgCount = -1;
749 //SUGAR.email2.folders.rebuildFolders();
753 var currIeId = ret['ieid'];
756 var serverCount = ret.count;
758 if (ret['status'] == 'done') {
759 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
760 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
764 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
766 currIeId = SUGAR.email2.accounts.ieIds[i+1];
768 SUGAR.email2.accounts.totalMsgCount = -1;
773 else if (ret.mbox && ret.totalcount && ret.count) {
774 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
775 if (ret.count >= ret.totalcount) {
778 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
779 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
782 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
783 SUGAR.email2.accounts.totalMsgCount = -1;
788 SUGAR.email2.accounts.totalMsgCount = -1;
790 SUGAR.email2.folders.rebuildFolders();
791 SE.listView.refreshGrid();
792 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
793 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
794 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
795 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
797 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
798 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
799 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
800 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
801 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
804 failure : AjaxObject.handleFailure,
805 timeout : AjaxObject.timeout,
810 ///////////////////////////////////////////////////////////////////////////////
812 AjaxObject.composeLayout = {
814 * Populates the record id
816 saveDraftCleanup : function(o) {
821 ret = YAHOO.lang.JSON.parse(o.responseText);
822 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
824 if (o.responseText) {
825 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
831 AjaxObject.composeLayout.callback = {
833 success : AjaxObject.composeLayout.saveDraftCleanup,
834 failure : AjaxObject.handleFailure,
835 timeout : AjaxObject.timeout,
840 AjaxObject.detailView = {
842 * Pops-up a printable view of an email
844 displayPrintable : function(o) {
845 var ret = YAHOO.lang.JSON.parse(o.responseText);
846 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
847 // 2 below must be in global context
849 meta['panelId'] = SUGAR.email2.util.getPanelId();
850 email = ret.meta.email;
851 if (typeof(email.cc) == 'undefined') {
855 var out = displayTemplate.exec({
856 'app_strings' : app_strings,
864 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
865 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
867 popup.document.write(out);
868 popup.document.close();
872 * Takes formatted response and creates a modal pop-over containing a title and content
874 displayView : function(o) {
875 var SED = SUGAR.email2.detailView;
876 var ret = YAHOO.lang.JSON.parse(o.responseText);
878 if(!SED.viewDialog) {
879 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
883 constraintoviewport: true,
886 SED.viewDialog.renderEvent.subscribe(function() {
887 var content = this.body.firstChild;
888 var viewH = YAHOO.util.Dom.getViewportHeight();
890 this.body.style.overflow = "auto";
891 this.body.style.width = "800px";
892 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
896 SED.viewDialog.setHeader(ret.title);
897 SED.viewDialog.setBody(ret.html);
898 SED.viewDialog.render();
899 SED.viewDialog.show();
903 * Generates a modal popup to populate with the contents of bean's full EditView
905 showQuickCreateForm : function(o) {
906 var SED = SUGAR.email2.detailView;
907 var ret = YAHOO.lang.JSON.parse(o.responseText);
909 if(!SED.quickCreateDialog) {
910 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
914 constraintoviewport: true,
918 SED.quickCreateDialog.renderEvent.subscribe(function() {
919 var viewH = YAHOO.util.Dom.getViewportHeight();
921 for (var i in this.body.childNodes) {
922 if (this.body.childNodes[i].clientHeight) {
923 contH += this.body.childNodes[i].clientHeight;
924 } else if (this.body.childNodes[i].offsetHeight) {
925 contH += this.body.childNodes[i].offsetHeight;
928 this.body.style.width = "800px";
929 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
930 this.body.style.overflow = "auto";
931 }, SED.quickCreateDialog);
933 SED.quickCreateDialog.hideEvent.subscribe(function(){
934 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
935 /*for(var qsField in qsFields){
936 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
937 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
940 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
943 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
945 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
946 SED.quickCreateDialog.render();
947 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
949 SED.quickCreateDialog.ieId = ret.ieId;
950 SED.quickCreateDialog.uid = ret.uid;
951 SED.quickCreateDialog.mbox = ret.mbox;
952 SED.quickCreateDialog.qcmodule = ret.module;
954 SED.quickCreateDialog.show();
956 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
958 editForm.module.value = 'Emails';
959 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
960 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
961 var instId = ret.module + count;
962 SED.quickCreateEmailsToAdd = ret.emailAddress;
963 SED.quickCreateEmailCallback = function(instId, tableId) {
964 var eaw = SUGAR.EmailAddressWidget.instances[instId];
965 if (typeof(eaw) == "undefined")
966 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
967 + instId + "','" + tableId + "');", 100);
968 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
970 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
971 + instId + "','" + tableId + "');", 100);
975 saveQuickCreateForm : function(o) {
977 SUGAR.email2.detailView.quickCreateDialog.hide();
978 validate['EditView'] = [ ];
981 saveQuickCreateFormAndReply : function(o) {
983 var ret = YAHOO.lang.JSON.parse(o.responseText);
984 SUGAR.email2.detailView.quickCreateDialog.hide();
985 var qcd = SUGAR.email2.detailView.quickCreateDialog;
986 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
988 var emailID = ret.id;
989 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
991 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
993 //Cean the validate cache to prevent errors on the next call
994 validate['EditView'] = [ ];
997 saveQuickCreateFormAndAddToAddressBook : function(o) {
999 SUGAR.email2.detailView.quickCreateDialog.hide();
1000 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
1001 validate['EditView'] = [ ];
1004 handleAssignmentDialogAssignAction : function() {
1007 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
1009 var dist = 'direct';
1013 var found_teams = false;
1014 var warning_message = mod_strings.LBL_WARN_NO_USERS;
1015 if(!found_teams && assign_user_id == '' )
1017 alert(warning_message);
1021 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1023 for(i=0; i<emailUids.length; i++) {
1025 uids += app_strings.LBL_EMAIL_DELIMITER;
1027 uids += emailUids[i];
1030 var row = SUGAR.email2.grid.getSelectedRows()[0];
1031 var data = SUGAR.email2.grid.getRecord(row).getData();
1032 var ieid = data.ieId;
1033 var mbox = data.mbox;
1034 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
1035 SUGAR.email2.contextMenus.assignToDialogue.hide();
1036 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
1040 handleAssignmentDialogDeleteAction : function() {
1041 // TO pass list of UIDS/emailIds
1042 var uids = SUGAR.email2.listView.getUidsFromSelection();
1043 var row = SUGAR.email2.grid.getSelections()[0];
1044 var ieid = row.data.ieId;
1045 var mbox = row.data.mbox;
1046 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
1047 SUGAR.email2.contextMenus.assignmentDialog.hide();
1048 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1054 showEmailDetailView : function(o) {
1056 var SED = SUGAR.email2.detailView;
1057 var ret = YAHOO.lang.JSON.parse(o.responseText);
1059 if(!SED.quickCreateDialog) {
1060 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
1064 constraintoviewport: true,
1066 autofillheight: "body",
1069 SED.quickCreateDialog.renderEvent.subscribe(function() {
1070 var viewHeight = YAHOO.util.Dom.getViewportHeight();
1072 for (var i in this.body.childNodes) {
1073 if (this.body.childNodes[i].offsetHeight)
1074 contH += this.body.childNodes[i].offsetHeight;
1076 this.body.style.overflow = "auto";
1077 this.body.style.width = "800px";
1078 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
1080 }, SED.quickCreateDialog);
1082 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
1083 SED.quickCreateDialog.setBody(ret.html);
1084 SED.quickCreateDialog.render();
1085 SUGAR.util.evalScript(ret.html);
1086 SED.quickCreateDialog.show();
1089 showAssignmentDialogWithData : function(o) {
1090 var SEC = SUGAR.email2.contextMenus;
1092 var ret = YAHOO.lang.JSON.parse(o.responseText);
1093 if (!SEC.assignmentDialog) {
1094 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
1097 constraintoviewport: true,
1100 SEC.assignmentDialog.setBody("");
1101 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
1102 SEC.assignmentDialog.renderEvent.subscribe(function() {
1103 var iev = YAHOO.util.Dom.get("Distribute");
1105 this.body.style.width = "700px";
1107 }, SEC.assignmentDialog);
1108 SEC.assignmentDialog.render();
1110 SEC.assignmentDialog.setBody(ret);
1111 SEC.assignmentDialog.render();
1113 SEC.assignmentDialog.show();
1114 SUGAR.util.evalScript(ret);
1117 showImportForm : function(o) {
1118 var SED = SUGAR.email2.detailView;
1119 var ret = YAHOO.lang.JSON.parse(o.responseText);
1121 document.getElementById('quickCreateContent').innerHTML = "";
1127 if(!SED.importDialog) {
1128 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
1132 constraintoviewport: true,
1134 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
1135 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
1139 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
1140 SED.importDialog.setBody("");
1141 SED.importDialog.hideEvent.subscribe(function(){
1142 for(var i in QSFieldsArray) {
1143 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
1144 QSFieldsArray[i].destroy();
1145 delete QSFieldsArray[i];
1147 if (QSProcessedFieldsArray[i]) {
1148 QSProcessedFieldsArray[i] = false;
1152 SED.importDialog.renderEvent.subscribe(function() {
1153 var iev = YAHOO.util.Dom.get("ImportEditView");
1155 //this.body.style.height = (iev.clientHeight + 10) + "px";
1156 this.body.style.width = "600px";
1158 }, SED.importDialog);
1159 SED.importDialog.render();
1161 SED.importDialog.setBody(ret.html);
1162 SED.importDialog.ret = ret;
1163 SUGAR.util.evalScript(ret.html);
1164 SED.importDialog.render();
1166 SED.importDialog.show();
1167 SED.importDialog.focusFirstButton();
1169 getImportAction : function(ret) {
1170 if (!check_form('ImportEditView')) return false;
1171 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
1172 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
1176 var editView = document.getElementById('ImportEditView');
1177 if (editView.assigned_user_id != null) {
1178 get = get + "&user_id=" + editView.assigned_user_id.value
1179 //var user_id = editView.assigned_user_id.value;
1181 var parent_id = editView.parent_id.value;
1182 var parent_type = editView.parent_type.value;
1183 var row = SUGAR.email2.grid.getSelectedRows()[0];
1184 row = SUGAR.email2.grid.getRecord(row);
1185 var data = row.getData();
1186 var ieId = data.ieId;
1187 var mbox = data.mbox;
1188 var serverDelete = editView.serverDelete.checked;
1189 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1191 for(i=0; i<emailUids.length; i++) {
1193 uids += app_strings.LBL_EMAIL_DELIMITER;
1195 uids += emailUids[i];
1198 var action = 'importEmail&uid=';
1200 action = 'moveEmails';
1201 action = action + '&sourceFolder=' + ret['srcFolder'];
1202 action = action + '&sourceIeId=' + ret['srcIeId'];
1203 action = action + '&destinationFolder=' + ret['dstFolder'];
1204 action = action + '&destinationIeId=' + ret['dstIeId'];
1205 action = action + '&emailUids=';
1207 if (action.search(/importEmail/) != -1) {
1208 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
1210 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
1213 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
1214 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
1215 SUGAR.email2.detailView.importDialog.hide();
1216 document.getElementById('importDialogContent').innerHTML = "";
1219 showRelateForm : function(o) {
1220 var SED = SUGAR.email2.detailView;
1221 var ret = YAHOO.lang.JSON.parse(o.responseText);
1222 document.getElementById('quickCreateContent').innerHTML = "";
1227 dialog_loaded = true;
1229 if(!SED.relateDialog) {
1230 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
1235 constraintoviewport: true,
1237 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
1238 if (!check_form('RelateEditView')) return false;
1240 var editView = document.getElementById('RelateEditView');
1241 var parent_id = editView.parent_id.value;
1242 var parent_type = editView.parent_type.value;
1243 var row = SUGAR.email2.grid.getSelectedRows()[0];
1244 row = SUGAR.email2.grid.getRecord(row);
1245 var ieId = row.getData().ieId;
1246 var mbox = row.getData().mbox;
1247 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1249 for(i=0; i<emailUids.length; i++) {
1251 uids += app_strings.LBL_EMAIL_DELIMITER;
1253 uids += emailUids[i];
1255 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1256 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
1257 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
1258 SED.relateDialog.hide();
1259 document.getElementById('relateDialogContent').innerHTML = "";
1264 SED.relateDialog.hideEvent.subscribe(function(){
1265 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
1266 QSFieldsArray['ImportEditView_parent_name'].destroy();
1267 delete QSFieldsArray['ImportEditView_parent_name'];
1269 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
1270 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
1274 SED.relateDialog.renderEvent.subscribe(function() {
1275 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
1277 for (var i in this.body.childNodes) {
1278 if (this.body.childNodes[i].clientHeight)
1279 contH += this.body.childNodes[i].clientHeight;
1281 }, SED.relateDialog);
1282 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
1285 SED.relateDialog.setBody(ret.html);
1286 SED.relateDialog.render();
1287 SUGAR.util.evalScript(ret.html);
1288 SED.relateDialog.show();
1292 * DetailView callbacks
1294 AjaxObject.detailView.callback = {
1296 success : function(o) {
1298 var ret = YAHOO.lang.JSON.parse(o.responseText);
1299 SUGAR.email2.detailView.consumeMetaDetail(ret);
1301 argument: [targetDiv],
1302 failure : AjaxObject.handleFailure,
1307 success : function(o) {
1309 var ret = YAHOO.lang.JSON.parse(o.responseText);
1310 SUGAR.email2.detailView.consumeMetaPreview(ret);
1312 failure : AjaxObject.handleFailure,
1317 success : AjaxObject.detailView.displayPrintable,
1318 failure : AjaxObject.handleFailure,
1319 timeout : AjaxObject.timeout,
1323 success : AjaxObject.detailView.displayView,
1324 failure : AjaxObject.handleFailure,
1325 timeout : AjaxObject.timeout,
1334 AjaxObject.folders = {
1336 * check-mail post actions
1338 checkMailCleanup : function(o) {
1340 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
1342 // refresh focus ListView
1343 SE.listView.refreshGrid();
1344 SUGAR.email2.folders.startCheckTimer(); // resets the timer
1349 rebuildFolders : function(o) {
1352 var data = YAHOO.lang.JSON.parse(o.responseText);
1354 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
1355 SUGAR.email2.folders.setSugarFolders();
1358 AjaxObject.folders.callback = {
1360 success : AjaxObject.folders.checkMailCleanup,
1361 failure : AjaxObject.handleFailure,
1362 timeout : 600000, // 5 mins
1367 AjaxObject.rules = {
1368 loadRulesForSettings : function(o) {
1369 document.getElementById("rulesListCell").innerHTML = o.responseText;
1370 // assume we have the class we need
1371 SUGAR.routing.getStrings();
1372 SUGAR.routing.getDependentDropdowns();
1375 //// END PER MODULE CALLBACK OBJECTS
1376 ///////////////////////////////////////////////////////////////////////////
1380 success : AjaxObject.handleSuccess,
1381 failure : AjaxObject.handleFailure,
1382 timeout : AjaxObject.timeout,
1385 var callbackAccount = {
1386 success : AjaxObject.ieSaveSuccess,
1387 failure : AjaxObject.handleFailure,
1388 timeout : AjaxObject.timeout,
1391 var callbackAccountDelete = {
1392 success : AjaxObject.ieDeleteSuccess,
1393 failure : AjaxObject.handleFailure,
1394 timeout : AjaxObject.timeout,
1397 var callbackOutboundTest = {
1398 success : AjaxObject.ieSendSuccess,
1399 failure : AjaxObject.handleFailure,
1400 timeout : AjaxObject.timeout,
1406 var callbackTeamInfoForSettings = {
1407 success : function (o) {
1408 var data = YAHOO.lang.JSON.parse(o.responseText);
1409 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
1411 failure : AjaxObject.handleFailure,
1412 timeout : AjaxObject.timeout,
1417 var callbackStatusForImport = {
1418 success : function (o) {
1420 if (o.responseText != "") {
1421 var statusString = "";
1422 var data = YAHOO.lang.JSON.parse(o.responseText);
1423 for(i=0; i<data.length; i++) {
1424 statusString = statusString + data[i] + '<br/>';
1426 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
1428 SE.listView.refreshGrid();
1431 failure : AjaxObject.handleFailure,
1432 timeout : AjaxObject.timeout,
1436 var callbackComposeCache = {
1437 success : AjaxObject.composeCache,
1438 failure : AjaxObject.handleFailure,
1439 timeout : AjaxObject.timeout,
1442 var callbackDelete = {
1443 success : AjaxObject.handleDeleteReturn,
1444 failure : AjaxObject.handleFailure,
1445 timeout : AjaxObject.timeout,
1448 var callbackEmailDetailMultiple = {
1449 success : function(o) {
1451 var retMulti = YAHOO.lang.JSON.parse(o.responseText);
1452 var ret = new Object();
1454 for(var i=0; i<retMulti.length; i++) {
1457 SUGAR.email2._setDetailCache(ret);
1458 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
1461 failure : AjaxObject.handleFailure,
1465 var callbackListViewSortOrderChange = {
1466 success : AjaxObject.saveListViewSortOrderPart2,
1467 failure : AjaxObject.handleFailure,
1468 timeout : AjaxObject.timeout,
1470 argument : [ieId, ieName, focusFolder]
1472 var callbackEmptyTrash = {
1473 success : function(o) {
1475 AjaxObject.folderRenameCleanup;
1477 failure : AjaxObject.handleFailure,
1478 timeout : AjaxObject.timeout,
1481 var callbackClearCacheFiles = {
1482 success : function(o) {
1485 failure : AjaxObject.handleFailure,
1486 timeout : AjaxObject.timeout,
1489 var callbackFolderRename = {
1490 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
1491 failure : AjaxObject.handleFailure,
1492 timeout : AjaxObject.timeout,
1495 var callbackFolderDelete = {
1496 success : function(o) {
1497 var ret = YAHOO.lang.JSON.parse(o.responseText);
1499 if (ret.folder_id) {
1500 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
1502 SUGAR.email2.tree.removeNode(node, true);
1503 } else if (ret.ieId && ret.mbox) {
1504 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
1506 SUGAR.email2.tree.removeNode(node, true);
1509 //SUGAR.email2.folders.loadSettingFolder();
1512 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
1515 failure : AjaxObject.handleFailure,
1516 timeout : AjaxObject.timeout,
1519 var callbackFolderSave = {
1520 success : function(o) {
1521 var ret = YAHOO.lang.JSON.parse(o.responseText);
1523 switch(ret.action) {
1524 case 'newFolderSave':
1525 SUGAR.email2.folders.rebuildFolders();
1529 failure : AjaxObject.handleFailure,
1530 timeout : AjaxObject.timeout,
1533 var callbackFolderSubscriptions = {
1534 success : AjaxObject.updateFolderSubscriptions,
1535 failure : AjaxObject.handleFailure,
1536 timeout : AjaxObject.timeout,
1539 var callbackFolderUpdate = {
1540 success : AjaxObject.updateFrameFolder,
1541 failure : AjaxObject.handleFailure,
1542 timeout : AjaxObject.timeout,
1545 var callbackFolders = {
1546 success : AjaxObject.folders.rebuildFolders,
1547 //success : void(true),
1548 failure : AjaxObject.handleFailure,
1549 timeout : AjaxObject.timeout,
1552 var callbackFullSync = {
1553 success : AjaxObject.fullSyncCleanup,
1554 failure : AjaxObject.handleFailure,
1555 timeout : 9999999999999,
1558 var callbackGeneric = {
1559 success : function() {
1562 failure : AjaxObject.handleFailure,
1563 timeout : AjaxObject.timeout,
1566 var callbackIeAccountRetrieve = {
1567 success : function(o) {
1568 // return JSON encoding
1570 SUGAR.email2.accounts.fillIeAccount(o.responseText);
1571 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
1573 failure : AjaxObject.handleFailure,
1574 timeout : AjaxObject.timeout,
1577 var callbackImportOneEmail = {
1578 success : AjaxObject.detailView.showImportForm,
1579 failure : AjaxObject.handleFailure,
1580 timeout : AjaxObject.timeout,
1583 var callbackRelateEmail = {
1584 success : AjaxObject.detailView.showRelateForm,
1585 failure : AjaxObject.handleFailure,
1586 timeout : AjaxObject.timeout,
1589 var callbackEmailDetailView = {
1590 success : AjaxObject.detailView.showEmailDetailView,
1591 failure : AjaxObject.handleFailure,
1592 timeout : AjaxObject.timeout,
1595 var callbackAssignmentDialog = {
1596 success : AjaxObject.detailView.showAssignmentDialogWithData,
1597 failure : AjaxObject.handleFailure,
1598 timeout : AjaxObject.timeout,
1601 var callbackAssignmentAction = {
1602 success : function(o) {
1603 SE.listView.refreshGrid();
1605 if(o.responseText != '') {
1606 overlay('Assignment action result', o.responseText, 'alert');
1609 failure : AjaxObject.handleFailure,
1610 timeout : AjaxObject.timeout,
1613 var callbackMoveEmails = {
1614 success : function(o) {
1615 SE.listView.refreshGrid();
1617 if(o.responseText != '') {
1618 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
1621 failure : AjaxObject.handleFailure,
1622 timeout : AjaxObject.timeout,
1625 var callbackLoadAttachments = {
1626 success : AjaxObject.loadAttachments,
1627 failure : AjaxObject.handleFailure,
1628 timeout : AjaxObject.timeout,
1631 var callbackLoadRules = {
1632 success : AjaxObject.rules.loadRulesForSettings,
1633 failure : AjaxObject.handleFailure,
1634 timeout : AjaxObject.timeout,
1637 var callbackLoadSignature = {
1638 success : AjaxObject.loadSignature,
1639 failure : AjaxObject.handleFailure,
1640 timeout : AjaxObject.timeout,
1643 var callbackDeleteSignature = {
1644 success : AjaxObject.handleDeleteSignature,
1645 failure : AjaxObject.handleFailure,
1646 timeout : AjaxObject.timeout,
1649 /*var callbackMoveEmails = {
1650 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
1651 failure : AjaxObject.handleFailure,
1652 timeout : AjaxObject.timeout,
1655 var callbackOutboundSave = {
1656 success : AjaxObject.accounts.saveOutboundCleanup,
1657 failure : AjaxObject.handleFailure,
1658 timeout : AjaxObject.timeout,
1661 var callbackDefaultOutboundSave = {
1662 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
1663 failure : AjaxObject.handleFailure,
1664 timeout : AjaxObject.timeout,
1667 var callbackQuickCreate = {
1668 success : AjaxObject.detailView.showQuickCreateForm,
1669 failure : AjaxObject.handleFailure,
1670 timeout : AjaxObject.timeout,
1673 var callbackQuickCreateSave = {
1674 success : AjaxObject.detailView.saveQuickCreateForm,
1675 failure : AjaxObject.handleFailure,
1676 timeout : AjaxObject.timeout,
1679 var callbackQuickCreateSaveAndAddToAddressBook = {
1680 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
1681 failure : AjaxObject.handleFailure,
1682 timeout : AjaxObject.timeout,
1685 var callbackQuickCreateSaveAndReply = {
1686 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
1687 failure : AjaxObject.handleFailure,
1688 timeout : AjaxObject.timeout,
1691 var callbackQuickCreateSaveAndReplyCase = {
1692 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
1693 failure : AjaxObject.handleFailure,
1694 timeout : AjaxObject.timeout,
1697 var callbackRebuildShowAccountList = {
1698 success : AjaxObject.rebuildShowFolders,
1699 failure : AjaxObject.handleFailure,
1700 timeout : AjaxObject.timeout,
1704 var callbackRefreshSugarFolders = {
1705 success : function(o) {
1706 var t = YAHOO.lang.JSON.parse(o.responseText);
1707 SUGAR.email2.folders.setSugarFoldersEnd(t);
1709 failure : AjaxObject.handleFailure,
1710 timeout : AjaxObject.timeout,
1713 var callbackReplyForward = {
1714 success : AjaxObject.handleReplyForward,
1715 finish : function(a, retryCount) {
1716 if (typeof(retryCount) == 'undefined') {
1721 var idx = SUGAR.email2.composeLayout.currentInstanceId;
1722 var t = tinyMCE.getInstanceById('htmleditor' + idx);
1724 var html = t.getContent();
1726 html = " <div><hr></div>" + a.description;
1728 t.setContent(html);//
1730 if (a.type != 'draft') {
1731 // Next step, attach signature
1732 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
1736 if (retryCount < 5) {
1737 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
1741 var tabArray = SUGAR.email2.innerLayout.get("tabs");
1742 if (tabArray != null && tabArray.length > 0) {
1743 for (i = 0 ; i < tabArray.length ; i++) {
1744 var tabObject = tabArray[i];
1745 if (tabObject.get("id") == ("composeTab" + idx)) {
1746 var tabLabel = a.name;
1747 if (tabLabel != null && tabLabel.length > 25) {
1748 tabLabel = tabLabel.substring(0, 25) + "...";
1750 tabObject.get("labelEl").firstChild.data = tabLabel;
1756 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
1757 if (a.parent_name != null && a.parent_name != "") {
1758 document.getElementById('data_parent_name' + idx).value = a.parent_name;
1760 if (a.parent_type != null && a.parent_type != "") {
1761 document.getElementById('data_parent_type' + idx).value = a.parent_type;
1763 if (a.parent_id != null && a.parent_id != "") {
1764 document.getElementById('data_parent_id' + idx).value = a.parent_id;
1766 if (a.fromAccounts.status) {
1767 var addressFrom = document.getElementById('addressFrom' + idx);
1768 SUGAR.email2.util.emptySelectOptions(addressFrom);
1769 var fromAccountOpts = a.fromAccounts.data;
1770 for(i=0; i<fromAccountOpts.length; i++) {
1771 var key = fromAccountOpts[i].value;
1772 var display = fromAccountOpts[i].text;
1773 var opt = new Option(display, key);
1774 if (fromAccountOpts[i].selected) {
1775 opt.selected = true;
1777 addressFrom.options.add(opt);
1783 failure : AjaxObject.handleFailure,
1784 timeout : AjaxObject.timeout,
1786 argument : [sendType]
1788 var callbackSendEmail = {
1789 success : AjaxObject.sendEmailCleanUp,
1790 failure : AjaxObject.handleFailure,
1791 timeout : AjaxObject.timeout,
1794 var callbackSettings = {
1795 success : AjaxObject.updateUserPrefs,
1796 failure : AjaxObject.handleFailure,
1797 timeout : AjaxObject.timeout,
1800 var callbackSettingsFolderRefresh = {
1801 success : AjaxObject.settingsFolderRefresh,
1802 failure : AjaxObject.handleFailure,
1803 timeout : AjaxObject.timeout,
1806 var callbackLoadSettingFolder = {
1807 success : function(o) {
1808 AjaxObject.settingsFolderRefresh(o);
1809 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
1811 failure : AjaxObject.handleFailure,
1812 timeout : AjaxObject.timeout,
1816 var callbackUploadAttachment = {
1817 success : AjaxObject.uploadAttachmentSuccessful,
1818 upload : AjaxObject.uploadAttachmentSuccessful,
1819 failure : AjaxObject.handleFailure,
1820 timeout : AjaxObject.timeout,
1823 var callbackUserPrefs = {
1824 success : function(o) {
1825 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
1827 failure : AjaxObject.handleFailure,
1828 timeout : AjaxObject.timeout,
1832 var callbackContextmenus = {
1834 success : AjaxObject.markEmailCleanup,
1835 failure : AjaxObject.handleFailure,
1836 timeout : AjaxObject.timeout,
1841 var callbackCheckEmail2 = {
1842 success : function(o) {
1843 var ret = YAHOO.lang.JSON.parse(o.responseText);
1844 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
1848 failure : AjaxObject.handleFailure,
1849 timeout : AjaxObject.timeout,
1851 }// End of File modules/Emails/javascript/ajax.js
1853 /*********************************************************************************
1854 * SugarCRM Community Edition is a customer relationship management program developed by
1855 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
1857 * This program is free software; you can redistribute it and/or modify it under
1858 * the terms of the GNU Affero General Public License version 3 as published by the
1859 * Free Software Foundation with the addition of the following permission added
1860 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
1861 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
1862 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
1864 * This program is distributed in the hope that it will be useful, but WITHOUT
1865 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1866 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
1869 * You should have received a copy of the GNU Affero General Public License along with
1870 * this program; if not, see http://www.gnu.org/licenses or write to the Free
1871 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
1874 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
1875 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
1877 * The interactive user interfaces in modified source and object code versions
1878 * of this program must display Appropriate Legal Notices, as required under
1879 * Section 5 of the GNU Affero General Public License version 3.
1881 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
1882 * these Appropriate Legal Notices must retain the display of the "Powered by
1883 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
1884 * technical reasons, the Appropriate Legal Notices must display the words
1885 * "Powered by SugarCRM".
1886 ********************************************************************************/
1888 function gridInit() {
1889 if(SUGAR.email2.grid) {
1890 SUGAR.email2.grid.destroy();
1896 var Ck = YAHOO.util.Cookie;
1897 var widths = [ 10, 10, 150, 250, 175, 125 ];
1899 if (Ck.get("EmailGridWidths")) {
1900 for (var i=0; i < widths.length; i++) {
1901 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
1904 for (var i=0; i < widths.length; i++) {
1905 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
1909 // changes "F" to an icon
1910 function flaggedIcon(cell, record, column, value) {
1912 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
1915 // changes "A" to replied icon
1916 function repliedIcon(cell, record, column, value) {
1918 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
1921 function attachIcon(cell, record, column, value) {
1923 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
1930 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
1935 formatter: attachIcon,
1939 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
1944 formatter: flaggedIcon,
1948 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
1953 formatter: repliedIcon,
1957 label: app_strings.LBL_EMAIL_FROM,
1964 label: app_strings.LBL_EMAIL_SUBJECT,
1971 label: mod_strings.LBL_LIST_DATE,
1978 label: app_strings.LBL_EMAIL_TO,
2014 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2015 responseType: YAHOO.util.DataSource.TYPE_JSON,
2017 resultsList: 'Email',
2018 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
2019 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
2025 action : "EmailUIAjax",
2026 emailUIAction : "getMessageList",
2029 forceRefresh : "false"
2031 if(lazyLoadFolder != null) {
2032 params['mbox'] = lazyLoadFolder.folder;
2033 params['ieId'] = lazyLoadFolder.ieId;
2034 //Check if the folder is a Sugar Folder
2035 var test = new String(lazyLoadFolder.folder);
2036 if(test.match(/SUGAR\./)) {
2037 params['emailUIAction'] = 'getMessageListSugarFolders';
2038 params['mbox'] = test.substr(6);
2041 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
2044 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
2045 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2047 paginator: new YAHOO.widget.Paginator({
2048 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
2049 containers : ["dt-pag-nav"],
2050 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2051 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2052 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2053 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2054 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2056 initialRequest:SUGAR.util.paramsToUrl(params),
2063 //Override Paging request construction
2064 grid.set("generateRequest", function(oState, oSelf) {
2065 oState = oState || {pagination:null, sortedBy:null};
2066 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[5].getKey();
2067 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_ASC) ? "asc" : "desc";
2068 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2069 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2070 // Build the request
2072 SUGAR.util.paramsToUrl(oSelf.params) +
2075 "&start=" + startIndex +
2076 ((results !== null) ? "&limit=" + results : "");
2081 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2082 oPayload = oPayload || { };
2084 oPayload.totalRecords = oResponse.meta.total;
2085 oPayload.unreadRecords = oResponse.meta.unread;
2087 var tabObject = SE.innerLayout.get("tabs")[0];
2089 if (this.params.mbox != null) {
2090 mboxTitle = this.params.mbox;
2092 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
2093 tabObject.get("labelEl").firstChild.data = tabtext;
2096 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
2098 node.data.unseen = oResponse.meta.unread;
2099 SE.accounts.renderTree();
2105 var resize = grid.resizeGrid = function () {
2106 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
2107 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
2109 grid.convertDDRows = function() {
2110 var rowEl = this.getFirstTrEl();
2111 while (rowEl != null) {
2112 new this.DDRow(this, this.getRecord(rowEl), rowEl);
2113 rowEl = this.getNextTrEl(rowEl);
2118 grid.on("columnResizeEvent", function(o) {
2119 //Find the index of the column
2120 var colSet = SUGAR.email2.grid.getColumnSet().flat;
2121 for (var i=0; i < colSet.length; i++) {
2122 if (o.column == colSet[i]) {
2123 //Store it in the cookie
2124 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
2127 //this.resizeGrid();
2130 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
2131 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
2132 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
2134 SUGAR.email2.listViewLayout.on("render", resize);
2137 //Setup the default load parameters
2138 SUGAR.email2.grid.params = params;
2140 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
2141 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2142 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2149 function initRowDD() {
2150 var sg = SUGAR.email2.grid,
2151 Dom = YAHOO.util.Dom;
2152 sg.DDRow = function(oDataTable, oRecord, elTr) {
2153 if(oDataTable && oRecord && elTr) {
2154 this.ddtable = oDataTable;
2155 this.table = oDataTable.getTableEl();
2158 this.newIndex = null;
2160 this.initFrame(); // Needed for DDProxy
2161 this.invalidHandleTypes = {};
2165 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
2166 _resizeProxy: function() {
2167 this.constructor.superclass._resizeProxy.apply(this, arguments);
2168 var dragEl = this.getDragEl(),
2170 var xy = Dom.getXY(el);
2172 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
2173 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
2174 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
2175 Dom.setStyle(dragEl, 'display', "");
2178 startDrag: function(x, y) {
2179 //Check if we should be dragging a set of rows rather than just the one.
2180 var selectedRows = this.ddtable.getSelectedRows();
2181 var iSelected = false;
2182 for (var i in selectedRows) {
2183 if (this.rowEl.id == selectedRows[i]) {
2190 for (var i in selectedRows) {
2191 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
2194 this.rows = [this.row];
2195 this.ddtable.unselectAllRows();
2196 this.ddtable.selectRow(this.row);
2199 //Initialize the dragable proxy
2200 var dragEl = this.getDragEl();
2201 var clickEl = this.getEl();
2202 Dom.setStyle(clickEl, "opacity", "0.25");
2203 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
2204 Dom.addClass(dragEl, "yui-dt-liner");
2205 Dom.setStyle(dragEl, "opacity", "0.5");
2206 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
2207 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
2208 Dom.setStyle(dragEl, "border", "2px solid gray");
2211 clickValidator: function(e) {
2212 if (this.row.getData()[0] == " ")
2214 var target = YAHOO.util.Event.getTarget(e);
2215 return ( this.isValidHandleChild(target) &&
2216 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
2219 * This funciton checks that the target of the drag is a table row in this
2220 * DDGroup and simply moves the sourceEL to that location as a preview.
2222 onDragOver: function(ev, id) {
2223 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
2224 if (node && node != this.targetNode) {
2225 this.targetNode = node;
2226 SUGAR.email2.folders.unhighliteAll();
2231 onDragOut: function(e, id) {
2232 if (this.targetNode) {
2233 SUGAR.email2.folders.unhighliteAll();
2234 this.targetNode = false;
2237 endDrag: function() {
2238 Dom.setStyle(this.getEl(), "opacity", "");
2239 Dom.setStyle(this.getDragEl(), "display", "none");
2240 if (this.targetNode) {
2241 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
2243 SUGAR.email2.folders.unhighliteAll();
2249 function AddressSearchGridInit() {
2250 function moduleIcon(elCell, oRecord, oColumn, oData) {
2251 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
2253 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
2254 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
2256 var checkHeader = '<input type="checkbox" ';
2257 if (SUGAR.email2.util.isIe()) {
2258 checkHeader += 'style="top:-5px" ';
2260 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
2265 formatter: selectionCheckBox,
2269 label: mod_strings.LBL_LIST_TYPE,
2271 formatter: moduleIcon,
2275 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
2281 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
2287 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2288 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
2290 resultsList: 'Person',
2291 fields: ['name', 'email', 'bean_id', 'bean_module'],
2292 metaFields: {total: 'TotalCount'}
2294 //enable sorting on the server accross all data
2297 dataModel.params = {
2300 action : "EmailUIAjax",
2301 emailUIAction:"getAddressSearchResults"
2303 var rb = document.getElementById('hasRelatedBean').checked;
2305 var idx = SUGAR.email2.composeLayout.currentInstanceId;
2306 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2307 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2308 dataModel.params['related_bean_id'] = relatedBeanId;
2309 dataModel.params['related_bean_type'] = relatedBeanType;
2310 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
2312 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
2314 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
2315 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2317 paginator: new YAHOO.widget.Paginator({
2319 containers : ["dt-pag-nav-addressbook"],
2320 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2321 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2322 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2323 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2324 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2326 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
2330 //Override Paging request construction
2331 grid.set("generateRequest", function(oState, oSelf) {
2332 oState = oState || {pagination:null, sortedBy:null};
2333 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
2334 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2335 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2336 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2337 // Build the request
2339 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
2340 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
2341 ((results !== null) ? "&limit=" + results : "");
2345 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2346 oPayload = oPayload || { };
2347 oPayload.totalRecords = oResponse.meta.total;
2351 grid.clickToggleSelect= function(args) {
2352 var isIE = (args.event.target == null);
2353 var targetElement = isIE ? args.event.srcElement : args.event.target;
2354 if(targetElement.type == null || targetElement.type != 'checkbox') {
2355 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
2359 grid.reSelectRowsOnRender = function (){
2360 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2361 for (var i = 0; i < rows.length; i++)
2363 var emailAddress = rows[i].getData("email");
2364 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
2367 rows[i].setData("selected", true);
2368 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2372 rows[i].setData("selected", false);
2373 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
2377 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
2378 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
2379 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
2380 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
2383 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2384 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2386 grid.toggleSelectCheckbox = function(id,checked){
2387 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2388 row.setData("checked",checked);
2390 grid.toggleSelect = function(id, checked) {
2391 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2392 checked = row.getData("selected");
2395 SUGAR.email2.addressBook.grid.selectRow(row);
2396 SE.addressBook.insertContactRowToResultTable(id,null)
2399 SUGAR.email2.addressBook.grid.unselectRow(row);
2400 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
2402 row.setData("selected", !checked);
2405 grid.toggleSelectAll = function(checked) {
2406 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2407 for (var i = 0; i < rows.length; i++) {
2408 if (typeof(rows[i]) != "undefined")
2409 rows[i].setData("checked", checked);
2411 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2412 for (var i = 0; i < checkBoxes.length; i++) {
2413 checkBoxes[i].checked = checked;
2417 //Initialize the grid result table.
2418 AddressSearchResultsGridInit();
2424 * Initalize the results table for the address book selection.
2427 function AddressSearchResultsGridInit()
2430 /* Full name sort funciton to compare by last name if available */
2431 var fullNameSort = function(a, b, desc) {
2432 // Deal with empty values
2433 if(!YAHOO.lang.isValue(a))
2434 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
2435 else if(!YAHOO.lang.isValue(b))
2438 var aNames = a.getData("name").split(' ');
2439 var bNames = b.getData("name").split(' ');
2441 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
2442 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
2444 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
2448 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
2449 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
2450 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
2452 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})},
2453 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
2455 var myDataSource = new YAHOO.util.DataSource([]);
2456 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
2457 myDataSource.responseSchema = {
2458 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
2461 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
2462 width: "350px",height: "250px", MSG_EMPTY: " "});
2464 var highlightEditableCell = function(oArgs) {
2465 var elCell = oArgs.target;
2466 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
2467 this.highlightCell(elCell);
2471 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
2472 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
2473 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
2474 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
2475 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
2477 //Setup the context menus
2478 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
2479 var task = p_aArgs[1];
2482 var elRow = this.contextEventTarget;
2483 elRow = p_myDataTable.getTrEl(elRow);
2490 var oRecord = p_myDataTable.getRecord(elRow);
2491 p_myDataTable.deleteRow(elRow);
2492 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2497 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
2498 {trigger:gridResults.getTbodyEl()});
2499 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
2500 contextMenu.render("addrSearchResultGrid");
2501 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
2503 // End of File modules/Emails/javascript/grid.js
2505 /*********************************************************************************
2506 * SugarCRM Community Edition is a customer relationship management program developed by
2507 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
2509 * This program is free software; you can redistribute it and/or modify it under
2510 * the terms of the GNU Affero General Public License version 3 as published by the
2511 * Free Software Foundation with the addition of the following permission added
2512 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
2513 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
2514 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
2516 * This program is distributed in the hope that it will be useful, but WITHOUT
2517 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
2518 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
2521 * You should have received a copy of the GNU Affero General Public License along with
2522 * this program; if not, see http://www.gnu.org/licenses or write to the Free
2523 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
2526 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
2527 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
2529 * The interactive user interfaces in modified source and object code versions
2530 * of this program must display Appropriate Legal Notices, as required under
2531 * Section 5 of the GNU Affero General Public License version 3.
2533 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
2534 * these Appropriate Legal Notices must retain the display of the "Powered by
2535 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
2536 * technical reasons, the Appropriate Legal Notices must display the words
2537 * "Powered by SugarCRM".
2538 ********************************************************************************/
2541 var sw = YAHOO.SUGAR,
2542 Event = YAHOO.util.Event,
2543 Connect = YAHOO.util.Connect,
2544 Dom = YAHOO.util.Dom
2547 ///////////////////////////////////////////////////////////////////////////////
2550 _contactCache : new Array(), // cache of contacts
2551 _dd : new Array(), // filtered list, same format as _contactCache
2552 _ddLists : new Array(), // list of Lists
2553 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
2554 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
2555 clickBubble : true, // hack to get around onclick event bubbling
2557 relatedBeanType : '',
2560 itemSpacing : 'white-space:nowrap; padding:2px;',
2566 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
2568 initFixForDatatableSort: function () {
2569 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
2570 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
2571 var oColumn = this._oColumnSet.getColumn(column);
2574 // Validate TD element
2575 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
2577 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
2579 // Validate TH element
2581 elCell = this.getThEl(column);
2584 var allColumns = this._oColumnSet.flat;
2585 for(var i=0, len=allColumns.length; i<len; i++) {
2586 if(allColumns[i].getThEl().id === elCell.id) {
2587 oColumn = allColumns[i];
2598 cancelEdit : function() {
2599 if(this.editContactDialog)
2600 this.editContactDialog.hide();
2601 if(this.editMailingListDialog)
2602 this.editMailingListDialog.hide();
2606 * Clears filter form
2608 clear : function() {
2609 var t = document.getElementById('contactsFilter');
2615 * handle context-menu Compose-to call
2616 * @param string type 'contacts' or 'lists'
2618 composeTo : function(type, waited) {
2619 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
2620 if (activePanel.substring(0, 10) != "composeTab") {
2621 SE.composeLayout.c0_composeNewEmail();
2622 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
2623 SE.contextMenus.contactsContextMenu.hide();
2626 var idx = activePanel.substring(10);
2629 // determine if we have a selection to work with
2630 if(type == 'contacts') {
2631 var ids = SE.contactView.getSelectedRows();
2632 for (var i in ids) {
2633 rows[i] = SE.contactView.getRecord(ids[i]);
2635 removeHiddenNodes(rows, SE.contactView);
2639 if(rows.length > 0) {
2640 SE.composeLayout.handleDrop(
2641 (type == 'contacts') ? SE.contactView : SE.emailListsView,
2642 null, rows, 'addressTO' + idx );
2644 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
2648 editContact : function() {
2649 SE.contextMenus.contactsContextMenu.hide();
2650 var element = SE.contactView.getSelectedNodes()[0];
2652 if (element.className.indexOf('address-contact') > -1) {
2653 elementId = element.id;
2654 } else if (element.className.indexOf('address-exp-contact') > -1) {
2655 elementId = element.id.substring(2);
2661 * Filters contact entries based on user input
2663 filter : function(inputEl) {
2664 var ret = new Object();
2665 var re = new RegExp(inputEl.value, "gi");
2667 for(var i in this._contactCache) {
2668 if(this._contactCache[i].name.match(re)) {
2669 ret[i] = this._contactCache[i];
2673 this.buildContactList(ret);
2676 fullForm : function(id, module) {
2677 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
2681 * returns a formatted email address from the addressBook cache
2683 getFormattedAddress : function(id) {
2684 var o = this._contactCache[id];
2685 var primaryEmail = '';
2687 for(var i=0; i<o.email.length; i++) {
2688 var currentEmail = o.email[i].email_address;
2690 if(o.email[i].primary_address == 1) {
2691 primaryEmail = o.email[i].email_address;
2695 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
2696 var name = new String(o.name);
2697 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
2698 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
2704 * Sets up async call to query for matching contacts, users, etc.
2706 searchContacts : function() {
2707 var fn = document.getElementById('input_searchField').value;
2708 var pe = document.getElementById('input_searchPerson').value;
2710 var rb = document.getElementById('hasRelatedBean').checked;
2713 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2714 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2715 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2716 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2718 this.addressBookDataModel.params['related_bean_id'] = '';
2721 this.addressBookDataModel.params['search_field'] = fn;
2722 this.addressBookDataModel.params['person'] = pe;
2723 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
2724 this.grid._oDataSource = this.addressBookDataModel;
2725 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
2729 * Clear Search Crieteria For Addressbook
2731 clearAddressBookSearch : function() {
2732 document.getElementById('input_searchField').value = "";
2733 document.getElementById('input_searchPerson').selectedIndex = 0;
2737 * Opens modal select window to add contacts to addressbook
2739 selectContactsDialogue : function(destId) {
2740 if(!this.contactsDialogue) {
2741 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
2745 constraintoviewport: true,
2747 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
2748 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
2750 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
2752 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
2753 dlg.setBody(body.innerHTML);
2754 dlg.renderEvent.subscribe(function() {
2755 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
2756 if (iev && !SUGAR.isIE) {
2757 this.body.style.width = "950px";
2762 dlg.beforeRenderEvent.subscribe(function() {
2763 var dd = new YAHOO.util.DDProxy(dlg.element);
2764 dd.setHandleElId(dlg.header);
2765 dd.on('endDragEvent', function() {
2771 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
2773 var tabContent = SUGAR.util.getAndRemove("searchForm");
2774 tp.addTab(new YAHOO.widget.Tab({
2775 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
2777 content : tabContent.innerHTML,
2778 id : "addressSearchTab",
2782 var addListenerFields = ['input_searchPerson','input_searchField' ]
2783 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
2784 if (e.keyCode == 13) {
2785 YAHOO.util.Event.stopEvent(e);
2786 SUGAR.email2.addressBook.searchContacts();
2790 this.contactsDialogue.render();
2793 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
2794 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
2798 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
2799 var idx = activePanel.substring(10);
2801 SE.addressBook.idx = idx;
2804 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
2805 document.getElementById('relatedBeanColumn').style.display = '';
2806 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
2807 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2808 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2809 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
2810 SE.addressBook.relatedBeanType = relatedBeanType;
2812 document.getElementById('relatedBeanColumn').style.display = 'none';
2813 document.getElementById('hasRelatedBean').checked = false;
2816 if (!SE.addressBook.grid)
2818 if (hasRelatedBeanId) {
2819 document.getElementById('hasRelatedBean').checked = true;
2821 AddressSearchGridInit();
2822 SE.addressBook.relatedBeanId = relatedBeanId;
2826 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
2828 SE.addressBook.relatedBeanId = relatedBeanId;
2829 document.getElementById('hasRelatedBean').checked = true;
2831 if (document.getElementById('hasRelatedBean').checked == true)
2833 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2834 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2836 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
2837 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
2839 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
2840 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
2841 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
2844 //Remove any lingering rows in the result set table if the module was closed.
2845 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2847 SE.addressBook.populateResulstTableEmailAddresses();
2849 this.contactsDialogue.show();
2852 * Clear all email addresses from result table.
2855 clearAllEmailAddressFieldsFromResultTable: function () {
2856 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2857 //Unhighlight any rows currently selected if the emails were cleared.
2858 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
2859 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2862 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
2863 * results table. This function is called when the address book is displayed.
2865 populateResulstTableEmailAddresses: function () {
2867 var idx = SE.addressBook.idx;
2868 var emailFields = ['to','cc','bcc'];
2870 for(var k=0;k<emailFields.length;k++)
2872 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2873 var allEmails = document.getElementById(elKey).value;
2877 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
2879 for (var i=0; i<formatedEmails.length; i++)
2881 var t_name = formatedEmails[i].name;
2882 var t_emailAddr = formatedEmails[i].email_address;
2883 var displayEmail = t_name + ' <' + t_emailAddr + '>';
2885 t_name = displayEmail = t_emailAddr;
2887 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
2888 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
2889 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
2895 * Checks all entries in the result table against a particular email address, returning true
2896 * if the email address is found, false otherwise.
2898 doesEmailAdddressExistInResultTable: function(emailAddress)
2900 if(trim(emailAddress) == '')
2903 var emailAddressFound = false;
2904 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2905 for (var i=0; i < contacts.length; i++)
2907 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2908 //If we are adding to cc or bcc fields, make them visible.
2909 if(data.email_address == emailAddress)
2911 emailAddressFound = true;
2916 return emailAddressFound;
2919 * Takes all email addresses that the users wishes to add from the address book and populates the To
2920 * fields on the compose tab.
2922 populateEmailAddressFieldsFromResultTable: function()
2924 //Clear the fields first, all email addresses are stored in the address book
2925 var idx = SE.addressBook.idx;
2926 var emailFields = ['to','cc','bcc'];
2927 for(var k=0;k<emailFields.length;k++)
2929 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2930 document.getElementById(elKey).value = "";
2933 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2934 for (var i=0; i < contacts.length; i++)
2936 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2938 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
2939 //If we are adding to cc or bcc fields, make them visible.
2940 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
2941 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
2942 //Construct the target id
2943 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
2945 var target = document.getElementById(target_id);
2946 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
2949 //Delete all rows from the result set table
2950 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2953 SE.addressBook.contactsDialogue.hide()
2956 * Insert contacts into the result table.
2958 insertContactToResultTable : function(event,address_type) {
2960 var contactsDialogue = SE.addressBook.contactsDialogue;
2961 var contacts = SE.addressBook.grid.getSelectedRows();
2963 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2964 for (var i = 0; i < rows.length; i++)
2966 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
2968 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
2969 SE.addressBook.insertContactRowToResultTable(recId,address_type);
2970 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2971 rows[i].setData("selected",true);
2974 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2975 for (var i = 0; i < checkBoxes.length; i++) {
2976 checkBoxes[i].checked = false;
2982 insertContactRowToResultTable : function(rowId, addressType) {
2983 var data = SE.addressBook.grid.getRecord(rowId).getData();
2984 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
2986 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
2987 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
2988 if(addressType == null)
2989 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
2990 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});
2993 * Remove a row from the gridsResult table.
2995 removeRowFromGridResults : function(rowId,emailAddress)
2997 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2998 for (var i=0; i < contacts.length; i++)
3000 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
3001 var data = rec.getData();
3002 if(data.email_address == emailAddress)
3004 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
3009 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
3012 * Translates between the addressType To|Cc|Bcc labels/keys.
3014 translateAddresType: function(addressType,fromKey)
3016 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
3017 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
3018 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
3019 var mappingObject = {};
3022 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
3025 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
3026 mappingObject[displayCc] = 'cc';
3027 mappingObject[displayBcc] = 'bcc';
3030 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
3036 toggleSearchRowIcon : function(rowId,show)
3040 var idToShow = rowId + '_add_img';
3041 var idToHide = rowId + '_rm_img';
3045 var idToShow = rowId + '_rm_img';
3046 var idToHide = rowId + '_add_img';
3050 Dom.addClass(idToHide, "yui-hidden");
3051 Dom.removeClass(idToShow, "yui-hidden");
3054 * Determine if an entry has already been added to the grid results table to prevent duplicates.
3056 doesGridResultsEntryExist: function(emailAddrs)
3059 var contactExists = false;
3060 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
3061 for (var i=0; i < contacts.length; i++)
3063 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
3064 if(data.email_address == emailAddrs)
3066 contactExists = true;
3070 return contactExists;
3074 * adds an email address to a string, but first checks if it exists
3075 * @param string concat The string we are appending email addresses to
3076 * @param string addr Email address to add
3079 smartAddEmailAddressToComposeField : function(concat, addr) {
3080 var re = new RegExp(addr);
3082 if(!concat.match(re)) {
3084 concat += "; " + addr;
3093 //// END ADDRESS BOOK
3094 ///////////////////////////////////////////////////////////////////////////////
3098 ///////////////////////////////////////////////////////////////////////////////
3101 * Auto-complete object
3105 delimChar : [";", ","],
3109 prehighlightClassName : "yui-ac-prehighlight",
3112 instances : new Array(),
3115 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
3116 * @param object Contact from AddressBook
3119 getPrimaryAddress : function(contact) {
3120 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
3122 for(var eIndex in contact.email) {
3123 address = contact.email[eIndex].email_address;
3124 if(contact.email[eIndex].primary_address == 1) {
3125 return contact.email[eIndex].email_address;
3133 * initializes autocomplete widgets for a given compose view
3136 init : function(idx) {
3137 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
3138 "queryMatchContains" : false,
3139 "queryMatchSubset" : true
3142 this.instances[idx] = {
3149 // instantiate the autoComplete widgets
3150 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
3151 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
3152 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
3154 // enable hiding of interfering textareas
3155 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3156 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3157 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3159 // enable reshowing of hidden textareas
3160 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3161 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3162 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3164 // enable refreshes of contact lists
3165 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3166 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3167 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3170 refreshDataSource : function(sType, aArgs) {
3171 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
3173 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
3175 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
3176 idx = textBoxId.substr(9);
3178 idx = textBoxId.substr(10);
3181 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
3182 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
3183 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
3187 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
3189 returnDataSource : function(contacts) {
3190 var ret = new Array();
3191 for(var id in contacts) {
3192 if (contacts[id].name) {
3193 var primary = this.getPrimaryAddress(contacts[id]);
3195 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
3196 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
3198 for(var emailIndex in contacts[id].email) {
3199 ret[ret.length] = contacts[id].email[emailIndex].email_address;
3208 * Hides address textareas to prevent autocomplete dropdown from being obscured
3210 toggleTextareaHide : function(sType, aArgs) {
3211 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3215 if(textBoxId.indexOf("addressTO") > -1) {
3217 } else if(textBoxId.indexOf("addressCC") > -1) {
3220 idx = textBoxId.substr(9);
3222 // follow through if not BCC
3224 var cc = document.getElementById("addressCC" + idx);
3225 var bcc = document.getElementById("addressBCC" + idx);
3229 cc.style.visibility = 'hidden';
3231 bcc.style.visibility = 'hidden';
3238 * Redisplays the textareas after an address is commited
3240 toggleTextareaShow : function(sType, aArgs) {
3241 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3245 if(textBoxId.indexOf("addressTO") > -1) {
3247 } else if(textBoxId.indexOf("addressCC") > -1) {
3250 idx = textBoxId.substr(9);
3252 // follow through if not BCC
3254 document.getElementById("addressCC" + idx).style.visibility = 'visible';
3255 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
3260 //// END AUTOCOMPLETE
3261 ///////////////////////////////////////////////////////////////////////////////
3263 ///////////////////////////////////////////////////////////////////////////////
3266 * expands the options sidebar
3268 SE.composeLayout = {
3269 currentInstanceId : 0,
3272 outboundAccountErrors : null,
3273 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
3275 showAddressDetails : function(e) {
3276 var linkElement = document.getElementById("More"+e.id);
3277 var spanElement = document.getElementById("Detail"+e.id);
3278 var emailAddressList = e.value;
3279 if(e.value.length > 96)
3281 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
3282 var displayArray = [];
3283 for (var i=0; i<resultArray.length; i++)
3285 var t_name = resultArray[i].name;
3286 var t_emailAddr = resultArray[i].email_address;
3288 displayArray.push('<br/><' + t_emailAddr + '>');
3290 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
3293 var result = displayArray.join('<br/>');
3295 linkElement.style.display = "inline";
3296 linkElement.style.height="10px";
3297 linkElement.style.overflow="visible";
3298 spanElement.innerHTML = result;
3301 linkElement.style.display = "none";
3306 * Given a string of email address, return an array containing the name portion (if available)
3307 * and email portion.
3309 _getEmailArrayFromString : function (emailAddressList){
3312 while ((results = reg.exec(emailAddressList)) != null)
3314 orignial = results[0];
3315 parsedResult = results[0].replace(';', ':::::');
3316 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3320 while ((results = reg.exec(emailAddressList)) != null)
3322 orignial = results[0];
3323 parsedResult = results[0].replace(',', ':::::');
3324 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3326 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
3327 var emailArr = emailAddressList.split(":::::");
3328 var resultsArray = [];
3330 for (var i=0; i<emailArr.length; i++)
3332 var rposition = emailArr[i].indexOf('<');
3333 var lposition = emailArr[i].indexOf('>');
3335 if(trim(emailArr[i]) != '')
3337 if(rposition != -1 && lposition != -1)
3339 var t_name = emailArr[i].substr(0, rposition-1);
3340 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
3341 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
3345 resultsArray.push({'name':'', 'email_address': emailArr[i]});
3349 return resultsArray;
3351 ///////////////////////////////////////////////////////////////////////////
3354 * Prepare bucket DIV and yui-ext tab panels
3356 _0_yui : function() {
3357 var idx = this.currentInstanceId;
3359 var composeTab = new YAHOO.SUGAR.ClosableTab({
3360 label: mod_strings.LNK_NEW_SEND_EMAIL,
3362 content : "<div id='htmleditordiv" + idx + "'/>",
3363 id : "composeTab" + idx,
3364 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
3367 SE.innerLayout.addTab(composeTab);
3369 // get template engine with template
3370 if (!SE.composeLayout.composeTemplate) {
3371 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
3374 // create Tab inner layout
3375 var composePanel = this.getComposeLayout();
3376 composePanel.getUnitByPosition("right").collapse();
3377 composePanel.autoSize();
3381 * Generate the quick compose layout
3382 * @method getQuickComposeLayout
3383 * @param {Pannel} parentPanel Parent pannel
3384 * @param {Object} o Options
3387 getQuickComposeLayout : function (parentPanel,o) {
3388 var idx = SE.composeLayout.currentInstanceId;
3390 //Before rendering the parent pannel we need to initalize the grid layout
3391 parentPanel.beforeRenderEvent.subscribe(function() {
3393 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3394 SE.composeLayout._createComposeLayout(idx);
3395 SE.composeLayout[idx].set('height', 350);
3396 SE.composeLayout[idx].render();
3400 //Wait until the Compose Layout has rendered, then add the
3401 //options tab and perform the tiny initialization.
3402 parentPanel.renderEvent.subscribe(function() {
3404 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3405 SE.composeLayout._initComposeOptionTabs(idx);
3406 SE.composeLayout[idx].getUnitByPosition("right").collapse();
3407 //Initialize tinyMCE
3408 SE.composeLayout._1_tiny(false);
3410 //Init templates and address book
3411 SE.composeLayout._2_final();
3413 SE.composeLayout.quickCreateComposePackage(o);
3418 //Check if we have the div override for the shortcut bar
3419 if(typeof o.menu_id != 'undefined') {
3420 parentPanel.render(o.menu_id);
3422 parentPanel.render(document.body);
3425 return SE.composeLayout[idx];
3428 * Fill in all fields into the quick compose layout.
3429 * @method quickCreateComposePackage
3430 * @param {Object} o Options
3433 quickCreateComposePackage: function(o)
3435 //If we have a compose package fill in defaults.
3436 if (typeof(o.composePackage) != 'undefined')
3438 composePackage = o.composePackage; //Set the compose data object
3439 //Hijack this method called by composePackage as it's not need for quick creates.
3440 SE.composeLayout.c0_composeNewEmail = function(){};
3441 SE.composeLayout.composePackage(); //Fill in defaults.
3444 getComposeLayout : function() {
3445 var idx = SE.composeLayout.currentInstanceId;
3447 this._createComposeLayout(idx);
3448 SE.composeLayout[idx].render();
3449 this._initComposeOptionTabs(idx);
3451 return SE.composeLayout[idx];
3455 * Create the layout manager for the compose window.
3457 _createComposeLayout : function(idx)
3459 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
3460 parent: SE.complexLayout,
3470 SE.composeLayout.composeTemplate.exec({
3471 'app_strings':app_strings,
3472 'mod_strings':mod_strings,
3474 'linkbeans_options' : linkBeans,
3475 'idx' : SE.composeLayout.currentInstanceId
3486 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
3489 header: app_strings.LBL_EMAIL_OPTIONS
3495 * Create compose tab which will populate the 'right' container in the compose window.
3497 _initComposeOptionTabs : function(idx)
3499 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
3500 var tab = new YAHOO.widget.Tab({
3501 label: app_strings.LBL_EMAIL_ATTACHMENT,
3503 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
3504 id : "divAttachments" + idx,
3508 tab.layout = SE.composeLayout[idx];
3510 tab.on("activeChange", function(o){
3512 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
3518 tab = new YAHOO.widget.Tab({
3519 label: app_strings.LBL_EMAIL_OPTIONS,
3521 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
3522 id : "divOptions" + idx,
3526 tab.layout = SE.composeLayout[idx];
3527 tab.on("activeChange", function(o){
3529 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
3534 SE.composeLayout[idx].autoSize = function() {
3535 var pEl = this.get("element").parentNode.parentNode.parentNode;
3536 this.set("height", pEl.clientHeight-30);
3540 SE.composeLayout[idx].rightTabs = cTabs;
3542 isParentTypeValid : function(idx) {
3543 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3544 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3545 if (trim(parentTypeValue) == ""){
3546 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
3552 isParentTypeAndNameValid : function(idx) {
3553 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3554 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3555 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
3556 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
3557 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
3558 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
3564 callopenpopupForEmail2 : function(idx,options) {
3566 var formName = 'emailCompose' + idx;
3568 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
3569 formName = options.form_name;
3571 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3572 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3573 if (!SE.composeLayout.isParentTypeValid(idx)) {
3576 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
3578 call_back_function:"SE.composeLayout.popupAddEmail",
3580 field_to_name_array:{
3581 id:'data_parent_id' + idx,
3582 name:'data_parent_name' + idx,
3587 popupAddEmail : function(o)
3589 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
3590 var data = o.name_to_value_array;
3591 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
3592 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
3594 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
3595 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
3602 _1_tiny : function(isReplyForward) {
3603 var idx = SE.composeLayout.currentInstanceId;
3604 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
3605 SE.tinyInstances[elId] = { };
3606 SE.tinyInstances[elId].ready = false;
3608 if (!SUGAR.util.isTouchScreen()) {
3609 var t = tinyMCE.getInstanceById(elId);
3611 if(typeof(t) == 'undefined') {
3612 if (!SUGAR.util.isTouchScreen()) {
3613 tinyMCE.execCommand('mceAddControl', false, elId);
3615 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
3616 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
3621 resizeEditorSetSignature : function(idx,setSignature)
3623 var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
3625 if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
3626 setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+isReplyForward+"');",500);
3630 SE.composeLayout.resizeEditor(idx);
3632 setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
3637 resizeEditor : function(idx)
3639 var cof = Dom.get('composeOverFrame' + idx);
3640 var head = Dom.get('composeHeaderTable' + idx);
3641 var targetHeight = cof.clientHeight - head.clientHeight;
3642 var instance = SE.util.getTiny('htmleditor' + idx);
3645 var parentEl = Dom.get(instance.editorId + '_parent');
3646 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
3647 var contentEl = instance.contentAreaContainer;
3648 var iFrame = contentEl.firstChild;
3649 var tinMceToolbarOffset = 18;
3650 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
3653 setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
3658 * Initializes d&d, auto-complete, email templates
3660 _2_final : function() {
3661 var idx = SE.composeLayout.currentInstanceId;
3663 if(this.emailTemplates) {
3664 this.setComposeOptions(idx);
3666 //populate email template cache
3667 AjaxObject.target = '';
3668 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
3671 // handle drop targets for addressBook
3672 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3673 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3674 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3675 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
3677 // auto-complete setup
3678 SE.autoComplete.init(idx);
3681 document.getElementById("addressTO" + idx).focus();
3685 * hide tinyMCE tool bar if send email as plaintext is checked
3687 renderTinyMCEToolBar : function (idx, hide) {
3689 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
3691 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
3695 c1_composeEmail : function(isReplyForward, retry) {
3699 if (!SUGAR.util.isTouchScreen() && (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined')){
3700 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
3702 this._1_tiny(isReplyForward);
3705 if(isReplyForward) {
3706 this.replyForwardEmailStage2();
3712 * takes draft info and prepopulates
3714 c0_composeDraft : function() {
3715 this.getNewInstanceId();
3717 document.getElementById('_blank').innerHTML = '';
3718 var idx = SE.composeLayout.currentInstanceId;
3719 SE.composeLayout.draftObject = new Object();
3720 SE.composeLayout.draftObject.id = idx;
3721 SE.composeLayout.draftObject.isDraft = true;
3722 SE.composeLayout.currentInstanceId = idx;
3723 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
3724 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
3725 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
3727 SE.composeLayout._0_yui();
3728 SE.composeLayout._1_tiny(true);
3731 SE.composeLayout._2_final();
3733 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
3734 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
3738 * Strip & Prep editor hidden fields
3740 c0_composeNewEmail : function() {
3741 this.getNewInstanceId();
3742 this.c1_composeEmail(false);
3746 * Sends async request to get the compose view.
3747 * Requests come from "reply" or "forwards"
3749 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
3750 SE.composeLayout.replyForwardObj = new Object();
3751 SE.composeLayout.replyForwardObj.ieId = ieId;
3752 SE.composeLayout.replyForwardObj.uid = uid;
3753 SE.composeLayout.replyForwardObj.mbox = mbox;
3754 SE.composeLayout.replyForwardObj.type = type;
3756 if(mbox == 'sugar::Emails') {
3757 SE.composeLayout.replyForwardObj.sugarEmail = true;
3760 SE.composeLayout.getNewInstanceId();
3761 SE.composeLayout.c1_composeEmail(true);
3763 //// END COMPOSE FLOW
3764 ///////////////////////////////////////////////////////////////////////////
3767 * Called when a contact, email, or mailinglist is dropped
3768 * into one of the compose fields.
3770 handleDrop : function (source, event, data, target) {
3773 target = event.getTarget();
3775 data.nodes = [data.nodes];
3779 target = document.getElementById(target);
3783 if (target.id.indexOf('address') > -1) {
3784 // dropped onto email to/cc/bcc field
3785 for(var i in nodes) {
3786 var node = nodes[i].getData();
3788 if (node[1].indexOf('contact') > -1) {
3789 email = SE.addressBook.getFormattedAddress(node[0]);
3790 } else if (node[1].indexOf('address-email') > -1){
3791 email = node[3].replace(/ /gi, '');
3792 email = email.replace('<', '<').replace('>', '>');
3793 var tr = source.getTrEl(nodes[i]);
3794 while (tr && !Dom.hasClass(tr, "address-contact")) {
3795 tr = source.getPreviousTrEl(tr);
3797 var CID = source.getRecord(tr).getData()[0];
3798 var o = SE.addressBook._contactCache[CID];
3799 var name = new String(o.name);
3800 var finalName = name.replace(/(<([^>]+)>)/ig, "");
3801 email = finalName + email;
3803 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
3809 /*/////////////////////////////////////////////////////////////////////////////
3810 /// EMAIL TEMPLATE CODE
3812 applyEmailTemplate : function (idx, id) {
3815 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
3816 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
3817 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
3820 var to_addr = document.getElementById('addressTO'+idx);
3821 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
3823 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
3824 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
3827 // id is selected index of email template drop-down
3828 if(id == '' || id == "0") {
3829 YAHOO.SUGAR.MessageBox.show({
3834 if(btn=='no'){return;};
3835 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
3842 YAHOO.SUGAR.MessageBox.show({
3847 if(btn=='no'){return;};
3848 SUGAR.email2.composeLayout.processResult(idx, id);},
3854 processNoneResult : function(idx, id) {
3855 var tiny = SE.util.getTiny('htmleditor' + idx);
3856 var tinyHTML = tiny.getContent();
3857 var openTag = '<div><span><span>';
3858 var htmllow = tinyHTML.toLowerCase();
3859 var start = htmllow.indexOf(openTag);
3861 tinyHTML = tinyHTML.substr(start);
3862 tiny.setContent(tinyHTML);
3864 tiny.setContent('');
3868 processResult : function(idx , id){
3869 var post_data = {"module":"EmailTemplates","record":id};
3870 var global_rpcClient = new SugarRPCClient();
3872 result = global_rpcClient.call_method('retrieve', post_data, true);
3873 if(!result['record']) return;
3874 json_objects['email_template_object'] = result['record'];
3875 this.appendEmailTemplateJSON();
3877 // get attachments if any
3878 AjaxObject.target = '';
3879 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
3882 appendEmailTemplateJSON : function() {
3883 var idx = SE.composeLayout.currentInstanceId; // post increment
3885 // query based on template, contact_id0,related_to
3886 //jchi 09/10/2008 refix #7743
3887 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
3888 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
3891 var text = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body_html'])).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
3893 // cn: bug 14361 - text-only templates don't fill compose screen
3895 text = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body'])).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"').replace(/\r\n/gi,"<br/>");
3898 var tiny = SE.util.getTiny('htmleditor' + idx);
3899 var tinyHTML = tiny.getContent();
3900 var openTag = '<div><span><span>';
3901 var closeTag = '</span></span></div>';
3902 var htmllow = tinyHTML.toLowerCase();
3903 var start = htmllow.indexOf(openTag);
3905 var htmlPart2 = tinyHTML.substr(start);
3906 tinyHTML = text + htmlPart2;
3907 tiny.setContent(tinyHTML);
3909 tiny.setContent(text);
3914 * Writes out the signature in the email editor
3916 setSignature : function(idx) {
3919 var hide = document.getElementById('setEditor' + idx).checked;
3920 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
3921 //wait for signatures to load before trying to set them
3922 if (!SE.composeLayout.signatures) {
3923 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
3928 var sel = document.getElementById('signatures' + idx);
3930 var sel = document.getElementById('signature_id');
3931 idx = SE.tinyInstances.currentHtmleditor;
3934 //Ensure that the tinyMCE html has been rendered.
3935 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
3936 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
3943 signature = sel.options[sel.selectedIndex].value;
3948 var openTag = '<div><span> </span>';
3949 var closeTag = '<span> </span></div>';
3950 var t = tinyMCE.getInstanceById('htmleditor' + idx);
3952 if(typeof(t) != 'undefined')
3954 t.contentDocument = t.contentWindow.document;
3955 var html = t.getContent();
3962 var htmllow = html.toLowerCase();
3963 var start = htmllow.indexOf(openTag);
3964 var end = htmllow.indexOf(closeTag) + closeTag.length;
3966 // selected "none" - remove signature from email
3967 if(signature == '') {
3969 var htmlPart1 = html.substr(0, start);
3970 var htmlPart2 = html.substr(end, html.length);
3972 html = htmlPart1 + htmlPart2;
3975 SE.signatures.lastAttemptedLoad = '';
3979 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
3980 SE.signatures.lastAttemptedLoad = '';
3982 SE.signatures.lastAttemptedLoad = signature;
3984 if(typeof(SE.signatures[signature]) == 'undefined') {
3986 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
3987 SE.signatures.targetInstance = (idx) ? idx : "";
3988 AjaxObject.target = '';
3989 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
3991 var newSignature = this.prepareSignature(SE.signatures[signature]);
3993 // clear out old signature
3994 if(SE.signatures.lastAttemptedLoad && start > -1) {
3995 var htmlPart1 = html.substr(0, start);
3996 var htmlPart2 = html.substr(end, html.length);
3998 html = htmlPart1 + htmlPart2;
4002 start = html.indexOf('<div><hr></div>');
4003 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
4004 var htmlPart1 = html.substr(0, start);
4005 var htmlPart2 = html.substr(start, html.length);
4006 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
4007 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
4008 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
4010 var body = html.indexOf('</body>');
4012 var part1 = html.substr(0, body);
4013 var part2 = html.substr(body, html.length);
4014 var newHtml = part1 + openTag + newSignature + closeTag + part2;
4016 var newHtml = html + openTag + newSignature + closeTag;
4019 //tinyMCE.setContent(newHtml);
4020 t.setContent(newHtml);
4024 prepareSignature : function(str) {
4025 var signature = new String(str);
4027 signature = signature.replace(/</gi, '<');
4028 signature = signature.replace(/>/gi, '>');
4034 showAttachmentPanel : function(idx) {
4035 var east = SE.composeLayout[idx].getUnitByPosition("right");
4036 var tabs = SE.composeLayout[idx].rightTabs;
4038 tabs.set("activeTab", tabs.getTab(0));
4042 * expands sidebar and displays options panel
4044 showOptionsPanel : function(idx) {
4045 var east = SE.composeLayout[idx].getUnitByPosition("right");
4046 var tabs = SE.composeLayout[idx].rightTabs;
4048 tabs.set("activeTab", tabs.getTab(1));
4052 * Selects the Contacts tab
4054 showContactsPanel : function() {
4055 SE.complexLayout.regions.west.showPanel("contactsTab");
4059 * Generates fields for Select Document
4061 addDocumentField : function(idx) {
4062 var basket = document.getElementById('addedDocuments' + idx);
4064 var index = (basket.childNodes.length / 7) - 1;
4071 var test = document.getElementById('documentId' + idx + index);
4073 while(test != null) {
4075 test = document.getElementById('documentId' + idx + index);
4078 var documentCup = document.createElement("div");
4079 documentCup.id = 'documentCup' + idx + index;
4080 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
4081 // document id field
4082 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
4083 // document name field
4084 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
4086 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
4087 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
4088 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
4090 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
4091 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
4092 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
4095 basket.appendChild(documentCup);
4096 //basket.innerHTML += out;
4101 * Makes async call to save a draft of the email
4102 * @param int Instance index
4104 saveDraft : function(tinyInstance) {
4105 this.sendEmail(tinyInstance, true);
4108 selectDocument : function(target) {
4109 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
4110 windowName = 'selectDocument';
4111 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
4113 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4115 // put the focus on the popup if the browser supports the focus() method
4121 * Modal popup for file attachment dialogue
4123 addFileField : function() {
4124 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
4125 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
4129 constraintoviewport: true,
4131 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
4132 fn:function(){SE.addFileDialog.hide();}
4135 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
4136 SE.addFileDialog.render();
4137 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
4139 Dom.removeClass("addFileDialog", "yui-hidden");
4141 SE.addFileDialog.show();
4145 * Async upload of file to temp dir
4147 uploadAttachment : function() {
4148 if(document.getElementById('email_attachment').value != "") {
4149 var formObject = document.getElementById('uploadAttachment');
4150 YAHOO.util.Connect.setForm(formObject, true, true);
4151 AjaxObject.target = '';
4152 AjaxObject.startRequest(callbackUploadAttachment, null);
4154 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
4159 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
4160 * @param string target in focus compose layout
4162 setDocument : function(idx, target, documentId, documentName, docRevId) {
4163 // fields are named/id'd [fieldName][instanceId][index]
4164 var addedDocs = document.getElementById("addedDocuments" + idx);
4165 var docId = document.getElementById('documentId' + idx + target);
4166 var docName = document.getElementById('documentName' + idx + target);
4167 var docRevisionId = document.getElementById('document' + idx + target);
4168 docId.value = documentId;
4169 docName.value = documentName;
4170 docRevisionId.value = docRevId;
4174 * Removes the bucket div containing the document input fields
4176 deleteDocumentField : function(documentCup) {
4177 var f0 = document.getElementById(documentCup);
4178 f0.parentNode.removeChild(f0);
4182 * Removes a Template Attachment field
4186 deleteTemplateAttachmentField : function(idx, index) {
4187 // create not-in-array values for removal filtering
4188 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
4194 r += document.getElementById('templateAttachmentId' + idx + index).value;
4195 document.getElementById("templateAttachmentsRemove" + idx).value = r;
4197 var target = 'templateAttachmentCup' + idx + index;
4198 d = document.getElementById(target);
4199 d.parentNode.removeChild(d);
4203 * Async removal of uploaded temp file
4204 * @param string index Should be a concatenation of idx and index
4207 deleteUploadAttachment : function(index, file) {
4208 var d = document.getElementById('email_attachment_bucket' + index);
4209 d.parentNode.removeChild(d);
4211 // make async call to delete cached file
4212 AjaxObject.target = '';
4213 AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
4217 * Attaches files coming from Email Templates
4219 addTemplateAttachmentField : function(idx) {
4221 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
4223 var basket = document.getElementById('addedTemplateAttachments' + idx);
4226 var index = basket.childNodes.length;
4233 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
4235 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
4236 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
4237 idx + "\",\"" + index + "\");'/>" +
4239 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
4240 // templateAttachment field
4241 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
4243 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
4245 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
4246 "<br id='br" + index + "></br>" +
4247 "<br id='brdoc" + index + "></br>" +
4249 basket.innerHTML = basket.innerHTML + out;
4255 * Sends one email via async call
4256 * @param int idx Editor instance ID
4257 * @param bool isDraft
4259 sendEmail : function(idx, isDraft) {
4261 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
4262 var obAccountID = document.getElementById('addressFrom' + idx).value;
4264 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
4266 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
4271 var form = document.getElementById('emailCompose' + idx);
4272 var composeOptionsFormName = "composeOptionsForm" + idx;
4275 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
4276 if (t != null || typeof(t) != "undefined") {
4277 var html = t.getContent();
4279 var html = "<p>" + document.getElementById('htmleditor' + idx).value + "</p>";
4282 var subj = document.getElementById('emailSubject' + idx).value;
4283 var to = trim(document.getElementById('addressTO' + idx).value);
4284 var cc = trim(document.getElementById('addressCC' + idx).value);
4285 var bcc = trim(document.getElementById('addressBCC' + idx).value);
4286 var email_id = document.getElementById('email_id' + idx).value;
4287 var composeType = document.getElementById('composeType').value;
4288 var parent_type = document.getElementById("parent_type").value;
4289 var parent_id = document.getElementById("parent_id").value;
4291 var el_uid = document.getElementById("uid");
4292 var uid = (el_uid == null) ? '' : el_uid.value;
4294 var el_ieId = document.getElementById("ieId");
4295 var ieId = (el_ieId == null) ? '' : el_ieId.value;
4297 var el_mbox = document.getElementById("mbox");
4298 var mbox = (el_mbox == null) ? '' : el_mbox.value;
4300 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
4301 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
4305 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
4308 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
4309 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
4310 parent_id = parentIdValue;
4311 parent_type = parentTypeValue;
4313 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
4314 // baseline viability check
4316 if(to == "" && cc == '' && bcc == '' && !isDraft) {
4317 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
4319 } else if(subj == '' && !isDraft) {
4320 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
4323 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
4325 } else if(html == '' && !isDraft) {
4326 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
4331 SE.util.clearHiddenFieldValues('emailCompose' + idx);
4332 document.getElementById('data_parent_id' + idx).value = parentIdValue;
4333 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
4334 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
4335 html = html.replace(/</ig, "sugarLessThan");
4336 html = html.replace(/>/ig, "sugarGreaterThan");
4338 form.sendDescription.value = html;
4339 form.sendSubject.value = subj;
4340 form.sendTo.value = to;
4341 form.sendCc.value = cc;
4342 form.sendBcc.value = bcc;
4343 form.email_id.value = email_id;
4344 form.composeType.value = composeType;
4345 form.composeLayoutId.value = 'composeLayout' + idx;
4346 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
4347 form.saveToSugar.value = 1;
4348 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
4349 form.parent_type.value = parent_type;
4350 form.parent_id.value = parent_id;
4351 form.uid.value = uid;
4352 form.ieId.value = ieId;
4353 form.mbox.value = mbox;
4355 // email attachments
4356 var addedFiles = document.getElementById('addedFiles' + idx);
4358 for(i=0; i<addedFiles.childNodes.length; i++) {
4359 var bucket = addedFiles.childNodes[i];
4361 for(j=0; j<bucket.childNodes.length; j++) {
4362 var node = bucket.childNodes[j];
4363 var nName = new String(node.name);
4365 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
4366 if(form.attachments.value != '') {
4367 form.attachments.value += "::";
4369 form.attachments.value += node.value;
4376 var addedDocs = document.getElementById('addedDocuments' + idx);
4378 for(i=0; i<addedDocs.childNodes.length; i++) {
4379 var cNode = addedDocs.childNodes[i];
4380 for(j=0; j<cNode.childNodes.length; j++) {
4381 var node = cNode.childNodes[j];
4382 var nName = new String(node.name);
4383 if(node.type == 'hidden' && nName.match(/documentId/)) {
4384 if(form.documents.value != '') {
4385 form.documents.value += "::";
4387 form.documents.value += node.value;
4393 // template attachments
4394 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
4395 if(addedTemplateAttachments) {
4396 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
4397 var cNode = addedTemplateAttachments.childNodes[i];
4398 for(j=0; j<cNode.childNodes.length; j++) {
4399 var node = cNode.childNodes[j];
4400 var nName = new String(node.name);
4401 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
4402 if(form.templateAttachments.value != "") {
4403 form.templateAttachments.value += "::";
4405 form.templateAttachments.value += node.value;
4411 // remove attachments
4412 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
4414 YAHOO.util.Connect.setForm(form);
4416 AjaxObject.target = 'frameFlex';
4418 // sending a draft email
4419 if(!isDraft && in_draft) {
4421 SE.listView.removeRowByUid(email_id);
4424 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
4425 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
4427 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
4431 * Handles clicking the email address link from a given view
4433 composePackage : function() {
4434 if(composePackage != null) {
4435 SE.composeLayout.c0_composeNewEmail();
4438 if(composePackage.to_email_addrs) {
4439 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
4441 if (composePackage.subject != null && composePackage.subject.length > 0) {
4442 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
4445 //If no parent fields are set in the composePackage, ensure they are cleared.
4446 var parentFields = ['parent_type','parent_name','parent_id'];
4447 for(var i=0;i<parentFields.length;i++)
4449 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
4450 composePackage[parentFields[i]] = "";
4453 document.getElementById("parent_type").value = composePackage.parent_type;
4454 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
4455 document.getElementById("parent_id").value = composePackage.parent_id;
4456 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
4457 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
4459 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
4460 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
4462 if (composePackage.body != null && composePackage.body.length > 0) {
4463 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4464 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
4465 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
4467 if (composePackage.attachments != null) {
4468 SE.composeLayout.loadAttachments(composePackage.attachments);
4471 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
4472 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
4473 SE.util.emptySelectOptions(addressFrom);
4474 var fromAccountOpts = composePackage.fromAccounts.data;
4475 for(i=0; i<fromAccountOpts.length; i++) {
4476 var key = fromAccountOpts[i].value;
4477 var display = fromAccountOpts[i].text;
4478 var opt = new Option(display, key);
4479 if (fromAccountOpts[i].selected) {
4480 opt.selected = true;
4482 addressFrom.options.add(opt);
4489 setContentOnThisTiny : function() {
4490 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4491 var tinyHTML = tiny.getContent();
4492 composePackage.body = decodeURI(encodeURI(composePackage.body));
4493 // cn: bug 14361 - text-only templates don't fill compose screen
4494 if(composePackage.body == '') {
4495 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4497 //Flag determines if we should clear the tiny contents or just append
4498 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
4499 SE.composeLayout.tinyHTML = '';
4501 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
4503 tiny.setContent(SE.composeLayout.tinyHTML);
4504 //Indicate that the contents has been loaded successfully.
4505 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
4508 * Confirms closure of a compose screen if "x" is clicked
4510 confirmClose : function(panel) {
4511 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
4512 SE.composeLayout.closeCompose(panel.id);
4520 * forces close of a compose screen
4522 forceCloseCompose : function(id) {
4523 SE.composeLayout.closeCompose(id);
4525 // handle flow back to originating view
4526 if(composePackage) {
4527 // check if it's a module we need to return to
4528 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
4529 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
4530 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
4531 window.location = url;
4538 * closes the editor that just sent email
4539 * @param string id ID of composeLayout tab
4541 closeCompose : function(id) {
4542 // destroy tinyMCE instance
4543 var idx = id.substr(13, id.length);
4544 var instanceId = "htmleditor" + idx;
4545 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
4547 // nullify DOM and namespace values.
4549 SE.composeLayout[idx] = null;
4550 SE.tinyInstances[instanceId] = null;
4551 var tabsArray = SE.innerLayout.get("tabs");
4552 for (i = 0 ; i < tabsArray.length ; i++) {
4553 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
4554 tabsArray[i].close();
4558 //SE.innerLayout.getTab(idx).close();
4562 * Enable the quick search for the compose relate field or search tab
4564 enableQuickSearchRelate: function(idx,overides){
4566 if(typeof overides != 'undefined')
4568 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
4569 var newModule = document.getElementById(newModuleID).value;
4570 var formName = overides['formName'];
4571 var fieldName = overides['fieldName'];
4572 var fieldId = overides['fieldId'];
4573 var fullName = formName + "_" + fieldName;
4574 var postBlurFunction = null;
4578 var newModule = document.getElementById('data_parent_type'+idx).value;
4579 var formName = 'emailCompose'+idx;
4580 var fieldName = 'data_parent_name'+idx;
4581 var fieldId = 'data_parent_id'+idx;
4582 var fullName = formName + "_" + fieldName;
4583 var postBlurFunction = "SE.composeLayout.qsAddAddress";
4586 if(typeof sqs_objects == 'undefined')
4587 window['sqs_objects'] = new Array;
4589 window['sqs_objects'][fullName] = {
4592 modules:[newModule],
4594 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
4595 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
4596 post_onblur_function: postBlurFunction,
4597 order:"name","limit":"30","no_match_text":"No Match"};
4600 if(typeof QSProcessedFieldsArray != 'undefined')
4601 QSProcessedFieldsArray[fullName] = false;
4602 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
4603 QSFieldsArray[fullName].destroy();
4604 delete QSFieldsArray[fullName];
4606 if (Dom.get(fullName + "_results")) {
4607 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
4613 qsAddAddress : function(o) {
4614 if (o.name != "" && o.email1 != "")
4616 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
4617 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
4621 * Returns a new instance ID, 0-index
4623 getNewInstanceId : function() {
4624 this.currentInstanceId = this.currentInstanceId + 1;
4625 return this.currentInstanceId;
4629 * 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.
4631 loadAttachments : function(result) {
4632 var idx = SE.composeLayout.currentInstanceId;
4634 if(typeof(result) == 'object') {
4635 //jchi #20680. Clean the former template attachments;
4636 var basket = document.getElementById('addedTemplateAttachments' + idx);
4637 if(basket.innerHTML != ''){
4638 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
4640 basket.innerHTML = '';
4645 if(typeof result[i] == 'object') {
4646 var index = SE.composeLayout.addTemplateAttachmentField(idx);
4647 var bean = result[i];
4648 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
4649 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
4656 * fills drop-down values for email templates and signatures
4658 setComposeOptions : function(idx) {
4659 // send from accounts
4660 var addressFrom = document.getElementById('addressFrom' + idx);
4662 if (addressFrom.options.length <= 0) {
4663 SE.util.emptySelectOptions(addressFrom);
4664 var fromAccountOpts = SE.composeLayout.fromAccounts;
4665 for (id = 0 ; id < fromAccountOpts.length ; id++) {
4666 var key = fromAccountOpts[id].value;
4667 var display = fromAccountOpts[id].text;
4668 var is_default = false;
4669 if(key == SUGAR.default_inbound_accnt_id)
4671 var opt = new Option(display, key);
4672 addressFrom.options.add(opt);
4673 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
4678 var et = document.getElementById('email_template' + idx);
4679 SE.util.emptySelectOptions(et);
4681 for(var key in this.emailTemplates) { // iterate through assoc array
4682 var display = this.emailTemplates[key];
4683 var opt = new Option(display, key);
4684 et.options.add(opt);
4688 var sigs = document.getElementById('signatures' + idx);
4689 SE.util.emptySelectOptions(sigs);
4691 for(var key in this.signatures) { // iterate through assoc array
4692 var display = this.signatures[key];
4693 var opt = new Option(display, key);
4695 if(key == SE.userPrefs.signatures.signature_default) {
4696 opt.selected = true;
4699 sigs.options.add(opt);
4702 // html/plain email?
4703 var htmlEmail = document.getElementById('setEditor' + idx);
4704 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
4705 htmlEmail.checked = true;
4707 htmlEmail.checked = false;
4710 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
4714 * After compose screen is rendered, async call to get email body from Sugar
4716 replyForwardEmailStage2 : function() {
4717 SE.util.clearHiddenFieldValues('emailUIForm');
4718 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
4720 var ieId = SE.composeLayout.replyForwardObj.ieId;
4721 var uid = SE.composeLayout.replyForwardObj.uid;
4722 var mbox = SE.composeLayout.replyForwardObj.mbox;
4723 var type = SE.composeLayout.replyForwardObj.type;
4724 var idx = SE.composeLayout.currentInstanceId;
4726 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
4728 document.getElementById('emailSubject' + idx).value = type;
4729 document.getElementById('emailUIAction').value = 'composeEmail';
4730 document.getElementById('composeType').value = type;
4731 document.getElementById('ieId').value = ieId;
4732 document.getElementById('uid').value = uid;
4733 document.getElementById('mbox').value = mbox;
4734 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
4735 var formObject = document.getElementById('emailUIForm');
4736 YAHOO.util.Connect.setForm(formObject);
4738 var sendType = type;
4739 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
4743 * Show the hidden cc or bcc fields
4745 showHiddenAddress: function(addrType,idx){
4747 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
4748 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
4749 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
4750 this[addrType+'Hidden'+idx] = false;
4752 //After bcc or cc is added, move options below last addr field
4753 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4755 //If both cc and bcc hidden, remove the empty row containing text.
4756 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
4757 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
4758 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
4760 // SE.composeLayout.resizeEditor(idx);
4763 * Hide the cc and bcc fields if they were shown.
4765 hideHiddenAddresses: function(idx){
4767 var addrTypes = ['cc','bcc'];
4768 for(var i = 0;i<addrTypes.length;i++)
4770 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
4771 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
4772 this[addrTypes[i] + 'Hidden'+idx] = true
4775 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
4776 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
4777 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4781 //// END SE.composeLayout
4782 ///////////////////////////////////////////////////////////////////////////////
4783 ///////////////////////////////////////////////////////////////////////////////
4787 * Cleans serialized UID lists of duplicates
4791 cleanUids : function(str) {
4792 var seen = new Object();
4794 var arr = new String(str).split(",");
4796 for(var i=0; i<arr.length; i++) {
4801 clean += (clean != "") ? "," : "";
4803 seen[arr[i]] = true;
4810 * Clears hidden field values
4811 * @param string id ID of form element to clear
4813 clearHiddenFieldValues : function(id) {
4814 var form = document.getElementById(id);
4816 for(i=0; i<form.elements.length; i++) {
4817 if(form.elements[i].type == 'hidden') {
4818 var e = form.elements[i];
4819 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
4827 * Reduces a SELECT drop-down to 0 items to prepare for new ones
4829 emptySelectOptions : function(el) {
4831 for(i=el.childNodes.length - 1; i >= 0; i--) {
4832 if(el.childNodes[i]) {
4833 el.removeChild(el.childNodes[i]);
4840 * Returns the MBOX path in the manner php_imap expects:
4841 * ie: INBOX.DEBUG.test
4842 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
4844 generateMboxPath : function(str) {
4845 var ex = str.split("::");
4847 /* we have a serialized MBOX path */
4851 for(var i=0; i<ex.length; i++) {
4852 if(ex[i] == 'INBOX') {
4864 /* we have a Sugar folder GUID - do nothing */
4872 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
4873 * @param HTMLElement el
4874 * @return string GUID of found element or empty on failure
4876 getGuidFromElement : function(el) {
4882 for(var i=0; i<iterations; i++) {
4884 if(el.id.match(SE.reGUID)) {
4896 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
4899 getPanelId : function() {
4900 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
4904 * wrapper to handle weirdness with IE
4905 * @param string instanceId
4906 * @return tinyMCE Controller object
4908 getTiny : function(instanceId) {
4909 if(instanceId == '') {
4913 var t = tinyMCE.getInstanceById(instanceId);
4917 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
4923 * Simple check for MSIE browser
4927 var nav = new String(navigator.appVersion);
4928 if(nav.match(/MSIE/)) {
4935 * Recursively removes an element from the DOM
4936 * @param HTMLElement
4938 removeElementRecursive : function(el) {
4939 this.emptySelectOptions(el);
4946 sleep : function(secs) {
4947 setTimeout("void(0);", secs);
4951 * Converts a <select> element to an Ext.form.combobox
4953 convertSelect : function(select) {
4954 alert('in convertSelect');
4955 if (typeof(select) == "string") {
4956 select = document.getElementById(select);
4960 findChildNode : function (parent, property, value) {
4961 for (i in parent.children) {
4962 var child = parent.children[i];
4963 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
4965 var searchChild = SE.util.findChildNode(child, property, value);
4972 cascadeNodes : function (parent, fn, scope, args) {
4973 for (i in parent.children) {
4974 var child = parent.children[i];
4975 var s = scope ? scope : child;
4976 var a = args ? args : child;
4978 SE.util.cascadeNodes(child, fn, scope, args);
4985 ///////////////////////////////////////////////////////////////////////////////
4988 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
4990 /*********************************************************************************
4991 * SugarCRM Community Edition is a customer relationship management program developed by
4992 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4994 * This program is free software; you can redistribute it and/or modify it under
4995 * the terms of the GNU Affero General Public License version 3 as published by the
4996 * Free Software Foundation with the addition of the following permission added
4997 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4998 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4999 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
5001 * This program is distributed in the hope that it will be useful, but WITHOUT
5002 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
5003 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
5006 * You should have received a copy of the GNU Affero General Public License along with
5007 * this program; if not, see http://www.gnu.org/licenses or write to the Free
5008 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
5011 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
5012 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
5014 * The interactive user interfaces in modified source and object code versions
5015 * of this program must display Appropriate Legal Notices, as required under
5016 * Section 5 of the GNU Affero General Public License version 3.
5018 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
5019 * these Appropriate Legal Notices must retain the display of the "Powered by
5020 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
5021 * technical reasons, the Appropriate Legal Notices must display the words
5022 * "Powered by SugarCRM".
5023 ********************************************************************************/
5025 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
5026 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
5027 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
5028 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
5029 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
5030 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
5031 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
5032 ' <input type="hidden" id="type{idx}" name="type" value="">' +
5033 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
5034 ' <input type="hidden" id="composeType" name="composeType">' +
5035 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
5036 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
5037 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
5038 ' <input type="hidden" id="sendTo" name="sendTo">' +
5039 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
5040 ' <input type="hidden" id="sendCc" name="sendCc">' +
5041 ' <input type="hidden" id="setEditor" name="setEditor">' +
5042 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
5043 ' <input type="hidden" id="parent_id" name="parent_id">' +
5044 ' <input type="hidden" id="parent_type" name="parent_type">' +
5045 ' <input type="hidden" id="attachments" name="attachments">' +
5046 ' <input type="hidden" id="documents" name="documents">' +
5047 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
5048 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
5049 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
5050 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
5052 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
5053 ' <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>' +
5054 ' <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>' +
5055 ' <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>' +
5056 ' <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>' +
5057 '</td><td style="padding: 0px !important;margin:0px; !important"> {mod_strings.LBL_EMAIL_RELATE}: <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>' +
5058 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
5059 '<input class="sqsEnabled" id="data_parent_name{idx}" name="data_parent_name{idx}" type="text" value=""> <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>' +
5060 ' </td></tr></tbody></table></th>' +
5064 ' <div style="margin:5px;">' +
5065 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
5067 ' <td class="emailUILabel" NOWRAP >' +
5068 ' {app_strings.LBL_EMAIL_FROM}:' +
5070 ' <td class="emailUIField" NOWRAP>' +
5072 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
5077 ' <td class="emailUILabel" NOWRAP>' +
5078 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
5079 ' {app_strings.LBL_EMAIL_TO}:' +
5082 ' <td class="emailUIField" NOWRAP>' +
5083 ' <div class="ac_autocomplete">' +
5084 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5085 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
5086 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
5090 ' <tr id="add_addr_options_tr{idx}">' +
5091 ' <td class="emailUILabel" NOWRAP> </td><td class="emailUIField" valign="top" NOWRAP> <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}"> {mod_strings.LBL_ADD_CC_BCC_SEP} </span><span id="bcc_span{idx}"><a href="#" onclick="SE.composeLayout.showHiddenAddress(\'bcc\',\'{idx}\');">{mod_strings.LBL_ADD_BCC}</a></span></td>'+
5093 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
5094 ' <td class="emailUILabel" NOWRAP>' +
5095 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
5096 ' {app_strings.LBL_EMAIL_CC}:' +
5099 ' <td class="emailUIField" NOWRAP>' +
5100 ' <div class="ac_autocomplete">' +
5101 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5102 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
5103 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
5107 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
5108 ' <td class="emailUILabel" NOWRAP>' +
5109 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
5110 ' {app_strings.LBL_EMAIL_BCC}:' +
5113 ' <td class="emailUIField" NOWRAP>' +
5114 ' <div class="ac_autocomplete">' +
5115 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5116 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
5117 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
5122 ' <td class="emailUILabel" NOWRAP width="1%">' +
5123 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
5125 ' <td class="emailUIField" NOWRAP width="99%">' +
5126 ' <div class="ac_autocomplete">' +
5127 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
5136 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
5137 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
5138 ' <div style="padding:5px;">' +
5139 ' <table cellpadding="2" cellspacing="0" border="0">' +
5142 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
5149 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
5150 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
5162 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
5169 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
5170 ' <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>' +
5182 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
5189 ' <div id="addedTemplateAttachments{idx}"></div>' +
5196 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
5197 ' <div style="padding:5px;">' +
5198 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
5199 ' <table border="0" width="100%">' +
5201 ' <td NOWRAP style="padding:2px;">' +
5202 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
5206 ' <td NOWRAP style="padding:2px;">' +
5207 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
5212 ' <table border="0" width="100%">' +
5214 ' <td NOWRAP style="padding:2px;">' +
5215 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
5219 ' <td NOWRAP style="padding:2px;">' +
5220 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
5224 ' <table border="0" width="100%">' +
5226 ' <td NOWRAP style="padding:2px;">' +
5227 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
5228 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
5236 // End of File modules/Emails/javascript/composeEmailTemplate.js
5238 /*********************************************************************************
5239 * SugarCRM Community Edition is a customer relationship management program developed by
5240 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5242 * This program is free software; you can redistribute it and/or modify it under
5243 * the terms of the GNU Affero General Public License version 3 as published by the
5244 * Free Software Foundation with the addition of the following permission added
5245 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
5246 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
5247 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
5249 * This program is distributed in the hope that it will be useful, but WITHOUT
5250 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
5251 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
5254 * You should have received a copy of the GNU Affero General Public License along with
5255 * this program; if not, see http://www.gnu.org/licenses or write to the Free
5256 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
5259 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
5260 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
5262 * The interactive user interfaces in modified source and object code versions
5263 * of this program must display Appropriate Legal Notices, as required under
5264 * Section 5 of the GNU Affero General Public License version 3.
5266 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
5267 * these Appropriate Legal Notices must retain the display of the "Powered by
5268 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
5269 * technical reasons, the Appropriate Legal Notices must display the words
5270 * "Powered by SugarCRM".
5271 ********************************************************************************/
5276 function complexLayoutInit() {
5277 var se = SUGAR.email2;
5278 var Dom = YAHOO.util.Dom;
5280 getInnerLayout : function(rows) {
5281 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
5282 parent: se.complexLayout,
5288 scroll:false, // grid should autoScroll itself
5290 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
5298 body: "<div id='listBottom' />"
5306 body: "<div id='listRight' />",
5307 titlebar: false //,header: "right"
5310 se.complexLayout.on("render", function(){
5311 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
5312 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5313 SUGAR.email2.listViewLayout.set("height", height);
5314 SUGAR.email2.listViewLayout.render();
5316 se.listViewLayout.render();
5318 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
5319 var rp = se.listViewLayout.resizePreview = function() {
5320 var pre = Dom.get("displayEmailFramePreview");
5322 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
5323 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
5326 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
5327 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
5328 se.e2Layout.setPreviewPanel(rows);
5329 se.previewLayout = se.listViewLayout;
5330 return se.listViewLayout;
5333 getInnerLayout2Rows : function() {
5334 return this.getInnerLayout(true);
5336 getInnerLayout2Columns : function() {
5337 return this.getInnerLayout(false);
5341 // initialize state manager, we will use cookies
5342 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
5343 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
5344 se.complexLayout = new YAHOO.widget.Layout("container", {
5347 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
5348 width: Dom.getViewportWidth() - 40,
5352 body: "<div id='emailtabs'></div>"
5357 body: "<div id='lefttabs'></div>",
5367 header: Dom.get('footerLinks').innerHTML,
5374 se.complexLayout.render();
5375 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
5376 tp.addTab(new YAHOO.widget.Tab({
5379 content : "<div id='listViewDiv'/>",
5383 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
5384 tp.appendTo(centerEl);
5386 tp.get("element").style.borderRight = "1px solid #666"
5388 var listV = this.getInnerLayout2Rows();
5389 listV.set("height", tp.get("element").clientHeight - 25);
5392 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
5393 var folderTab = new YAHOO.widget.Tab({
5394 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
5396 content : "<div id='emailtree'/>",
5400 folderTab.on("activeChange", function(o){
5402 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
5405 se.leftTabs.addTab(folderTab);
5407 var tabContent = SUGAR.util.getAndRemove("searchTab");
5408 var searchTab = new YAHOO.widget.Tab({
5409 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
5411 content : tabContent.innerHTML,
5414 searchTab.on("activeChange", function(o){
5417 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
5418 //Setup the calendars if needed
5419 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
5420 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
5422 //Initalize sqs object for assigned user name
5423 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
5425 //Attach event handler for when the relate module option is selected for the correct sqs object
5426 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
5427 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
5428 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
5429 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
5431 //If enter key is pressed, perform search
5432 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
5433 for(var i=0; i < addKeyPressFields.length;i++)
5435 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
5436 if (e.keyCode == 13) {
5437 YAHOO.util.Event.stopEvent(e);
5438 SUGAR.email2.search.searchAdvanced();
5442 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
5444 //Clear parent values if selecting another parent type.
5445 YAHOO.util.Event.addListener('data_parent_type_search','change',
5447 document.getElementById('data_parent_id_search').value ='';
5448 document.getElementById('data_parent_name_search').value ='';
5453 se.leftTabs.addTab(searchTab);
5455 var resizeTabBody = function() {
5456 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
5457 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5460 se.complexLayout.on("render", resizeTabBody);
5461 se.leftTabs.on("activeTabChange", resizeTabBody);
5462 //hack to allow left pane scroll bar to fully show
5463 var lefttabsDiv = document.getElementById('lefttabs');
5464 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
5465 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
5466 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
5469 initSQSObject: function(formName,fieldName)
5471 var fullFieldName = formName + '_' + fieldName; //SQS Convention
5472 var resultName = fullFieldName + '_' + 'results';
5474 if (QSFieldsArray[fullFieldName] != null)
5476 QSFieldsArray[fullFieldName].destroy();
5477 delete QSFieldsArray[fullFieldName];
5479 if (QSProcessedFieldsArray[fullFieldName])
5480 QSProcessedFieldsArray[fullFieldName] = false;
5482 if( Dom.get(resultName) )
5484 var obj = document.getElementById(resultName);
5485 obj.parentNode.removeChild(obj);
5488 setPreviewPanel: function(rows) {
5490 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
5491 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
5492 Dom.get("listRight").innerHTML = "";
5493 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
5495 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
5496 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
5497 Dom.get("listBottom").innerHTML = "";
5498 Dom.get("listRight").innerHTML = "<div id='_blank' />";
5505 var myBufferedListenerObject = new Object();
5506 myBufferedListenerObject.refit = function() {
5507 if(SUGAR.email2.grid) {
5508 SUGAR.email2.grid.autoSize();
5511 // End of File modules/Emails/javascript/complexLayout.js