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(){var clone_id=this.form+'_'+this.field+'_collection_0';YAHOO.util.Event.onContentReady(clone_id,function(c){c.create_clone();enableQS();c.changePrimary(true);for(key in c.secondaries_values){if(isInteger(key)){c.add(c.secondaries_values[key]);}}
97 c.js_more();initEditView(document.forms[c.form]);},this);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
98 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
99 var count=this.fields_count;var 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);}}}
100 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
101 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';}
102 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(typeof(input_els[x].id)=='undefined'||input_els[x].id==''){input_els[x].id=currentNode.id;}
103 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);var new_id=currentNode.id.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_id;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_id.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_id;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_id;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_id;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!='undefined'&&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(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!='undefined'&&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_element_name+"_collection_"+i);var id_field=document.getElementById("id_"+this.field_element_name+"_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].name==(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=='';}
122 return false;}};SUGAR.collection.safe_clone=function(e,recursive)
123 {if(e.nodeName=="#text")
124 {return document.createTextNode(e.data);}
125 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')
126 {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'];}
127 for(var i in properties)
128 {if(e[properties[i]])
129 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
130 newNode[properties[i]]=e[properties[i]];}}
132 {for(var i in e.childNodes)
133 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
134 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
136 // End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
138 /*********************************************************************************
139 * SugarCRM Community Edition is a customer relationship management program developed by
140 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
142 * This program is free software; you can redistribute it and/or modify it under
143 * the terms of the GNU Affero General Public License version 3 as published by the
144 * Free Software Foundation with the addition of the following permission added
145 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
146 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
147 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
149 * This program is distributed in the hope that it will be useful, but WITHOUT
150 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
151 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
154 * You should have received a copy of the GNU Affero General Public License along with
155 * this program; if not, see http://www.gnu.org/licenses or write to the Free
156 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
159 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
160 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
162 * The interactive user interfaces in modified source and object code versions
163 * of this program must display Appropriate Legal Notices, as required under
164 * Section 5 of the GNU Affero General Public License version 3.
166 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
167 * these Appropriate Legal Notices must retain the display of the "Powered by
168 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
169 * technical reasons, the Appropriate Legal Notices must display the words
170 * "Powered by SugarCRM".
171 ********************************************************************************/
174 cache : new Object(),
175 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
176 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
179 currentHtmleditor : ''
183 * preserves hits from email server
185 _setDetailCache : function(ret) {
187 var compKey = ret.meta.mbox + ret.meta.uid;
189 if(!SUGAR.email2.cache[compKey]) {
190 SUGAR.email2.cache[compKey] = ret;
195 autoSetLayout : function() {
196 var c = document.getElementById('container');
197 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
198 //Ensure a minimum height.
199 tHeight = Math.max(tHeight, 550);
200 c.style.height = tHeight + "px";
201 SUGAR.email2.complexLayout.set('height', tHeight);
202 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
203 SUGAR.email2.complexLayout.render();
204 SUGAR.email2.listViewLayout.resizePreview();
210 * Shows overlay progress message
214 SUGAR.showMessageBoxModal = function(title, body) {
215 SUGAR.showMessageBox(title, body);
219 SUGAR.showMessageBox = function(reqtitle, body, type, additconfig) {
221 if (typeof(additconfig) == "object") {
222 var config = additconfig;
225 config.title = reqtitle;
227 YAHOO.SUGAR.MessageBox.show(config);
231 SUGAR.hideMessageBox = function() {
232 YAHOO.SUGAR.MessageBox.hide();
234 // End of File modules/Emails/javascript/EmailUIShared.js
236 /*********************************************************************************
237 * SugarCRM Community Edition is a customer relationship management program developed by
238 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
240 * This program is free software; you can redistribute it and/or modify it under
241 * the terms of the GNU Affero General Public License version 3 as published by the
242 * Free Software Foundation with the addition of the following permission added
243 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
244 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
245 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
247 * This program is distributed in the hope that it will be useful, but WITHOUT
248 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
249 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
252 * You should have received a copy of the GNU Affero General Public License along with
253 * this program; if not, see http://www.gnu.org/licenses or write to the Free
254 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
257 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
258 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
260 * The interactive user interfaces in modified source and object code versions
261 * of this program must display Appropriate Legal Notices, as required under
262 * Section 5 of the GNU Affero General Public License version 3.
264 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
265 * these Appropriate Legal Notices must retain the display of the "Powered by
266 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
267 * technical reasons, the Appropriate Legal Notices must display the words
268 * "Powered by SugarCRM".
269 ********************************************************************************/
272 if (typeof console == "undefined")
273 console = { log: function(o) {alert(o)} };
277 currentRequestObject : null,
278 //timeout : 30000, // 30 second timeout default
279 timeout : 9999999999, // 30 second timeout default
285 _reset : function() {
286 this.timeout = 30000;
287 this.forceAbort = false;
290 folderRenameCleanup : function() {
291 SUGAR.email2.folders.setSugarFolders();
294 fullSyncCleanup : function(o) {
295 this.folders.checkMailCleanup(o);
296 SUGAR.email2.settings.settingsDialog.hide();
301 composeCache : function(o) {
302 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
303 // get email templates and user signatures
304 var ret = YAHOO.lang.JSON.parse(o.responseText);
306 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
307 SUGAR.email2.composeLayout.signatures = ret.signatures;
308 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
310 SUGAR.email2.composeLayout.setComposeOptions(idx);
312 //Set the error array so we can notify the user when they try to hit send if any errors
313 //are present. We will also notify them now (after hitting compose button).
314 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
317 //if error element is returning an array, then check the length to make sure we have error messages
318 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
319 //add error messages for display
320 for(i in ret.errorArray)
321 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
322 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
323 //if error element is returning an object, and the object value is not empty or null, then display error message
324 for(i in ret.errorArray)
325 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
328 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
330 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
332 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
338 handleDeleteSignature : function(o) {
339 SUGAR.hideMessageBox();
340 var ret = YAHOO.lang.JSON.parse(o.responseText);
341 SUGAR.email2.composeLayout.signatures = ret.signatures;
342 var field = document.getElementById('signature_id');
343 SUGAR.email2.util.emptySelectOptions(field);
345 for(var i in ret.signatures) { // iterate through assoc array
346 var opt = new Option(ret.signatures[i], i);
347 field.options.add(opt);
349 setSigEditButtonVisibility();
354 handleDeleteReturn : function(o) {
355 // force refresh ListView
356 SUGAR.hideMessageBox();
357 if(document.getElementById('focusEmailMbox')) {
358 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
361 // need to display success message before calling next async call?
362 document.getElementById(this.target).innerHTML = o.responseText;
367 handleFailure : function(o) {
369 SUGAR.showMessageBox('Exception occurred...', o.statusText, 'alert');
370 if(document.getElementById('saveButton')) {
371 document.getElementById('saveButton').disabled = false;
375 handleReplyForward : function(o) {
376 var a = YAHOO.lang.JSON.parse(o.responseText);
378 var idx = SUGAR.email2.composeLayout.currentInstanceId;
380 document.getElementById('email_id' + idx).value = a.uid;
381 document.getElementById('emailSubject' + idx).value = a.name;
382 document.getElementById('addressTO' + idx).value = a.from;
383 document.getElementById('uid' + idx).value = a.uid;
385 document.getElementById('addressCC' + idx).value = a.cc;
386 SE.composeLayout.showHiddenAddress('cc', idx);
390 document.getElementById('type' + idx).value = a.type;
393 // apply attachment values
394 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
396 setTimeout("callbackReplyForward.finish(globalA);", 500);
399 handleReplyForwardForDraft : function(o) {
400 var a = YAHOO.lang.JSON.parse(o.responseText);
402 var idx = SUGAR.email2.composeLayout.currentInstanceId;
404 document.getElementById('email_id' + idx).value = a.uid;
405 document.getElementById('emailSubject' + idx).value = a.name;
406 document.getElementById('addressTO' + idx).value = a.to;
409 document.getElementById('addressCC' + idx).value = a.cc;
410 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
414 document.getElementById('addressBCC' + idx).value = a.bcc;
415 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
420 document.getElementById('type' + idx).value = a.type;
424 // apply attachment values
425 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
427 setTimeout("callbackReplyForward.finish(globalA);", 500);
432 handleSuccess : function(o) {
433 document.getElementById(this.target).innerHTML = o.responseText;
434 SUGAR.hideMessageBox();
439 ieDeleteSuccess : function(o) {
440 SUGAR.hideMessageBox();
441 SUGAR.email2.accounts.refreshInboundAccountTable();
442 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
443 SUGAR.email2.accounts.rebuildFolderList();
448 ieSaveSuccess : function(o) {
449 document.getElementById('saveButton').disabled = false;
450 var a = YAHOO.lang.JSON.parse(o.responseText);
453 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
454 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
456 resp = YAHOO.lang.JSON.parse(o.responseText);
457 SUGAR.email2.accounts.refreshInboundAccountTable();
458 SUGAR.email2.accounts.refreshOuboundAccountTable();
459 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
460 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
463 SUGAR.hideMessageBox();
464 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
471 loadAttachments : function(o) {
472 var result = YAHOO.lang.JSON.parse(o.responseText);
474 SUGAR.email2.composeLayout.loadAttachments(result);
479 loadSignature : function(o) {
480 var ret = YAHOO.lang.JSON.parse(o.responseText);
481 SUGAR.email2.signatures[ret.id] = ret.signature_html;
482 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
486 * Follow up to mark email read|unread|flagged
488 markEmailCleanup : function(o) {
489 var ret = YAHOO.lang.JSON.parse(o.responseText);
490 if (!ret['status']) {
491 SUGAR.hideMessageBox();
492 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
494 SUGAR.email2.contextMenus.markEmailCleanup();
500 rebuildShowFolders : function(o) {
501 var t = YAHOO.lang.JSON.parse(o.responseText);
502 var show = document.getElementById('ieAccountListShow');
504 SUGAR.email2.util.emptySelectOptions(show);
506 for(i=0; i<t.length; i++) { // iterate through assoc array
507 var opt = new Option(t[i].text, t[i].value, t[i].selected);
508 opt.selected = t[i].selected;
509 show.options.add(opt);
512 SUGAR.email2.accounts.renderTree();
516 saveListViewSortOrderPart2 : function() {
517 // create the JSON string the func expects
518 focusFolderPath = '[ "Home", "' + ieName + '"';
520 var f = new String(focusFolder);
521 var fEx = f.split('.');
523 for(i=0; i<fEx.length; i++) {
524 focusFolderPath += ', "' + fEx[i] +'"'
527 focusFolderPath += ']';
529 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
530 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
536 sendEmailCleanUp : function(o) {
538 SUGAR.hideMessageBox();
541 ret = YAHOO.lang.JSON.parse(o.responseText);
542 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
543 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
545 if (o.responseText) {
546 SUGAR.showMessageBox(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
548 // Else we have an error here.
551 if (typeof(SE.grid) != 'undefined')
552 SE.listView.refreshGrid();
553 //Disabled while address book is disabled
555 //If this call back was initiated by quick compose from a Detail View page, refresh the
556 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
557 //close the shortcut bar menu
558 if ( (typeof(action_sugar_grp1) != 'undefined')) {
559 if(action_sugar_grp1 == 'DetailView') {
560 showSubPanel('history',null,true);
561 } else if(action_sugar_grp1 == 'quickcreate') {
568 ieSendSuccess : function(o) {
569 SUGAR.hideMessageBox();
570 SUGAR.showMessageBox(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
575 settingsFolderRefresh : function(o) {
576 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
577 var ret = YAHOO.lang.JSON.parse(o.responseText);
578 var user = document.getElementById('userFolders');
580 SUGAR.email2.util.emptySelectOptions(user);
582 for(i=0; i<ret.userFolders.length; i++) {
583 var display = ret.userFolders[i].name;
584 var value = ret.userFolders[i].id;
585 var selected = (ret.userFolders[i].selected != "") ? true : false;
586 var opt = new Option(display, value, selected);
587 opt.selected = selected;
588 user.options.add(opt);
594 startRequest : function(callback, args, forceAbort) {
595 if(this.currentRequestObject != null) {
596 if(this.forceAbort == true) {
597 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
600 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
604 requestInProgress : function() {
605 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
610 updateFolderSubscriptions : function() {
611 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
612 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
613 SUGAR.hideMessageBox();
618 updateFrameFolder : function() {
619 SUGAR.email2.folders.checkEmailAccounts();
624 updateUserPrefs : function(o) {
625 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
626 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
631 uploadAttachmentSuccessful : function(o) {
633 document.getElementById('email_attachment').value = '';
635 var ret = YAHOO.lang.JSON.parse(o.responseText);
636 var idx = SUGAR.email2.composeLayout.currentInstanceId;
637 var overall = document.getElementById('addedFiles' + idx);
638 var index = overall.childNodes.length;
640 "<div id='email_attachment_bucket" + idx + index + "'>" +
642 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
643 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
644 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
646 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
647 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
649 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
651 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
654 overall.innerHTML += out;
655 if(SUGAR.email2.util.isIe()) {
656 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
660 SUGAR.email2.addFileDialog.hide();
662 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
667 ///////////////////////////////////////////////////////////////////////////
668 //// PER MODULE CALLBACK OBJECTS
669 AjaxObject.accounts = {
670 saveOutboundCleanup : function(o) {
671 SUGAR.email2.accounts.refreshOuboundAccountTable();
672 SUGAR.email2.accounts.outboundDialog.hide();
673 var id = o.responseText;
674 SUGAR.email2.accounts.newAddedOutboundId = id;
676 saveDefaultOutboundCleanup: function(o){
679 callbackEditOutbound : {
680 success : function(o)
682 var ret = YAHOO.lang.JSON.parse(o.responseText);
684 SUGAR.email2.accounts.showAddSmtp();
687 document.getElementById("mail_id").value = ret.id;
688 document.getElementById("type").value = ret.type;
689 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
690 document.getElementById("mail_name").value = ret.name;
691 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
692 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
693 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
694 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
695 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
696 SUGAR.email2.accounts.smtp_authenticate_field_display();
697 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
699 if(ret.type == 'system-override') {
700 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
701 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
704 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
705 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
707 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
710 failure : AjaxObject.handleFailure,
711 timeout : AjaxObject.timeout,
714 callbackDeleteOutbound : {
715 success : function(o) {
716 var ret = YAHOO.lang.JSON.parse(o.responseText);
719 if(confirm(ret.error_message))
721 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
722 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
725 SUGAR.hideMessageBox();
729 SUGAR.hideMessageBox();
730 SUGAR.email2.accounts.refreshOuboundAccountTable();
734 failure : AjaxObject.handleFailure,
735 timeout : AjaxObject.timeout,
739 callbackCheckMailProgress : {
740 success : function(o) {
741 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
742 SUGAR.email2.accounts.totalMsgCount = -1;
745 //Check for server timeout / errors
746 var ret = YAHOO.lang.JSON.parse(o.responseText);
749 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
750 SUGAR.hideMessageBox();
751 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
752 SUGAR.email2.accounts.totalMsgCount = -1;
753 //SUGAR.email2.folders.rebuildFolders();
757 var currIeId = ret['ieid'];
760 var serverCount = ret.count;
762 if (ret['status'] == 'done') {
763 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
764 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
768 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
770 currIeId = SUGAR.email2.accounts.ieIds[i+1];
772 SUGAR.email2.accounts.totalMsgCount = -1;
777 else if (ret.mbox && ret.totalcount && ret.count) {
778 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
779 if (ret.count >= ret.totalcount) {
782 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
783 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
785 SUGAR.hideMessageBox();
786 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
787 SUGAR.email2.accounts.totalMsgCount = -1;
792 SUGAR.email2.accounts.totalMsgCount = -1;
793 SUGAR.hideMessageBox();
794 SUGAR.email2.folders.rebuildFolders();
795 SE.listView.refreshGrid();
796 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
797 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
798 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
799 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
801 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
802 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
803 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
804 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
805 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
808 failure : AjaxObject.handleFailure,
809 timeout : AjaxObject.timeout,
814 ///////////////////////////////////////////////////////////////////////////////
816 AjaxObject.composeLayout = {
818 * Populates the record id
820 saveDraftCleanup : function(o) {
822 SUGAR.hideMessageBox();
825 ret = YAHOO.lang.JSON.parse(o.responseText);
826 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
828 if (o.responseText) {
829 SUGAR.showMessageBox(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
835 AjaxObject.composeLayout.callback = {
837 success : AjaxObject.composeLayout.saveDraftCleanup,
838 failure : AjaxObject.handleFailure,
839 timeout : AjaxObject.timeout,
844 AjaxObject.detailView = {
846 * Pops-up a printable view of an email
848 displayPrintable : function(o) {
849 var ret = YAHOO.lang.JSON.parse(o.responseText);
850 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
851 // 2 below must be in global context
853 meta['panelId'] = SUGAR.email2.util.getPanelId();
854 email = ret.meta.email;
855 if (typeof(email.cc) == 'undefined') {
859 var out = displayTemplate.exec({
860 'app_strings' : app_strings,
868 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
869 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
871 popup.document.write(out);
872 popup.document.close();
876 * Takes formatted response and creates a modal pop-over containing a title and content
878 displayView : function(o) {
879 var SED = SUGAR.email2.detailView;
880 var ret = YAHOO.lang.JSON.parse(o.responseText);
882 if(!SED.viewDialog) {
883 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
887 constraintoviewport: true,
890 SED.viewDialog.renderEvent.subscribe(function() {
891 var content = this.body.firstChild;
892 var viewH = YAHOO.util.Dom.getViewportHeight();
894 this.body.style.overflow = "auto";
895 this.body.style.width = "800px";
896 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
900 SED.viewDialog.setHeader(ret.title);
901 SED.viewDialog.setBody(ret.html);
902 SED.viewDialog.render();
903 SED.viewDialog.show();
907 * Generates a modal popup to populate with the contents of bean's full EditView
909 showQuickCreateForm : function(o) {
910 var SED = SUGAR.email2.detailView;
911 var ret = YAHOO.lang.JSON.parse(o.responseText);
913 if(!SED.quickCreateDialog) {
914 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
918 constraintoviewport: true,
922 SED.quickCreateDialog.renderEvent.subscribe(function() {
923 var viewH = YAHOO.util.Dom.getViewportHeight();
925 for (var i in this.body.childNodes) {
926 if (this.body.childNodes[i].clientHeight) {
927 contH += this.body.childNodes[i].clientHeight;
928 } else if (this.body.childNodes[i].offsetHeight) {
929 contH += this.body.childNodes[i].offsetHeight;
932 this.body.style.width = "800px";
933 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
934 this.body.style.overflow = "auto";
935 }, SED.quickCreateDialog);
937 SED.quickCreateDialog.hideEvent.subscribe(function(){
938 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
939 /*for(var qsField in qsFields){
940 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
941 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
944 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
947 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
949 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
950 SED.quickCreateDialog.render();
951 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
953 SED.quickCreateDialog.ieId = ret.ieId;
954 SED.quickCreateDialog.uid = ret.uid;
955 SED.quickCreateDialog.mbox = ret.mbox;
956 SED.quickCreateDialog.qcmodule = ret.module;
958 SED.quickCreateDialog.show();
960 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
962 editForm.module.value = 'Emails';
963 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
964 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
965 var instId = ret.module + count;
966 SED.quickCreateEmailsToAdd = ret.emailAddress;
967 SED.quickCreateEmailCallback = function(instId, tableId) {
968 var eaw = SUGAR.EmailAddressWidget.instances[instId];
969 if (typeof(eaw) == "undefined")
970 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
971 + instId + "','" + tableId + "');", 100);
972 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
974 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
975 + instId + "','" + tableId + "');", 100);
979 saveQuickCreateForm : function(o) {
980 SUGAR.hideMessageBox();
981 SUGAR.email2.detailView.quickCreateDialog.hide();
982 validate['EditView'] = [ ];
985 saveQuickCreateFormAndReply : function(o) {
986 SUGAR.hideMessageBox();
987 var ret = YAHOO.lang.JSON.parse(o.responseText);
988 SUGAR.email2.detailView.quickCreateDialog.hide();
989 var qcd = SUGAR.email2.detailView.quickCreateDialog;
990 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
992 var emailID = ret.id;
993 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
995 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
997 //Cean the validate cache to prevent errors on the next call
998 validate['EditView'] = [ ];
1001 saveQuickCreateFormAndAddToAddressBook : function(o) {
1002 SUGAR.hideMessageBox();
1003 SUGAR.email2.detailView.quickCreateDialog.hide();
1004 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
1005 validate['EditView'] = [ ];
1008 handleAssignmentDialogAssignAction : function() {
1011 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
1013 var dist = 'direct';
1017 var found_teams = false;
1018 var warning_message = mod_strings.LBL_WARN_NO_USERS;
1019 if(!found_teams && assign_user_id == '' )
1021 alert(warning_message);
1025 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1027 for(i=0; i<emailUids.length; i++) {
1029 uids += app_strings.LBL_EMAIL_DELIMITER;
1031 uids += emailUids[i];
1034 var row = SUGAR.email2.grid.getSelectedRows()[0];
1035 var data = SUGAR.email2.grid.getRecord(row).getData();
1036 var ieid = data.ieId;
1037 var mbox = data.mbox;
1038 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
1039 SUGAR.email2.contextMenus.assignToDialogue.hide();
1040 SUGAR.showMessageBox('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
1044 handleAssignmentDialogDeleteAction : function() {
1045 // TO pass list of UIDS/emailIds
1046 var uids = SUGAR.email2.listView.getUidsFromSelection();
1047 var row = SUGAR.email2.grid.getSelections()[0];
1048 var ieid = row.data.ieId;
1049 var mbox = row.data.mbox;
1050 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
1051 SUGAR.email2.contextMenus.assignmentDialog.hide();
1052 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1058 showEmailDetailView : function(o) {
1059 SUGAR.hideMessageBox();
1060 var SED = SUGAR.email2.detailView;
1061 var ret = YAHOO.lang.JSON.parse(o.responseText);
1063 if(!SED.quickCreateDialog) {
1064 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
1068 constraintoviewport: true,
1070 autofillheight: "body",
1073 SED.quickCreateDialog.renderEvent.subscribe(function() {
1074 var viewHeight = YAHOO.util.Dom.getViewportHeight();
1076 for (var i in this.body.childNodes) {
1077 if (this.body.childNodes[i].offsetHeight)
1078 contH += this.body.childNodes[i].offsetHeight;
1080 this.body.style.overflow = "auto";
1081 this.body.style.width = "800px";
1082 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
1084 }, SED.quickCreateDialog);
1086 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
1087 SED.quickCreateDialog.setBody(ret.html);
1088 SED.quickCreateDialog.render();
1089 SUGAR.util.evalScript(ret.html);
1090 SED.quickCreateDialog.show();
1093 showAssignmentDialogWithData : function(o) {
1094 var SEC = SUGAR.email2.contextMenus;
1095 SUGAR.hideMessageBox();
1096 var ret = YAHOO.lang.JSON.parse(o.responseText);
1097 if (!SEC.assignmentDialog) {
1098 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
1101 constraintoviewport: true,
1104 SEC.assignmentDialog.setBody("");
1105 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
1106 SEC.assignmentDialog.renderEvent.subscribe(function() {
1107 var iev = YAHOO.util.Dom.get("Distribute");
1109 this.body.style.width = "700px";
1111 }, SEC.assignmentDialog);
1112 SEC.assignmentDialog.render();
1114 SEC.assignmentDialog.setBody(ret);
1115 SEC.assignmentDialog.render();
1117 SEC.assignmentDialog.show();
1118 SUGAR.util.evalScript(ret);
1121 showImportForm : function(o) {
1122 var SED = SUGAR.email2.detailView;
1123 var ret = YAHOO.lang.JSON.parse(o.responseText);
1125 document.getElementById('quickCreateContent').innerHTML = "";
1126 SUGAR.hideMessageBox();
1131 if(!SED.importDialog) {
1132 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
1136 constraintoviewport: true,
1138 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
1139 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
1143 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
1144 SED.importDialog.setBody("");
1145 SED.importDialog.hideEvent.subscribe(function(){
1146 for(var i in QSFieldsArray) {
1147 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
1148 QSFieldsArray[i].destroy();
1149 delete QSFieldsArray[i];
1151 if (QSProcessedFieldsArray[i]) {
1152 QSProcessedFieldsArray[i] = false;
1156 SED.importDialog.renderEvent.subscribe(function() {
1157 var iev = YAHOO.util.Dom.get("ImportEditView");
1159 //this.body.style.height = (iev.clientHeight + 10) + "px";
1160 this.body.style.width = "600px";
1162 }, SED.importDialog);
1163 SED.importDialog.render();
1165 SED.importDialog.setBody(ret.html);
1166 SED.importDialog.ret = ret;
1167 SUGAR.util.evalScript(ret.html);
1168 SED.importDialog.render();
1170 SED.importDialog.show();
1171 SED.importDialog.focusFirstButton();
1173 getImportAction : function(ret) {
1174 if (!check_form('ImportEditView')) return false;
1175 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
1176 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
1180 var editView = document.getElementById('ImportEditView');
1181 if (editView.assigned_user_id != null) {
1182 get = get + "&user_id=" + editView.assigned_user_id.value
1183 //var user_id = editView.assigned_user_id.value;
1185 var parent_id = editView.parent_id.value;
1186 var parent_type = editView.parent_type.value;
1187 var row = SUGAR.email2.grid.getSelectedRows()[0];
1188 row = SUGAR.email2.grid.getRecord(row);
1189 var data = row.getData();
1190 var ieId = data.ieId;
1191 var mbox = data.mbox;
1192 var serverDelete = editView.serverDelete.checked;
1193 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1195 for(i=0; i<emailUids.length; i++) {
1197 uids += app_strings.LBL_EMAIL_DELIMITER;
1199 uids += emailUids[i];
1202 var action = 'importEmail&uid=';
1204 action = 'moveEmails';
1205 action = action + '&sourceFolder=' + ret['srcFolder'];
1206 action = action + '&sourceIeId=' + ret['srcIeId'];
1207 action = action + '&destinationFolder=' + ret['dstFolder'];
1208 action = action + '&destinationIeId=' + ret['dstIeId'];
1209 action = action + '&emailUids=';
1211 if (action.search(/importEmail/) != -1) {
1212 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
1214 SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
1217 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
1218 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
1219 SUGAR.email2.detailView.importDialog.hide();
1220 document.getElementById('importDialogContent').innerHTML = "";
1223 showRelateForm : function(o) {
1224 var SED = SUGAR.email2.detailView;
1225 var ret = YAHOO.lang.JSON.parse(o.responseText);
1226 document.getElementById('quickCreateContent').innerHTML = "";
1227 SUGAR.hideMessageBox();
1231 dialog_loaded = true;
1233 if(!SED.relateDialog) {
1234 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
1239 constraintoviewport: true,
1241 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
1242 if (!check_form('RelateEditView')) return false;
1244 var editView = document.getElementById('RelateEditView');
1245 var parent_id = editView.parent_id.value;
1246 var parent_type = editView.parent_type.value;
1247 var row = SUGAR.email2.grid.getSelectedRows()[0];
1248 row = SUGAR.email2.grid.getRecord(row);
1249 var ieId = row.getData().ieId;
1250 var mbox = row.getData().mbox;
1251 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1253 for(i=0; i<emailUids.length; i++) {
1255 uids += app_strings.LBL_EMAIL_DELIMITER;
1257 uids += emailUids[i];
1259 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1260 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
1261 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
1262 SED.relateDialog.hide();
1263 document.getElementById('relateDialogContent').innerHTML = "";
1268 SED.relateDialog.hideEvent.subscribe(function(){
1269 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
1270 QSFieldsArray['ImportEditView_parent_name'].destroy();
1271 delete QSFieldsArray['ImportEditView_parent_name'];
1273 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
1274 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
1278 SED.relateDialog.renderEvent.subscribe(function() {
1279 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
1281 for (var i in this.body.childNodes) {
1282 if (this.body.childNodes[i].clientHeight)
1283 contH += this.body.childNodes[i].clientHeight;
1285 }, SED.relateDialog);
1286 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
1289 SED.relateDialog.setBody(ret.html);
1290 SED.relateDialog.render();
1291 SUGAR.util.evalScript(ret.html);
1292 SED.relateDialog.show();
1296 * DetailView callbacks
1298 AjaxObject.detailView.callback = {
1300 success : function(o) {
1302 var ret = YAHOO.lang.JSON.parse(o.responseText);
1303 SUGAR.email2.detailView.consumeMetaDetail(ret);
1305 argument: [targetDiv],
1306 failure : AjaxObject.handleFailure,
1311 success : function(o) {
1313 var ret = YAHOO.lang.JSON.parse(o.responseText);
1314 SUGAR.email2.detailView.consumeMetaPreview(ret);
1316 failure : AjaxObject.handleFailure,
1321 success : AjaxObject.detailView.displayPrintable,
1322 failure : AjaxObject.handleFailure,
1323 timeout : AjaxObject.timeout,
1327 success : AjaxObject.detailView.displayView,
1328 failure : AjaxObject.handleFailure,
1329 timeout : AjaxObject.timeout,
1338 AjaxObject.folders = {
1340 * check-mail post actions
1342 checkMailCleanup : function(o) {
1343 SUGAR.hideMessageBox();
1344 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
1346 // refresh focus ListView
1347 SE.listView.refreshGrid();
1348 SUGAR.email2.folders.startCheckTimer(); // resets the timer
1353 rebuildFolders : function(o) {
1354 SUGAR.hideMessageBox();
1356 var data = YAHOO.lang.JSON.parse(o.responseText);
1358 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
1359 SUGAR.email2.folders.setSugarFolders();
1362 AjaxObject.folders.callback = {
1364 success : AjaxObject.folders.checkMailCleanup,
1365 failure : AjaxObject.handleFailure,
1366 timeout : 600000, // 5 mins
1371 AjaxObject.rules = {
1372 loadRulesForSettings : function(o) {
1373 document.getElementById("rulesListCell").innerHTML = o.responseText;
1374 // assume we have the class we need
1375 SUGAR.routing.getStrings();
1376 SUGAR.routing.getDependentDropdowns();
1379 //// END PER MODULE CALLBACK OBJECTS
1380 ///////////////////////////////////////////////////////////////////////////
1384 success : AjaxObject.handleSuccess,
1385 failure : AjaxObject.handleFailure,
1386 timeout : AjaxObject.timeout,
1389 var callbackAccount = {
1390 success : AjaxObject.ieSaveSuccess,
1391 failure : AjaxObject.handleFailure,
1392 timeout : AjaxObject.timeout,
1395 var callbackAccountDelete = {
1396 success : AjaxObject.ieDeleteSuccess,
1397 failure : AjaxObject.handleFailure,
1398 timeout : AjaxObject.timeout,
1401 var callbackOutboundTest = {
1402 success : AjaxObject.ieSendSuccess,
1403 failure : AjaxObject.handleFailure,
1404 timeout : AjaxObject.timeout,
1410 var callbackTeamInfoForSettings = {
1411 success : function (o) {
1412 var data = YAHOO.lang.JSON.parse(o.responseText);
1413 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
1415 failure : AjaxObject.handleFailure,
1416 timeout : AjaxObject.timeout,
1421 var callbackStatusForImport = {
1422 success : function (o) {
1423 SUGAR.hideMessageBox();
1424 if (o.responseText != "") {
1425 var statusString = "";
1426 var data = YAHOO.lang.JSON.parse(o.responseText);
1427 for(i=0; i<data.length; i++) {
1428 statusString = statusString + data[i] + '<br/>';
1430 SUGAR.showMessageBox(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
1432 SE.listView.refreshGrid();
1435 failure : AjaxObject.handleFailure,
1436 timeout : AjaxObject.timeout,
1440 var callbackComposeCache = {
1441 success : AjaxObject.composeCache,
1442 failure : AjaxObject.handleFailure,
1443 timeout : AjaxObject.timeout,
1446 var callbackDelete = {
1447 success : AjaxObject.handleDeleteReturn,
1448 failure : AjaxObject.handleFailure,
1449 timeout : AjaxObject.timeout,
1452 var callbackEmailDetailMultiple = {
1453 success : function(o) {
1454 SUGAR.hideMessageBox();
1455 var retMulti = YAHOO.lang.JSON.parse(o.responseText);
1456 var ret = new Object();
1458 for(var i=0; i<retMulti.length; i++) {
1461 SUGAR.email2._setDetailCache(ret);
1462 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
1465 failure : AjaxObject.handleFailure,
1469 var callbackListViewSortOrderChange = {
1470 success : AjaxObject.saveListViewSortOrderPart2,
1471 failure : AjaxObject.handleFailure,
1472 timeout : AjaxObject.timeout,
1474 argument : [ieId, ieName, focusFolder]
1476 var callbackEmptyTrash = {
1477 success : function(o) {
1478 SUGAR.hideMessageBox();
1479 AjaxObject.folderRenameCleanup;
1481 failure : AjaxObject.handleFailure,
1482 timeout : AjaxObject.timeout,
1485 var callbackClearCacheFiles = {
1486 success : function(o) {
1487 SUGAR.hideMessageBox();
1489 failure : AjaxObject.handleFailure,
1490 timeout : AjaxObject.timeout,
1493 var callbackFolderRename = {
1494 success : function(o) {SUGAR.hideMessageBox();SUGAR.email2.folders.rebuildFolders();},
1495 failure : AjaxObject.handleFailure,
1496 timeout : AjaxObject.timeout,
1499 var callbackFolderDelete = {
1500 success : function(o) {
1501 var ret = YAHOO.lang.JSON.parse(o.responseText);
1503 if (ret.folder_id) {
1504 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
1506 SUGAR.email2.tree.removeNode(node, true);
1507 } else if (ret.ieId && ret.mbox) {
1508 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
1510 SUGAR.email2.tree.removeNode(node, true);
1512 SUGAR.hideMessageBox();
1513 //SUGAR.email2.folders.loadSettingFolder();
1515 SUGAR.hideMessageBox();
1516 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
1519 failure : AjaxObject.handleFailure,
1520 timeout : AjaxObject.timeout,
1523 var callbackFolderSave = {
1524 success : function(o) {
1525 var ret = YAHOO.lang.JSON.parse(o.responseText);
1527 switch(ret.action) {
1528 case 'newFolderSave':
1529 SUGAR.email2.folders.rebuildFolders();
1533 failure : AjaxObject.handleFailure,
1534 timeout : AjaxObject.timeout,
1537 var callbackFolderSubscriptions = {
1538 success : AjaxObject.updateFolderSubscriptions,
1539 failure : AjaxObject.handleFailure,
1540 timeout : AjaxObject.timeout,
1543 var callbackFolderUpdate = {
1544 success : AjaxObject.updateFrameFolder,
1545 failure : AjaxObject.handleFailure,
1546 timeout : AjaxObject.timeout,
1549 var callbackFolders = {
1550 success : AjaxObject.folders.rebuildFolders,
1551 //success : void(true),
1552 failure : AjaxObject.handleFailure,
1553 timeout : AjaxObject.timeout,
1556 var callbackFullSync = {
1557 success : AjaxObject.fullSyncCleanup,
1558 failure : AjaxObject.handleFailure,
1559 timeout : 9999999999999,
1562 var callbackGeneric = {
1563 success : function() {
1564 SUGAR.hideMessageBox();
1566 failure : AjaxObject.handleFailure,
1567 timeout : AjaxObject.timeout,
1570 var callbackIeAccountRetrieve = {
1571 success : function(o) {
1572 // return JSON encoding
1573 SUGAR.hideMessageBox();
1574 SUGAR.email2.accounts.fillIeAccount(o.responseText);
1575 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
1577 failure : AjaxObject.handleFailure,
1578 timeout : AjaxObject.timeout,
1581 var callbackImportOneEmail = {
1582 success : AjaxObject.detailView.showImportForm,
1583 failure : AjaxObject.handleFailure,
1584 timeout : AjaxObject.timeout,
1587 var callbackRelateEmail = {
1588 success : AjaxObject.detailView.showRelateForm,
1589 failure : AjaxObject.handleFailure,
1590 timeout : AjaxObject.timeout,
1593 var callbackEmailDetailView = {
1594 success : AjaxObject.detailView.showEmailDetailView,
1595 failure : AjaxObject.handleFailure,
1596 timeout : AjaxObject.timeout,
1599 var callbackAssignmentDialog = {
1600 success : AjaxObject.detailView.showAssignmentDialogWithData,
1601 failure : AjaxObject.handleFailure,
1602 timeout : AjaxObject.timeout,
1605 var callbackAssignmentAction = {
1606 success : function(o) {
1607 SE.listView.refreshGrid();
1608 SUGAR.hideMessageBox();
1609 if(o.responseText != '') {
1610 SUGAR.showMessageBox('Assignment action result', o.responseText, 'alert');
1613 failure : AjaxObject.handleFailure,
1614 timeout : AjaxObject.timeout,
1617 var callbackMoveEmails = {
1618 success : function(o) {
1619 SE.listView.refreshGrid();
1620 SUGAR.hideMessageBox();
1621 if(o.responseText != '') {
1622 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
1625 failure : AjaxObject.handleFailure,
1626 timeout : AjaxObject.timeout,
1629 var callbackLoadAttachments = {
1630 success : AjaxObject.loadAttachments,
1631 failure : AjaxObject.handleFailure,
1632 timeout : AjaxObject.timeout,
1635 var callbackLoadRules = {
1636 success : AjaxObject.rules.loadRulesForSettings,
1637 failure : AjaxObject.handleFailure,
1638 timeout : AjaxObject.timeout,
1641 var callbackLoadSignature = {
1642 success : AjaxObject.loadSignature,
1643 failure : AjaxObject.handleFailure,
1644 timeout : AjaxObject.timeout,
1647 var callbackDeleteSignature = {
1648 success : AjaxObject.handleDeleteSignature,
1649 failure : AjaxObject.handleFailure,
1650 timeout : AjaxObject.timeout,
1653 /*var callbackMoveEmails = {
1654 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
1655 failure : AjaxObject.handleFailure,
1656 timeout : AjaxObject.timeout,
1659 var callbackOutboundSave = {
1660 success : AjaxObject.accounts.saveOutboundCleanup,
1661 failure : AjaxObject.handleFailure,
1662 timeout : AjaxObject.timeout,
1665 var callbackDefaultOutboundSave = {
1666 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
1667 failure : AjaxObject.handleFailure,
1668 timeout : AjaxObject.timeout,
1671 var callbackQuickCreate = {
1672 success : AjaxObject.detailView.showQuickCreateForm,
1673 failure : AjaxObject.handleFailure,
1674 timeout : AjaxObject.timeout,
1677 var callbackQuickCreateSave = {
1678 success : AjaxObject.detailView.saveQuickCreateForm,
1679 failure : AjaxObject.handleFailure,
1680 timeout : AjaxObject.timeout,
1683 var callbackQuickCreateSaveAndAddToAddressBook = {
1684 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
1685 failure : AjaxObject.handleFailure,
1686 timeout : AjaxObject.timeout,
1689 var callbackQuickCreateSaveAndReply = {
1690 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
1691 failure : AjaxObject.handleFailure,
1692 timeout : AjaxObject.timeout,
1695 var callbackQuickCreateSaveAndReplyCase = {
1696 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
1697 failure : AjaxObject.handleFailure,
1698 timeout : AjaxObject.timeout,
1701 var callbackRebuildShowAccountList = {
1702 success : AjaxObject.rebuildShowFolders,
1703 failure : AjaxObject.handleFailure,
1704 timeout : AjaxObject.timeout,
1708 var callbackRefreshSugarFolders = {
1709 success : function(o) {
1710 var t = YAHOO.lang.JSON.parse(o.responseText);
1711 SUGAR.email2.folders.setSugarFoldersEnd(t);
1713 failure : AjaxObject.handleFailure,
1714 timeout : AjaxObject.timeout,
1717 var callbackReplyForward = {
1718 success : AjaxObject.handleReplyForward,
1719 finish : function(a, retryCount) {
1720 if (typeof(retryCount) == 'undefined') {
1725 var idx = SUGAR.email2.composeLayout.currentInstanceId;
1726 var t = tinyMCE.getInstanceById('htmleditor' + idx);
1728 var html = t.getContent();
1730 html = " <div><hr></div>" + a.description;
1732 t.setContent(html);//
1734 if (a.type != 'draft') {
1735 // Next step, attach signature
1736 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
1740 if (retryCount < 5) {
1741 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
1745 var tabArray = SUGAR.email2.innerLayout.get("tabs");
1746 if (tabArray != null && tabArray.length > 0) {
1747 for (i = 0 ; i < tabArray.length ; i++) {
1748 var tabObject = tabArray[i];
1749 if (tabObject.get("id") == ("composeTab" + idx)) {
1750 var tabLabel = a.name;
1751 if (tabLabel != null && tabLabel.length > 25) {
1752 tabLabel = tabLabel.substring(0, 25) + "...";
1754 tabObject.get("labelEl").firstChild.data = tabLabel;
1760 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
1761 if (a.parent_name != null && a.parent_name != "") {
1762 document.getElementById('data_parent_name' + idx).value = a.parent_name;
1764 if (a.parent_type != null && a.parent_type != "") {
1765 document.getElementById('data_parent_type' + idx).value = a.parent_type;
1767 if (a.parent_id != null && a.parent_id != "") {
1768 document.getElementById('data_parent_id' + idx).value = a.parent_id;
1770 if (a.fromAccounts.status) {
1771 var addressFrom = document.getElementById('addressFrom' + idx);
1772 SUGAR.email2.util.emptySelectOptions(addressFrom);
1773 var fromAccountOpts = a.fromAccounts.data;
1774 for(i=0; i<fromAccountOpts.length; i++) {
1775 var key = fromAccountOpts[i].value;
1776 var display = fromAccountOpts[i].text;
1777 var opt = new Option(display, key);
1778 if (fromAccountOpts[i].selected) {
1779 opt.selected = true;
1781 addressFrom.options.add(opt);
1784 SUGAR.hideMessageBox();
1787 failure : AjaxObject.handleFailure,
1788 timeout : AjaxObject.timeout,
1790 argument : [sendType]
1792 var callbackSendEmail = {
1793 success : AjaxObject.sendEmailCleanUp,
1794 failure : AjaxObject.handleFailure,
1795 timeout : AjaxObject.timeout,
1798 var callbackSettings = {
1799 success : AjaxObject.updateUserPrefs,
1800 failure : AjaxObject.handleFailure,
1801 timeout : AjaxObject.timeout,
1804 var callbackSettingsFolderRefresh = {
1805 success : AjaxObject.settingsFolderRefresh,
1806 failure : AjaxObject.handleFailure,
1807 timeout : AjaxObject.timeout,
1810 var callbackLoadSettingFolder = {
1811 success : function(o) {
1812 AjaxObject.settingsFolderRefresh(o);
1813 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
1815 failure : AjaxObject.handleFailure,
1816 timeout : AjaxObject.timeout,
1820 var callbackUploadAttachment = {
1821 success : AjaxObject.uploadAttachmentSuccessful,
1822 upload : AjaxObject.uploadAttachmentSuccessful,
1823 failure : AjaxObject.handleFailure,
1824 timeout : AjaxObject.timeout,
1827 var callbackUserPrefs = {
1828 success : function(o) {
1829 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
1831 failure : AjaxObject.handleFailure,
1832 timeout : AjaxObject.timeout,
1836 var callbackContextmenus = {
1838 success : AjaxObject.markEmailCleanup,
1839 failure : AjaxObject.handleFailure,
1840 timeout : AjaxObject.timeout,
1845 var callbackCheckEmail2 = {
1846 success : function(o) {
1847 var ret = YAHOO.lang.JSON.parse(o.responseText);
1848 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
1852 failure : AjaxObject.handleFailure,
1853 timeout : AjaxObject.timeout,
1855 }// End of File modules/Emails/javascript/ajax.js
1857 /*********************************************************************************
1858 * SugarCRM Community Edition is a customer relationship management program developed by
1859 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
1861 * This program is free software; you can redistribute it and/or modify it under
1862 * the terms of the GNU Affero General Public License version 3 as published by the
1863 * Free Software Foundation with the addition of the following permission added
1864 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
1865 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
1866 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
1868 * This program is distributed in the hope that it will be useful, but WITHOUT
1869 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1870 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
1873 * You should have received a copy of the GNU Affero General Public License along with
1874 * this program; if not, see http://www.gnu.org/licenses or write to the Free
1875 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
1878 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
1879 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
1881 * The interactive user interfaces in modified source and object code versions
1882 * of this program must display Appropriate Legal Notices, as required under
1883 * Section 5 of the GNU Affero General Public License version 3.
1885 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
1886 * these Appropriate Legal Notices must retain the display of the "Powered by
1887 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
1888 * technical reasons, the Appropriate Legal Notices must display the words
1889 * "Powered by SugarCRM".
1890 ********************************************************************************/
1892 function gridInit() {
1893 if(SUGAR.email2.grid) {
1894 SUGAR.email2.grid.destroy();
1900 var Ck = YAHOO.util.Cookie;
1901 var widths = [ 10, 10, 150, 250, 175, 125 ];
1903 if (Ck.get("EmailGridWidths")) {
1904 for (var i=0; i < widths.length; i++) {
1905 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
1908 for (var i=0; i < widths.length; i++) {
1909 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
1913 // changes "F" to an icon
1914 function flaggedIcon(cell, record, column, value) {
1916 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
1919 // changes "A" to replied icon
1920 function repliedIcon(cell, record, column, value) {
1922 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
1925 function attachIcon(cell, record, column, value) {
1927 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
1934 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
1939 formatter: attachIcon,
1943 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
1948 formatter: flaggedIcon,
1952 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
1957 formatter: repliedIcon,
1961 label: app_strings.LBL_EMAIL_FROM,
1968 label: app_strings.LBL_EMAIL_SUBJECT,
1975 label: mod_strings.LBL_LIST_DATE,
1982 label: app_strings.LBL_EMAIL_TO,
2018 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2019 responseType: YAHOO.util.DataSource.TYPE_JSON,
2021 resultsList: 'Email',
2022 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
2023 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
2029 action : "EmailUIAjax",
2030 emailUIAction : "getMessageList",
2033 forceRefresh : "false"
2035 if(lazyLoadFolder != null) {
2036 params['mbox'] = lazyLoadFolder.folder;
2037 params['ieId'] = lazyLoadFolder.ieId;
2038 //Check if the folder is a Sugar Folder
2039 var test = new String(lazyLoadFolder.folder);
2040 if(test.match(/SUGAR\./)) {
2041 params['emailUIAction'] = 'getMessageListSugarFolders';
2042 params['mbox'] = test.substr(6);
2045 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
2048 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
2049 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2051 paginator: new YAHOO.widget.Paginator({
2052 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
2053 containers : ["dt-pag-nav"],
2054 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2055 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2056 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2057 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2058 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2060 initialRequest:SUGAR.util.paramsToUrl(params),
2067 //Override Paging request construction
2068 grid.set("generateRequest", function(oState, oSelf) {
2069 oState = oState || {pagination:null, sortedBy:null};
2070 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[5].getKey();
2071 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_ASC) ? "asc" : "desc";
2072 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2073 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2074 // Build the request
2076 SUGAR.util.paramsToUrl(oSelf.params) +
2079 "&start=" + startIndex +
2080 ((results !== null) ? "&limit=" + results : "");
2085 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2086 oPayload = oPayload || { };
2088 oPayload.totalRecords = oResponse.meta.total;
2089 oPayload.unreadRecords = oResponse.meta.unread;
2091 var tabObject = SE.innerLayout.get("tabs")[0];
2093 if (this.params.mbox != null) {
2094 mboxTitle = this.params.mbox;
2096 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
2097 tabObject.get("labelEl").firstChild.data = tabtext;
2100 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
2102 node.data.unseen = oResponse.meta.unread;
2103 SE.accounts.renderTree();
2109 var resize = grid.resizeGrid = function () {
2110 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
2111 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
2113 grid.convertDDRows = function() {
2114 var rowEl = this.getFirstTrEl();
2115 while (rowEl != null) {
2116 new this.DDRow(this, this.getRecord(rowEl), rowEl);
2117 rowEl = this.getNextTrEl(rowEl);
2122 grid.on("columnResizeEvent", function(o) {
2123 //Find the index of the column
2124 var colSet = SUGAR.email2.grid.getColumnSet().flat;
2125 for (var i=0; i < colSet.length; i++) {
2126 if (o.column == colSet[i]) {
2127 //Store it in the cookie
2128 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
2131 //this.resizeGrid();
2134 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
2135 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
2136 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
2138 SUGAR.email2.listViewLayout.on("render", resize);
2141 //Setup the default load parameters
2142 SUGAR.email2.grid.params = params;
2144 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
2145 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2146 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2153 function initRowDD() {
2154 var sg = SUGAR.email2.grid,
2155 Dom = YAHOO.util.Dom;
2156 sg.DDRow = function(oDataTable, oRecord, elTr) {
2157 if(oDataTable && oRecord && elTr) {
2158 this.ddtable = oDataTable;
2159 this.table = oDataTable.getTableEl();
2162 this.newIndex = null;
2164 this.initFrame(); // Needed for DDProxy
2165 this.invalidHandleTypes = {};
2169 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
2170 _resizeProxy: function() {
2171 this.constructor.superclass._resizeProxy.apply(this, arguments);
2172 var dragEl = this.getDragEl(),
2174 var xy = Dom.getXY(el);
2176 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
2177 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
2178 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
2179 Dom.setStyle(dragEl, 'display', "");
2182 startDrag: function(x, y) {
2183 //Check if we should be dragging a set of rows rather than just the one.
2184 var selectedRows = this.ddtable.getSelectedRows();
2185 var iSelected = false;
2186 for (var i in selectedRows) {
2187 if (this.rowEl.id == selectedRows[i]) {
2194 for (var i in selectedRows) {
2195 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
2198 this.rows = [this.row];
2199 this.ddtable.unselectAllRows();
2200 this.ddtable.selectRow(this.row);
2203 //Initialize the dragable proxy
2204 var dragEl = this.getDragEl();
2205 var clickEl = this.getEl();
2206 Dom.setStyle(clickEl, "opacity", "0.25");
2207 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
2208 Dom.addClass(dragEl, "yui-dt-liner");
2209 Dom.setStyle(dragEl, "opacity", "0.5");
2210 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
2211 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
2212 Dom.setStyle(dragEl, "border", "2px solid gray");
2215 clickValidator: function(e) {
2216 if (this.row.getData()[0] == " ")
2218 var target = YAHOO.util.Event.getTarget(e);
2219 return ( this.isValidHandleChild(target) &&
2220 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
2223 * This funciton checks that the target of the drag is a table row in this
2224 * DDGroup and simply moves the sourceEL to that location as a preview.
2226 onDragOver: function(ev, id) {
2227 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
2228 if (node && node != this.targetNode) {
2229 this.targetNode = node;
2230 SUGAR.email2.folders.unhighliteAll();
2235 onDragOut: function(e, id) {
2236 if (this.targetNode) {
2237 SUGAR.email2.folders.unhighliteAll();
2238 this.targetNode = false;
2241 endDrag: function() {
2242 Dom.setStyle(this.getEl(), "opacity", "");
2243 Dom.setStyle(this.getDragEl(), "display", "none");
2244 if (this.targetNode) {
2245 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
2247 SUGAR.email2.folders.unhighliteAll();
2253 function AddressSearchGridInit() {
2254 function moduleIcon(elCell, oRecord, oColumn, oData) {
2255 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
2257 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
2258 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
2260 var checkHeader = '<input type="checkbox" ';
2261 if (SUGAR.email2.util.isIe()) {
2262 checkHeader += 'style="top:-5px" ';
2264 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
2269 formatter: selectionCheckBox,
2273 label: mod_strings.LBL_LIST_TYPE,
2275 formatter: moduleIcon,
2279 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
2285 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
2291 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2292 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
2294 resultsList: 'Person',
2295 fields: ['name', 'email', 'bean_id', 'bean_module'],
2296 metaFields: {total: 'TotalCount'}
2298 //enable sorting on the server accross all data
2301 dataModel.params = {
2304 action : "EmailUIAjax",
2305 emailUIAction:"getAddressSearchResults"
2307 var rb = document.getElementById('hasRelatedBean').checked;
2309 var idx = SUGAR.email2.composeLayout.currentInstanceId;
2310 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2311 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2312 dataModel.params['related_bean_id'] = relatedBeanId;
2313 dataModel.params['related_bean_type'] = relatedBeanType;
2314 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
2316 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
2318 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
2319 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2321 paginator: new YAHOO.widget.Paginator({
2323 containers : ["dt-pag-nav-addressbook"],
2324 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2325 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2326 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2327 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2328 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2330 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
2334 //Override Paging request construction
2335 grid.set("generateRequest", function(oState, oSelf) {
2336 oState = oState || {pagination:null, sortedBy:null};
2337 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
2338 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2339 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2340 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2341 // Build the request
2343 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
2344 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
2345 ((results !== null) ? "&limit=" + results : "");
2349 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2350 oPayload = oPayload || { };
2351 oPayload.totalRecords = oResponse.meta.total;
2355 grid.clickToggleSelect= function(args) {
2356 var isIE = (args.event.target == null);
2357 var targetElement = isIE ? args.event.srcElement : args.event.target;
2358 if(targetElement.type == null || targetElement.type != 'checkbox') {
2359 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
2363 grid.reSelectRowsOnRender = function (){
2364 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2365 for (var i = 0; i < rows.length; i++)
2367 var emailAddress = rows[i].getData("email");
2368 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
2371 rows[i].setData("selected", true);
2372 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2376 rows[i].setData("selected", false);
2377 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
2381 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
2382 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
2383 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
2384 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
2387 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2388 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2390 grid.toggleSelectCheckbox = function(id,checked){
2391 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2392 row.setData("checked",checked);
2394 grid.toggleSelect = function(id, checked) {
2395 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2396 checked = row.getData("selected");
2399 SUGAR.email2.addressBook.grid.selectRow(row);
2400 SE.addressBook.insertContactRowToResultTable(id,null)
2403 SUGAR.email2.addressBook.grid.unselectRow(row);
2404 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
2406 row.setData("selected", !checked);
2409 grid.toggleSelectAll = function(checked) {
2410 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2411 for (var i = 0; i < rows.length; i++) {
2412 if (typeof(rows[i]) != "undefined")
2413 rows[i].setData("checked", checked);
2415 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2416 for (var i = 0; i < checkBoxes.length; i++) {
2417 checkBoxes[i].checked = checked;
2421 //Initialize the grid result table.
2422 AddressSearchResultsGridInit();
2428 * Initalize the results table for the address book selection.
2431 function AddressSearchResultsGridInit()
2434 /* Full name sort funciton to compare by last name if available */
2435 var fullNameSort = function(a, b, desc) {
2436 // Deal with empty values
2437 if(!YAHOO.lang.isValue(a))
2438 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
2439 else if(!YAHOO.lang.isValue(b))
2442 var aNames = a.getData("name").split(' ');
2443 var bNames = b.getData("name").split(' ');
2445 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
2446 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
2448 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
2452 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
2453 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
2454 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
2456 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})},
2457 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
2459 var myDataSource = new YAHOO.util.DataSource([]);
2460 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
2461 myDataSource.responseSchema = {
2462 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
2465 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
2466 width: "350px",height: "250px", MSG_EMPTY: " "});
2468 var highlightEditableCell = function(oArgs) {
2469 var elCell = oArgs.target;
2470 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
2471 this.highlightCell(elCell);
2475 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
2476 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
2477 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
2478 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
2479 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
2481 //Setup the context menus
2482 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
2483 var task = p_aArgs[1];
2486 var elRow = this.contextEventTarget;
2487 elRow = p_myDataTable.getTrEl(elRow);
2494 var oRecord = p_myDataTable.getRecord(elRow);
2495 p_myDataTable.deleteRow(elRow);
2496 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2501 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
2502 {trigger:gridResults.getTbodyEl()});
2503 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
2504 contextMenu.render("addrSearchResultGrid");
2505 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
2507 // End of File modules/Emails/javascript/grid.js
2509 /*********************************************************************************
2510 * SugarCRM Community Edition is a customer relationship management program developed by
2511 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
2513 * This program is free software; you can redistribute it and/or modify it under
2514 * the terms of the GNU Affero General Public License version 3 as published by the
2515 * Free Software Foundation with the addition of the following permission added
2516 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
2517 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
2518 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
2520 * This program is distributed in the hope that it will be useful, but WITHOUT
2521 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
2522 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
2525 * You should have received a copy of the GNU Affero General Public License along with
2526 * this program; if not, see http://www.gnu.org/licenses or write to the Free
2527 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
2530 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
2531 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
2533 * The interactive user interfaces in modified source and object code versions
2534 * of this program must display Appropriate Legal Notices, as required under
2535 * Section 5 of the GNU Affero General Public License version 3.
2537 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
2538 * these Appropriate Legal Notices must retain the display of the "Powered by
2539 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
2540 * technical reasons, the Appropriate Legal Notices must display the words
2541 * "Powered by SugarCRM".
2542 ********************************************************************************/
2545 var sw = YAHOO.SUGAR,
2546 Event = YAHOO.util.Event,
2547 Connect = YAHOO.util.Connect,
2548 Dom = YAHOO.util.Dom
2551 ///////////////////////////////////////////////////////////////////////////////
2554 _contactCache : new Array(), // cache of contacts
2555 _dd : new Array(), // filtered list, same format as _contactCache
2556 _ddLists : new Array(), // list of Lists
2557 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
2558 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
2559 clickBubble : true, // hack to get around onclick event bubbling
2561 relatedBeanType : '',
2564 itemSpacing : 'white-space:nowrap; padding:2px;',
2570 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
2572 initFixForDatatableSort: function () {
2573 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
2574 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
2575 var oColumn = this._oColumnSet.getColumn(column);
2578 // Validate TD element
2579 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
2581 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
2583 // Validate TH element
2585 elCell = this.getThEl(column);
2588 var allColumns = this._oColumnSet.flat;
2589 for(var i=0, len=allColumns.length; i<len; i++) {
2590 if(allColumns[i].getThEl().id === elCell.id) {
2591 oColumn = allColumns[i];
2602 cancelEdit : function() {
2603 if(this.editContactDialog)
2604 this.editContactDialog.hide();
2605 if(this.editMailingListDialog)
2606 this.editMailingListDialog.hide();
2610 * Clears filter form
2612 clear : function() {
2613 var t = document.getElementById('contactsFilter');
2619 * handle context-menu Compose-to call
2620 * @param string type 'contacts' or 'lists'
2622 composeTo : function(type, waited) {
2623 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
2624 if (activePanel.substring(0, 10) != "composeTab") {
2625 SE.composeLayout.c0_composeNewEmail();
2626 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
2627 SE.contextMenus.contactsContextMenu.hide();
2630 var idx = activePanel.substring(10);
2633 // determine if we have a selection to work with
2634 if(type == 'contacts') {
2635 var ids = SE.contactView.getSelectedRows();
2636 for (var i in ids) {
2637 rows[i] = SE.contactView.getRecord(ids[i]);
2639 removeHiddenNodes(rows, SE.contactView);
2643 if(rows.length > 0) {
2644 SE.composeLayout.handleDrop(
2645 (type == 'contacts') ? SE.contactView : SE.emailListsView,
2646 null, rows, 'addressTO' + idx );
2648 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
2652 editContact : function() {
2653 SE.contextMenus.contactsContextMenu.hide();
2654 var element = SE.contactView.getSelectedNodes()[0];
2656 if (element.className.indexOf('address-contact') > -1) {
2657 elementId = element.id;
2658 } else if (element.className.indexOf('address-exp-contact') > -1) {
2659 elementId = element.id.substring(2);
2665 * Filters contact entries based on user input
2667 filter : function(inputEl) {
2668 var ret = new Object();
2669 var re = new RegExp(inputEl.value, "gi");
2671 for(var i in this._contactCache) {
2672 if(this._contactCache[i].name.match(re)) {
2673 ret[i] = this._contactCache[i];
2677 this.buildContactList(ret);
2680 fullForm : function(id, module) {
2681 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
2685 * returns a formatted email address from the addressBook cache
2687 getFormattedAddress : function(id) {
2688 var o = this._contactCache[id];
2689 var primaryEmail = '';
2691 for(var i=0; i<o.email.length; i++) {
2692 var currentEmail = o.email[i].email_address;
2694 if(o.email[i].primary_address == 1) {
2695 primaryEmail = o.email[i].email_address;
2699 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
2700 var name = new String(o.name);
2701 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
2702 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
2708 * Sets up async call to query for matching contacts, users, etc.
2710 searchContacts : function() {
2711 var fn = document.getElementById('input_searchField').value;
2712 var pe = document.getElementById('input_searchPerson').value;
2714 var rb = document.getElementById('hasRelatedBean').checked;
2717 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2718 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2719 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2720 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2722 this.addressBookDataModel.params['related_bean_id'] = '';
2725 this.addressBookDataModel.params['search_field'] = fn;
2726 this.addressBookDataModel.params['person'] = pe;
2727 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
2728 this.grid._oDataSource = this.addressBookDataModel;
2729 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
2733 * Clear Search Crieteria For Addressbook
2735 clearAddressBookSearch : function() {
2736 document.getElementById('input_searchField').value = "";
2737 document.getElementById('input_searchPerson').selectedIndex = 0;
2741 * Opens modal select window to add contacts to addressbook
2743 selectContactsDialogue : function(destId) {
2744 if(!this.contactsDialogue) {
2745 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
2749 constraintoviewport: true,
2751 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
2752 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
2754 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
2756 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
2757 dlg.setBody(body.innerHTML);
2758 dlg.renderEvent.subscribe(function() {
2759 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
2760 if (iev && !SUGAR.isIE) {
2761 this.body.style.width = "950px";
2766 dlg.beforeRenderEvent.subscribe(function() {
2767 var dd = new YAHOO.util.DDProxy(dlg.element);
2768 dd.setHandleElId(dlg.header);
2769 dd.on('endDragEvent', function() {
2775 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
2777 var tabContent = SUGAR.util.getAndRemove("searchForm");
2778 tp.addTab(new YAHOO.widget.Tab({
2779 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
2781 content : tabContent.innerHTML,
2782 id : "addressSearchTab",
2786 var addListenerFields = ['input_searchPerson','input_searchField' ]
2787 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
2788 if (e.keyCode == 13) {
2789 YAHOO.util.Event.stopEvent(e);
2790 SUGAR.email2.addressBook.searchContacts();
2794 this.contactsDialogue.render();
2797 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
2798 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
2802 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
2803 var idx = activePanel.substring(10);
2805 SE.addressBook.idx = idx;
2808 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
2809 document.getElementById('relatedBeanColumn').style.display = '';
2810 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
2811 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2812 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2813 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
2814 SE.addressBook.relatedBeanType = relatedBeanType;
2816 document.getElementById('relatedBeanColumn').style.display = 'none';
2817 document.getElementById('hasRelatedBean').checked = false;
2820 if (!SE.addressBook.grid)
2822 if (hasRelatedBeanId) {
2823 document.getElementById('hasRelatedBean').checked = true;
2825 AddressSearchGridInit();
2826 SE.addressBook.relatedBeanId = relatedBeanId;
2830 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
2832 SE.addressBook.relatedBeanId = relatedBeanId;
2833 document.getElementById('hasRelatedBean').checked = true;
2835 if (document.getElementById('hasRelatedBean').checked == true)
2837 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2838 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2840 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
2841 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
2843 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
2844 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
2845 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
2848 //Remove any lingering rows in the result set table if the module was closed.
2849 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2851 SE.addressBook.populateResulstTableEmailAddresses();
2853 this.contactsDialogue.show();
2856 * Clear all email addresses from result table.
2859 clearAllEmailAddressFieldsFromResultTable: function () {
2860 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2861 //Unhighlight any rows currently selected if the emails were cleared.
2862 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
2863 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2866 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
2867 * results table. This function is called when the address book is displayed.
2869 populateResulstTableEmailAddresses: function () {
2871 var idx = SE.addressBook.idx;
2872 var emailFields = ['to','cc','bcc'];
2874 for(var k=0;k<emailFields.length;k++)
2876 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2877 var allEmails = document.getElementById(elKey).value;
2881 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
2883 for (var i=0; i<formatedEmails.length; i++)
2885 var t_name = formatedEmails[i].name;
2886 var t_emailAddr = formatedEmails[i].email_address;
2887 var displayEmail = t_name + ' <' + t_emailAddr + '>';
2889 t_name = displayEmail = t_emailAddr;
2891 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
2892 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
2893 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
2899 * Checks all entries in the result table against a particular email address, returning true
2900 * if the email address is found, false otherwise.
2902 doesEmailAdddressExistInResultTable: function(emailAddress)
2904 if(trim(emailAddress) == '')
2907 var emailAddressFound = false;
2908 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2909 for (var i=0; i < contacts.length; i++)
2911 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2912 //If we are adding to cc or bcc fields, make them visible.
2913 if(data.email_address == emailAddress)
2915 emailAddressFound = true;
2920 return emailAddressFound;
2923 * Takes all email addresses that the users wishes to add from the address book and populates the To
2924 * fields on the compose tab.
2926 populateEmailAddressFieldsFromResultTable: function()
2928 //Clear the fields first, all email addresses are stored in the address book
2929 var idx = SE.addressBook.idx;
2930 var emailFields = ['to','cc','bcc'];
2931 for(var k=0;k<emailFields.length;k++)
2933 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2934 document.getElementById(elKey).value = "";
2937 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2938 for (var i=0; i < contacts.length; i++)
2940 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2942 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
2943 //If we are adding to cc or bcc fields, make them visible.
2944 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
2945 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
2946 //Construct the target id
2947 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
2949 var target = document.getElementById(target_id);
2950 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
2953 //Delete all rows from the result set table
2954 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2957 SE.addressBook.contactsDialogue.hide()
2960 * Insert contacts into the result table.
2962 insertContactToResultTable : function(event,address_type) {
2964 var contactsDialogue = SE.addressBook.contactsDialogue;
2965 var contacts = SE.addressBook.grid.getSelectedRows();
2967 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2968 for (var i = 0; i < rows.length; i++)
2970 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
2972 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
2973 SE.addressBook.insertContactRowToResultTable(recId,address_type);
2974 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2975 rows[i].setData("selected",true);
2978 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2979 for (var i = 0; i < checkBoxes.length; i++) {
2980 checkBoxes[i].checked = false;
2986 insertContactRowToResultTable : function(rowId, addressType) {
2987 var data = SE.addressBook.grid.getRecord(rowId).getData();
2988 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
2990 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
2991 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
2992 if(addressType == null)
2993 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
2994 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});
2997 * Remove a row from the gridsResult table.
2999 removeRowFromGridResults : function(rowId,emailAddress)
3001 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
3002 for (var i=0; i < contacts.length; i++)
3004 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
3005 var data = rec.getData();
3006 if(data.email_address == emailAddress)
3008 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
3013 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
3016 * Translates between the addressType To|Cc|Bcc labels/keys.
3018 translateAddresType: function(addressType,fromKey)
3020 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
3021 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
3022 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
3023 var mappingObject = {};
3026 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
3029 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
3030 mappingObject[displayCc] = 'cc';
3031 mappingObject[displayBcc] = 'bcc';
3034 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
3040 toggleSearchRowIcon : function(rowId,show)
3044 var idToShow = rowId + '_add_img';
3045 var idToHide = rowId + '_rm_img';
3049 var idToShow = rowId + '_rm_img';
3050 var idToHide = rowId + '_add_img';
3054 Dom.addClass(idToHide, "yui-hidden");
3055 Dom.removeClass(idToShow, "yui-hidden");
3058 * Determine if an entry has already been added to the grid results table to prevent duplicates.
3060 doesGridResultsEntryExist: function(emailAddrs)
3063 var contactExists = false;
3064 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
3065 for (var i=0; i < contacts.length; i++)
3067 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
3068 if(data.email_address == emailAddrs)
3070 contactExists = true;
3074 return contactExists;
3078 * adds an email address to a string, but first checks if it exists
3079 * @param string concat The string we are appending email addresses to
3080 * @param string addr Email address to add
3083 smartAddEmailAddressToComposeField : function(concat, addr) {
3084 var re = new RegExp(addr);
3086 if(!concat.match(re)) {
3088 concat += "; " + addr;
3097 //// END ADDRESS BOOK
3098 ///////////////////////////////////////////////////////////////////////////////
3102 ///////////////////////////////////////////////////////////////////////////////
3105 * Auto-complete object
3109 delimChar : [";", ","],
3113 prehighlightClassName : "yui-ac-prehighlight",
3116 instances : new Array(),
3119 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
3120 * @param object Contact from AddressBook
3123 getPrimaryAddress : function(contact) {
3124 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
3126 for(var eIndex in contact.email) {
3127 address = contact.email[eIndex].email_address;
3128 if(contact.email[eIndex].primary_address == 1) {
3129 return contact.email[eIndex].email_address;
3137 * initializes autocomplete widgets for a given compose view
3140 init : function(idx) {
3141 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
3142 "queryMatchContains" : false,
3143 "queryMatchSubset" : true
3146 this.instances[idx] = {
3153 // instantiate the autoComplete widgets
3154 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
3155 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
3156 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
3158 // enable hiding of interfering textareas
3159 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3160 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3161 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3163 // enable reshowing of hidden textareas
3164 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3165 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3166 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3168 // enable refreshes of contact lists
3169 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3170 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3171 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3174 refreshDataSource : function(sType, aArgs) {
3175 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
3177 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
3179 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
3180 idx = textBoxId.substr(9);
3182 idx = textBoxId.substr(10);
3185 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
3186 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
3187 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
3191 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
3193 returnDataSource : function(contacts) {
3194 var ret = new Array();
3195 for(var id in contacts) {
3196 if (contacts[id].name) {
3197 var primary = this.getPrimaryAddress(contacts[id]);
3199 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
3200 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
3202 for(var emailIndex in contacts[id].email) {
3203 ret[ret.length] = contacts[id].email[emailIndex].email_address;
3212 * Hides address textareas to prevent autocomplete dropdown from being obscured
3214 toggleTextareaHide : function(sType, aArgs) {
3215 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3219 if(textBoxId.indexOf("addressTO") > -1) {
3221 } else if(textBoxId.indexOf("addressCC") > -1) {
3224 idx = textBoxId.substr(9);
3226 // follow through if not BCC
3228 var cc = document.getElementById("addressCC" + idx);
3229 var bcc = document.getElementById("addressBCC" + idx);
3233 cc.style.visibility = 'hidden';
3235 bcc.style.visibility = 'hidden';
3242 * Redisplays the textareas after an address is commited
3244 toggleTextareaShow : function(sType, aArgs) {
3245 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3249 if(textBoxId.indexOf("addressTO") > -1) {
3251 } else if(textBoxId.indexOf("addressCC") > -1) {
3254 idx = textBoxId.substr(9);
3256 // follow through if not BCC
3258 document.getElementById("addressCC" + idx).style.visibility = 'visible';
3259 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
3264 //// END AUTOCOMPLETE
3265 ///////////////////////////////////////////////////////////////////////////////
3267 ///////////////////////////////////////////////////////////////////////////////
3270 * expands the options sidebar
3272 SE.composeLayout = {
3273 currentInstanceId : 0,
3276 outboundAccountErrors : null,
3277 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
3279 showAddressDetails : function(e) {
3280 var linkElement = document.getElementById("More"+e.id);
3281 var spanElement = document.getElementById("Detail"+e.id);
3282 var emailAddressList = e.value;
3283 if(e.value.length > 96)
3285 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
3286 var displayArray = [];
3287 for (var i=0; i<resultArray.length; i++)
3289 var t_name = resultArray[i].name;
3290 var t_emailAddr = resultArray[i].email_address;
3292 displayArray.push('<br/><' + t_emailAddr + '>');
3294 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
3297 var result = displayArray.join('<br/>');
3299 linkElement.style.display = "inline";
3300 linkElement.style.height="10px";
3301 linkElement.style.overflow="visible";
3302 spanElement.innerHTML = result;
3305 linkElement.style.display = "none";
3310 * Given a string of email address, return an array containing the name portion (if available)
3311 * and email portion.
3313 _getEmailArrayFromString : function (emailAddressList){
3316 while ((results = reg.exec(emailAddressList)) != null)
3318 orignial = results[0];
3319 parsedResult = results[0].replace(';', ':::::');
3320 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3324 while ((results = reg.exec(emailAddressList)) != null)
3326 orignial = results[0];
3327 parsedResult = results[0].replace(',', ':::::');
3328 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3330 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
3331 var emailArr = emailAddressList.split(":::::");
3332 var resultsArray = [];
3334 for (var i=0; i<emailArr.length; i++)
3336 var rposition = emailArr[i].indexOf('<');
3337 var lposition = emailArr[i].indexOf('>');
3339 if(trim(emailArr[i]) != '')
3341 if(rposition != -1 && lposition != -1)
3343 var t_name = emailArr[i].substr(0, rposition-1);
3344 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
3345 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
3349 resultsArray.push({'name':'', 'email_address': emailArr[i]});
3353 return resultsArray;
3355 ///////////////////////////////////////////////////////////////////////////
3358 * Prepare bucket DIV and yui-ext tab panels
3360 _0_yui : function() {
3361 var idx = this.currentInstanceId;
3363 var composeTab = new YAHOO.SUGAR.ClosableTab({
3364 label: mod_strings.LNK_NEW_SEND_EMAIL,
3366 content : "<div id='htmleditordiv" + idx + "'/>",
3367 id : "composeTab" + idx,
3368 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
3371 SE.innerLayout.addTab(composeTab);
3373 // get template engine with template
3374 if (!SE.composeLayout.composeTemplate) {
3375 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
3378 // create Tab inner layout
3379 var composePanel = this.getComposeLayout();
3380 composePanel.getUnitByPosition("right").collapse();
3381 composePanel.autoSize();
3385 * Generate the quick compose layout
3386 * @method getQuickComposeLayout
3387 * @param {Pannel} parentPanel Parent pannel
3388 * @param {Object} o Options
3391 getQuickComposeLayout : function (parentPanel,o) {
3392 var idx = SE.composeLayout.currentInstanceId;
3394 //Before rendering the parent pannel we need to initalize the grid layout
3395 parentPanel.beforeRenderEvent.subscribe(function() {
3397 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3398 SE.composeLayout._createComposeLayout(idx);
3399 SE.composeLayout[idx].set('height', 350);
3400 SE.composeLayout[idx].render();
3404 //Wait until the Compose Layout has rendered, then add the
3405 //options tab and perform the tiny initialization.
3406 parentPanel.renderEvent.subscribe(function() {
3408 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3409 SE.composeLayout._initComposeOptionTabs(idx);
3410 SE.composeLayout[idx].getUnitByPosition("right").collapse();
3411 //Initialize tinyMCE
3412 SE.composeLayout._1_tiny(false);
3414 //Init templates and address book
3415 SE.composeLayout._2_final();
3417 SE.composeLayout.quickCreateComposePackage(o);
3422 //Check if we have the div override for the shortcut bar
3423 if(typeof o.menu_id != 'undefined') {
3424 parentPanel.render(o.menu_id);
3426 parentPanel.render(document.body);
3429 return SE.composeLayout[idx];
3432 * Fill in all fields into the quick compose layout.
3433 * @method quickCreateComposePackage
3434 * @param {Object} o Options
3437 quickCreateComposePackage: function(o)
3439 //If we have a compose package fill in defaults.
3440 if (typeof(o.composePackage) != 'undefined')
3442 composePackage = o.composePackage; //Set the compose data object
3443 //Hijack this method called by composePackage as it's not need for quick creates.
3444 SE.composeLayout.c0_composeNewEmail = function(){};
3445 SE.composeLayout.composePackage(); //Fill in defaults.
3448 getComposeLayout : function() {
3449 var idx = SE.composeLayout.currentInstanceId;
3451 this._createComposeLayout(idx);
3452 SE.composeLayout[idx].render();
3453 this._initComposeOptionTabs(idx);
3455 return SE.composeLayout[idx];
3459 * Create the layout manager for the compose window.
3461 _createComposeLayout : function(idx)
3463 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
3464 parent: SE.complexLayout,
3474 SE.composeLayout.composeTemplate.exec({
3475 'app_strings':app_strings,
3476 'mod_strings':mod_strings,
3477 'linkbeans_options' : linkBeans,
3478 'idx' : SE.composeLayout.currentInstanceId
3489 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
3492 header: app_strings.LBL_EMAIL_OPTIONS
3498 * Create compose tab which will populate the 'right' container in the compose window.
3500 _initComposeOptionTabs : function(idx)
3502 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
3503 var tab = new YAHOO.widget.Tab({
3504 label: app_strings.LBL_EMAIL_ATTACHMENT,
3506 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
3507 id : "divAttachments" + idx,
3511 tab.layout = SE.composeLayout[idx];
3513 tab.on("activeChange", function(o){
3515 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
3521 tab = new YAHOO.widget.Tab({
3522 label: app_strings.LBL_EMAIL_OPTIONS,
3524 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
3525 id : "divOptions" + idx,
3529 tab.layout = SE.composeLayout[idx];
3530 tab.on("activeChange", function(o){
3532 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
3537 SE.composeLayout[idx].autoSize = function() {
3538 var pEl = this.get("element").parentNode.parentNode.parentNode;
3539 this.set("height", pEl.clientHeight-30);
3543 SE.composeLayout[idx].rightTabs = cTabs;
3545 isParentTypeValid : function(idx) {
3546 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3547 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3548 if (trim(parentTypeValue) == ""){
3549 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
3555 isParentTypeAndNameValid : function(idx) {
3556 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3557 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3558 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
3559 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
3560 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
3561 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
3567 callopenpopupForEmail2 : function(idx,options) {
3569 var formName = 'emailCompose' + idx;
3571 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
3572 formName = options.form_name;
3574 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3575 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3576 if (!SE.composeLayout.isParentTypeValid(idx)) {
3579 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
3581 call_back_function:"SE.composeLayout.popupAddEmail",
3583 field_to_name_array:{
3584 id:'data_parent_id' + idx,
3585 name:'data_parent_name' + idx,
3590 popupAddEmail : function(o)
3592 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
3593 var data = o.name_to_value_array;
3594 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
3595 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
3597 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
3598 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
3605 _1_tiny : function(isReplyForward) {
3606 var idx = SE.composeLayout.currentInstanceId;
3607 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
3608 SE.tinyInstances[elId] = { };
3609 SE.tinyInstances[elId].ready = false;
3611 if (!SUGAR.util.isTouchScreen()) {
3612 var t = tinyMCE.getInstanceById(elId);
3614 if(typeof(t) == 'undefined') {
3615 if (!SUGAR.util.isTouchScreen()) {
3616 tinyMCE.execCommand('mceAddControl', false, elId);
3618 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
3619 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
3624 resizeEditorSetSignature : function(idx,setSignature)
3626 var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
3628 if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
3629 setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+setSignature+"');",500);
3633 SE.composeLayout.resizeEditor(idx);
3635 setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
3640 resizeEditor : function(idx)
3642 var cof = Dom.get('composeOverFrame' + idx);
3643 var head = Dom.get('composeHeaderTable' + idx);
3644 var targetHeight = cof.clientHeight - head.clientHeight;
3645 var instance = SE.util.getTiny('htmleditor' + idx);
3648 var parentEl = Dom.get(instance.editorId + '_parent');
3649 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
3650 var contentEl = instance.contentAreaContainer;
3651 var iFrame = contentEl.firstChild;
3652 var tinMceToolbarOffset = 18;
3653 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
3656 setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
3661 * Initializes d&d, auto-complete, email templates
3663 _2_final : function() {
3664 var idx = SE.composeLayout.currentInstanceId;
3666 if(this.emailTemplates) {
3667 this.setComposeOptions(idx);
3669 //populate email template cache
3670 AjaxObject.target = '';
3671 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
3674 // handle drop targets for addressBook
3675 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3676 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3677 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3678 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
3680 // auto-complete setup
3681 SE.autoComplete.init(idx);
3684 document.getElementById("addressTO" + idx).focus();
3688 * hide tinyMCE tool bar if send email as plaintext is checked
3690 renderTinyMCEToolBar : function (idx, hide) {
3692 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
3694 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
3698 c1_composeEmail : function(isReplyForward, retry) {
3702 if (!SUGAR.util.isTouchScreen() && (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined')){
3703 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
3705 this._1_tiny(isReplyForward);
3708 if(isReplyForward) {
3709 this.replyForwardEmailStage2();
3715 * takes draft info and prepopulates
3717 c0_composeDraft : function() {
3718 this.getNewInstanceId();
3720 document.getElementById('_blank').innerHTML = '';
3721 var idx = SE.composeLayout.currentInstanceId;
3722 SE.composeLayout.draftObject = new Object();
3723 SE.composeLayout.draftObject.id = idx;
3724 SE.composeLayout.draftObject.isDraft = true;
3725 SE.composeLayout.currentInstanceId = idx;
3726 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
3727 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
3728 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
3730 SE.composeLayout._0_yui();
3731 SE.composeLayout._1_tiny(true);
3734 SE.composeLayout._2_final();
3736 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
3737 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
3741 * Strip & Prep editor hidden fields
3743 c0_composeNewEmail : function() {
3744 this.getNewInstanceId();
3745 this.c1_composeEmail(false);
3749 * Sends async request to get the compose view.
3750 * Requests come from "reply" or "forwards"
3752 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
3753 SE.composeLayout.replyForwardObj = new Object();
3754 SE.composeLayout.replyForwardObj.ieId = ieId;
3755 SE.composeLayout.replyForwardObj.uid = uid;
3756 SE.composeLayout.replyForwardObj.mbox = mbox;
3757 SE.composeLayout.replyForwardObj.type = type;
3759 if(mbox == 'sugar::Emails') {
3760 SE.composeLayout.replyForwardObj.sugarEmail = true;
3763 SE.composeLayout.getNewInstanceId();
3764 SE.composeLayout.c1_composeEmail(true);
3766 //// END COMPOSE FLOW
3767 ///////////////////////////////////////////////////////////////////////////
3770 * Called when a contact, email, or mailinglist is dropped
3771 * into one of the compose fields.
3773 handleDrop : function (source, event, data, target) {
3776 target = event.getTarget();
3778 data.nodes = [data.nodes];
3782 target = document.getElementById(target);
3786 if (target.id.indexOf('address') > -1) {
3787 // dropped onto email to/cc/bcc field
3788 for(var i in nodes) {
3789 var node = nodes[i].getData();
3791 if (node[1].indexOf('contact') > -1) {
3792 email = SE.addressBook.getFormattedAddress(node[0]);
3793 } else if (node[1].indexOf('address-email') > -1){
3794 email = node[3].replace(/ /gi, '');
3795 email = email.replace('<', '<').replace('>', '>');
3796 var tr = source.getTrEl(nodes[i]);
3797 while (tr && !Dom.hasClass(tr, "address-contact")) {
3798 tr = source.getPreviousTrEl(tr);
3800 var CID = source.getRecord(tr).getData()[0];
3801 var o = SE.addressBook._contactCache[CID];
3802 var name = new String(o.name);
3803 var finalName = name.replace(/(<([^>]+)>)/ig, "");
3804 email = finalName + email;
3806 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
3812 /*/////////////////////////////////////////////////////////////////////////////
3813 /// EMAIL TEMPLATE CODE
3815 applyEmailTemplate : function (idx, id) {
3818 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
3819 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
3820 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
3823 var to_addr = document.getElementById('addressTO'+idx);
3824 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
3826 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
3827 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
3830 // id is selected index of email template drop-down
3831 if(id == '' || id == "0") {
3832 YAHOO.SUGAR.MessageBox.show({
3837 if(btn=='no'){return;};
3838 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
3845 YAHOO.SUGAR.MessageBox.show({
3850 if(btn=='no'){return;};
3851 SUGAR.email2.composeLayout.processResult(idx, id);},
3857 processNoneResult : function(idx, id) {
3858 var tiny = SE.util.getTiny('htmleditor' + idx);
3859 var tinyHTML = tiny.getContent();
3860 var openTag = '<div><span><span>';
3861 var htmllow = tinyHTML.toLowerCase();
3862 var start = htmllow.indexOf(openTag);
3864 tinyHTML = tinyHTML.substr(start);
3865 tiny.setContent(tinyHTML);
3867 tiny.setContent('');
3871 processResult : function(idx , id){
3872 var post_data = {"module":"EmailTemplates","record":id};
3873 var global_rpcClient = new SugarRPCClient();
3875 result = global_rpcClient.call_method('retrieve', post_data, true);
3876 if(!result['record']) return;
3877 json_objects['email_template_object'] = result['record'];
3878 this.appendEmailTemplateJSON();
3880 // get attachments if any
3881 AjaxObject.target = '';
3882 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
3885 appendEmailTemplateJSON : function() {
3886 var idx = SE.composeLayout.currentInstanceId; // post increment
3888 // query based on template, contact_id0,related_to
3889 //jchi 09/10/2008 refix #7743
3890 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
3891 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
3894 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,'"');
3896 // cn: bug 14361 - text-only templates don't fill compose screen
3898 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/>");
3901 var tiny = SE.util.getTiny('htmleditor' + idx);
3902 var tinyHTML = tiny.getContent();
3903 var openTag = '<div><span><span>';
3904 var closeTag = '</span></span></div>';
3905 var htmllow = tinyHTML.toLowerCase();
3906 var start = htmllow.indexOf(openTag);
3908 var htmlPart2 = tinyHTML.substr(start);
3909 tinyHTML = text + htmlPart2;
3910 tiny.setContent(tinyHTML);
3912 tiny.setContent(text);
3917 * Writes out the signature in the email editor
3919 setSignature : function(idx) {
3922 var hide = document.getElementById('setEditor' + idx).checked;
3923 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
3924 //wait for signatures to load before trying to set them
3925 if (!SE.composeLayout.signatures) {
3926 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
3931 var sel = document.getElementById('signatures' + idx);
3933 var sel = document.getElementById('signature_id');
3934 idx = SE.tinyInstances.currentHtmleditor;
3937 //Ensure that the tinyMCE html has been rendered.
3938 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
3939 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
3946 signature = sel.options[sel.selectedIndex].value;
3951 var openTag = '<div><span> </span>';
3952 var closeTag = '<span> </span></div>';
3953 var t = tinyMCE.getInstanceById('htmleditor' + idx);
3955 if(typeof(t) != 'undefined')
3957 t.contentDocument = t.contentWindow.document;
3958 var html = t.getContent();
3965 var htmllow = html.toLowerCase();
3966 var start = htmllow.indexOf(openTag);
3967 var end = htmllow.indexOf(closeTag) + closeTag.length;
3969 // selected "none" - remove signature from email
3970 if(signature == '') {
3972 var htmlPart1 = html.substr(0, start);
3973 var htmlPart2 = html.substr(end, html.length);
3975 html = htmlPart1 + htmlPart2;
3978 SE.signatures.lastAttemptedLoad = '';
3982 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
3983 SE.signatures.lastAttemptedLoad = '';
3985 SE.signatures.lastAttemptedLoad = signature;
3987 if(typeof(SE.signatures[signature]) == 'undefined') {
3989 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
3990 SE.signatures.targetInstance = (idx) ? idx : "";
3991 AjaxObject.target = '';
3992 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
3994 var newSignature = this.prepareSignature(SE.signatures[signature]);
3996 // clear out old signature
3997 if(SE.signatures.lastAttemptedLoad && start > -1) {
3998 var htmlPart1 = html.substr(0, start);
3999 var htmlPart2 = html.substr(end, html.length);
4001 html = htmlPart1 + htmlPart2;
4005 start = html.indexOf('<div><hr></div>');
4006 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
4007 var htmlPart1 = html.substr(0, start);
4008 var htmlPart2 = html.substr(start, html.length);
4009 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
4010 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
4011 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
4013 var body = html.indexOf('</body>');
4015 var part1 = html.substr(0, body);
4016 var part2 = html.substr(body, html.length);
4017 var newHtml = part1 + openTag + newSignature + closeTag + part2;
4019 var newHtml = html + openTag + newSignature + closeTag;
4022 //tinyMCE.setContent(newHtml);
4023 t.setContent(newHtml);
4027 prepareSignature : function(str) {
4028 var signature = new String(str);
4030 signature = signature.replace(/</gi, '<');
4031 signature = signature.replace(/>/gi, '>');
4037 showAttachmentPanel : function(idx) {
4038 var east = SE.composeLayout[idx].getUnitByPosition("right");
4039 var tabs = SE.composeLayout[idx].rightTabs;
4041 tabs.set("activeTab", tabs.getTab(0));
4045 * expands sidebar and displays options panel
4047 showOptionsPanel : function(idx) {
4048 var east = SE.composeLayout[idx].getUnitByPosition("right");
4049 var tabs = SE.composeLayout[idx].rightTabs;
4051 tabs.set("activeTab", tabs.getTab(1));
4055 * Selects the Contacts tab
4057 showContactsPanel : function() {
4058 SE.complexLayout.regions.west.showPanel("contactsTab");
4062 * Generates fields for Select Document
4064 addDocumentField : function(idx) {
4065 var basket = document.getElementById('addedDocuments' + idx);
4067 var index = (basket.childNodes.length / 7) - 1;
4074 var test = document.getElementById('documentId' + idx + index);
4076 while(test != null) {
4078 test = document.getElementById('documentId' + idx + index);
4081 var documentCup = document.createElement("div");
4082 documentCup.id = 'documentCup' + idx + index;
4083 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
4084 // document id field
4085 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
4086 // document name field
4087 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
4089 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
4090 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
4091 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
4093 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
4094 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
4095 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
4098 basket.appendChild(documentCup);
4099 //basket.innerHTML += out;
4104 * Makes async call to save a draft of the email
4105 * @param int Instance index
4107 saveDraft : function(tinyInstance) {
4108 this.sendEmail(tinyInstance, true);
4111 selectDocument : function(target) {
4112 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
4113 windowName = 'selectDocument';
4114 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
4116 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4118 // put the focus on the popup if the browser supports the focus() method
4124 * Modal popup for file attachment dialogue
4126 addFileField : function() {
4127 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
4128 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
4132 constraintoviewport: true,
4134 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
4135 fn:function(){SE.addFileDialog.hide();}
4138 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
4139 SE.addFileDialog.render();
4140 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
4142 Dom.removeClass("addFileDialog", "yui-hidden");
4144 SE.addFileDialog.show();
4148 * Async upload of file to temp dir
4150 uploadAttachment : function() {
4151 if(document.getElementById('email_attachment').value != "") {
4152 var formObject = document.getElementById('uploadAttachment');
4153 YAHOO.util.Connect.setForm(formObject, true, true);
4154 AjaxObject.target = '';
4155 AjaxObject.startRequest(callbackUploadAttachment, null);
4157 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
4162 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
4163 * @param string target in focus compose layout
4165 setDocument : function(idx, target, documentId, documentName, docRevId) {
4166 // fields are named/id'd [fieldName][instanceId][index]
4167 var addedDocs = document.getElementById("addedDocuments" + idx);
4168 var docId = document.getElementById('documentId' + idx + target);
4169 var docName = document.getElementById('documentName' + idx + target);
4170 var docRevisionId = document.getElementById('document' + idx + target);
4171 docId.value = documentId;
4172 docName.value = documentName;
4173 docRevisionId.value = docRevId;
4177 * Removes the bucket div containing the document input fields
4179 deleteDocumentField : function(documentCup) {
4180 var f0 = document.getElementById(documentCup);
4181 f0.parentNode.removeChild(f0);
4185 * Removes a Template Attachment field
4189 deleteTemplateAttachmentField : function(idx, index) {
4190 // create not-in-array values for removal filtering
4191 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
4197 r += document.getElementById('templateAttachmentId' + idx + index).value;
4198 document.getElementById("templateAttachmentsRemove" + idx).value = r;
4200 var target = 'templateAttachmentCup' + idx + index;
4201 d = document.getElementById(target);
4202 d.parentNode.removeChild(d);
4206 * Async removal of uploaded temp file
4207 * @param string index Should be a concatenation of idx and index
4210 deleteUploadAttachment : function(index, file) {
4211 var d = document.getElementById('email_attachment_bucket' + index);
4212 d.parentNode.removeChild(d);
4214 // make async call to delete cached file
4215 AjaxObject.target = '';
4216 AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
4220 * Attaches files coming from Email Templates
4222 addTemplateAttachmentField : function(idx) {
4224 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
4226 var basket = document.getElementById('addedTemplateAttachments' + idx);
4229 var index = basket.childNodes.length;
4236 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
4238 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
4239 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
4240 idx + "\",\"" + index + "\");'/>" +
4242 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
4243 // templateAttachment field
4244 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
4246 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
4248 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
4249 "<br id='br" + index + "></br>" +
4250 "<br id='brdoc" + index + "></br>" +
4252 basket.innerHTML = basket.innerHTML + out;
4258 * Sends one email via async call
4259 * @param int idx Editor instance ID
4260 * @param bool isDraft
4262 sendEmail : function(idx, isDraft) {
4264 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
4265 var obAccountID = document.getElementById('addressFrom' + idx).value;
4267 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
4269 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
4274 var form = document.getElementById('emailCompose' + idx);
4275 var composeOptionsFormName = "composeOptionsForm" + idx;
4278 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
4279 if (t != null || typeof(t) != "undefined") {
4280 var html = t.getContent();
4282 var html = "<p>" + document.getElementById('htmleditor' + idx).value + "</p>";
4285 var subj = document.getElementById('emailSubject' + idx).value;
4286 var to = trim(document.getElementById('addressTO' + idx).value);
4287 var cc = trim(document.getElementById('addressCC' + idx).value);
4288 var bcc = trim(document.getElementById('addressBCC' + idx).value);
4289 var email_id = document.getElementById('email_id' + idx).value;
4290 var composeType = document.getElementById('composeType').value;
4291 var parent_type = document.getElementById("parent_type").value;
4292 var parent_id = document.getElementById("parent_id").value;
4294 var el_uid = document.getElementById("uid");
4295 var uid = (el_uid == null) ? '' : el_uid.value;
4297 var el_ieId = document.getElementById("ieId");
4298 var ieId = (el_ieId == null) ? '' : el_ieId.value;
4300 var el_mbox = document.getElementById("mbox");
4301 var mbox = (el_mbox == null) ? '' : el_mbox.value;
4303 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
4304 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
4308 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
4311 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
4312 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
4313 parent_id = parentIdValue;
4314 parent_type = parentTypeValue;
4316 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
4317 // baseline viability check
4319 if(to == "" && cc == '' && bcc == '' && !isDraft) {
4320 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
4322 } else if(subj == '' && !isDraft) {
4323 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
4326 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
4328 } else if(html == '' && !isDraft) {
4329 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
4334 SE.util.clearHiddenFieldValues('emailCompose' + idx);
4335 document.getElementById('data_parent_id' + idx).value = parentIdValue;
4336 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
4337 SUGAR.showMessageBox(title, app_strings.LBL_EMAIL_ONE_MOMENT);
4338 html = html.replace(/</ig, "sugarLessThan");
4339 html = html.replace(/>/ig, "sugarGreaterThan");
4341 form.sendDescription.value = html;
4342 form.sendSubject.value = subj;
4343 form.sendTo.value = to;
4344 form.sendCc.value = cc;
4345 form.sendBcc.value = bcc;
4346 form.email_id.value = email_id;
4347 form.composeType.value = composeType;
4348 form.composeLayoutId.value = 'composeLayout' + idx;
4349 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
4350 form.saveToSugar.value = 1;
4351 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
4352 form.parent_type.value = parent_type;
4353 form.parent_id.value = parent_id;
4354 form.uid.value = uid;
4355 form.ieId.value = ieId;
4356 form.mbox.value = mbox;
4358 // email attachments
4359 var addedFiles = document.getElementById('addedFiles' + idx);
4361 for(i=0; i<addedFiles.childNodes.length; i++) {
4362 var bucket = addedFiles.childNodes[i];
4364 for(j=0; j<bucket.childNodes.length; j++) {
4365 var node = bucket.childNodes[j];
4366 var nName = new String(node.name);
4368 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
4369 if(form.attachments.value != '') {
4370 form.attachments.value += "::";
4372 form.attachments.value += node.value;
4379 var addedDocs = document.getElementById('addedDocuments' + idx);
4381 for(i=0; i<addedDocs.childNodes.length; i++) {
4382 var cNode = addedDocs.childNodes[i];
4383 for(j=0; j<cNode.childNodes.length; j++) {
4384 var node = cNode.childNodes[j];
4385 var nName = new String(node.name);
4386 if(node.type == 'hidden' && nName.match(/documentId/)) {
4387 if(form.documents.value != '') {
4388 form.documents.value += "::";
4390 form.documents.value += node.value;
4396 // template attachments
4397 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
4398 if(addedTemplateAttachments) {
4399 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
4400 var cNode = addedTemplateAttachments.childNodes[i];
4401 for(j=0; j<cNode.childNodes.length; j++) {
4402 var node = cNode.childNodes[j];
4403 var nName = new String(node.name);
4404 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
4405 if(form.templateAttachments.value != "") {
4406 form.templateAttachments.value += "::";
4408 form.templateAttachments.value += node.value;
4414 // remove attachments
4415 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
4417 YAHOO.util.Connect.setForm(form);
4419 AjaxObject.target = 'frameFlex';
4421 // sending a draft email
4422 if(!isDraft && in_draft) {
4424 SE.listView.removeRowByUid(email_id);
4427 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
4428 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
4430 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
4434 * Handles clicking the email address link from a given view
4436 composePackage : function() {
4437 if(composePackage != null) {
4438 SE.composeLayout.c0_composeNewEmail();
4441 if(composePackage.to_email_addrs) {
4442 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
4444 if (composePackage.subject != null && composePackage.subject.length > 0) {
4445 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
4448 //If no parent fields are set in the composePackage, ensure they are cleared.
4449 var parentFields = ['parent_type','parent_name','parent_id'];
4450 for(var i=0;i<parentFields.length;i++)
4452 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
4453 composePackage[parentFields[i]] = "";
4456 document.getElementById("parent_type").value = composePackage.parent_type;
4457 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
4458 document.getElementById("parent_id").value = composePackage.parent_id;
4459 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
4460 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
4462 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
4463 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
4465 if (composePackage.body != null && composePackage.body.length > 0) {
4466 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4467 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
4468 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
4470 if (composePackage.attachments != null) {
4471 SE.composeLayout.loadAttachments(composePackage.attachments);
4474 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
4475 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
4476 SE.util.emptySelectOptions(addressFrom);
4477 var fromAccountOpts = composePackage.fromAccounts.data;
4478 for(i=0; i<fromAccountOpts.length; i++) {
4479 var key = fromAccountOpts[i].value;
4480 var display = fromAccountOpts[i].text;
4481 var opt = new Option(display, key);
4482 if (fromAccountOpts[i].selected) {
4483 opt.selected = true;
4485 addressFrom.options.add(opt);
4492 setContentOnThisTiny : function() {
4493 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4494 var tinyHTML = tiny.getContent();
4495 composePackage.body = decodeURI(encodeURI(composePackage.body));
4496 // cn: bug 14361 - text-only templates don't fill compose screen
4497 if(composePackage.body == '') {
4498 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4500 //Flag determines if we should clear the tiny contents or just append
4501 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
4502 SE.composeLayout.tinyHTML = '';
4504 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
4506 tiny.setContent(SE.composeLayout.tinyHTML);
4507 //Indicate that the contents has been loaded successfully.
4508 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
4511 * Confirms closure of a compose screen if "x" is clicked
4513 confirmClose : function(panel) {
4514 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
4515 SE.composeLayout.closeCompose(panel.id);
4523 * forces close of a compose screen
4525 forceCloseCompose : function(id) {
4526 SE.composeLayout.closeCompose(id);
4528 // handle flow back to originating view
4529 if(composePackage) {
4530 // check if it's a module we need to return to
4531 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
4532 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
4533 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
4534 window.location = url;
4541 * closes the editor that just sent email
4542 * @param string id ID of composeLayout tab
4544 closeCompose : function(id) {
4545 // destroy tinyMCE instance
4546 var idx = id.substr(13, id.length);
4547 var instanceId = "htmleditor" + idx;
4548 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
4550 // nullify DOM and namespace values.
4552 SE.composeLayout[idx] = null;
4553 SE.tinyInstances[instanceId] = null;
4554 var tabsArray = SE.innerLayout.get("tabs");
4555 for (i = 0 ; i < tabsArray.length ; i++) {
4556 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
4557 tabsArray[i].close();
4561 //SE.innerLayout.getTab(idx).close();
4565 * Enable the quick search for the compose relate field or search tab
4567 enableQuickSearchRelate: function(idx,overides){
4569 if(typeof overides != 'undefined')
4571 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
4572 var newModule = document.getElementById(newModuleID).value;
4573 var formName = overides['formName'];
4574 var fieldName = overides['fieldName'];
4575 var fieldId = overides['fieldId'];
4576 var fullName = formName + "_" + fieldName;
4577 var postBlurFunction = null;
4581 var newModule = document.getElementById('data_parent_type'+idx).value;
4582 var formName = 'emailCompose'+idx;
4583 var fieldName = 'data_parent_name'+idx;
4584 var fieldId = 'data_parent_id'+idx;
4585 var fullName = formName + "_" + fieldName;
4586 var postBlurFunction = "SE.composeLayout.qsAddAddress";
4589 if(typeof sqs_objects == 'undefined')
4590 window['sqs_objects'] = new Array;
4592 window['sqs_objects'][fullName] = {
4595 modules:[newModule],
4597 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
4598 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
4599 post_onblur_function: postBlurFunction,
4600 order:"name","limit":"30","no_match_text":"No Match"};
4603 if(typeof QSProcessedFieldsArray != 'undefined')
4604 QSProcessedFieldsArray[fullName] = false;
4605 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
4606 QSFieldsArray[fullName].destroy();
4607 delete QSFieldsArray[fullName];
4609 if (Dom.get(fullName + "_results")) {
4610 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
4616 qsAddAddress : function(o) {
4617 if (o.name != "" && o.email1 != "")
4619 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
4620 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
4624 * Returns a new instance ID, 0-index
4626 getNewInstanceId : function() {
4627 this.currentInstanceId = this.currentInstanceId + 1;
4628 return this.currentInstanceId;
4632 * 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.
4634 loadAttachments : function(result) {
4635 var idx = SE.composeLayout.currentInstanceId;
4637 if(typeof(result) == 'object') {
4638 //jchi #20680. Clean the former template attachments;
4639 var basket = document.getElementById('addedTemplateAttachments' + idx);
4640 if(basket.innerHTML != ''){
4641 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
4643 basket.innerHTML = '';
4648 if(typeof result[i] == 'object') {
4649 var index = SE.composeLayout.addTemplateAttachmentField(idx);
4650 var bean = result[i];
4651 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
4652 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
4659 * fills drop-down values for email templates and signatures
4661 setComposeOptions : function(idx) {
4662 // send from accounts
4663 var addressFrom = document.getElementById('addressFrom' + idx);
4665 if (addressFrom.options.length <= 0) {
4666 SE.util.emptySelectOptions(addressFrom);
4667 var fromAccountOpts = SE.composeLayout.fromAccounts;
4668 for (id = 0 ; id < fromAccountOpts.length ; id++) {
4669 var key = fromAccountOpts[id].value;
4670 var display = fromAccountOpts[id].text;
4671 var is_default = false;
4672 if(key == SUGAR.default_inbound_accnt_id)
4674 var opt = new Option(display, key);
4675 addressFrom.options.add(opt);
4676 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
4681 var et = document.getElementById('email_template' + idx);
4682 SE.util.emptySelectOptions(et);
4684 for(var key in this.emailTemplates) { // iterate through assoc array
4685 var display = this.emailTemplates[key];
4686 var opt = new Option(display, key);
4687 et.options.add(opt);
4691 var sigs = document.getElementById('signatures' + idx);
4692 SE.util.emptySelectOptions(sigs);
4694 for(var key in this.signatures) { // iterate through assoc array
4695 var display = this.signatures[key];
4696 var opt = new Option(display, key);
4698 if(key == SE.userPrefs.signatures.signature_default) {
4699 opt.selected = true;
4702 sigs.options.add(opt);
4705 // html/plain email?
4706 var htmlEmail = document.getElementById('setEditor' + idx);
4707 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
4708 htmlEmail.checked = true;
4710 htmlEmail.checked = false;
4713 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
4717 * After compose screen is rendered, async call to get email body from Sugar
4719 replyForwardEmailStage2 : function() {
4720 SE.util.clearHiddenFieldValues('emailUIForm');
4721 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
4723 var ieId = SE.composeLayout.replyForwardObj.ieId;
4724 var uid = SE.composeLayout.replyForwardObj.uid;
4725 var mbox = SE.composeLayout.replyForwardObj.mbox;
4726 var type = SE.composeLayout.replyForwardObj.type;
4727 var idx = SE.composeLayout.currentInstanceId;
4729 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
4731 document.getElementById('emailSubject' + idx).value = type;
4732 document.getElementById('emailUIAction').value = 'composeEmail';
4733 document.getElementById('composeType').value = type;
4734 document.getElementById('ieId').value = ieId;
4735 document.getElementById('uid').value = uid;
4736 document.getElementById('mbox').value = mbox;
4737 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
4738 var formObject = document.getElementById('emailUIForm');
4739 YAHOO.util.Connect.setForm(formObject);
4741 var sendType = type;
4742 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
4746 * Show the hidden cc or bcc fields
4748 showHiddenAddress: function(addrType,idx){
4750 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
4751 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
4752 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
4753 this[addrType+'Hidden'+idx] = false;
4755 //After bcc or cc is added, move options below last addr field
4756 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4758 //If both cc and bcc hidden, remove the empty row containing text.
4759 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
4760 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
4761 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
4763 // SE.composeLayout.resizeEditor(idx);
4766 * Hide the cc and bcc fields if they were shown.
4768 hideHiddenAddresses: function(idx){
4770 var addrTypes = ['cc','bcc'];
4771 for(var i = 0;i<addrTypes.length;i++)
4773 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
4774 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
4775 this[addrTypes[i] + 'Hidden'+idx] = true
4778 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
4779 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
4780 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4784 //// END SE.composeLayout
4785 ///////////////////////////////////////////////////////////////////////////////
4786 ///////////////////////////////////////////////////////////////////////////////
4790 * Cleans serialized UID lists of duplicates
4794 cleanUids : function(str) {
4795 var seen = new Object();
4797 var arr = new String(str).split(",");
4799 for(var i=0; i<arr.length; i++) {
4804 clean += (clean != "") ? "," : "";
4806 seen[arr[i]] = true;
4813 * Clears hidden field values
4814 * @param string id ID of form element to clear
4816 clearHiddenFieldValues : function(id) {
4817 var form = document.getElementById(id);
4819 for(i=0; i<form.elements.length; i++) {
4820 if(form.elements[i].type == 'hidden') {
4821 var e = form.elements[i];
4822 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
4830 * Reduces a SELECT drop-down to 0 items to prepare for new ones
4832 emptySelectOptions : function(el) {
4834 for(i=el.childNodes.length - 1; i >= 0; i--) {
4835 if(el.childNodes[i]) {
4836 el.removeChild(el.childNodes[i]);
4843 * Returns the MBOX path in the manner php_imap expects:
4844 * ie: INBOX.DEBUG.test
4845 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
4847 generateMboxPath : function(str) {
4848 var ex = str.split("::");
4850 /* we have a serialized MBOX path */
4854 for(var i=0; i<ex.length; i++) {
4855 if(ex[i] == 'INBOX') {
4867 /* we have a Sugar folder GUID - do nothing */
4875 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
4876 * @param HTMLElement el
4877 * @return string GUID of found element or empty on failure
4879 getGuidFromElement : function(el) {
4885 for(var i=0; i<iterations; i++) {
4887 if(el.id.match(SE.reGUID)) {
4899 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
4902 getPanelId : function() {
4903 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
4907 * wrapper to handle weirdness with IE
4908 * @param string instanceId
4909 * @return tinyMCE Controller object
4911 getTiny : function(instanceId) {
4912 if(instanceId == '') {
4916 var t = tinyMCE.getInstanceById(instanceId);
4920 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
4926 * Simple check for MSIE browser
4930 var nav = new String(navigator.appVersion);
4931 if(nav.match(/MSIE/)) {
4938 * Recursively removes an element from the DOM
4939 * @param HTMLElement
4941 removeElementRecursive : function(el) {
4942 this.emptySelectOptions(el);
4949 sleep : function(secs) {
4950 setTimeout("void(0);", secs);
4954 * Converts a <select> element to an Ext.form.combobox
4956 convertSelect : function(select) {
4957 alert('in convertSelect');
4958 if (typeof(select) == "string") {
4959 select = document.getElementById(select);
4963 findChildNode : function (parent, property, value) {
4964 for (i in parent.children) {
4965 var child = parent.children[i];
4966 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
4968 var searchChild = SE.util.findChildNode(child, property, value);
4975 cascadeNodes : function (parent, fn, scope, args) {
4976 for (i in parent.children) {
4977 var child = parent.children[i];
4978 var s = scope ? scope : child;
4979 var a = args ? args : child;
4981 SE.util.cascadeNodes(child, fn, scope, args);
4988 ///////////////////////////////////////////////////////////////////////////////
4991 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
4993 /*********************************************************************************
4994 * SugarCRM Community Edition is a customer relationship management program developed by
4995 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4997 * This program is free software; you can redistribute it and/or modify it under
4998 * the terms of the GNU Affero General Public License version 3 as published by the
4999 * Free Software Foundation with the addition of the following permission added
5000 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
5001 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
5002 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
5004 * This program is distributed in the hope that it will be useful, but WITHOUT
5005 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
5006 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
5009 * You should have received a copy of the GNU Affero General Public License along with
5010 * this program; if not, see http://www.gnu.org/licenses or write to the Free
5011 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
5014 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
5015 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
5017 * The interactive user interfaces in modified source and object code versions
5018 * of this program must display Appropriate Legal Notices, as required under
5019 * Section 5 of the GNU Affero General Public License version 3.
5021 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
5022 * these Appropriate Legal Notices must retain the display of the "Powered by
5023 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
5024 * technical reasons, the Appropriate Legal Notices must display the words
5025 * "Powered by SugarCRM".
5026 ********************************************************************************/
5028 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
5029 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
5030 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
5031 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
5032 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
5033 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
5034 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
5035 ' <input type="hidden" id="type{idx}" name="type" value="">' +
5036 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
5037 ' <input type="hidden" id="composeType" name="composeType">' +
5038 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
5039 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
5040 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
5041 ' <input type="hidden" id="sendTo" name="sendTo">' +
5042 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
5043 ' <input type="hidden" id="sendCc" name="sendCc">' +
5044 ' <input type="hidden" id="setEditor" name="setEditor">' +
5045 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
5046 ' <input type="hidden" id="parent_id" name="parent_id">' +
5047 ' <input type="hidden" id="parent_type" name="parent_type">' +
5048 ' <input type="hidden" id="attachments" name="attachments">' +
5049 ' <input type="hidden" id="documents" name="documents">' +
5050 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
5051 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
5052 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
5053 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
5055 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
5056 ' <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>' +
5057 ' <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>' +
5058 ' <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>' +
5059 ' <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>' +
5060 '</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>' +
5061 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
5062 '<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>' +
5063 ' </td></tr></tbody></table></th>' +
5067 ' <div style="margin:5px;">' +
5068 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
5070 ' <td class="emailUILabel" NOWRAP >' +
5071 ' {app_strings.LBL_EMAIL_FROM}:' +
5073 ' <td class="emailUIField" NOWRAP>' +
5075 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
5080 ' <td class="emailUILabel" NOWRAP>' +
5081 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
5082 ' {app_strings.LBL_EMAIL_TO}:' +
5085 ' <td class="emailUIField" NOWRAP>' +
5086 ' <div class="ac_autocomplete">' +
5087 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5088 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
5089 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
5093 ' <tr id="add_addr_options_tr{idx}">' +
5094 ' <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>'+
5096 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
5097 ' <td class="emailUILabel" NOWRAP>' +
5098 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
5099 ' {app_strings.LBL_EMAIL_CC}:' +
5102 ' <td class="emailUIField" NOWRAP>' +
5103 ' <div class="ac_autocomplete">' +
5104 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5105 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
5106 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
5110 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
5111 ' <td class="emailUILabel" NOWRAP>' +
5112 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
5113 ' {app_strings.LBL_EMAIL_BCC}:' +
5116 ' <td class="emailUIField" NOWRAP>' +
5117 ' <div class="ac_autocomplete">' +
5118 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5119 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
5120 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
5125 ' <td class="emailUILabel" NOWRAP width="1%">' +
5126 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
5128 ' <td class="emailUIField" NOWRAP width="99%">' +
5129 ' <div class="ac_autocomplete">' +
5130 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
5139 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
5140 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
5141 ' <div style="padding:5px;">' +
5142 ' <table cellpadding="2" cellspacing="0" border="0">' +
5145 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
5152 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
5153 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
5165 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
5172 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
5173 ' <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>' +
5185 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
5192 ' <div id="addedTemplateAttachments{idx}"></div>' +
5199 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
5200 ' <div style="padding:5px;">' +
5201 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
5202 ' <table border="0" width="100%">' +
5204 ' <td NOWRAP style="padding:2px;">' +
5205 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
5209 ' <td NOWRAP style="padding:2px;">' +
5210 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
5215 ' <table border="0" width="100%">' +
5217 ' <td NOWRAP style="padding:2px;">' +
5218 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
5222 ' <td NOWRAP style="padding:2px;">' +
5223 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
5227 ' <table border="0" width="100%">' +
5229 ' <td NOWRAP style="padding:2px;">' +
5230 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
5231 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
5239 // End of File modules/Emails/javascript/composeEmailTemplate.js
5241 /*********************************************************************************
5242 * SugarCRM Community Edition is a customer relationship management program developed by
5243 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5245 * This program is free software; you can redistribute it and/or modify it under
5246 * the terms of the GNU Affero General Public License version 3 as published by the
5247 * Free Software Foundation with the addition of the following permission added
5248 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
5249 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
5250 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
5252 * This program is distributed in the hope that it will be useful, but WITHOUT
5253 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
5254 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
5257 * You should have received a copy of the GNU Affero General Public License along with
5258 * this program; if not, see http://www.gnu.org/licenses or write to the Free
5259 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
5262 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
5263 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
5265 * The interactive user interfaces in modified source and object code versions
5266 * of this program must display Appropriate Legal Notices, as required under
5267 * Section 5 of the GNU Affero General Public License version 3.
5269 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
5270 * these Appropriate Legal Notices must retain the display of the "Powered by
5271 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
5272 * technical reasons, the Appropriate Legal Notices must display the words
5273 * "Powered by SugarCRM".
5274 ********************************************************************************/
5279 function complexLayoutInit() {
5280 var se = SUGAR.email2;
5281 var Dom = YAHOO.util.Dom;
5283 getInnerLayout : function(rows) {
5284 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
5285 parent: se.complexLayout,
5291 scroll:false, // grid should autoScroll itself
5293 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
5301 body: "<div id='listBottom' />"
5309 body: "<div id='listRight' />",
5310 titlebar: false //,header: "right"
5313 se.complexLayout.on("render", function(){
5314 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
5315 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5316 SUGAR.email2.listViewLayout.set("height", height);
5317 SUGAR.email2.listViewLayout.render();
5319 se.listViewLayout.render();
5321 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
5322 var rp = se.listViewLayout.resizePreview = function() {
5323 var pre = Dom.get("displayEmailFramePreview");
5325 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
5326 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
5329 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
5330 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
5331 se.e2Layout.setPreviewPanel(rows);
5332 se.previewLayout = se.listViewLayout;
5333 return se.listViewLayout;
5336 getInnerLayout2Rows : function() {
5337 return this.getInnerLayout(true);
5339 getInnerLayout2Columns : function() {
5340 return this.getInnerLayout(false);
5344 // initialize state manager, we will use cookies
5345 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
5346 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
5347 se.complexLayout = new YAHOO.widget.Layout("container", {
5350 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
5351 width: Dom.getViewportWidth() - 40,
5355 body: "<div id='emailtabs'></div>"
5360 body: "<div id='lefttabs'></div>",
5370 header: Dom.get('footerLinks').innerHTML,
5377 se.complexLayout.render();
5378 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
5379 tp.addTab(new YAHOO.widget.Tab({
5382 content : "<div id='listViewDiv'/>",
5386 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
5387 tp.appendTo(centerEl);
5389 tp.get("element").style.borderRight = "1px solid #666"
5391 var listV = this.getInnerLayout2Rows();
5392 listV.set("height", tp.get("element").clientHeight - 25);
5395 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
5396 var folderTab = new YAHOO.widget.Tab({
5397 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
5399 content : "<div id='emailtree'/>",
5403 folderTab.on("activeChange", function(o){
5405 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
5408 se.leftTabs.addTab(folderTab);
5410 var tabContent = SUGAR.util.getAndRemove("searchTab");
5411 var searchTab = new YAHOO.widget.Tab({
5412 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
5414 content : tabContent.innerHTML,
5417 searchTab.on("activeChange", function(o){
5420 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
5421 //Setup the calendars if needed
5422 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
5423 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
5425 //Initalize sqs object for assigned user name
5426 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
5428 //Attach event handler for when the relate module option is selected for the correct sqs object
5429 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
5430 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
5431 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
5432 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
5434 //If enter key is pressed, perform search
5435 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
5436 for(var i=0; i < addKeyPressFields.length;i++)
5438 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
5439 if (e.keyCode == 13) {
5440 YAHOO.util.Event.stopEvent(e);
5441 SUGAR.email2.search.searchAdvanced();
5445 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
5447 //Clear parent values if selecting another parent type.
5448 YAHOO.util.Event.addListener('data_parent_type_search','change',
5450 document.getElementById('data_parent_id_search').value ='';
5451 document.getElementById('data_parent_name_search').value ='';
5456 se.leftTabs.addTab(searchTab);
5458 var resizeTabBody = function() {
5459 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
5460 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5463 se.complexLayout.on("render", resizeTabBody);
5464 se.leftTabs.on("activeTabChange", resizeTabBody);
5465 //hack to allow left pane scroll bar to fully show
5466 var lefttabsDiv = document.getElementById('lefttabs');
5467 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
5468 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
5469 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
5472 initSQSObject: function(formName,fieldName)
5474 var fullFieldName = formName + '_' + fieldName; //SQS Convention
5475 var resultName = fullFieldName + '_' + 'results';
5477 if (QSFieldsArray[fullFieldName] != null)
5479 QSFieldsArray[fullFieldName].destroy();
5480 delete QSFieldsArray[fullFieldName];
5482 if (QSProcessedFieldsArray[fullFieldName])
5483 QSProcessedFieldsArray[fullFieldName] = false;
5485 if( Dom.get(resultName) )
5487 var obj = document.getElementById(resultName);
5488 obj.parentNode.removeChild(obj);
5491 setPreviewPanel: function(rows) {
5493 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
5494 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
5495 Dom.get("listRight").innerHTML = "";
5496 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
5498 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
5499 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
5500 Dom.get("listBottom").innerHTML = "";
5501 Dom.get("listRight").innerHTML = "<div id='_blank' />";
5508 var myBufferedListenerObject = new Object();
5509 myBufferedListenerObject.refit = function() {
5510 if(SUGAR.email2.grid) {
5511 SUGAR.email2.grid.autoSize();
5514 // End of File modules/Emails/javascript/complexLayout.js