1 /*********************************************************************************
2 * SugarCRM 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 is a customer relationship management program developed by
57 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
59 * This program is free software; you can redistribute it and/or modify it under
60 * the terms of the GNU Affero General Public License version 3 as published by the
61 * Free Software Foundation with the addition of the following permission added
62 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
63 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
64 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
66 * This program is distributed in the hope that it will be useful, but WITHOUT
67 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
68 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
71 * You should have received a copy of the GNU Affero General Public License along with
72 * this program; if not, see http://www.gnu.org/licenses or write to the Free
73 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
76 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
77 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
79 * The interactive user interfaces in modified source and object code versions
80 * of this program must display Appropriate Legal Notices, as required under
81 * Section 5 of the GNU Affero General Public License version 3.
83 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
84 * these Appropriate Legal Notices must retain the display of the "Powered by
85 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
86 * technical reasons, the Appropriate Legal Notices must display the words
87 * "Powered by SugarCRM".
88 ********************************************************************************/
89 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
90 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
91 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
92 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
93 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
94 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
95 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
96 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
97 this.js_more();this.js_more();}
98 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
99 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
100 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
101 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
102 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&¤tNode.tagName=='SPAN'){currentNode.id=/_input/.test(currentNode.id)?this.field_element_name+'_input_div_'+this.fields_count:this.field_element_name+'_radio_div_'+this.fields_count;if(/_input/.test(currentNode.id)){currentNode.name='teamset_div';}
103 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
104 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
105 currentNode.name=new_name;currentNode.id=new_name;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_name;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
106 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
107 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
109 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
111 if(!has_primary){return false;}
113 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
114 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
115 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
116 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
117 if(noAdd){enableQS(false);}
118 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_collection_"+i);var id_field=document.getElementById("id_"+this.field+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].id==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
120 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
121 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
123 SUGAR.collection.safe_clone=function(e,recursive)
124 {if(e.nodeName=="#text")
125 {return document.createTextNode(e.data);}
126 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];for(var i in properties)
127 {if(e[properties[i]])
128 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
129 newNode[properties[i]]=e[properties[i]];}}
131 {for(var i in e.childNodes)
132 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
133 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
134 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
136 /*********************************************************************************
137 * SugarCRM is a customer relationship management program developed by
138 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
140 * This program is free software; you can redistribute it and/or modify it under
141 * the terms of the GNU Affero General Public License version 3 as published by the
142 * Free Software Foundation with the addition of the following permission added
143 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
144 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
145 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
147 * This program is distributed in the hope that it will be useful, but WITHOUT
148 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
149 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
152 * You should have received a copy of the GNU Affero General Public License along with
153 * this program; if not, see http://www.gnu.org/licenses or write to the Free
154 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
157 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
158 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
160 * The interactive user interfaces in modified source and object code versions
161 * of this program must display Appropriate Legal Notices, as required under
162 * Section 5 of the GNU Affero General Public License version 3.
164 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
165 * these Appropriate Legal Notices must retain the display of the "Powered by
166 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
167 * technical reasons, the Appropriate Legal Notices must display the words
168 * "Powered by SugarCRM".
169 ********************************************************************************/
172 cache : new Object(),
173 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
174 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
177 currentHtmleditor : ''
181 * preserves hits from email server
183 _setDetailCache : function(ret) {
185 var compKey = ret.meta.mbox + ret.meta.uid;
187 if(!SUGAR.email2.cache[compKey]) {
188 SUGAR.email2.cache[compKey] = ret;
193 autoSetLayout : function() {
194 var c = document.getElementById('container');
195 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
196 //Ensure a minimum height.
197 tHeight = Math.max(tHeight, 550);
198 c.style.height = tHeight + "px";
199 SUGAR.email2.complexLayout.set('height', tHeight);
200 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
201 SUGAR.email2.complexLayout.render();
202 SUGAR.email2.listViewLayout.resizePreview();
207 * Shows overlay progress message
209 function overlayModal(title, body) {
210 overlay(title, body);
212 function overlay(reqtitle, body, type, additconfig) {
214 if (typeof(additconfig) == "object") {
215 var config = additconfig;
218 config.title = reqtitle;
220 YAHOO.SUGAR.MessageBox.show(config);
223 function hideOverlay() {
224 YAHOO.SUGAR.MessageBox.hide();
226 // End of File modules/Emails/javascript/EmailUIShared.js
228 /*********************************************************************************
229 * SugarCRM is a customer relationship management program developed by
230 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
232 * This program is free software; you can redistribute it and/or modify it under
233 * the terms of the GNU Affero General Public License version 3 as published by the
234 * Free Software Foundation with the addition of the following permission added
235 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
236 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
237 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
239 * This program is distributed in the hope that it will be useful, but WITHOUT
240 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
241 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
244 * You should have received a copy of the GNU Affero General Public License along with
245 * this program; if not, see http://www.gnu.org/licenses or write to the Free
246 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
249 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
250 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
252 * The interactive user interfaces in modified source and object code versions
253 * of this program must display Appropriate Legal Notices, as required under
254 * Section 5 of the GNU Affero General Public License version 3.
256 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
257 * these Appropriate Legal Notices must retain the display of the "Powered by
258 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
259 * technical reasons, the Appropriate Legal Notices must display the words
260 * "Powered by SugarCRM".
261 ********************************************************************************/
264 if (typeof console == "undefined")
265 console = { log: function(o) {alert(o)} };
269 currentRequestObject : null,
270 //timeout : 30000, // 30 second timeout default
271 timeout : 9999999999, // 30 second timeout default
277 _reset : function() {
278 this.timeout = 30000;
279 this.forceAbort = false;
282 folderRenameCleanup : function() {
283 SUGAR.email2.folders.setSugarFolders();
286 fullSyncCleanup : function(o) {
287 this.folders.checkMailCleanup(o);
288 SUGAR.email2.settings.settingsDialog.hide();
293 composeCache : function(o) {
294 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
295 // get email templates and user signatures
296 var ret = JSON.parse(o.responseText);
298 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
299 SUGAR.email2.composeLayout.signatures = ret.signatures;
300 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
302 SUGAR.email2.composeLayout.setComposeOptions(idx);
304 //Set the error array so we can notify the user when they try to hit send if any errors
305 //are present. We will also notify them now (after hitting compose button).
306 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
309 //if error element is returning an array, then check the length to make sure we have error messages
310 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
311 //add error messages for display
312 for(i in ret.errorArray)
313 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
314 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
315 //if error element is returning an object, and the object value is not empty or null, then display error message
316 for(i in ret.errorArray)
317 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
320 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
322 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
324 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
330 handleDeleteSignature : function(o) {
332 var ret = JSON.parse(o.responseText);
333 SUGAR.email2.composeLayout.signatures = ret.signatures;
334 var field = document.getElementById('signature_id');
335 SUGAR.email2.util.emptySelectOptions(field);
337 for(var i in ret.signatures) { // iterate through assoc array
338 var opt = new Option(ret.signatures[i], i);
339 field.options.add(opt);
341 setSigEditButtonVisibility();
346 handleDeleteReturn : function(o) {
347 // force refresh ListView
349 if(document.getElementById('focusEmailMbox')) {
350 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
353 // need to display success message before calling next async call?
354 document.getElementById(this.target).innerHTML = o.responseText;
359 handleFailure : function(o) {
361 overlay('Exception occurred...', o.statusText, 'alert');
364 handleReplyForward : function(o) {
365 var a = JSON.parse(o.responseText);
367 var idx = SUGAR.email2.composeLayout.currentInstanceId;
369 document.getElementById('email_id' + idx).value = a.uid;
370 document.getElementById('emailSubject' + idx).value = a.name;
371 document.getElementById('addressTO' + idx).value = a.from;
372 document.getElementById('uid' + idx).value = a.uid;
374 document.getElementById('addressCC' + idx).value = a.cc;
375 SE.composeLayout.showHiddenAddress('cc', idx);
379 document.getElementById('type' + idx).value = a.type;
382 // apply attachment values
383 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
385 setTimeout("callbackReplyForward.finish(globalA);", 500);
388 handleReplyForwardForDraft : function(o) {
389 var a = JSON.parse(o.responseText);
391 var idx = SUGAR.email2.composeLayout.currentInstanceId;
393 document.getElementById('email_id' + idx).value = a.uid;
394 document.getElementById('emailSubject' + idx).value = a.name;
395 document.getElementById('addressTO' + idx).value = a.to;
398 document.getElementById('addressCC' + idx).value = a.cc;
399 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
403 document.getElementById('addressBCC' + idx).value = a.bcc;
404 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
409 document.getElementById('type' + idx).value = a.type;
413 // apply attachment values
414 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
416 setTimeout("callbackReplyForward.finish(globalA);", 500);
421 handleSuccess : function(o) {
422 document.getElementById(this.target).innerHTML = o.responseText;
428 ieDeleteSuccess : function(o) {
431 var ret = JSON.parse(o.responseText);
433 SUGAR.email2.accounts.refreshInboundAccountTable();
434 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
435 SUGAR.email2.accounts.rebuildFolderList();
441 ieSaveSuccess : function(o) {
442 document.getElementById('saveButton').disabled = false;
443 var a = JSON.parse(o.responseText);
446 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
447 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
449 resp = JSON.parse(o.responseText);
450 SUGAR.email2.accounts.refreshInboundAccountTable();
451 SUGAR.email2.accounts.refreshOuboundAccountTable();
452 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
453 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
457 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
464 loadAttachments : function(o) {
465 var result = JSON.parse(o.responseText);
467 SUGAR.email2.composeLayout.loadAttachments(result);
472 loadSignature : function(o) {
473 var ret = JSON.parse(o.responseText);
474 SUGAR.email2.signatures[ret.id] = ret.signature_html;
475 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
479 * Follow up to mark email read|unread|flagged
481 markEmailCleanup : function(o) {
482 var ret = JSON.parse(o.responseText);
483 if (!ret['status']) {
485 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
487 SUGAR.email2.contextMenus.markEmailCleanup();
493 rebuildShowFolders : function(o) {
494 var t = JSON.parse(o.responseText);
495 var show = document.getElementById('ieAccountListShow');
497 SUGAR.email2.util.emptySelectOptions(show);
499 for(i=0; i<t.length; i++) { // iterate through assoc array
500 var opt = new Option(t[i].text, t[i].value, t[i].selected);
501 opt.selected = t[i].selected;
502 show.options.add(opt);
505 SUGAR.email2.accounts.renderTree();
509 saveListViewSortOrderPart2 : function() {
510 // create the JSON string the func expects
511 focusFolderPath = '[ "Home", "' + ieName + '"';
513 var f = new String(focusFolder);
514 var fEx = f.split('.');
516 for(i=0; i<fEx.length; i++) {
517 focusFolderPath += ', "' + fEx[i] +'"'
520 focusFolderPath += ']';
522 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
523 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
529 sendEmailCleanUp : function(o) {
531 var ret = JSON.parse(o.responseText);
533 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
534 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
535 } else if (o.responseText) {
536 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
539 if (typeof(SE.grid) != 'undefined')
540 SE.listView.refreshGrid();
541 //Disabled while address book is disabled
543 //If this call back was initiated by quick compose from a Detail View page, refresh the
544 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
545 //close the shortcut bar menu
546 if ( (typeof(action_sugar_grp1) != 'undefined')) {
547 if(action_sugar_grp1 == 'DetailView') {
548 showSubPanel('history',null,true);
549 } else if(action_sugar_grp1 == 'quickcreate') {
556 ieSendSuccess : function(o) {
558 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
563 settingsFolderRefresh : function(o) {
564 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
565 var ret = JSON.parse(o.responseText);
566 var user = document.getElementById('userFolders');
568 SUGAR.email2.util.emptySelectOptions(user);
570 for(i=0; i<ret.userFolders.length; i++) {
571 var display = ret.userFolders[i].name;
572 var value = ret.userFolders[i].id;
573 var selected = (ret.userFolders[i].selected != "") ? true : false;
574 var opt = new Option(display, value, selected);
575 opt.selected = selected;
576 user.options.add(opt);
582 startRequest : function(callback, args, forceAbort) {
583 if(this.currentRequestObject != null) {
584 if(this.forceAbort == true) {
585 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
588 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
592 requestInProgress : function() {
593 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
598 updateFolderSubscriptions : function() {
599 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
600 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
606 updateFrameFolder : function() {
607 SUGAR.email2.folders.checkEmailAccounts();
612 updateUserPrefs : function(o) {
613 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
614 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
619 uploadAttachmentSuccessful : function(o) {
621 document.getElementById('email_attachment').value = '';
623 var ret = JSON.parse(o.responseText);
624 var idx = SUGAR.email2.composeLayout.currentInstanceId;
625 var overall = document.getElementById('addedFiles' + idx);
626 var index = overall.childNodes.length;
628 "<div id='email_attachment_bucket" + idx + index + "'>" +
630 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
631 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
632 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
634 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
635 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
637 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
639 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
642 overall.innerHTML += out;
643 if(SUGAR.email2.util.isIe()) {
644 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
648 SUGAR.email2.addFileDialog.hide();
650 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
655 ///////////////////////////////////////////////////////////////////////////
656 //// PER MODULE CALLBACK OBJECTS
657 AjaxObject.accounts = {
658 saveOutboundCleanup : function(o) {
659 SUGAR.email2.accounts.refreshOuboundAccountTable();
660 SUGAR.email2.accounts.outboundDialog.hide();
661 var id = o.responseText;
662 SUGAR.email2.accounts.newAddedOutboundId = id;
664 saveDefaultOutboundCleanup: function(o){
667 callbackEditOutbound : {
668 success : function(o)
670 var ret = JSON.parse(o.responseText);
672 SUGAR.email2.accounts.showAddSmtp();
675 document.getElementById("mail_id").value = ret.id;
676 document.getElementById("type").value = ret.type;
677 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
678 document.getElementById("mail_name").value = ret.name;
679 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
680 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
681 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
682 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
683 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
684 SUGAR.email2.accounts.smtp_authenticate_field_display();
685 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
687 if(ret.type == 'system-override') {
688 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
689 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
692 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
693 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
695 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
698 failure : AjaxObject.handleFailure,
699 timeout : AjaxObject.timeout,
702 callbackDeleteOutbound : {
703 success : function(o) {
704 var ret = JSON.parse(o.responseText);
707 if(confirm(ret.error_message))
709 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
710 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
718 SUGAR.email2.accounts.refreshOuboundAccountTable();
722 failure : AjaxObject.handleFailure,
723 timeout : AjaxObject.timeout,
727 callbackCheckMailProgress : {
728 success : function(o) {
729 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
730 SUGAR.email2.accounts.totalMsgCount = -1;
733 //Check for server timeout / errors
734 var ret = JSON.parse(o.responseText);
737 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
739 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
740 SUGAR.email2.accounts.totalMsgCount = -1;
741 //SUGAR.email2.folders.rebuildFolders();
745 var currIeId = ret['ieid'];
748 var serverCount = ret.count;
750 if (ret['status'] == 'done') {
751 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
752 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
756 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
758 currIeId = SUGAR.email2.accounts.ieIds[i+1];
760 SUGAR.email2.accounts.totalMsgCount = -1;
765 else if (ret.mbox && ret.totalcount && ret.count) {
766 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
767 if (ret.count >= ret.totalcount) {
770 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
771 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
774 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
775 SUGAR.email2.accounts.totalMsgCount = -1;
780 SUGAR.email2.accounts.totalMsgCount = -1;
782 SUGAR.email2.folders.rebuildFolders();
783 SE.listView.refreshGrid();
784 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
785 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
786 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
787 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
789 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
790 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
791 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
792 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
793 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
796 failure : AjaxObject.handleFailure,
797 timeout : AjaxObject.timeout,
802 ///////////////////////////////////////////////////////////////////////////////
804 AjaxObject.composeLayout = {
806 * Populates the record id
808 saveDraftCleanup : function(o) {
810 var ret = JSON.parse(o.responseText);
812 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
813 else if (o.responseText)
814 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
818 AjaxObject.composeLayout.callback = {
820 success : AjaxObject.composeLayout.saveDraftCleanup,
821 failure : AjaxObject.handleFailure,
822 timeout : AjaxObject.timeout,
827 AjaxObject.detailView = {
829 * Pops-up a printable view of an email
831 displayPrintable : function(o) {
832 var ret = JSON.parse(o.responseText);
833 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
834 // 2 below must be in global context
836 meta['panelId'] = SUGAR.email2.util.getPanelId();
837 email = ret.meta.email;
838 if (typeof(email.cc) == 'undefined') {
842 var out = displayTemplate.exec({
843 'app_strings' : app_strings,
851 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
852 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
854 popup.document.write(out);
855 popup.document.close();
859 * Takes formatted response and creates a modal pop-over containing a title and content
861 displayView : function(o) {
862 var SED = SUGAR.email2.detailView;
863 var ret = JSON.parse(o.responseText);
865 if(!SED.viewDialog) {
866 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
870 constraintoviewport: true,
873 SED.viewDialog.renderEvent.subscribe(function() {
874 var content = this.body.firstChild;
875 var viewH = YAHOO.util.Dom.getViewportHeight();
877 this.body.style.overflow = "auto";
878 this.body.style.width = "800px";
879 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
883 SED.viewDialog.setHeader(ret.title);
884 SED.viewDialog.setBody(ret.html);
885 SED.viewDialog.render();
886 SED.viewDialog.show();
890 * Generates a modal popup to populate with the contents of bean's full EditView
892 showQuickCreateForm : function(o) {
893 var SED = SUGAR.email2.detailView;
894 var ret = JSON.parse(o.responseText);
896 if(!SED.quickCreateDialog) {
897 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
901 constraintoviewport: true,
905 SED.quickCreateDialog.renderEvent.subscribe(function() {
906 var viewH = YAHOO.util.Dom.getViewportHeight();
908 for (var i in this.body.childNodes) {
909 if (this.body.childNodes[i].clientHeight) {
910 contH += this.body.childNodes[i].clientHeight;
911 } else if (this.body.childNodes[i].offsetHeight) {
912 contH += this.body.childNodes[i].offsetHeight;
915 this.body.style.width = "800px";
916 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
917 this.body.style.overflow = "auto";
918 }, SED.quickCreateDialog);
920 SED.quickCreateDialog.hideEvent.subscribe(function(){
921 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
922 /*for(var qsField in qsFields){
923 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
924 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
927 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
930 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
932 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
933 SED.quickCreateDialog.render();
934 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
936 SED.quickCreateDialog.ieId = ret.ieId;
937 SED.quickCreateDialog.uid = ret.uid;
938 SED.quickCreateDialog.mbox = ret.mbox;
939 SED.quickCreateDialog.qcmodule = ret.module;
941 SED.quickCreateDialog.show();
943 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
945 editForm.module.value = 'Emails';
946 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
947 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
948 var instId = ret.module + count;
949 SED.quickCreateEmailsToAdd = ret.emailAddress;
950 SED.quickCreateEmailCallback = function(instId, tableId) {
951 var eaw = SUGAR.EmailAddressWidget.instances[instId];
952 if (typeof(eaw) == "undefined")
953 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
954 + instId + "','" + tableId + "');", 100);
955 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
957 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
958 + instId + "','" + tableId + "');", 100);
962 saveQuickCreateForm : function(o) {
964 SUGAR.email2.detailView.quickCreateDialog.hide();
965 validate['EditView'] = [ ];
968 saveQuickCreateFormAndReply : function(o) {
970 var ret = JSON.parse(o.responseText);
971 SUGAR.email2.detailView.quickCreateDialog.hide();
972 var qcd = SUGAR.email2.detailView.quickCreateDialog;
973 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
975 var emailID = ret.id;
976 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
978 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
980 //Cean the validate cache to prevent errors on the next call
981 validate['EditView'] = [ ];
984 saveQuickCreateFormAndAddToAddressBook : function(o) {
986 SUGAR.email2.detailView.quickCreateDialog.hide();
987 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
988 validate['EditView'] = [ ];
991 handleAssignmentDialogAssignAction : function() {
994 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
1000 var found_teams = false;
1001 var warning_message = mod_strings.LBL_WARN_NO_USERS;
1002 if(!found_teams && assign_user_id == '' )
1004 alert(warning_message);
1008 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1010 for(i=0; i<emailUids.length; i++) {
1012 uids += app_strings.LBL_EMAIL_DELIMITER;
1014 uids += emailUids[i];
1017 var row = SUGAR.email2.grid.getSelectedRows()[0];
1018 var data = SUGAR.email2.grid.getRecord(row).getData();
1019 var ieid = data.ieId;
1020 var mbox = data.mbox;
1021 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
1022 SUGAR.email2.contextMenus.assignToDialogue.hide();
1023 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
1027 handleAssignmentDialogDeleteAction : function() {
1028 // TO pass list of UIDS/emailIds
1029 var uids = SUGAR.email2.listView.getUidsFromSelection();
1030 var row = SUGAR.email2.grid.getSelections()[0];
1031 var ieid = row.data.ieId;
1032 var mbox = row.data.mbox;
1033 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
1034 SUGAR.email2.contextMenus.assignmentDialog.hide();
1035 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1041 showEmailDetailView : function(o) {
1043 var SED = SUGAR.email2.detailView;
1044 var ret = JSON.parse(o.responseText);
1046 if(!SED.quickCreateDialog) {
1047 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
1051 constraintoviewport: true,
1053 autofillheight: "body",
1056 SED.quickCreateDialog.renderEvent.subscribe(function() {
1057 var viewHeight = YAHOO.util.Dom.getViewportHeight();
1059 for (var i in this.body.childNodes) {
1060 if (this.body.childNodes[i].offsetHeight)
1061 contH += this.body.childNodes[i].offsetHeight;
1063 this.body.style.overflow = "auto";
1064 this.body.style.width = "800px";
1065 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
1067 }, SED.quickCreateDialog);
1069 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
1070 SED.quickCreateDialog.setBody(ret.html);
1071 SED.quickCreateDialog.render();
1072 SUGAR.util.evalScript(ret.html);
1073 SED.quickCreateDialog.show();
1076 showAssignmentDialogWithData : function(o) {
1077 var SEC = SUGAR.email2.contextMenus;
1079 var ret = JSON.parse(o.responseText);
1080 if (!SEC.assignmentDialog) {
1081 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
1084 constraintoviewport: true,
1087 SEC.assignmentDialog.setBody("");
1088 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
1089 SEC.assignmentDialog.renderEvent.subscribe(function() {
1090 var iev = YAHOO.util.Dom.get("Distribute");
1092 this.body.style.width = "700px";
1094 }, SEC.assignmentDialog);
1095 SEC.assignmentDialog.render();
1097 SEC.assignmentDialog.setBody(ret);
1098 SEC.assignmentDialog.render();
1100 SEC.assignmentDialog.show();
1101 SUGAR.util.evalScript(ret);
1104 showImportForm : function(o) {
1105 var SED = SUGAR.email2.detailView;
1106 var ret = JSON.parse(o.responseText);
1108 document.getElementById('quickCreateContent').innerHTML = "";
1114 if(!SED.importDialog) {
1115 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
1119 constraintoviewport: true,
1121 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
1122 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
1126 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
1127 SED.importDialog.setBody("");
1128 SED.importDialog.hideEvent.subscribe(function(){
1129 for(var i in QSFieldsArray) {
1130 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
1131 QSFieldsArray[i].destroy();
1132 delete QSFieldsArray[i];
1134 if (QSProcessedFieldsArray[i]) {
1135 QSProcessedFieldsArray[i] = false;
1139 SED.importDialog.renderEvent.subscribe(function() {
1140 var iev = YAHOO.util.Dom.get("ImportEditView");
1142 //this.body.style.height = (iev.clientHeight + 10) + "px";
1143 this.body.style.width = "600px";
1145 }, SED.importDialog);
1146 SED.importDialog.render();
1148 SED.importDialog.setBody(ret.html);
1149 SED.importDialog.ret = ret;
1150 SUGAR.util.evalScript(ret.html);
1151 SED.importDialog.render();
1153 SED.importDialog.show();
1154 SED.importDialog.focusFirstButton();
1156 getImportAction : function(ret) {
1157 if (!check_form('ImportEditView')) return false;
1158 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
1159 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
1163 var editView = document.getElementById('ImportEditView');
1164 if (editView.assigned_user_id != null) {
1165 get = get + "&user_id=" + editView.assigned_user_id.value
1166 //var user_id = editView.assigned_user_id.value;
1168 var parent_id = editView.parent_id.value;
1169 var parent_type = editView.parent_type.value;
1170 var row = SUGAR.email2.grid.getSelectedRows()[0];
1171 row = SUGAR.email2.grid.getRecord(row);
1172 var data = row.getData();
1173 var ieId = data.ieId;
1174 var mbox = data.mbox;
1175 var serverDelete = editView.serverDelete.checked;
1176 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1178 for(i=0; i<emailUids.length; i++) {
1180 uids += app_strings.LBL_EMAIL_DELIMITER;
1182 uids += emailUids[i];
1185 var action = 'importEmail&uid=';
1187 action = 'moveEmails';
1188 action = action + '&sourceFolder=' + ret['srcFolder'];
1189 action = action + '&sourceIeId=' + ret['srcIeId'];
1190 action = action + '&destinationFolder=' + ret['dstFolder'];
1191 action = action + '&destinationIeId=' + ret['dstIeId'];
1192 action = action + '&emailUids=';
1194 if (action.search(/importEmail/) != -1) {
1195 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
1197 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
1200 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
1201 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
1202 SUGAR.email2.detailView.importDialog.hide();
1203 document.getElementById('importDialogContent').innerHTML = "";
1206 showRelateForm : function(o) {
1207 var SED = SUGAR.email2.detailView;
1208 var ret = JSON.parse(o.responseText);
1209 document.getElementById('quickCreateContent').innerHTML = "";
1214 dialog_loaded = true;
1216 if(!SED.relateDialog) {
1217 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
1222 constraintoviewport: true,
1224 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
1225 if (!check_form('RelateEditView')) return false;
1227 var editView = document.getElementById('RelateEditView');
1228 var parent_id = editView.parent_id.value;
1229 var parent_type = editView.parent_type.value;
1230 var row = SUGAR.email2.grid.getSelectedRows()[0];
1231 row = SUGAR.email2.grid.getRecord(row);
1232 var ieId = row.getData().ieId;
1233 var mbox = row.getData().mbox;
1234 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1236 for(i=0; i<emailUids.length; i++) {
1238 uids += app_strings.LBL_EMAIL_DELIMITER;
1240 uids += emailUids[i];
1242 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1243 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
1244 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
1245 SED.relateDialog.hide();
1246 document.getElementById('relateDialogContent').innerHTML = "";
1251 SED.relateDialog.hideEvent.subscribe(function(){
1252 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
1253 QSFieldsArray['ImportEditView_parent_name'].destroy();
1254 delete QSFieldsArray['ImportEditView_parent_name'];
1256 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
1257 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
1261 SED.relateDialog.renderEvent.subscribe(function() {
1262 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
1264 for (var i in this.body.childNodes) {
1265 if (this.body.childNodes[i].clientHeight)
1266 contH += this.body.childNodes[i].clientHeight;
1268 }, SED.relateDialog);
1269 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
1272 SED.relateDialog.setBody(ret.html);
1273 SED.relateDialog.render();
1274 SUGAR.util.evalScript(ret.html);
1275 SED.relateDialog.show();
1279 * DetailView callbacks
1281 AjaxObject.detailView.callback = {
1283 success : function(o) {
1285 var ret = JSON.parse(o.responseText);
1286 SUGAR.email2.detailView.consumeMetaDetail(ret);
1288 argument: [targetDiv],
1289 failure : AjaxObject.handleFailure,
1294 success : function(o) {
1296 var ret = JSON.parse(o.responseText);
1297 SUGAR.email2.detailView.consumeMetaPreview(ret);
1299 failure : AjaxObject.handleFailure,
1304 success : AjaxObject.detailView.displayPrintable,
1305 failure : AjaxObject.handleFailure,
1306 timeout : AjaxObject.timeout,
1310 success : AjaxObject.detailView.displayView,
1311 failure : AjaxObject.handleFailure,
1312 timeout : AjaxObject.timeout,
1321 AjaxObject.folders = {
1323 * check-mail post actions
1325 checkMailCleanup : function(o) {
1327 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
1329 // refresh focus ListView
1330 SE.listView.refreshGrid();
1331 SUGAR.email2.folders.startCheckTimer(); // resets the timer
1336 rebuildFolders : function(o) {
1339 var data = JSON.parse(o.responseText);
1341 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
1342 SUGAR.email2.folders.setSugarFolders();
1345 AjaxObject.folders.callback = {
1347 success : AjaxObject.folders.checkMailCleanup,
1348 failure : AjaxObject.handleFailure,
1349 timeout : 600000, // 5 mins
1354 AjaxObject.rules = {
1355 loadRulesForSettings : function(o) {
1356 document.getElementById("rulesListCell").innerHTML = o.responseText;
1357 // assume we have the class we need
1358 SUGAR.routing.getStrings();
1359 SUGAR.routing.getDependentDropdowns();
1362 //// END PER MODULE CALLBACK OBJECTS
1363 ///////////////////////////////////////////////////////////////////////////
1367 success : AjaxObject.handleSuccess,
1368 failure : AjaxObject.handleFailure,
1369 timeout : AjaxObject.timeout,
1372 var callbackAccount = {
1373 success : AjaxObject.ieSaveSuccess,
1374 failure : AjaxObject.handleFailure,
1375 timeout : AjaxObject.timeout,
1378 var callbackAccountDelete = {
1379 success : AjaxObject.ieDeleteSuccess,
1380 failure : AjaxObject.handleFailure,
1381 timeout : AjaxObject.timeout,
1384 var callbackOutboundTest = {
1385 success : AjaxObject.ieSendSuccess,
1386 failure : AjaxObject.handleFailure,
1387 timeout : AjaxObject.timeout,
1393 var callbackTeamInfoForSettings = {
1394 success : function (o) {
1395 var data = JSON.parse(o.responseText);
1396 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
1398 failure : AjaxObject.handleFailure,
1399 timeout : AjaxObject.timeout,
1404 var callbackStatusForImport = {
1405 success : function (o) {
1407 if (o.responseText != "") {
1408 var statusString = "";
1409 var data = JSON.parse(o.responseText);
1410 for(i=0; i<data.length; i++) {
1411 statusString = statusString + data[i] + '<br/>';
1413 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
1415 SE.listView.refreshGrid();
1418 failure : AjaxObject.handleFailure,
1419 timeout : AjaxObject.timeout,
1423 var callbackComposeCache = {
1424 success : AjaxObject.composeCache,
1425 failure : AjaxObject.handleFailure,
1426 timeout : AjaxObject.timeout,
1429 var callbackDelete = {
1430 success : AjaxObject.handleDeleteReturn,
1431 failure : AjaxObject.handleFailure,
1432 timeout : AjaxObject.timeout,
1435 var callbackEmailDetailMultiple = {
1436 success : function(o) {
1438 var retMulti = JSON.parse(o.responseText);
1439 var ret = new Object();
1441 for(var i=0; i<retMulti.length; i++) {
1444 SUGAR.email2._setDetailCache(ret);
1445 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
1448 failure : AjaxObject.handleFailure,
1452 var callbackListViewSortOrderChange = {
1453 success : AjaxObject.saveListViewSortOrderPart2,
1454 failure : AjaxObject.handleFailure,
1455 timeout : AjaxObject.timeout,
1457 argument : [ieId, ieName, focusFolder]
1459 var callbackEmptyTrash = {
1460 success : function(o) {
1462 AjaxObject.folderRenameCleanup;
1464 failure : AjaxObject.handleFailure,
1465 timeout : AjaxObject.timeout,
1468 var callbackClearCacheFiles = {
1469 success : function(o) {
1472 failure : AjaxObject.handleFailure,
1473 timeout : AjaxObject.timeout,
1476 var callbackFolderRename = {
1477 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
1478 failure : AjaxObject.handleFailure,
1479 timeout : AjaxObject.timeout,
1482 var callbackFolderDelete = {
1483 success : function(o) {
1484 var ret = JSON.parse(o.responseText);
1486 if (ret.folder_id) {
1487 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
1489 SUGAR.email2.tree.removeNode(node, true);
1490 } else if (ret.ieId && ret.mbox) {
1491 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
1493 SUGAR.email2.tree.removeNode(node, true);
1496 //SUGAR.email2.folders.loadSettingFolder();
1499 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
1502 failure : AjaxObject.handleFailure,
1503 timeout : AjaxObject.timeout,
1506 var callbackFolderSave = {
1507 success : function(o) {
1508 var ret = JSON.parse(o.responseText);
1510 switch(ret.action) {
1511 case 'newFolderSave':
1512 SUGAR.email2.folders.rebuildFolders();
1516 failure : AjaxObject.handleFailure,
1517 timeout : AjaxObject.timeout,
1520 var callbackFolderSubscriptions = {
1521 success : AjaxObject.updateFolderSubscriptions,
1522 failure : AjaxObject.handleFailure,
1523 timeout : AjaxObject.timeout,
1526 var callbackFolderUpdate = {
1527 success : AjaxObject.updateFrameFolder,
1528 failure : AjaxObject.handleFailure,
1529 timeout : AjaxObject.timeout,
1532 var callbackFolders = {
1533 success : AjaxObject.folders.rebuildFolders,
1534 //success : void(true),
1535 failure : AjaxObject.handleFailure,
1536 timeout : AjaxObject.timeout,
1539 var callbackFullSync = {
1540 success : AjaxObject.fullSyncCleanup,
1541 failure : AjaxObject.handleFailure,
1542 timeout : 9999999999999,
1545 var callbackGeneric = {
1546 success : function() {
1549 failure : AjaxObject.handleFailure,
1550 timeout : AjaxObject.timeout,
1553 var callbackIeAccountRetrieve = {
1554 success : function(o) {
1555 // return JSON encoding
1557 SUGAR.email2.accounts.fillIeAccount(o.responseText);
1558 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
1560 failure : AjaxObject.handleFailure,
1561 timeout : AjaxObject.timeout,
1564 var callbackImportOneEmail = {
1565 success : AjaxObject.detailView.showImportForm,
1566 failure : AjaxObject.handleFailure,
1567 timeout : AjaxObject.timeout,
1570 var callbackRelateEmail = {
1571 success : AjaxObject.detailView.showRelateForm,
1572 failure : AjaxObject.handleFailure,
1573 timeout : AjaxObject.timeout,
1576 var callbackEmailDetailView = {
1577 success : AjaxObject.detailView.showEmailDetailView,
1578 failure : AjaxObject.handleFailure,
1579 timeout : AjaxObject.timeout,
1582 var callbackAssignmentDialog = {
1583 success : AjaxObject.detailView.showAssignmentDialogWithData,
1584 failure : AjaxObject.handleFailure,
1585 timeout : AjaxObject.timeout,
1588 var callbackAssignmentAction = {
1589 success : function(o) {
1590 SE.listView.refreshGrid();
1592 if(o.responseText != '') {
1593 overlay('Assignment action result', o.responseText, 'alert');
1596 failure : AjaxObject.handleFailure,
1597 timeout : AjaxObject.timeout,
1600 var callbackMoveEmails = {
1601 success : function(o) {
1602 SE.listView.refreshGrid();
1604 if(o.responseText != '') {
1605 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
1608 failure : AjaxObject.handleFailure,
1609 timeout : AjaxObject.timeout,
1612 var callbackLoadAttachments = {
1613 success : AjaxObject.loadAttachments,
1614 failure : AjaxObject.handleFailure,
1615 timeout : AjaxObject.timeout,
1618 var callbackLoadRules = {
1619 success : AjaxObject.rules.loadRulesForSettings,
1620 failure : AjaxObject.handleFailure,
1621 timeout : AjaxObject.timeout,
1624 var callbackLoadSignature = {
1625 success : AjaxObject.loadSignature,
1626 failure : AjaxObject.handleFailure,
1627 timeout : AjaxObject.timeout,
1630 var callbackDeleteSignature = {
1631 success : AjaxObject.handleDeleteSignature,
1632 failure : AjaxObject.handleFailure,
1633 timeout : AjaxObject.timeout,
1636 /*var callbackMoveEmails = {
1637 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
1638 failure : AjaxObject.handleFailure,
1639 timeout : AjaxObject.timeout,
1642 var callbackOutboundSave = {
1643 success : AjaxObject.accounts.saveOutboundCleanup,
1644 failure : AjaxObject.handleFailure,
1645 timeout : AjaxObject.timeout,
1648 var callbackDefaultOutboundSave = {
1649 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
1650 failure : AjaxObject.handleFailure,
1651 timeout : AjaxObject.timeout,
1654 var callbackQuickCreate = {
1655 success : AjaxObject.detailView.showQuickCreateForm,
1656 failure : AjaxObject.handleFailure,
1657 timeout : AjaxObject.timeout,
1660 var callbackQuickCreateSave = {
1661 success : AjaxObject.detailView.saveQuickCreateForm,
1662 failure : AjaxObject.handleFailure,
1663 timeout : AjaxObject.timeout,
1666 var callbackQuickCreateSaveAndAddToAddressBook = {
1667 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
1668 failure : AjaxObject.handleFailure,
1669 timeout : AjaxObject.timeout,
1672 var callbackQuickCreateSaveAndReply = {
1673 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
1674 failure : AjaxObject.handleFailure,
1675 timeout : AjaxObject.timeout,
1678 var callbackQuickCreateSaveAndReplyCase = {
1679 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
1680 failure : AjaxObject.handleFailure,
1681 timeout : AjaxObject.timeout,
1684 var callbackRebuildShowAccountList = {
1685 success : AjaxObject.rebuildShowFolders,
1686 failure : AjaxObject.handleFailure,
1687 timeout : AjaxObject.timeout,
1691 var callbackRefreshSugarFolders = {
1692 success : function(o) {
1693 var t = JSON.parse(o.responseText);
1694 SUGAR.email2.folders.setSugarFoldersEnd(t);
1696 failure : AjaxObject.handleFailure,
1697 timeout : AjaxObject.timeout,
1700 var callbackReplyForward = {
1701 success : AjaxObject.handleReplyForward,
1702 finish : function(a, retryCount) {
1703 if (typeof(retryCount) == 'undefined') {
1708 var idx = SUGAR.email2.composeLayout.currentInstanceId;
1709 var t = tinyMCE.getInstanceById('htmleditor' + idx);
1711 var html = t.getContent();
1713 if (a.type != 'draft') {
1714 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
1715 html += " <div><hr></div>" + a.description;
1717 html = " <div><hr></div>" + a.description + html;
1720 html = a.description;
1723 t.setContent(html);//
1726 if (retryCount < 5) {
1727 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
1731 var tabArray = SUGAR.email2.innerLayout.get("tabs");
1732 if (tabArray != null && tabArray.length > 0) {
1733 for (i = 0 ; i < tabArray.length ; i++) {
1734 var tabObject = tabArray[i];
1735 if (tabObject.get("id") == ("composeTab" + idx)) {
1736 var tabLabel = a.name;
1737 if (tabLabel != null && tabLabel.length > 25) {
1738 tabLabel = tabLabel.substring(0, 25) + "...";
1740 tabObject.get("labelEl").firstChild.data = tabLabel;
1746 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
1747 if (a.parent_name != null && a.parent_name != "") {
1748 document.getElementById('data_parent_name' + idx).value = a.parent_name;
1750 if (a.parent_type != null && a.parent_type != "") {
1751 document.getElementById('data_parent_type' + idx).value = a.parent_type;
1753 if (a.parent_id != null && a.parent_id != "") {
1754 document.getElementById('data_parent_id' + idx).value = a.parent_id;
1756 if (a.fromAccounts.status) {
1757 var addressFrom = document.getElementById('addressFrom' + idx);
1758 SUGAR.email2.util.emptySelectOptions(addressFrom);
1759 var fromAccountOpts = a.fromAccounts.data;
1760 for(i=0; i<fromAccountOpts.length; i++) {
1761 var key = fromAccountOpts[i].value;
1762 var display = fromAccountOpts[i].text;
1763 var opt = new Option(display, key);
1764 if (fromAccountOpts[i].selected) {
1765 opt.selected = true;
1767 addressFrom.options.add(opt);
1773 failure : AjaxObject.handleFailure,
1774 timeout : AjaxObject.timeout,
1776 argument : [sendType]
1778 var callbackSendEmail = {
1779 success : AjaxObject.sendEmailCleanUp,
1780 failure : AjaxObject.handleFailure,
1781 timeout : AjaxObject.timeout,
1784 var callbackSettings = {
1785 success : AjaxObject.updateUserPrefs,
1786 failure : AjaxObject.handleFailure,
1787 timeout : AjaxObject.timeout,
1790 var callbackSettingsFolderRefresh = {
1791 success : AjaxObject.settingsFolderRefresh,
1792 failure : AjaxObject.handleFailure,
1793 timeout : AjaxObject.timeout,
1796 var callbackLoadSettingFolder = {
1797 success : function(o) {
1798 AjaxObject.settingsFolderRefresh(o);
1799 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
1801 failure : AjaxObject.handleFailure,
1802 timeout : AjaxObject.timeout,
1806 var callbackUploadAttachment = {
1807 success : AjaxObject.uploadAttachmentSuccessful,
1808 upload : AjaxObject.uploadAttachmentSuccessful,
1809 failure : AjaxObject.handleFailure,
1810 timeout : AjaxObject.timeout,
1813 var callbackUserPrefs = {
1814 success : function(o) {
1815 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
1817 failure : AjaxObject.handleFailure,
1818 timeout : AjaxObject.timeout,
1822 var callbackContextmenus = {
1824 success : AjaxObject.markEmailCleanup,
1825 failure : AjaxObject.handleFailure,
1826 timeout : AjaxObject.timeout,
1831 var callbackCheckEmail2 = {
1832 success : function(o) {
1833 var ret = JSON.parse(o.responseText);
1834 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
1838 failure : AjaxObject.handleFailure,
1839 timeout : AjaxObject.timeout,
1841 }// End of File modules/Emails/javascript/ajax.js
1843 /*********************************************************************************
1844 * SugarCRM is a customer relationship management program developed by
1845 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
1847 * This program is free software; you can redistribute it and/or modify it under
1848 * the terms of the GNU Affero General Public License version 3 as published by the
1849 * Free Software Foundation with the addition of the following permission added
1850 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
1851 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
1852 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
1854 * This program is distributed in the hope that it will be useful, but WITHOUT
1855 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1856 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
1859 * You should have received a copy of the GNU Affero General Public License along with
1860 * this program; if not, see http://www.gnu.org/licenses or write to the Free
1861 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
1864 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
1865 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
1867 * The interactive user interfaces in modified source and object code versions
1868 * of this program must display Appropriate Legal Notices, as required under
1869 * Section 5 of the GNU Affero General Public License version 3.
1871 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
1872 * these Appropriate Legal Notices must retain the display of the "Powered by
1873 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
1874 * technical reasons, the Appropriate Legal Notices must display the words
1875 * "Powered by SugarCRM".
1876 ********************************************************************************/
1878 function gridInit() {
1879 if(SUGAR.email2.grid) {
1880 SUGAR.email2.grid.destroy();
1886 var Ck = YAHOO.util.Cookie;
1887 var widths = [ 10, 10, 150, 250, 175, 125 ];
1889 if (Ck.get("EmailGridWidths")) {
1890 for (var i=0; i < widths.length; i++) {
1891 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
1894 for (var i=0; i < widths.length; i++) {
1895 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
1899 // changes "F" to an icon
1900 function flaggedIcon(cell, record, column, value) {
1902 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
1905 // changes "A" to replied icon
1906 function repliedIcon(cell, record, column, value) {
1908 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
1911 function attachIcon(cell, record, column, value) {
1913 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
1920 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
1925 formatter: attachIcon,
1929 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
1934 formatter: flaggedIcon,
1938 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
1943 formatter: repliedIcon,
1947 label: app_strings.LBL_EMAIL_FROM,
1954 label: app_strings.LBL_EMAIL_SUBJECT,
1961 label: mod_strings.LBL_LIST_DATE,
1968 label: app_strings.LBL_EMAIL_TO,
2004 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2005 responseType: YAHOO.util.DataSource.TYPE_JSON,
2007 resultsList: 'Email',
2008 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
2009 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
2015 action : "EmailUIAjax",
2016 emailUIAction : "getMessageList",
2019 forceRefresh : "false"
2021 if(lazyLoadFolder != null) {
2022 params['mbox'] = lazyLoadFolder.folder;
2023 params['ieId'] = lazyLoadFolder.ieId;
2024 //Check if the folder is a Sugar Folder
2025 var test = new String(lazyLoadFolder.folder);
2026 if(test.match(/SUGAR\./)) {
2027 params['emailUIAction'] = 'getMessageListSugarFolders';
2028 params['mbox'] = test.substr(6);
2031 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
2034 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
2035 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2037 paginator: new YAHOO.widget.Paginator({
2038 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
2039 containers : ["dt-pag-nav"],
2040 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2041 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2042 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2043 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2044 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2046 initialRequest:SUGAR.util.paramsToUrl(params),
2053 //Override Paging request construction
2054 grid.set("generateRequest", function(oState, oSelf) {
2055 oState = oState || {pagination:null, sortedBy:null};
2056 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
2057 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2058 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2059 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2060 // Build the request
2062 SUGAR.util.paramsToUrl(oSelf.params) +
2065 "&start=" + startIndex +
2066 ((results !== null) ? "&limit=" + results : "");
2071 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2072 oPayload = oPayload || { };
2074 oPayload.totalRecords = oResponse.meta.total;
2075 oPayload.unreadRecords = oResponse.meta.unread;
2077 var tabObject = SE.innerLayout.get("tabs")[0];
2079 if (this.params.mbox != null) {
2080 mboxTitle = this.params.mbox;
2082 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
2083 tabObject.get("labelEl").firstChild.data = tabtext;
2086 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
2088 node.data.unseen = oResponse.meta.unread;
2089 SE.accounts.renderTree();
2095 var resize = grid.resizeGrid = function () {
2096 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
2097 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
2099 grid.convertDDRows = function() {
2100 var rowEl = this.getFirstTrEl();
2101 while (rowEl != null) {
2102 new this.DDRow(this, this.getRecord(rowEl), rowEl);
2103 rowEl = this.getNextTrEl(rowEl);
2108 grid.on("columnResizeEvent", function(o) {
2109 //Find the index of the column
2110 var colSet = SUGAR.email2.grid.getColumnSet().flat;
2111 for (var i=0; i < colSet.length; i++) {
2112 if (o.column == colSet[i]) {
2113 //Store it in the cookie
2114 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
2117 //this.resizeGrid();
2120 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
2121 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
2122 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
2124 SUGAR.email2.listViewLayout.on("render", resize);
2127 //Setup the default load parameters
2128 SUGAR.email2.grid.params = params;
2130 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
2131 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2132 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2139 function initRowDD() {
2140 var sg = SUGAR.email2.grid,
2141 Dom = YAHOO.util.Dom;
2142 sg.DDRow = function(oDataTable, oRecord, elTr) {
2143 if(oDataTable && oRecord && elTr) {
2144 this.ddtable = oDataTable;
2145 this.table = oDataTable.getTableEl();
2148 this.newIndex = null;
2150 this.initFrame(); // Needed for DDProxy
2151 this.invalidHandleTypes = {};
2155 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
2156 _resizeProxy: function() {
2157 this.constructor.superclass._resizeProxy.apply(this, arguments);
2158 var dragEl = this.getDragEl(),
2160 var xy = Dom.getXY(el);
2162 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
2163 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
2164 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
2165 Dom.setStyle(dragEl, 'display', "");
2168 startDrag: function(x, y) {
2169 //Check if we should be dragging a set of rows rather than just the one.
2170 var selectedRows = this.ddtable.getSelectedRows();
2171 var iSelected = false;
2172 for (var i in selectedRows) {
2173 if (this.rowEl.id == selectedRows[i]) {
2180 for (var i in selectedRows) {
2181 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
2184 this.rows = [this.row];
2185 this.ddtable.unselectAllRows();
2186 this.ddtable.selectRow(this.row);
2189 //Initialize the dragable proxy
2190 var dragEl = this.getDragEl();
2191 var clickEl = this.getEl();
2192 Dom.setStyle(clickEl, "opacity", "0.25");
2193 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
2194 Dom.addClass(dragEl, "yui-dt-liner");
2195 Dom.setStyle(dragEl, "opacity", "0.5");
2196 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
2197 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
2198 Dom.setStyle(dragEl, "border", "2px solid gray");
2201 clickValidator: function(e) {
2202 if (this.row.getData()[0] == " ")
2204 var target = YAHOO.util.Event.getTarget(e);
2205 return ( this.isValidHandleChild(target) &&
2206 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
2209 * This funciton checks that the target of the drag is a table row in this
2210 * DDGroup and simply moves the sourceEL to that location as a preview.
2212 onDragOver: function(ev, id) {
2213 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
2214 if (node && node != this.targetNode) {
2215 this.targetNode = node;
2216 SUGAR.email2.folders.unhighliteAll();
2221 onDragOut: function(e, id) {
2222 if (this.targetNode) {
2223 SUGAR.email2.folders.unhighliteAll();
2224 this.targetNode = false;
2227 endDrag: function() {
2228 Dom.setStyle(this.getEl(), "opacity", "");
2229 Dom.setStyle(this.getDragEl(), "display", "none");
2230 if (this.targetNode) {
2231 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
2233 SUGAR.email2.folders.unhighliteAll();
2239 function AddressSearchGridInit() {
2240 function moduleIcon(elCell, oRecord, oColumn, oData) {
2241 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
2243 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
2244 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
2246 var checkHeader = '<input type="checkbox" ';
2247 if (SUGAR.email2.util.isIe()) {
2248 checkHeader += 'style="top:-5px" ';
2250 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
2255 formatter: selectionCheckBox,
2259 label: mod_strings.LBL_LIST_TYPE,
2261 formatter: moduleIcon,
2265 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
2271 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
2277 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2278 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
2280 resultsList: 'Person',
2281 fields: ['name', 'email', 'bean_id', 'bean_module'],
2282 metaFields: {total: 'TotalCount'}
2284 //enable sorting on the server accross all data
2287 dataModel.params = {
2290 action : "EmailUIAjax",
2291 emailUIAction:"getAddressSearchResults"
2293 var rb = document.getElementById('hasRelatedBean').checked;
2295 var idx = SUGAR.email2.composeLayout.currentInstanceId;
2296 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2297 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2298 dataModel.params['related_bean_id'] = relatedBeanId;
2299 dataModel.params['related_bean_type'] = relatedBeanType;
2300 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
2302 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
2304 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
2305 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2307 paginator: new YAHOO.widget.Paginator({
2309 containers : ["dt-pag-nav-addressbook"],
2310 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2311 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2312 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2313 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2314 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2316 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
2320 //Override Paging request construction
2321 grid.set("generateRequest", function(oState, oSelf) {
2322 oState = oState || {pagination:null, sortedBy:null};
2323 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
2324 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2325 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2326 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2327 // Build the request
2329 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
2330 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
2331 ((results !== null) ? "&limit=" + results : "");
2335 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2336 oPayload = oPayload || { };
2337 oPayload.totalRecords = oResponse.meta.total;
2341 grid.clickToggleSelect= function(args) {
2342 var isIE = (args.event.target == null);
2343 var targetElement = isIE ? args.event.srcElement : args.event.target;
2344 if(targetElement.type == null || targetElement.type != 'checkbox') {
2345 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
2349 grid.reSelectRowsOnRender = function (){
2350 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2351 for (var i = 0; i < rows.length; i++)
2353 var emailAddress = rows[i].getData("email");
2354 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
2357 rows[i].setData("selected", true);
2358 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2362 rows[i].setData("selected", false);
2363 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
2367 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
2368 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
2369 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
2370 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
2373 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2374 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2376 grid.toggleSelectCheckbox = function(id,checked){
2377 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2378 row.setData("checked",checked);
2380 grid.toggleSelect = function(id, checked) {
2381 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2382 checked = row.getData("selected");
2385 SUGAR.email2.addressBook.grid.selectRow(row);
2386 SE.addressBook.insertContactRowToResultTable(id,null)
2389 SUGAR.email2.addressBook.grid.unselectRow(row);
2390 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
2392 row.setData("selected", !checked);
2395 grid.toggleSelectAll = function(checked) {
2396 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2397 for (var i = 0; i < rows.length; i++) {
2398 if (typeof(rows[i]) != "undefined")
2399 rows[i].setData("checked", checked);
2401 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2402 for (var i = 0; i < checkBoxes.length; i++) {
2403 checkBoxes[i].checked = checked;
2407 //Initialize the grid result table.
2408 AddressSearchResultsGridInit();
2414 * Initalize the results table for the address book selection.
2417 function AddressSearchResultsGridInit()
2420 /* Full name sort funciton to compare by last name if available */
2421 var fullNameSort = function(a, b, desc) {
2422 // Deal with empty values
2423 if(!YAHOO.lang.isValue(a))
2424 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
2425 else if(!YAHOO.lang.isValue(b))
2428 var aNames = a.getData("name").split(' ');
2429 var bNames = b.getData("name").split(' ');
2431 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
2432 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
2434 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
2438 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
2439 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
2440 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
2442 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})},
2443 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
2445 var myDataSource = new YAHOO.util.DataSource([]);
2446 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
2447 myDataSource.responseSchema = {
2448 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
2451 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
2452 width: "350px",height: "250px", MSG_EMPTY: " "});
2454 var highlightEditableCell = function(oArgs) {
2455 var elCell = oArgs.target;
2456 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
2457 this.highlightCell(elCell);
2461 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
2462 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
2463 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
2464 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
2465 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
2467 //Setup the context menus
2468 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
2469 var task = p_aArgs[1];
2472 var elRow = this.contextEventTarget;
2473 elRow = p_myDataTable.getTrEl(elRow);
2480 var oRecord = p_myDataTable.getRecord(elRow);
2481 p_myDataTable.deleteRow(elRow);
2482 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2487 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
2488 {trigger:gridResults.getTbodyEl()});
2489 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
2490 contextMenu.render("addrSearchResultGrid");
2491 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
2493 // End of File modules/Emails/javascript/grid.js
2495 /*********************************************************************************
2496 * SugarCRM is a customer relationship management program developed by
2497 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
2499 * This program is free software; you can redistribute it and/or modify it under
2500 * the terms of the GNU Affero General Public License version 3 as published by the
2501 * Free Software Foundation with the addition of the following permission added
2502 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
2503 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
2504 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
2506 * This program is distributed in the hope that it will be useful, but WITHOUT
2507 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
2508 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
2511 * You should have received a copy of the GNU Affero General Public License along with
2512 * this program; if not, see http://www.gnu.org/licenses or write to the Free
2513 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
2516 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
2517 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
2519 * The interactive user interfaces in modified source and object code versions
2520 * of this program must display Appropriate Legal Notices, as required under
2521 * Section 5 of the GNU Affero General Public License version 3.
2523 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
2524 * these Appropriate Legal Notices must retain the display of the "Powered by
2525 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
2526 * technical reasons, the Appropriate Legal Notices must display the words
2527 * "Powered by SugarCRM".
2528 ********************************************************************************/
2531 var sw = YAHOO.SUGAR,
2532 Event = YAHOO.util.Event,
2533 Connect = YAHOO.util.Connect,
2534 Dom = YAHOO.util.Dom
2537 ///////////////////////////////////////////////////////////////////////////////
2540 _contactCache : new Array(), // cache of contacts
2541 _dd : new Array(), // filtered list, same format as _contactCache
2542 _ddLists : new Array(), // list of Lists
2543 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
2544 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
2545 clickBubble : true, // hack to get around onclick event bubbling
2547 relatedBeanType : '',
2550 itemSpacing : 'white-space:nowrap; padding:2px;',
2556 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
2558 initFixForDatatableSort: function () {
2559 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
2560 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
2561 var oColumn = this._oColumnSet.getColumn(column);
2564 // Validate TD element
2565 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
2567 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
2569 // Validate TH element
2571 elCell = this.getThEl(column);
2574 var allColumns = this._oColumnSet.flat;
2575 for(var i=0, len=allColumns.length; i<len; i++) {
2576 if(allColumns[i].getThEl().id === elCell.id) {
2577 oColumn = allColumns[i];
2588 cancelEdit : function() {
2589 if(this.editContactDialog)
2590 this.editContactDialog.hide();
2591 if(this.editMailingListDialog)
2592 this.editMailingListDialog.hide();
2596 * Clears filter form
2598 clear : function() {
2599 var t = document.getElementById('contactsFilter');
2605 * handle context-menu Compose-to call
2606 * @param string type 'contacts' or 'lists'
2608 composeTo : function(type, waited) {
2609 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
2610 if (activePanel.substring(0, 10) != "composeTab") {
2611 SE.composeLayout.c0_composeNewEmail();
2612 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
2613 SE.contextMenus.contactsContextMenu.hide();
2616 var idx = activePanel.substring(10);
2619 // determine if we have a selection to work with
2620 if(type == 'contacts') {
2621 var ids = SE.contactView.getSelectedRows();
2622 for (var i in ids) {
2623 rows[i] = SE.contactView.getRecord(ids[i]);
2625 removeHiddenNodes(rows, SE.contactView);
2629 if(rows.length > 0) {
2630 SE.composeLayout.handleDrop(
2631 (type == 'contacts') ? SE.contactView : SE.emailListsView,
2632 null, rows, 'addressTO' + idx );
2634 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
2638 editContact : function() {
2639 SE.contextMenus.contactsContextMenu.hide();
2640 var element = SE.contactView.getSelectedNodes()[0];
2642 if (element.className.indexOf('address-contact') > -1) {
2643 elementId = element.id;
2644 } else if (element.className.indexOf('address-exp-contact') > -1) {
2645 elementId = element.id.substring(2);
2651 * Filters contact entries based on user input
2653 filter : function(inputEl) {
2654 var ret = new Object();
2655 var re = new RegExp(inputEl.value, "gi");
2657 for(var i in this._contactCache) {
2658 if(this._contactCache[i].name.match(re)) {
2659 ret[i] = this._contactCache[i];
2663 this.buildContactList(ret);
2666 fullForm : function(id, module) {
2667 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
2671 * returns a formatted email address from the addressBook cache
2673 getFormattedAddress : function(id) {
2674 var o = this._contactCache[id];
2675 var primaryEmail = '';
2677 for(var i=0; i<o.email.length; i++) {
2678 var currentEmail = o.email[i].email_address;
2680 if(o.email[i].primary_address == 1) {
2681 primaryEmail = o.email[i].email_address;
2685 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
2686 var name = new String(o.name);
2687 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
2688 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
2694 * Sets up async call to query for matching contacts, users, etc.
2696 searchContacts : function() {
2697 var fn = document.getElementById('input_searchField').value;
2698 var pe = document.getElementById('input_searchPerson').value;
2700 var rb = document.getElementById('hasRelatedBean').checked;
2703 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2704 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2705 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2706 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2708 this.addressBookDataModel.params['related_bean_id'] = '';
2711 this.addressBookDataModel.params['search_field'] = fn;
2712 this.addressBookDataModel.params['person'] = pe;
2713 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
2714 this.grid._oDataSource = this.addressBookDataModel;
2715 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
2719 * Clear Search Crieteria For Addressbook
2721 clearAddressBookSearch : function() {
2722 document.getElementById('input_searchField').value = "";
2723 document.getElementById('input_searchPerson').selectedIndex = 0;
2727 * Opens modal select window to add contacts to addressbook
2729 selectContactsDialogue : function(destId) {
2730 if(!this.contactsDialogue) {
2731 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
2735 constraintoviewport: true,
2737 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
2738 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
2740 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
2742 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
2743 dlg.setBody(body.innerHTML);
2744 dlg.renderEvent.subscribe(function() {
2745 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
2746 if (iev && !SUGAR.isIE) {
2747 this.body.style.width = "950px";
2752 dlg.beforeRenderEvent.subscribe(function() {
2753 var dd = new YAHOO.util.DDProxy(dlg.element);
2754 dd.setHandleElId(dlg.header);
2755 dd.on('endDragEvent', function() {
2761 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
2763 var tabContent = SUGAR.util.getAndRemove("searchForm");
2764 tp.addTab(new YAHOO.widget.Tab({
2765 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
2767 content : tabContent.innerHTML,
2768 id : "addressSearchTab",
2772 var addListenerFields = ['input_searchPerson','input_searchField' ]
2773 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
2774 if (e.keyCode == 13) {
2775 YAHOO.util.Event.stopEvent(e);
2776 SUGAR.email2.addressBook.searchContacts();
2780 this.contactsDialogue.render();
2783 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
2784 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
2788 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
2789 var idx = activePanel.substring(10);
2791 SE.addressBook.idx = idx;
2794 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
2795 document.getElementById('relatedBeanColumn').style.display = '';
2796 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
2797 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2798 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2799 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
2800 SE.addressBook.relatedBeanType = relatedBeanType;
2802 document.getElementById('relatedBeanColumn').style.display = 'none';
2803 document.getElementById('hasRelatedBean').checked = false;
2806 if (!SE.addressBook.grid)
2808 if (hasRelatedBeanId) {
2809 document.getElementById('hasRelatedBean').checked = true;
2811 AddressSearchGridInit();
2812 SE.addressBook.relatedBeanId = relatedBeanId;
2816 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
2818 SE.addressBook.relatedBeanId = relatedBeanId;
2819 document.getElementById('hasRelatedBean').checked = true;
2821 if (document.getElementById('hasRelatedBean').checked == true)
2823 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2824 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2826 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
2827 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
2829 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
2830 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
2831 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
2834 //Remove any lingering rows in the result set table if the module was closed.
2835 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2837 SE.addressBook.populateResulstTableEmailAddresses();
2839 this.contactsDialogue.show();
2842 * Clear all email addresses from result table.
2845 clearAllEmailAddressFieldsFromResultTable: function () {
2846 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2847 //Unhighlight any rows currently selected if the emails were cleared.
2848 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
2849 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2852 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
2853 * results table. This function is called when the address book is displayed.
2855 populateResulstTableEmailAddresses: function () {
2857 var idx = SE.addressBook.idx;
2858 var emailFields = ['to','cc','bcc'];
2860 for(var k=0;k<emailFields.length;k++)
2862 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2863 var allEmails = document.getElementById(elKey).value;
2867 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
2869 for (var i=0; i<formatedEmails.length; i++)
2871 var t_name = formatedEmails[i].name;
2872 var t_emailAddr = formatedEmails[i].email_address;
2873 var displayEmail = t_name + ' <' + t_emailAddr + '>';
2875 t_name = displayEmail = t_emailAddr;
2877 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
2878 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
2879 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
2885 * Checks all entries in the result table against a particular email address, returning true
2886 * if the email address is found, false otherwise.
2888 doesEmailAdddressExistInResultTable: function(emailAddress)
2890 if(trim(emailAddress) == '')
2893 var emailAddressFound = false;
2894 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2895 for (var i=0; i < contacts.length; i++)
2897 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2898 //If we are adding to cc or bcc fields, make them visible.
2899 if(data.email_address == emailAddress)
2901 emailAddressFound = true;
2906 return emailAddressFound;
2909 * Takes all email addresses that the users wishes to add from the address book and populates the To
2910 * fields on the compose tab.
2912 populateEmailAddressFieldsFromResultTable: function()
2914 //Clear the fields first, all email addresses are stored in the address book
2915 var idx = SE.addressBook.idx;
2916 var emailFields = ['to','cc','bcc'];
2917 for(var k=0;k<emailFields.length;k++)
2919 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2920 document.getElementById(elKey).value = "";
2923 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2924 for (var i=0; i < contacts.length; i++)
2926 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2928 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
2929 //If we are adding to cc or bcc fields, make them visible.
2930 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
2931 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
2932 //Construct the target id
2933 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
2935 var target = document.getElementById(target_id);
2936 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
2939 //Delete all rows from the result set table
2940 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2943 SE.addressBook.contactsDialogue.hide()
2946 * Insert contacts into the result table.
2948 insertContactToResultTable : function(event,address_type) {
2950 var contactsDialogue = SE.addressBook.contactsDialogue;
2951 var contacts = SE.addressBook.grid.getSelectedRows();
2953 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2954 for (var i = 0; i < rows.length; i++)
2956 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
2958 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
2959 SE.addressBook.insertContactRowToResultTable(recId,address_type);
2960 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2961 rows[i].setData("selected",true);
2964 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2965 for (var i = 0; i < checkBoxes.length; i++) {
2966 checkBoxes[i].checked = false;
2972 insertContactRowToResultTable : function(rowId, addressType) {
2973 var data = SE.addressBook.grid.getRecord(rowId).getData();
2974 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
2976 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
2977 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
2978 if(addressType == null)
2979 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
2980 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});
2983 * Remove a row from the gridsResult table.
2985 removeRowFromGridResults : function(rowId,emailAddress)
2987 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2988 for (var i=0; i < contacts.length; i++)
2990 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
2991 var data = rec.getData();
2992 if(data.email_address == emailAddress)
2994 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
2999 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
3002 * Translates between the addressType To|Cc|Bcc labels/keys.
3004 translateAddresType: function(addressType,fromKey)
3006 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
3007 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
3008 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
3009 var mappingObject = {};
3012 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
3015 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
3016 mappingObject[displayCc] = 'cc';
3017 mappingObject[displayBcc] = 'bcc';
3020 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
3026 toggleSearchRowIcon : function(rowId,show)
3030 var idToShow = rowId + '_add_img';
3031 var idToHide = rowId + '_rm_img';
3035 var idToShow = rowId + '_rm_img';
3036 var idToHide = rowId + '_add_img';
3040 Dom.addClass(idToHide, "yui-hidden");
3041 Dom.removeClass(idToShow, "yui-hidden");
3044 * Determine if an entry has already been added to the grid results table to prevent duplicates.
3046 doesGridResultsEntryExist: function(emailAddrs)
3049 var contactExists = false;
3050 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
3051 for (var i=0; i < contacts.length; i++)
3053 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
3054 if(data.email_address == emailAddrs)
3056 contactExists = true;
3060 return contactExists;
3064 * adds an email address to a string, but first checks if it exists
3065 * @param string concat The string we are appending email addresses to
3066 * @param string addr Email address to add
3069 smartAddEmailAddressToComposeField : function(concat, addr) {
3070 var re = new RegExp(addr);
3072 if(!concat.match(re)) {
3074 concat += "; " + addr;
3083 //// END ADDRESS BOOK
3084 ///////////////////////////////////////////////////////////////////////////////
3088 ///////////////////////////////////////////////////////////////////////////////
3091 * Auto-complete object
3095 delimChar : [";", ","],
3099 prehighlightClassName : "yui-ac-prehighlight",
3102 instances : new Array(),
3105 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
3106 * @param object Contact from AddressBook
3109 getPrimaryAddress : function(contact) {
3110 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
3112 for(var eIndex in contact.email) {
3113 address = contact.email[eIndex].email_address;
3114 if(contact.email[eIndex].primary_address == 1) {
3115 return contact.email[eIndex].email_address;
3123 * initializes autocomplete widgets for a given compose view
3126 init : function(idx) {
3127 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
3128 "queryMatchContains" : false,
3129 "queryMatchSubset" : true
3132 this.instances[idx] = {
3139 // instantiate the autoComplete widgets
3140 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
3141 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
3142 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
3144 // enable hiding of interfering textareas
3145 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3146 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3147 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3149 // enable reshowing of hidden textareas
3150 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3151 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3152 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3154 // enable refreshes of contact lists
3155 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3156 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3157 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3160 refreshDataSource : function(sType, aArgs) {
3161 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
3163 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
3165 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
3166 idx = textBoxId.substr(9);
3168 idx = textBoxId.substr(10);
3171 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
3172 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
3173 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
3177 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
3179 returnDataSource : function(contacts) {
3180 var ret = new Array();
3181 for(var id in contacts) {
3182 if (contacts[id].name) {
3183 var primary = this.getPrimaryAddress(contacts[id]);
3185 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
3186 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
3188 for(var emailIndex in contacts[id].email) {
3189 ret[ret.length] = contacts[id].email[emailIndex].email_address;
3198 * Hides address textareas to prevent autocomplete dropdown from being obscured
3200 toggleTextareaHide : function(sType, aArgs) {
3201 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3205 if(textBoxId.indexOf("addressTO") > -1) {
3207 } else if(textBoxId.indexOf("addressCC") > -1) {
3210 idx = textBoxId.substr(9);
3212 // follow through if not BCC
3214 var cc = document.getElementById("addressCC" + idx);
3215 var bcc = document.getElementById("addressBCC" + idx);
3219 cc.style.visibility = 'hidden';
3221 bcc.style.visibility = 'hidden';
3228 * Redisplays the textareas after an address is commited
3230 toggleTextareaShow : function(sType, aArgs) {
3231 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3235 if(textBoxId.indexOf("addressTO") > -1) {
3237 } else if(textBoxId.indexOf("addressCC") > -1) {
3240 idx = textBoxId.substr(9);
3242 // follow through if not BCC
3244 document.getElementById("addressCC" + idx).style.visibility = 'visible';
3245 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
3250 //// END AUTOCOMPLETE
3251 ///////////////////////////////////////////////////////////////////////////////
3253 ///////////////////////////////////////////////////////////////////////////////
3256 * expands the options sidebar
3258 SE.composeLayout = {
3259 currentInstanceId : 0,
3262 outboundAccountErrors : null,
3263 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
3265 showAddressDetails : function(e) {
3266 var linkElement = document.getElementById("More"+e.id);
3267 var spanElement = document.getElementById("Detail"+e.id);
3268 var emailAddressList = e.value;
3269 if(e.value.length > 96)
3271 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
3272 var displayArray = [];
3273 for (var i=0; i<resultArray.length; i++)
3275 var t_name = resultArray[i].name;
3276 var t_emailAddr = resultArray[i].email_address;
3278 displayArray.push('<br/><' + t_emailAddr + '>');
3280 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
3283 var result = displayArray.join('<br/>');
3285 linkElement.style.display = "inline";
3286 linkElement.style.height="10px";
3287 linkElement.style.overflow="visible";
3288 spanElement.innerHTML = result;
3291 linkElement.style.display = "none";
3296 * Given a string of email address, return an array containing the name portion (if available)
3297 * and email portion.
3299 _getEmailArrayFromString : function (emailAddressList){
3302 while ((results = reg.exec(emailAddressList)) != null)
3304 orignial = results[0];
3305 parsedResult = results[0].replace(';', ':::::');
3306 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3310 while ((results = reg.exec(emailAddressList)) != null)
3312 orignial = results[0];
3313 parsedResult = results[0].replace(',', ':::::');
3314 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3316 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
3317 var emailArr = emailAddressList.split(":::::");
3318 var resultsArray = [];
3320 for (var i=0; i<emailArr.length; i++)
3322 var rposition = emailArr[i].indexOf('<');
3323 var lposition = emailArr[i].indexOf('>');
3325 if(trim(emailArr[i]) != '')
3327 if(rposition != -1 && lposition != -1)
3329 var t_name = emailArr[i].substr(0, rposition-1);
3330 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
3331 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
3335 resultsArray.push({'name':'', 'email_address': emailArr[i]});
3339 return resultsArray;
3341 ///////////////////////////////////////////////////////////////////////////
3344 * Prepare bucket DIV and yui-ext tab panels
3346 _0_yui : function() {
3347 var idx = this.currentInstanceId;
3349 var composeTab = new YAHOO.SUGAR.ClosableTab({
3350 label: mod_strings.LNK_NEW_SEND_EMAIL,
3352 content : "<div id='htmleditordiv" + idx + "'/>",
3353 id : "composeTab" + idx,
3354 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
3357 SE.innerLayout.addTab(composeTab);
3359 // get template engine with template
3360 if (!SE.composeLayout.composeTemplate) {
3361 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
3364 // create Tab inner layout
3365 var composePanel = this.getComposeLayout();
3366 composePanel.getUnitByPosition("right").collapse();
3367 composePanel.autoSize();
3371 * Generate the quick compose layout
3372 * @method getQuickComposeLayout
3373 * @param {Pannel} parentPanel Parent pannel
3374 * @param {Object} o Options
3377 getQuickComposeLayout : function (parentPanel,o) {
3378 var idx = SE.composeLayout.currentInstanceId;
3380 //Before rendering the parent pannel we need to initalize the grid layout
3381 parentPanel.beforeRenderEvent.subscribe(function() {
3383 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3384 SE.composeLayout._createComposeLayout(idx);
3385 SE.composeLayout[idx].set('height', 350);
3386 SE.composeLayout[idx].render();
3390 //Wait until the Compose Layout has rendered, then add the
3391 //options tab and perform the tiny initialization.
3392 parentPanel.renderEvent.subscribe(function() {
3394 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3395 SE.composeLayout._initComposeOptionTabs(idx);
3396 SE.composeLayout[idx].getUnitByPosition("right").collapse();
3397 //Initialize tinyMCE
3398 if (!SUGAR.util.isTouchScreen())
3399 SE.composeLayout._1_tiny();
3400 //Init templates and address book
3401 SE.composeLayout._2_final();
3403 SE.composeLayout.quickCreateComposePackage(o);
3408 //Check if we have the div override for the shortcut bar
3409 if(typeof o.menu_id != 'undefined') {
3410 parentPanel.render(o.menu_id);
3412 parentPanel.render(document.body);
3415 return SE.composeLayout[idx];
3418 * Fill in all fields into the quick compose layout.
3419 * @method quickCreateComposePackage
3420 * @param {Object} o Options
3423 quickCreateComposePackage: function(o)
3425 //If we have a compose package fill in defaults.
3426 if (typeof(o.composePackage) != 'undefined')
3428 composePackage = o.composePackage; //Set the compose data object
3429 //Hijack this method called by composePackage as it's not need for quick creates.
3430 SE.composeLayout.c0_composeNewEmail = function(){};
3431 SE.composeLayout.composePackage(); //Fill in defaults.
3434 getComposeLayout : function() {
3435 var idx = SE.composeLayout.currentInstanceId;
3437 this._createComposeLayout(idx);
3438 SE.composeLayout[idx].render();
3439 this._initComposeOptionTabs(idx);
3441 return SE.composeLayout[idx];
3445 * Create the layout manager for the compose window.
3447 _createComposeLayout : function(idx)
3449 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
3450 parent: SE.complexLayout,
3460 SE.composeLayout.composeTemplate.exec({
3461 'app_strings':app_strings,
3462 'mod_strings':mod_strings,
3464 'linkbeans_options' : linkBeans,
3465 'idx' : SE.composeLayout.currentInstanceId
3476 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
3479 header: app_strings.LBL_EMAIL_OPTIONS
3485 * Create compose tab which will populate the 'right' container in the compose window.
3487 _initComposeOptionTabs : function(idx)
3489 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
3490 var tab = new YAHOO.widget.Tab({
3491 label: app_strings.LBL_EMAIL_ATTACHMENT,
3493 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
3494 id : "divAttachments" + idx,
3498 tab.layout = SE.composeLayout[idx];
3500 tab.on("activeChange", function(o){
3502 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
3508 tab = new YAHOO.widget.Tab({
3509 label: app_strings.LBL_EMAIL_OPTIONS,
3511 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
3512 id : "divOptions" + idx,
3516 tab.layout = SE.composeLayout[idx];
3517 tab.on("activeChange", function(o){
3519 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
3524 SE.composeLayout[idx].autoSize = function() {
3525 var pEl = this.get("element").parentNode.parentNode.parentNode;
3526 this.set("height", pEl.clientHeight-30);
3530 SE.composeLayout[idx].rightTabs = cTabs;
3532 isParentTypeValid : function(idx) {
3533 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3534 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3535 if (trim(parentTypeValue) == ""){
3536 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
3542 isParentTypeAndNameValid : function(idx) {
3543 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3544 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3545 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
3546 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
3547 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
3548 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
3554 callopenpopupForEmail2 : function(idx,options) {
3556 var formName = 'emailCompose' + idx;
3558 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
3559 formName = options.form_name;
3561 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3562 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3563 if (!SE.composeLayout.isParentTypeValid(idx)) {
3566 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
3568 call_back_function:"SE.composeLayout.popupAddEmail",
3570 field_to_name_array:{
3571 id:'data_parent_id' + idx,
3572 name:'data_parent_name' + idx,
3577 popupAddEmail : function(o)
3579 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
3580 var data = o.name_to_value_array;
3581 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
3582 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
3584 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
3585 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
3592 _1_tiny : function() {
3593 var idx = SE.composeLayout.currentInstanceId;
3594 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
3595 SE.tinyInstances[elId] = { };
3596 SE.tinyInstances[elId].ready = false;
3597 var t = tinyMCE.getInstanceById(elId);
3599 if(typeof(t) == 'undefined') {
3600 tinyMCE.execCommand('mceAddControl', false, elId);
3601 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
3602 SE.composeLayout.resizeEditor(idx);
3603 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
3608 resizeEditor : function(idx)
3610 var cof = Dom.get('composeOverFrame' + idx);
3611 var head = Dom.get('composeHeaderTable' + idx);
3612 var targetHeight = cof.clientHeight - head.clientHeight;
3613 var instance = tinyMCE.get(SE.tinyInstances.currentHtmleditor);
3615 var parentEl = Dom.get(instance.editorId + '_parent');
3616 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
3617 var contentEl = instance.contentAreaContainer;
3618 var iFrame = contentEl.firstChild;
3619 var tinMceToolbarOffset = 18;
3620 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
3624 * Initializes d&d, auto-complete, email templates
3626 _2_final : function() {
3627 var idx = SE.composeLayout.currentInstanceId;
3629 if(this.emailTemplates) {
3630 this.setComposeOptions(idx);
3632 //populate email template cache
3633 AjaxObject.target = '';
3634 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
3637 // handle drop targets for addressBook
3638 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3639 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3640 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3641 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
3643 // auto-complete setup
3644 SE.autoComplete.init(idx);
3647 document.getElementById("addressTO" + idx).focus();
3651 * hide tinyMCE tool bar if send email as plaintext is checked
3653 renderTinyMCEToolBar : function (idx, hide) {
3655 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
3657 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
3661 c1_composeEmail : function(isReplyForward, retry) {
3665 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
3666 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
3671 if(isReplyForward) {
3672 this.replyForwardEmailStage2();
3678 * takes draft info and prepopulates
3680 c0_composeDraft : function() {
3681 this.getNewInstanceId();
3683 document.getElementById('_blank').innerHTML = '';
3684 var idx = SE.composeLayout.currentInstanceId;
3685 SE.composeLayout.draftObject = new Object();
3686 SE.composeLayout.draftObject.id = idx;
3687 SE.composeLayout.draftObject.isDraft = true;
3688 SE.composeLayout.currentInstanceId = idx;
3689 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
3690 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
3691 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
3693 SE.composeLayout._0_yui();
3694 SE.composeLayout._1_tiny();
3697 SE.composeLayout._2_final();
3699 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
3700 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
3704 * Strip & Prep editor hidden fields
3706 c0_composeNewEmail : function() {
3707 this.getNewInstanceId();
3708 this.c1_composeEmail(false);
3712 * Sends async request to get the compose view.
3713 * Requests come from "reply" or "forwards"
3715 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
3716 SE.composeLayout.replyForwardObj = new Object();
3717 SE.composeLayout.replyForwardObj.ieId = ieId;
3718 SE.composeLayout.replyForwardObj.uid = uid;
3719 SE.composeLayout.replyForwardObj.mbox = mbox;
3720 SE.composeLayout.replyForwardObj.type = type;
3722 if(mbox == 'sugar::Emails') {
3723 SE.composeLayout.replyForwardObj.sugarEmail = true;
3726 SE.composeLayout.getNewInstanceId();
3727 SE.composeLayout.c1_composeEmail(true);
3729 //// END COMPOSE FLOW
3730 ///////////////////////////////////////////////////////////////////////////
3733 * Called when a contact, email, or mailinglist is dropped
3734 * into one of the compose fields.
3736 handleDrop : function (source, event, data, target) {
3739 target = event.getTarget();
3741 data.nodes = [data.nodes];
3745 target = document.getElementById(target);
3749 if (target.id.indexOf('address') > -1) {
3750 // dropped onto email to/cc/bcc field
3751 for(var i in nodes) {
3752 var node = nodes[i].getData();
3754 if (node[1].indexOf('contact') > -1) {
3755 email = SE.addressBook.getFormattedAddress(node[0]);
3756 } else if (node[1].indexOf('address-email') > -1){
3757 email = node[3].replace(/ /gi, '');
3758 email = email.replace('<', '<').replace('>', '>');
3759 var tr = source.getTrEl(nodes[i]);
3760 while (tr && !Dom.hasClass(tr, "address-contact")) {
3761 tr = source.getPreviousTrEl(tr);
3763 var CID = source.getRecord(tr).getData()[0];
3764 var o = SE.addressBook._contactCache[CID];
3765 var name = new String(o.name);
3766 var finalName = name.replace(/(<([^>]+)>)/ig, "");
3767 email = finalName + email;
3769 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
3775 /*/////////////////////////////////////////////////////////////////////////////
3776 /// EMAIL TEMPLATE CODE
3778 applyEmailTemplate : function (idx, id) {
3781 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
3782 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
3783 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
3785 // id is selected index of email template drop-down
3786 if(id == '' || id == "0") {
3787 YAHOO.SUGAR.MessageBox.show({
3792 if(btn=='no'){return;};
3793 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
3800 YAHOO.SUGAR.MessageBox.show({
3805 if(btn=='no'){return;};
3806 SUGAR.email2.composeLayout.processResult(idx, id);},
3812 processNoneResult : function(idx, id) {
3813 var tiny = SE.util.getTiny('htmleditor' + idx);
3814 var tinyHTML = tiny.getContent();
3815 var openTag = '<div><span><span>';
3816 var htmllow = tinyHTML.toLowerCase();
3817 var start = htmllow.indexOf(openTag);
3819 tinyHTML = tinyHTML.substr(start);
3820 tiny.setContent(tinyHTML);
3822 tiny.setContent('');
3826 processResult : function(idx , id){
3827 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
3829 // get attachments if any
3830 AjaxObject.target = '';
3831 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
3834 appendEmailTemplateJSON : function() {
3835 var idx = SE.composeLayout.currentInstanceId; // post increment
3837 // query based on template, contact_id0,related_to
3838 //jchi 09/10/2008 refix #7743
3839 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
3840 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
3843 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,'"');
3845 // cn: bug 14361 - text-only templates don't fill compose screen
3847 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/>");
3850 var tiny = SE.util.getTiny('htmleditor' + idx);
3851 var tinyHTML = tiny.getContent();
3852 var openTag = '<div><span><span>';
3853 var closeTag = '</span></span></div>';
3854 var htmllow = tinyHTML.toLowerCase();
3855 var start = htmllow.indexOf(openTag);
3857 var htmlPart2 = tinyHTML.substr(start);
3858 tinyHTML = text + htmlPart2;
3859 tiny.setContent(tinyHTML);
3861 tiny.setContent(text);
3866 * Writes out the signature in the email editor
3868 setSignature : function(idx) {
3871 var hide = document.getElementById('setEditor' + idx).checked;
3872 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
3873 //wait for signatures to load before trying to set them
3874 if (!SE.composeLayout.signatures) {
3875 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
3880 var sel = document.getElementById('signatures' + idx);
3882 var sel = document.getElementById('signature_id');
3883 idx = SE.tinyInstances.currentHtmleditor;
3886 //Ensure that the tinyMCE html has been rendered.
3887 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
3888 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
3895 signature = sel.options[sel.selectedIndex].value;
3900 var openTag = '<div><span><span>';
3901 var closeTag = '</span></span></div>';
3902 var t = SE.util.getTiny('htmleditor' + idx);
3904 if(typeof(t) != 'undefined')
3906 t.contentDocument = t.contentWindow.document;
3907 var html = t.getContent();
3912 var htmllow = html.toLowerCase();
3913 var start = htmllow.indexOf(openTag);
3914 var end = htmllow.indexOf(closeTag) + closeTag.length;
3916 // selected "none" - remove signature from email
3917 if(signature == '') {
3919 var htmlPart1 = html.substr(0, start);
3920 var htmlPart2 = html.substr(end, html.length);
3922 html = htmlPart1 + htmlPart2;
3925 SE.signatures.lastAttemptedLoad = '';
3929 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
3930 SE.signatures.lastAttemptedLoad = '';
3932 SE.signatures.lastAttemptedLoad = signature;
3934 if(typeof(SE.signatures[signature]) == 'undefined') {
3936 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
3937 SE.signatures.targetInstance = (idx) ? idx : "";
3938 AjaxObject.target = '';
3939 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
3941 var newSignature = this.prepareSignature(SE.signatures[signature]);
3943 // clear out old signature
3944 if(SE.signatures.lastAttemptedLoad && start > -1) {
3945 var htmlPart1 = html.substr(0, start);
3946 var htmlPart2 = html.substr(end, html.length);
3948 html = htmlPart1 + htmlPart2;
3952 start = html.indexOf('<div><hr></div>');
3953 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
3954 var htmlPart1 = html.substr(0, start);
3955 var htmlPart2 = html.substr(start, html.length);
3956 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
3957 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
3958 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
3960 var newHtml = html + openTag + newSignature + closeTag;
3962 //tinyMCE.setContent(newHtml);
3963 t.setContent(newHtml);
3967 prepareSignature : function(str) {
3968 var signature = new String(str);
3970 signature = signature.replace(/</gi, '<');
3971 signature = signature.replace(/>/gi, '>');
3977 showAttachmentPanel : function(idx) {
3978 var east = SE.composeLayout[idx].getUnitByPosition("right");
3979 var tabs = SE.composeLayout[idx].rightTabs;
3981 tabs.set("activeTab", tabs.getTab(0));
3985 * expands sidebar and displays options panel
3987 showOptionsPanel : function(idx) {
3988 var east = SE.composeLayout[idx].getUnitByPosition("right");
3989 var tabs = SE.composeLayout[idx].rightTabs;
3991 tabs.set("activeTab", tabs.getTab(1));
3995 * Selects the Contacts tab
3997 showContactsPanel : function() {
3998 SE.complexLayout.regions.west.showPanel("contactsTab");
4002 * Generates fields for Select Document
4004 addDocumentField : function(idx) {
4005 var basket = document.getElementById('addedDocuments' + idx);
4007 var index = (basket.childNodes.length / 7) - 1;
4014 var test = document.getElementById('documentId' + idx + index);
4016 while(test != null) {
4018 test = document.getElementById('documentId' + idx + index);
4021 var documentCup = document.createElement("div");
4022 documentCup.id = 'documentCup' + idx + index;
4023 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
4024 // document id field
4025 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
4026 // document name field
4027 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
4029 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
4030 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
4031 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
4033 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
4034 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
4035 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
4038 basket.appendChild(documentCup);
4039 //basket.innerHTML += out;
4044 * Makes async call to save a draft of the email
4045 * @param int Instance index
4047 saveDraft : function(tinyInstance) {
4048 this.sendEmail(tinyInstance, true);
4051 selectDocument : function(target) {
4052 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
4053 windowName = 'selectDocument';
4054 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
4056 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4058 // put the focus on the popup if the browser supports the focus() method
4064 * Modal popup for file attachment dialogue
4066 addFileField : function() {
4067 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
4068 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
4072 constraintoviewport: true,
4074 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
4075 fn:function(){SE.addFileDialog.hide();}
4078 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
4079 SE.addFileDialog.render();
4080 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
4082 Dom.removeClass("addFileDialog", "yui-hidden");
4084 SE.addFileDialog.show();
4088 * Async upload of file to temp dir
4090 uploadAttachment : function() {
4091 if(document.getElementById('email_attachment').value != "") {
4092 var formObject = document.getElementById('uploadAttachment');
4093 YAHOO.util.Connect.setForm(formObject, true, true);
4094 AjaxObject.target = '';
4095 AjaxObject.startRequest(callbackUploadAttachment, null);
4097 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
4102 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
4103 * @param string target in focus compose layout
4105 setDocument : function(idx, target, documentId, documentName, docRevId) {
4106 // fields are named/id'd [fieldName][instanceId][index]
4107 var addedDocs = document.getElementById("addedDocuments" + idx);
4108 var docId = document.getElementById('documentId' + idx + target);
4109 var docName = document.getElementById('documentName' + idx + target);
4110 var docRevisionId = document.getElementById('document' + idx + target);
4111 docId.value = documentId;
4112 docName.value = documentName;
4113 docRevisionId.value = docRevId;
4117 * Removes the bucket div containing the document input fields
4119 deleteDocumentField : function(documentCup) {
4120 var f0 = document.getElementById(documentCup);
4121 f0.parentNode.removeChild(f0);
4125 * Removes a Template Attachment field
4129 deleteTemplateAttachmentField : function(idx, index) {
4130 // create not-in-array values for removal filtering
4131 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
4137 r += document.getElementById('templateAttachmentId' + idx + index).value;
4138 document.getElementById("templateAttachmentsRemove" + idx).value = r;
4140 var target = 'templateAttachmentCup' + idx + index;
4141 d = document.getElementById(target);
4142 d.parentNode.removeChild(d);
4146 * Async removal of uploaded temp file
4147 * @param string index Should be a concatenation of idx and index
4150 deleteUploadAttachment : function(index, file) {
4151 var d = document.getElementById('email_attachment_bucket' + index);
4152 d.parentNode.removeChild(d);
4154 // make async call to delete cached file
4155 AjaxObject.target = '';
4156 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
4160 * Attaches files coming from Email Templates
4162 addTemplateAttachmentField : function(idx) {
4164 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
4166 var basket = document.getElementById('addedTemplateAttachments' + idx);
4169 var index = basket.childNodes.length;
4176 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
4178 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
4179 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
4180 idx + "\",\"" + index + "\");'/>" +
4182 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
4183 // templateAttachment field
4184 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
4186 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
4188 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
4189 "<br id='br" + index + "></br>" +
4190 "<br id='brdoc" + index + "></br>" +
4192 basket.innerHTML = basket.innerHTML + out;
4198 * Sends one email via async call
4199 * @param int idx Editor instance ID
4200 * @param bool isDraft
4202 sendEmail : function(idx, isDraft) {
4204 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
4205 var obAccountID = document.getElementById('addressFrom' + idx).value;
4207 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
4209 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
4214 var form = document.getElementById('emailCompose' + idx);
4215 var composeOptionsFormName = "composeOptionsForm" + idx;
4216 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
4217 var html = t.getContent();
4218 var subj = document.getElementById('emailSubject' + idx).value;
4219 var to = trim(document.getElementById('addressTO' + idx).value);
4220 var cc = trim(document.getElementById('addressCC' + idx).value);
4221 var bcc = trim(document.getElementById('addressBCC' + idx).value);
4222 var email_id = document.getElementById('email_id' + idx).value;
4223 var composeType = document.getElementById('composeType').value;
4224 var parent_type = document.getElementById("parent_type").value;
4225 var parent_id = document.getElementById("parent_id").value;
4227 var el_uid = document.getElementById("uid");
4228 var uid = (el_uid == null) ? '' : el_uid.value;
4230 var el_ieId = document.getElementById("ieId");
4231 var ieId = (el_ieId == null) ? '' : el_ieId.value;
4233 var el_mbox = document.getElementById("mbox");
4234 var mbox = (el_mbox == null) ? '' : el_mbox.value;
4236 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
4237 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
4241 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
4244 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
4245 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
4246 parent_id = parentIdValue;
4247 parent_type = parentTypeValue;
4249 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
4250 // baseline viability check
4252 if(to == "" && cc == '' && bcc == '' && !isDraft) {
4253 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
4255 } else if(subj == '' && !isDraft) {
4256 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
4259 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
4261 } else if(html == '' && !isDraft) {
4262 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
4267 SE.util.clearHiddenFieldValues('emailCompose' + idx);
4268 document.getElementById('data_parent_id' + idx).value = parentIdValue;
4269 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
4270 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
4271 html = html.replace(/</ig, "sugarLessThan");
4272 html = html.replace(/>/ig, "sugarGreaterThan");
4274 form.sendDescription.value = html;
4275 form.sendSubject.value = subj;
4276 form.sendTo.value = to;
4277 form.sendCc.value = cc;
4278 form.sendBcc.value = bcc;
4279 form.email_id.value = email_id;
4280 form.composeType.value = composeType;
4281 form.composeLayoutId.value = 'composeLayout' + idx;
4282 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
4283 form.saveToSugar.value = 1;
4284 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
4285 form.parent_type.value = parent_type;
4286 form.parent_id.value = parent_id;
4287 form.uid.value = uid;
4288 form.ieId.value = ieId;
4289 form.mbox.value = mbox;
4291 // email attachments
4292 var addedFiles = document.getElementById('addedFiles' + idx);
4294 for(i=0; i<addedFiles.childNodes.length; i++) {
4295 var bucket = addedFiles.childNodes[i];
4297 for(j=0; j<bucket.childNodes.length; j++) {
4298 var node = bucket.childNodes[j];
4299 var nName = new String(node.name);
4301 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
4302 if(form.attachments.value != '') {
4303 form.attachments.value += "::";
4305 form.attachments.value += node.value;
4312 var addedDocs = document.getElementById('addedDocuments' + idx);
4314 for(i=0; i<addedDocs.childNodes.length; i++) {
4315 var cNode = addedDocs.childNodes[i];
4316 for(j=0; j<cNode.childNodes.length; j++) {
4317 var node = cNode.childNodes[j];
4318 var nName = new String(node.name);
4319 if(node.type == 'hidden' && nName.match(/documentId/)) {
4320 if(form.documents.value != '') {
4321 form.documents.value += "::";
4323 form.documents.value += node.value;
4329 // template attachments
4330 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
4331 if(addedTemplateAttachments) {
4332 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
4333 var cNode = addedTemplateAttachments.childNodes[i];
4334 for(j=0; j<cNode.childNodes.length; j++) {
4335 var node = cNode.childNodes[j];
4336 var nName = new String(node.name);
4337 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
4338 if(form.templateAttachments.value != "") {
4339 form.templateAttachments.value += "::";
4341 form.templateAttachments.value += node.value;
4347 // remove attachments
4348 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
4350 YAHOO.util.Connect.setForm(form);
4352 AjaxObject.target = 'frameFlex';
4354 // sending a draft email
4355 if(!isDraft && in_draft) {
4357 SE.listView.removeRowByUid(email_id);
4360 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
4361 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
4363 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
4367 * Handles clicking the email address link from a given view
4369 composePackage : function() {
4370 if(composePackage != null) {
4371 SE.composeLayout.c0_composeNewEmail();
4374 if(composePackage.to_email_addrs) {
4375 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
4377 if (composePackage.subject != null && composePackage.subject.length > 0) {
4378 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
4381 //If no parent fields are set in the composePackage, ensure they are cleared.
4382 var parentFields = ['parent_type','parent_name','parent_id'];
4383 for(var i=0;i<parentFields.length;i++)
4385 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
4386 composePackage[parentFields[i]] = "";
4389 document.getElementById("parent_type").value = composePackage.parent_type;
4390 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
4391 document.getElementById("parent_id").value = composePackage.parent_id;
4392 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
4393 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
4395 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
4396 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
4398 if (composePackage.body != null && composePackage.body.length > 0) {
4399 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4400 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
4401 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
4403 if (composePackage.attachments != null) {
4404 SE.composeLayout.loadAttachments(composePackage.attachments);
4407 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
4408 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
4409 SE.util.emptySelectOptions(addressFrom);
4410 var fromAccountOpts = composePackage.fromAccounts.data;
4411 for(i=0; i<fromAccountOpts.length; i++) {
4412 var key = fromAccountOpts[i].value;
4413 var display = fromAccountOpts[i].text;
4414 var opt = new Option(display, key);
4415 if (fromAccountOpts[i].selected) {
4416 opt.selected = true;
4418 addressFrom.options.add(opt);
4425 setContentOnThisTiny : function() {
4426 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4427 var tinyHTML = tiny.getContent();
4428 composePackage.body = decodeURI(encodeURI(composePackage.body));
4429 // cn: bug 14361 - text-only templates don't fill compose screen
4430 if(composePackage.body == '') {
4431 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4433 //Flag determines if we should clear the tiny contents or just append
4434 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
4435 SE.composeLayout.tinyHTML = '';
4437 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
4439 tiny.setContent(SE.composeLayout.tinyHTML);
4440 //Indicate that the contents has been loaded successfully.
4441 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
4444 * Confirms closure of a compose screen if "x" is clicked
4446 confirmClose : function(panel) {
4447 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
4448 SE.composeLayout.closeCompose(panel.id);
4456 * forces close of a compose screen
4458 forceCloseCompose : function(id) {
4459 SE.composeLayout.closeCompose(id);
4461 // handle flow back to originating view
4462 if(composePackage) {
4463 // check if it's a module we need to return to
4464 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
4465 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
4466 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
4467 window.location = url;
4474 * closes the editor that just sent email
4475 * @param string id ID of composeLayout tab
4477 closeCompose : function(id) {
4478 // destroy tinyMCE instance
4479 var idx = id.substr(13, id.length);
4480 var instanceId = "htmleditor" + idx;
4481 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
4483 // nullify DOM and namespace values.
4485 SE.composeLayout[idx] = null;
4486 SE.tinyInstances[instanceId] = null;
4487 var tabsArray = SE.innerLayout.get("tabs");
4488 for (i = 0 ; i < tabsArray.length ; i++) {
4489 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
4490 tabsArray[i].close();
4494 //SE.innerLayout.getTab(idx).close();
4498 * Enable the quick search for the compose relate field or search tab
4500 enableQuickSearchRelate: function(idx,overides){
4502 if(typeof overides != 'undefined')
4504 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
4505 var newModule = document.getElementById(newModuleID).value;
4506 var formName = overides['formName'];
4507 var fieldName = overides['fieldName'];
4508 var fieldId = overides['fieldId'];
4509 var fullName = formName + "_" + fieldName;
4510 var postBlurFunction = null;
4514 var newModule = document.getElementById('data_parent_type'+idx).value;
4515 var formName = 'emailCompose'+idx;
4516 var fieldName = 'data_parent_name'+idx;
4517 var fieldId = 'data_parent_id'+idx;
4518 var fullName = formName + "_" + fieldName;
4519 var postBlurFunction = "SE.composeLayout.qsAddAddress";
4522 if(typeof sqs_objects == 'undefined')
4523 window['sqs_objects'] = new Array;
4525 window['sqs_objects'][fullName] = {
4528 modules:[newModule],
4530 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
4531 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
4532 post_onblur_function: postBlurFunction,
4533 order:"name","limit":"30","no_match_text":"No Match"};
4536 if(typeof QSProcessedFieldsArray != 'undefined')
4537 QSProcessedFieldsArray[fullName] = false;
4538 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
4539 QSFieldsArray[fullName].destroy();
4540 delete QSFieldsArray[fullName];
4542 if (Dom.get(fullName + "_results")) {
4543 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
4549 qsAddAddress : function(o) {
4550 if (o.name != "" && o.email1 != "")
4552 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
4553 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
4557 * Returns a new instance ID, 0-index
4559 getNewInstanceId : function() {
4560 this.currentInstanceId = this.currentInstanceId + 1;
4561 return this.currentInstanceId;
4565 * 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.
4567 loadAttachments : function(result) {
4568 var idx = SE.composeLayout.currentInstanceId;
4570 if(typeof(result) == 'object') {
4571 //jchi #20680. Clean the former template attachments;
4572 var basket = document.getElementById('addedTemplateAttachments' + idx);
4573 if(basket.innerHTML != ''){
4574 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
4576 basket.innerHTML = '';
4581 if(typeof result[i] == 'object') {
4582 var index = SE.composeLayout.addTemplateAttachmentField(idx);
4583 var bean = result[i];
4584 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
4585 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
4592 * fills drop-down values for email templates and signatures
4594 setComposeOptions : function(idx) {
4595 // send from accounts
4596 var addressFrom = document.getElementById('addressFrom' + idx);
4598 if (addressFrom.options.length <= 0) {
4599 SE.util.emptySelectOptions(addressFrom);
4600 var fromAccountOpts = SE.composeLayout.fromAccounts;
4601 for (id = 0 ; id < fromAccountOpts.length ; id++) {
4602 var key = fromAccountOpts[id].value;
4603 var display = fromAccountOpts[id].text;
4604 var is_default = false;
4605 if(key == SUGAR.default_inbound_accnt_id)
4607 var opt = new Option(display, key);
4608 addressFrom.options.add(opt);
4609 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
4614 var et = document.getElementById('email_template' + idx);
4615 SE.util.emptySelectOptions(et);
4617 for(var key in this.emailTemplates) { // iterate through assoc array
4618 var display = this.emailTemplates[key];
4619 var opt = new Option(display, key);
4620 et.options.add(opt);
4624 var sigs = document.getElementById('signatures' + idx);
4625 SE.util.emptySelectOptions(sigs);
4627 for(var key in this.signatures) { // iterate through assoc array
4628 var display = this.signatures[key];
4629 var opt = new Option(display, key);
4631 if(key == SE.userPrefs.signatures.signature_default) {
4632 opt.selected = true;
4635 sigs.options.add(opt);
4638 // html/plain email?
4639 var htmlEmail = document.getElementById('setEditor' + idx);
4640 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
4641 htmlEmail.checked = true;
4643 htmlEmail.checked = false;
4646 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
4650 * After compose screen is rendered, async call to get email body from Sugar
4652 replyForwardEmailStage2 : function() {
4653 SE.util.clearHiddenFieldValues('emailUIForm');
4654 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
4656 var ieId = SE.composeLayout.replyForwardObj.ieId;
4657 var uid = SE.composeLayout.replyForwardObj.uid;
4658 var mbox = SE.composeLayout.replyForwardObj.mbox;
4659 var type = SE.composeLayout.replyForwardObj.type;
4660 var idx = SE.composeLayout.currentInstanceId;
4662 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
4664 document.getElementById('emailSubject' + idx).value = type;
4665 document.getElementById('emailUIAction').value = 'composeEmail';
4666 document.getElementById('composeType').value = type;
4667 document.getElementById('ieId').value = ieId;
4668 document.getElementById('uid').value = uid;
4669 document.getElementById('mbox').value = mbox;
4670 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
4671 var formObject = document.getElementById('emailUIForm');
4672 YAHOO.util.Connect.setForm(formObject);
4674 var sendType = type;
4675 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
4679 * Show the hidden cc or bcc fields
4681 showHiddenAddress: function(addrType,idx){
4683 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
4684 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
4685 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
4686 this[addrType+'Hidden'+idx] = false;
4688 //After bcc or cc is added, move options below last addr field
4689 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4691 //If both cc and bcc hidden, remove the empty row containing text.
4692 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
4693 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
4694 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
4696 SE.composeLayout.resizeEditor(idx);
4699 * Hide the cc and bcc fields if they were shown.
4701 hideHiddenAddresses: function(idx){
4703 var addrTypes = ['cc','bcc'];
4704 for(var i = 0;i<addrTypes.length;i++)
4706 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
4707 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
4708 this[addrTypes[i] + 'Hidden'+idx] = true
4711 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
4712 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
4713 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4717 //// END SE.composeLayout
4718 ///////////////////////////////////////////////////////////////////////////////
4719 ///////////////////////////////////////////////////////////////////////////////
4723 * Cleans serialized UID lists of duplicates
4727 cleanUids : function(str) {
4728 var seen = new Object();
4730 var arr = new String(str).split(",");
4732 for(var i=0; i<arr.length; i++) {
4737 clean += (clean != "") ? "," : "";
4739 seen[arr[i]] = true;
4746 * Clears hidden field values
4747 * @param string id ID of form element to clear
4749 clearHiddenFieldValues : function(id) {
4750 var form = document.getElementById(id);
4752 for(i=0; i<form.elements.length; i++) {
4753 if(form.elements[i].type == 'hidden') {
4754 var e = form.elements[i];
4755 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
4763 * Reduces a SELECT drop-down to 0 items to prepare for new ones
4765 emptySelectOptions : function(el) {
4767 for(i=el.childNodes.length - 1; i >= 0; i--) {
4768 if(el.childNodes[i]) {
4769 el.removeChild(el.childNodes[i]);
4776 * Returns the MBOX path in the manner php_imap expects:
4777 * ie: INBOX.DEBUG.test
4778 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
4780 generateMboxPath : function(str) {
4781 var ex = str.split("::");
4783 /* we have a serialized MBOX path */
4787 for(var i=0; i<ex.length; i++) {
4788 if(ex[i] == 'INBOX') {
4800 /* we have a Sugar folder GUID - do nothing */
4808 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
4809 * @param HTMLElement el
4810 * @return string GUID of found element or empty on failure
4812 getGuidFromElement : function(el) {
4818 for(var i=0; i<iterations; i++) {
4820 if(el.id.match(SE.reGUID)) {
4832 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
4835 getPanelId : function() {
4836 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
4840 * wrapper to handle weirdness with IE
4841 * @param string instanceId
4842 * @return tinyMCE Controller object
4844 getTiny : function(instanceId) {
4845 if(instanceId == '') {
4849 var t = tinyMCE.getInstanceById(instanceId);
4853 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
4859 * Simple check for MSIE browser
4863 var nav = new String(navigator.appVersion);
4864 if(nav.match(/MSIE/)) {
4871 * Recursively removes an element from the DOM
4872 * @param HTMLElement
4874 removeElementRecursive : function(el) {
4875 this.emptySelectOptions(el);
4882 sleep : function(secs) {
4883 setTimeout("void(0);", secs);
4887 * Converts a <select> element to an Ext.form.combobox
4889 convertSelect : function(select) {
4890 alert('in convertSelect');
4891 if (typeof(select) == "string") {
4892 select = document.getElementById(select);
4896 findChildNode : function (parent, property, value) {
4897 for (i in parent.children) {
4898 var child = parent.children[i];
4899 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
4901 var searchChild = SE.util.findChildNode(child, property, value);
4908 cascadeNodes : function (parent, fn, scope, args) {
4909 for (i in parent.children) {
4910 var child = parent.children[i];
4911 var s = scope ? scope : child;
4912 var a = args ? args : child;
4914 SE.util.cascadeNodes(child, fn, scope, args);
4921 ///////////////////////////////////////////////////////////////////////////////
4924 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
4926 /*********************************************************************************
4927 * SugarCRM is a customer relationship management program developed by
4928 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4930 * This program is free software; you can redistribute it and/or modify it under
4931 * the terms of the GNU Affero General Public License version 3 as published by the
4932 * Free Software Foundation with the addition of the following permission added
4933 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4934 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4935 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4937 * This program is distributed in the hope that it will be useful, but WITHOUT
4938 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4939 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4942 * You should have received a copy of the GNU Affero General Public License along with
4943 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4944 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4947 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4948 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4950 * The interactive user interfaces in modified source and object code versions
4951 * of this program must display Appropriate Legal Notices, as required under
4952 * Section 5 of the GNU Affero General Public License version 3.
4954 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4955 * these Appropriate Legal Notices must retain the display of the "Powered by
4956 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4957 * technical reasons, the Appropriate Legal Notices must display the words
4958 * "Powered by SugarCRM".
4959 ********************************************************************************/
4961 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
4962 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
4963 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
4964 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
4965 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
4966 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
4967 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
4968 ' <input type="hidden" id="type{idx}" name="type" value="">' +
4969 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
4970 ' <input type="hidden" id="composeType" name="composeType">' +
4971 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
4972 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
4973 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
4974 ' <input type="hidden" id="sendTo" name="sendTo">' +
4975 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
4976 ' <input type="hidden" id="sendCc" name="sendCc">' +
4977 ' <input type="hidden" id="setEditor" name="setEditor">' +
4978 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
4979 ' <input type="hidden" id="parent_id" name="parent_id">' +
4980 ' <input type="hidden" id="parent_type" name="parent_type">' +
4981 ' <input type="hidden" id="attachments" name="attachments">' +
4982 ' <input type="hidden" id="documents" name="documents">' +
4983 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
4984 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
4985 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
4986 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
4988 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
4989 ' <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>' +
4990 ' <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>' +
4991 ' <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>' +
4992 ' <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>' +
4993 '</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>' +
4994 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
4995 '<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>' +
4996 ' </td></tr></tbody></table></th>' +
5000 ' <div style="margin:5px;">' +
5001 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
5003 ' <td class="emailUILabel" NOWRAP >' +
5004 ' {app_strings.LBL_EMAIL_FROM}:' +
5006 ' <td class="emailUIField" NOWRAP>' +
5008 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
5013 ' <td class="emailUILabel" NOWRAP>' +
5014 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
5015 ' {app_strings.LBL_EMAIL_TO}:' +
5018 ' <td class="emailUIField" NOWRAP>' +
5019 ' <div class="ac_autocomplete">' +
5020 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5021 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
5022 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
5026 ' <tr id="add_addr_options_tr{idx}">' +
5027 ' <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>'+
5029 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
5030 ' <td class="emailUILabel" NOWRAP>' +
5031 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
5032 ' {app_strings.LBL_EMAIL_CC}:' +
5035 ' <td class="emailUIField" NOWRAP>' +
5036 ' <div class="ac_autocomplete">' +
5037 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5038 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
5039 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
5043 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
5044 ' <td class="emailUILabel" NOWRAP>' +
5045 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
5046 ' {app_strings.LBL_EMAIL_BCC}:' +
5049 ' <td class="emailUIField" NOWRAP>' +
5050 ' <div class="ac_autocomplete">' +
5051 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5052 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
5053 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
5058 ' <td class="emailUILabel" NOWRAP width="1%">' +
5059 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
5061 ' <td class="emailUIField" NOWRAP width="99%">' +
5062 ' <div class="ac_autocomplete">' +
5063 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
5072 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
5073 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
5074 ' <div style="padding:5px;">' +
5075 ' <table cellpadding="2" cellspacing="0" border="0">' +
5078 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
5085 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
5086 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
5098 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
5105 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
5106 ' <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>' +
5118 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
5125 ' <div id="addedTemplateAttachments{idx}"></div>' +
5132 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
5133 ' <div style="padding:5px;">' +
5134 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
5135 ' <table border="0" width="100%">' +
5137 ' <td NOWRAP style="padding:2px;">' +
5138 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
5142 ' <td NOWRAP style="padding:2px;">' +
5143 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
5148 ' <table border="0" width="100%">' +
5150 ' <td NOWRAP style="padding:2px;">' +
5151 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
5155 ' <td NOWRAP style="padding:2px;">' +
5156 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
5160 ' <table border="0" width="100%">' +
5162 ' <td NOWRAP style="padding:2px;">' +
5163 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
5164 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
5172 // End of File modules/Emails/javascript/composeEmailTemplate.js
5174 /*********************************************************************************
5175 * SugarCRM is a customer relationship management program developed by
5176 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5178 * This program is free software; you can redistribute it and/or modify it under
5179 * the terms of the GNU Affero General Public License version 3 as published by the
5180 * Free Software Foundation with the addition of the following permission added
5181 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
5182 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
5183 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
5185 * This program is distributed in the hope that it will be useful, but WITHOUT
5186 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
5187 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
5190 * You should have received a copy of the GNU Affero General Public License along with
5191 * this program; if not, see http://www.gnu.org/licenses or write to the Free
5192 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
5195 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
5196 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
5198 * The interactive user interfaces in modified source and object code versions
5199 * of this program must display Appropriate Legal Notices, as required under
5200 * Section 5 of the GNU Affero General Public License version 3.
5202 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
5203 * these Appropriate Legal Notices must retain the display of the "Powered by
5204 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
5205 * technical reasons, the Appropriate Legal Notices must display the words
5206 * "Powered by SugarCRM".
5207 ********************************************************************************/
5212 function complexLayoutInit() {
5213 var se = SUGAR.email2;
5214 var Dom = YAHOO.util.Dom;
5216 getInnerLayout : function(rows) {
5217 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
5218 parent: se.complexLayout,
5224 scroll:false, // grid should autoScroll itself
5226 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
5234 body: "<div id='listBottom' />"
5242 body: "<div id='listRight' />",
5243 titlebar: false //,header: "right"
5246 se.complexLayout.on("render", function(){
5247 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
5248 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5249 SUGAR.email2.listViewLayout.set("height", height);
5250 SUGAR.email2.listViewLayout.render();
5252 se.listViewLayout.render();
5254 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
5255 var rp = se.listViewLayout.resizePreview = function() {
5256 var pre = Dom.get("displayEmailFramePreview");
5258 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
5259 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
5262 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
5263 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
5264 se.e2Layout.setPreviewPanel(rows);
5265 se.previewLayout = se.listViewLayout;
5266 return se.listViewLayout;
5269 getInnerLayout2Rows : function() {
5270 return this.getInnerLayout(true);
5272 getInnerLayout2Columns : function() {
5273 return this.getInnerLayout(false);
5277 // initialize state manager, we will use cookies
5278 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
5279 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
5280 se.complexLayout = new YAHOO.widget.Layout("container", {
5283 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
5284 width: Dom.getViewportWidth() - 40,
5288 body: "<div id='emailtabs'></div>"
5293 body: "<div id='lefttabs'></div>",
5303 header: Dom.get('footerLinks').innerHTML,
5310 se.complexLayout.render();
5311 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
5312 tp.addTab(new YAHOO.widget.Tab({
5315 content : "<div id='listViewDiv'/>",
5319 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
5320 tp.appendTo(centerEl);
5322 tp.get("element").style.borderRight = "1px solid #666"
5324 var listV = this.getInnerLayout2Rows();
5325 listV.set("height", tp.get("element").clientHeight - 25);
5328 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
5329 var folderTab = new YAHOO.widget.Tab({
5330 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
5332 content : "<div id='emailtree'/>",
5336 folderTab.on("activeChange", function(o){
5338 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
5341 se.leftTabs.addTab(folderTab);
5343 var tabContent = SUGAR.util.getAndRemove("searchTab");
5344 var searchTab = new YAHOO.widget.Tab({
5345 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
5347 content : tabContent.innerHTML,
5350 searchTab.on("activeChange", function(o){
5353 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
5354 //Setup the calendars if needed
5355 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_from", singleClick : true, step : 1, weekNumbers:false});
5356 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_to", singleClick : true, step : 1, weekNumbers:false});
5358 //Initalize sqs object for assigned user name
5359 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
5361 //Attach event handler for when the relate module option is selected for the correct sqs object
5362 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
5363 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
5364 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
5365 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
5367 //If enter key is pressed, perform search
5368 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
5369 for(var i=0; i < addKeyPressFields.length;i++)
5371 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
5372 if (e.keyCode == 13) {
5373 YAHOO.util.Event.stopEvent(e);
5374 SUGAR.email2.search.searchAdvanced();
5378 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
5380 //Clear parent values if selecting another parent type.
5381 YAHOO.util.Event.addListener('data_parent_type_search','change',
5383 document.getElementById('data_parent_id_search').value ='';
5384 document.getElementById('data_parent_name_search').value ='';
5389 se.leftTabs.addTab(searchTab);
5391 var resizeTabBody = function() {
5392 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
5393 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5396 se.complexLayout.on("render", resizeTabBody);
5397 se.leftTabs.on("activeTabChange", resizeTabBody);
5398 //hack to allow left pane scroll bar to fully show
5399 var lefttabsDiv = document.getElementById('lefttabs');
5400 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
5401 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
5402 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
5405 initSQSObject: function(formName,fieldName)
5407 var fullFieldName = formName + '_' + fieldName; //SQS Convention
5408 var resultName = fullFieldName + '_' + 'results';
5410 if (QSFieldsArray[fullFieldName] != null)
5412 QSFieldsArray[fullFieldName].destroy();
5413 delete QSFieldsArray[fullFieldName];
5415 if (QSProcessedFieldsArray[fullFieldName])
5416 QSProcessedFieldsArray[fullFieldName] = false;
5418 if( Dom.get(resultName) )
5420 var obj = document.getElementById(resultName);
5421 obj.parentNode.removeChild(obj);
5424 setPreviewPanel: function(rows) {
5426 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
5427 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
5428 Dom.get("listRight").innerHTML = "";
5429 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
5431 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
5432 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
5433 Dom.get("listBottom").innerHTML = "";
5434 Dom.get("listRight").innerHTML = "<div id='_blank' />";
5441 var myBufferedListenerObject = new Object();
5442 myBufferedListenerObject.refit = function() {
5443 if(SUGAR.email2.grid) {
5444 SUGAR.email2.grid.autoSize();
5447 // End of File modules/Emails/javascript/complexLayout.js