1 /*********************************************************************************
2 * SugarCRM Community Edition is a customer relationship management program developed by
3 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5 * This program is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU Affero General Public License version 3 as published by the
7 * Free Software Foundation with the addition of the following permission added
8 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
17 * You should have received a copy of the GNU Affero General Public License along with
18 * this program; if not, see http://www.gnu.org/licenses or write to the Free
19 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
23 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25 * The interactive user interfaces in modified source and object code versions
26 * of this program must display Appropriate Legal Notices, as required under
27 * Section 5 of the GNU Affero General Public License version 3.
29 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
30 * these Appropriate Legal Notices must retain the display of the "Powered by
31 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
32 * technical reasons, the Appropriate Legal Notices must display the words
33 * "Powered by SugarCRM".
34 ********************************************************************************/
38 var flexContentOld = "";
39 var forcePreview = false;
40 var inCompose = false;
42 /* globals for Callback functions */
43 var email; // AjaxObject.showEmailPreview
47 var meta; // AjaxObject.showEmailPreview
50 var urlBase = 'index.php';
51 var urlStandard = 'sugar_body_only=true&to_pdf=true&module=Emails&action=EmailUIAjax';
53 var lazyLoadFolder = null;// End of File modules/Emails/javascript/vars.js
55 /*********************************************************************************
56 * SugarCRM Community Edition is a customer relationship management program developed by
57 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
59 * This program is free software; you can redistribute it and/or modify it under
60 * the terms of the GNU Affero General Public License version 3 as published by the
61 * Free Software Foundation with the addition of the following permission added
62 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
63 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
64 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
66 * This program is distributed in the hope that it will be useful, but WITHOUT
67 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
68 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
71 * You should have received a copy of the GNU Affero General Public License along with
72 * this program; if not, see http://www.gnu.org/licenses or write to the Free
73 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
76 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
77 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
79 * The interactive user interfaces in modified source and object code versions
80 * of this program must display Appropriate Legal Notices, as required under
81 * Section 5 of the GNU Affero General Public License version 3.
83 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
84 * these Appropriate Legal Notices must retain the display of the "Powered by
85 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
86 * technical reasons, the Appropriate Legal Notices must display the words
87 * "Powered by SugarCRM".
88 ********************************************************************************/
89 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
90 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
91 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
92 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
93 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
94 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
95 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
96 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',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;if(SUGAR.isIE7&&e.tagName.toLowerCase()=='input')
127 {var properties=['class','style','name','type','valign','border','width','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}else{var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}
128 for(var i in properties)
129 {if(e[properties[i]])
130 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
131 newNode[properties[i]]=e[properties[i]];}}
133 {for(var i in e.childNodes)
134 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
135 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
136 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
138 /*********************************************************************************
139 * SugarCRM Community Edition is a customer relationship management program developed by
140 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
142 * This program is free software; you can redistribute it and/or modify it under
143 * the terms of the GNU Affero General Public License version 3 as published by the
144 * Free Software Foundation with the addition of the following permission added
145 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
146 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
147 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
149 * This program is distributed in the hope that it will be useful, but WITHOUT
150 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
151 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
154 * You should have received a copy of the GNU Affero General Public License along with
155 * this program; if not, see http://www.gnu.org/licenses or write to the Free
156 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
159 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
160 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
162 * The interactive user interfaces in modified source and object code versions
163 * of this program must display Appropriate Legal Notices, as required under
164 * Section 5 of the GNU Affero General Public License version 3.
166 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
167 * these Appropriate Legal Notices must retain the display of the "Powered by
168 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
169 * technical reasons, the Appropriate Legal Notices must display the words
170 * "Powered by SugarCRM".
171 ********************************************************************************/
174 cache : new Object(),
175 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
176 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
179 currentHtmleditor : ''
183 * preserves hits from email server
185 _setDetailCache : function(ret) {
187 var compKey = ret.meta.mbox + ret.meta.uid;
189 if(!SUGAR.email2.cache[compKey]) {
190 SUGAR.email2.cache[compKey] = ret;
195 autoSetLayout : function() {
196 var c = document.getElementById('container');
197 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
198 //Ensure a minimum height.
199 tHeight = Math.max(tHeight, 550);
200 c.style.height = tHeight + "px";
201 SUGAR.email2.complexLayout.set('height', tHeight);
202 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
203 SUGAR.email2.complexLayout.render();
204 SUGAR.email2.listViewLayout.resizePreview();
209 * Shows overlay progress message
211 function overlayModal(title, body) {
212 overlay(title, body);
214 function overlay(reqtitle, body, type, additconfig) {
216 if (typeof(additconfig) == "object") {
217 var config = additconfig;
220 config.title = reqtitle;
222 YAHOO.SUGAR.MessageBox.show(config);
225 function hideOverlay() {
226 YAHOO.SUGAR.MessageBox.hide();
228 // End of File modules/Emails/javascript/EmailUIShared.js
230 /*********************************************************************************
231 * SugarCRM Community Edition is a customer relationship management program developed by
232 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
234 * This program is free software; you can redistribute it and/or modify it under
235 * the terms of the GNU Affero General Public License version 3 as published by the
236 * Free Software Foundation with the addition of the following permission added
237 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
238 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
239 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
241 * This program is distributed in the hope that it will be useful, but WITHOUT
242 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
243 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
246 * You should have received a copy of the GNU Affero General Public License along with
247 * this program; if not, see http://www.gnu.org/licenses or write to the Free
248 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
251 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
252 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
254 * The interactive user interfaces in modified source and object code versions
255 * of this program must display Appropriate Legal Notices, as required under
256 * Section 5 of the GNU Affero General Public License version 3.
258 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
259 * these Appropriate Legal Notices must retain the display of the "Powered by
260 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
261 * technical reasons, the Appropriate Legal Notices must display the words
262 * "Powered by SugarCRM".
263 ********************************************************************************/
266 if (typeof console == "undefined")
267 console = { log: function(o) {alert(o)} };
271 currentRequestObject : null,
272 //timeout : 30000, // 30 second timeout default
273 timeout : 9999999999, // 30 second timeout default
279 _reset : function() {
280 this.timeout = 30000;
281 this.forceAbort = false;
284 folderRenameCleanup : function() {
285 SUGAR.email2.folders.setSugarFolders();
288 fullSyncCleanup : function(o) {
289 this.folders.checkMailCleanup(o);
290 SUGAR.email2.settings.settingsDialog.hide();
295 composeCache : function(o) {
296 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
297 // get email templates and user signatures
298 var ret = JSON.parse(o.responseText);
300 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
301 SUGAR.email2.composeLayout.signatures = ret.signatures;
302 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
304 SUGAR.email2.composeLayout.setComposeOptions(idx);
306 //Set the error array so we can notify the user when they try to hit send if any errors
307 //are present. We will also notify them now (after hitting compose button).
308 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
311 //if error element is returning an array, then check the length to make sure we have error messages
312 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
313 //add error messages for display
314 for(i in ret.errorArray)
315 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
316 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
317 //if error element is returning an object, and the object value is not empty or null, then display error message
318 for(i in ret.errorArray)
319 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
322 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
324 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
326 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
332 handleDeleteSignature : function(o) {
334 var ret = JSON.parse(o.responseText);
335 SUGAR.email2.composeLayout.signatures = ret.signatures;
336 var field = document.getElementById('signature_id');
337 SUGAR.email2.util.emptySelectOptions(field);
339 for(var i in ret.signatures) { // iterate through assoc array
340 var opt = new Option(ret.signatures[i], i);
341 field.options.add(opt);
343 setSigEditButtonVisibility();
348 handleDeleteReturn : function(o) {
349 // force refresh ListView
351 if(document.getElementById('focusEmailMbox')) {
352 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
355 // need to display success message before calling next async call?
356 document.getElementById(this.target).innerHTML = o.responseText;
361 handleFailure : function(o) {
363 overlay('Exception occurred...', o.statusText, 'alert');
364 if(document.getElementById('saveButton')) {
365 document.getElementById('saveButton').disabled = false;
369 handleReplyForward : function(o) {
370 var a = JSON.parse(o.responseText);
372 var idx = SUGAR.email2.composeLayout.currentInstanceId;
374 document.getElementById('email_id' + idx).value = a.uid;
375 document.getElementById('emailSubject' + idx).value = a.name;
376 document.getElementById('addressTO' + idx).value = a.from;
377 document.getElementById('uid' + idx).value = a.uid;
379 document.getElementById('addressCC' + idx).value = a.cc;
380 SE.composeLayout.showHiddenAddress('cc', idx);
384 document.getElementById('type' + idx).value = a.type;
387 // apply attachment values
388 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
390 setTimeout("callbackReplyForward.finish(globalA);", 500);
393 handleReplyForwardForDraft : function(o) {
394 var a = JSON.parse(o.responseText);
396 var idx = SUGAR.email2.composeLayout.currentInstanceId;
398 document.getElementById('email_id' + idx).value = a.uid;
399 document.getElementById('emailSubject' + idx).value = a.name;
400 document.getElementById('addressTO' + idx).value = a.to;
403 document.getElementById('addressCC' + idx).value = a.cc;
404 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
408 document.getElementById('addressBCC' + idx).value = a.bcc;
409 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
414 document.getElementById('type' + idx).value = a.type;
418 // apply attachment values
419 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
421 setTimeout("callbackReplyForward.finish(globalA);", 500);
426 handleSuccess : function(o) {
427 document.getElementById(this.target).innerHTML = o.responseText;
433 ieDeleteSuccess : function(o) {
436 var ret = JSON.parse(o.responseText);
438 SUGAR.email2.accounts.refreshInboundAccountTable();
439 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
440 SUGAR.email2.accounts.rebuildFolderList();
446 ieSaveSuccess : function(o) {
447 document.getElementById('saveButton').disabled = false;
448 var a = JSON.parse(o.responseText);
451 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
452 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
454 resp = JSON.parse(o.responseText);
455 SUGAR.email2.accounts.refreshInboundAccountTable();
456 SUGAR.email2.accounts.refreshOuboundAccountTable();
457 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
458 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
462 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
469 loadAttachments : function(o) {
470 var result = JSON.parse(o.responseText);
472 SUGAR.email2.composeLayout.loadAttachments(result);
477 loadSignature : function(o) {
478 var ret = JSON.parse(o.responseText);
479 SUGAR.email2.signatures[ret.id] = ret.signature_html;
480 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
484 * Follow up to mark email read|unread|flagged
486 markEmailCleanup : function(o) {
487 var ret = JSON.parse(o.responseText);
488 if (!ret['status']) {
490 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
492 SUGAR.email2.contextMenus.markEmailCleanup();
498 rebuildShowFolders : function(o) {
499 var t = JSON.parse(o.responseText);
500 var show = document.getElementById('ieAccountListShow');
502 SUGAR.email2.util.emptySelectOptions(show);
504 for(i=0; i<t.length; i++) { // iterate through assoc array
505 var opt = new Option(t[i].text, t[i].value, t[i].selected);
506 opt.selected = t[i].selected;
507 show.options.add(opt);
510 SUGAR.email2.accounts.renderTree();
514 saveListViewSortOrderPart2 : function() {
515 // create the JSON string the func expects
516 focusFolderPath = '[ "Home", "' + ieName + '"';
518 var f = new String(focusFolder);
519 var fEx = f.split('.');
521 for(i=0; i<fEx.length; i++) {
522 focusFolderPath += ', "' + fEx[i] +'"'
525 focusFolderPath += ']';
527 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
528 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
534 sendEmailCleanUp : function(o) {
536 var ret = JSON.parse(o.responseText);
538 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
539 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
540 } else if (o.responseText) {
541 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
544 if (typeof(SE.grid) != 'undefined')
545 SE.listView.refreshGrid();
546 //Disabled while address book is disabled
548 //If this call back was initiated by quick compose from a Detail View page, refresh the
549 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
550 //close the shortcut bar menu
551 if ( (typeof(action_sugar_grp1) != 'undefined')) {
552 if(action_sugar_grp1 == 'DetailView') {
553 showSubPanel('history',null,true);
554 } else if(action_sugar_grp1 == 'quickcreate') {
561 ieSendSuccess : function(o) {
563 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
568 settingsFolderRefresh : function(o) {
569 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
570 var ret = JSON.parse(o.responseText);
571 var user = document.getElementById('userFolders');
573 SUGAR.email2.util.emptySelectOptions(user);
575 for(i=0; i<ret.userFolders.length; i++) {
576 var display = ret.userFolders[i].name;
577 var value = ret.userFolders[i].id;
578 var selected = (ret.userFolders[i].selected != "") ? true : false;
579 var opt = new Option(display, value, selected);
580 opt.selected = selected;
581 user.options.add(opt);
587 startRequest : function(callback, args, forceAbort) {
588 if(this.currentRequestObject != null) {
589 if(this.forceAbort == true) {
590 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
593 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
597 requestInProgress : function() {
598 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
603 updateFolderSubscriptions : function() {
604 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
605 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
611 updateFrameFolder : function() {
612 SUGAR.email2.folders.checkEmailAccounts();
617 updateUserPrefs : function(o) {
618 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
619 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
624 uploadAttachmentSuccessful : function(o) {
626 document.getElementById('email_attachment').value = '';
628 var ret = JSON.parse(o.responseText);
629 var idx = SUGAR.email2.composeLayout.currentInstanceId;
630 var overall = document.getElementById('addedFiles' + idx);
631 var index = overall.childNodes.length;
633 "<div id='email_attachment_bucket" + idx + index + "'>" +
635 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
636 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
637 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
639 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
640 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
642 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
644 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
647 overall.innerHTML += out;
648 if(SUGAR.email2.util.isIe()) {
649 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
653 SUGAR.email2.addFileDialog.hide();
655 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
660 ///////////////////////////////////////////////////////////////////////////
661 //// PER MODULE CALLBACK OBJECTS
662 AjaxObject.accounts = {
663 saveOutboundCleanup : function(o) {
664 SUGAR.email2.accounts.refreshOuboundAccountTable();
665 SUGAR.email2.accounts.outboundDialog.hide();
666 var id = o.responseText;
667 SUGAR.email2.accounts.newAddedOutboundId = id;
669 saveDefaultOutboundCleanup: function(o){
672 callbackEditOutbound : {
673 success : function(o)
675 var ret = JSON.parse(o.responseText);
677 SUGAR.email2.accounts.showAddSmtp();
680 document.getElementById("mail_id").value = ret.id;
681 document.getElementById("type").value = ret.type;
682 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
683 document.getElementById("mail_name").value = ret.name;
684 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
685 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
686 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
687 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
688 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
689 SUGAR.email2.accounts.smtp_authenticate_field_display();
690 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
692 if(ret.type == 'system-override') {
693 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
694 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
697 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
698 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
700 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
703 failure : AjaxObject.handleFailure,
704 timeout : AjaxObject.timeout,
707 callbackDeleteOutbound : {
708 success : function(o) {
709 var ret = JSON.parse(o.responseText);
712 if(confirm(ret.error_message))
714 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
715 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
723 SUGAR.email2.accounts.refreshOuboundAccountTable();
727 failure : AjaxObject.handleFailure,
728 timeout : AjaxObject.timeout,
732 callbackCheckMailProgress : {
733 success : function(o) {
734 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
735 SUGAR.email2.accounts.totalMsgCount = -1;
738 //Check for server timeout / errors
739 var ret = JSON.parse(o.responseText);
742 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
744 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
745 SUGAR.email2.accounts.totalMsgCount = -1;
746 //SUGAR.email2.folders.rebuildFolders();
750 var currIeId = ret['ieid'];
753 var serverCount = ret.count;
755 if (ret['status'] == 'done') {
756 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
757 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
761 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
763 currIeId = SUGAR.email2.accounts.ieIds[i+1];
765 SUGAR.email2.accounts.totalMsgCount = -1;
770 else if (ret.mbox && ret.totalcount && ret.count) {
771 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
772 if (ret.count >= ret.totalcount) {
775 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
776 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
779 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
780 SUGAR.email2.accounts.totalMsgCount = -1;
785 SUGAR.email2.accounts.totalMsgCount = -1;
787 SUGAR.email2.folders.rebuildFolders();
788 SE.listView.refreshGrid();
789 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
790 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
791 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
792 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
794 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
795 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
796 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
797 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
798 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
801 failure : AjaxObject.handleFailure,
802 timeout : AjaxObject.timeout,
807 ///////////////////////////////////////////////////////////////////////////////
809 AjaxObject.composeLayout = {
811 * Populates the record id
813 saveDraftCleanup : function(o) {
815 var ret = JSON.parse(o.responseText);
817 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
818 else if (o.responseText)
819 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
823 AjaxObject.composeLayout.callback = {
825 success : AjaxObject.composeLayout.saveDraftCleanup,
826 failure : AjaxObject.handleFailure,
827 timeout : AjaxObject.timeout,
832 AjaxObject.detailView = {
834 * Pops-up a printable view of an email
836 displayPrintable : function(o) {
837 var ret = JSON.parse(o.responseText);
838 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
839 // 2 below must be in global context
841 meta['panelId'] = SUGAR.email2.util.getPanelId();
842 email = ret.meta.email;
843 if (typeof(email.cc) == 'undefined') {
847 var out = displayTemplate.exec({
848 'app_strings' : app_strings,
856 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
857 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
859 popup.document.write(out);
860 popup.document.close();
864 * Takes formatted response and creates a modal pop-over containing a title and content
866 displayView : function(o) {
867 var SED = SUGAR.email2.detailView;
868 var ret = JSON.parse(o.responseText);
870 if(!SED.viewDialog) {
871 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
875 constraintoviewport: true,
878 SED.viewDialog.renderEvent.subscribe(function() {
879 var content = this.body.firstChild;
880 var viewH = YAHOO.util.Dom.getViewportHeight();
882 this.body.style.overflow = "auto";
883 this.body.style.width = "800px";
884 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
888 SED.viewDialog.setHeader(ret.title);
889 SED.viewDialog.setBody(ret.html);
890 SED.viewDialog.render();
891 SED.viewDialog.show();
895 * Generates a modal popup to populate with the contents of bean's full EditView
897 showQuickCreateForm : function(o) {
898 var SED = SUGAR.email2.detailView;
899 var ret = JSON.parse(o.responseText);
901 if(!SED.quickCreateDialog) {
902 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
906 constraintoviewport: true,
910 SED.quickCreateDialog.renderEvent.subscribe(function() {
911 var viewH = YAHOO.util.Dom.getViewportHeight();
913 for (var i in this.body.childNodes) {
914 if (this.body.childNodes[i].clientHeight) {
915 contH += this.body.childNodes[i].clientHeight;
916 } else if (this.body.childNodes[i].offsetHeight) {
917 contH += this.body.childNodes[i].offsetHeight;
920 this.body.style.width = "800px";
921 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
922 this.body.style.overflow = "auto";
923 }, SED.quickCreateDialog);
925 SED.quickCreateDialog.hideEvent.subscribe(function(){
926 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
927 /*for(var qsField in qsFields){
928 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
929 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
932 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
935 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
937 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
938 SED.quickCreateDialog.render();
939 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
941 SED.quickCreateDialog.ieId = ret.ieId;
942 SED.quickCreateDialog.uid = ret.uid;
943 SED.quickCreateDialog.mbox = ret.mbox;
944 SED.quickCreateDialog.qcmodule = ret.module;
946 SED.quickCreateDialog.show();
948 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
950 editForm.module.value = 'Emails';
951 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
952 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
953 var instId = ret.module + count;
954 SED.quickCreateEmailsToAdd = ret.emailAddress;
955 SED.quickCreateEmailCallback = function(instId, tableId) {
956 var eaw = SUGAR.EmailAddressWidget.instances[instId];
957 if (typeof(eaw) == "undefined")
958 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
959 + instId + "','" + tableId + "');", 100);
960 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
962 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
963 + instId + "','" + tableId + "');", 100);
967 saveQuickCreateForm : function(o) {
969 SUGAR.email2.detailView.quickCreateDialog.hide();
970 validate['EditView'] = [ ];
973 saveQuickCreateFormAndReply : function(o) {
975 var ret = JSON.parse(o.responseText);
976 SUGAR.email2.detailView.quickCreateDialog.hide();
977 var qcd = SUGAR.email2.detailView.quickCreateDialog;
978 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
980 var emailID = ret.id;
981 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
983 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
985 //Cean the validate cache to prevent errors on the next call
986 validate['EditView'] = [ ];
989 saveQuickCreateFormAndAddToAddressBook : function(o) {
991 SUGAR.email2.detailView.quickCreateDialog.hide();
992 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
993 validate['EditView'] = [ ];
996 handleAssignmentDialogAssignAction : function() {
999 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
1001 var dist = 'direct';
1005 var found_teams = false;
1006 var warning_message = mod_strings.LBL_WARN_NO_USERS;
1007 if(!found_teams && assign_user_id == '' )
1009 alert(warning_message);
1013 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1015 for(i=0; i<emailUids.length; i++) {
1017 uids += app_strings.LBL_EMAIL_DELIMITER;
1019 uids += emailUids[i];
1022 var row = SUGAR.email2.grid.getSelectedRows()[0];
1023 var data = SUGAR.email2.grid.getRecord(row).getData();
1024 var ieid = data.ieId;
1025 var mbox = data.mbox;
1026 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
1027 SUGAR.email2.contextMenus.assignToDialogue.hide();
1028 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
1032 handleAssignmentDialogDeleteAction : function() {
1033 // TO pass list of UIDS/emailIds
1034 var uids = SUGAR.email2.listView.getUidsFromSelection();
1035 var row = SUGAR.email2.grid.getSelections()[0];
1036 var ieid = row.data.ieId;
1037 var mbox = row.data.mbox;
1038 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
1039 SUGAR.email2.contextMenus.assignmentDialog.hide();
1040 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1046 showEmailDetailView : function(o) {
1048 var SED = SUGAR.email2.detailView;
1049 var ret = JSON.parse(o.responseText);
1051 if(!SED.quickCreateDialog) {
1052 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
1056 constraintoviewport: true,
1058 autofillheight: "body",
1061 SED.quickCreateDialog.renderEvent.subscribe(function() {
1062 var viewHeight = YAHOO.util.Dom.getViewportHeight();
1064 for (var i in this.body.childNodes) {
1065 if (this.body.childNodes[i].offsetHeight)
1066 contH += this.body.childNodes[i].offsetHeight;
1068 this.body.style.overflow = "auto";
1069 this.body.style.width = "800px";
1070 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
1072 }, SED.quickCreateDialog);
1074 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
1075 SED.quickCreateDialog.setBody(ret.html);
1076 SED.quickCreateDialog.render();
1077 SUGAR.util.evalScript(ret.html);
1078 SED.quickCreateDialog.show();
1081 showAssignmentDialogWithData : function(o) {
1082 var SEC = SUGAR.email2.contextMenus;
1084 var ret = JSON.parse(o.responseText);
1085 if (!SEC.assignmentDialog) {
1086 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
1089 constraintoviewport: true,
1092 SEC.assignmentDialog.setBody("");
1093 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
1094 SEC.assignmentDialog.renderEvent.subscribe(function() {
1095 var iev = YAHOO.util.Dom.get("Distribute");
1097 this.body.style.width = "700px";
1099 }, SEC.assignmentDialog);
1100 SEC.assignmentDialog.render();
1102 SEC.assignmentDialog.setBody(ret);
1103 SEC.assignmentDialog.render();
1105 SEC.assignmentDialog.show();
1106 SUGAR.util.evalScript(ret);
1109 showImportForm : function(o) {
1110 var SED = SUGAR.email2.detailView;
1111 var ret = JSON.parse(o.responseText);
1113 document.getElementById('quickCreateContent').innerHTML = "";
1119 if(!SED.importDialog) {
1120 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
1124 constraintoviewport: true,
1126 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
1127 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
1131 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
1132 SED.importDialog.setBody("");
1133 SED.importDialog.hideEvent.subscribe(function(){
1134 for(var i in QSFieldsArray) {
1135 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
1136 QSFieldsArray[i].destroy();
1137 delete QSFieldsArray[i];
1139 if (QSProcessedFieldsArray[i]) {
1140 QSProcessedFieldsArray[i] = false;
1144 SED.importDialog.renderEvent.subscribe(function() {
1145 var iev = YAHOO.util.Dom.get("ImportEditView");
1147 //this.body.style.height = (iev.clientHeight + 10) + "px";
1148 this.body.style.width = "600px";
1150 }, SED.importDialog);
1151 SED.importDialog.render();
1153 SED.importDialog.setBody(ret.html);
1154 SED.importDialog.ret = ret;
1155 SUGAR.util.evalScript(ret.html);
1156 SED.importDialog.render();
1158 SED.importDialog.show();
1159 SED.importDialog.focusFirstButton();
1161 getImportAction : function(ret) {
1162 if (!check_form('ImportEditView')) return false;
1163 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
1164 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
1168 var editView = document.getElementById('ImportEditView');
1169 if (editView.assigned_user_id != null) {
1170 get = get + "&user_id=" + editView.assigned_user_id.value
1171 //var user_id = editView.assigned_user_id.value;
1173 var parent_id = editView.parent_id.value;
1174 var parent_type = editView.parent_type.value;
1175 var row = SUGAR.email2.grid.getSelectedRows()[0];
1176 row = SUGAR.email2.grid.getRecord(row);
1177 var data = row.getData();
1178 var ieId = data.ieId;
1179 var mbox = data.mbox;
1180 var serverDelete = editView.serverDelete.checked;
1181 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1183 for(i=0; i<emailUids.length; i++) {
1185 uids += app_strings.LBL_EMAIL_DELIMITER;
1187 uids += emailUids[i];
1190 var action = 'importEmail&uid=';
1192 action = 'moveEmails';
1193 action = action + '&sourceFolder=' + ret['srcFolder'];
1194 action = action + '&sourceIeId=' + ret['srcIeId'];
1195 action = action + '&destinationFolder=' + ret['dstFolder'];
1196 action = action + '&destinationIeId=' + ret['dstIeId'];
1197 action = action + '&emailUids=';
1199 if (action.search(/importEmail/) != -1) {
1200 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
1202 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
1205 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
1206 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
1207 SUGAR.email2.detailView.importDialog.hide();
1208 document.getElementById('importDialogContent').innerHTML = "";
1211 showRelateForm : function(o) {
1212 var SED = SUGAR.email2.detailView;
1213 var ret = JSON.parse(o.responseText);
1214 document.getElementById('quickCreateContent').innerHTML = "";
1219 dialog_loaded = true;
1221 if(!SED.relateDialog) {
1222 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
1227 constraintoviewport: true,
1229 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
1230 if (!check_form('RelateEditView')) return false;
1232 var editView = document.getElementById('RelateEditView');
1233 var parent_id = editView.parent_id.value;
1234 var parent_type = editView.parent_type.value;
1235 var row = SUGAR.email2.grid.getSelectedRows()[0];
1236 row = SUGAR.email2.grid.getRecord(row);
1237 var ieId = row.getData().ieId;
1238 var mbox = row.getData().mbox;
1239 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1241 for(i=0; i<emailUids.length; i++) {
1243 uids += app_strings.LBL_EMAIL_DELIMITER;
1245 uids += emailUids[i];
1247 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1248 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
1249 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
1250 SED.relateDialog.hide();
1251 document.getElementById('relateDialogContent').innerHTML = "";
1256 SED.relateDialog.hideEvent.subscribe(function(){
1257 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
1258 QSFieldsArray['ImportEditView_parent_name'].destroy();
1259 delete QSFieldsArray['ImportEditView_parent_name'];
1261 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
1262 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
1266 SED.relateDialog.renderEvent.subscribe(function() {
1267 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
1269 for (var i in this.body.childNodes) {
1270 if (this.body.childNodes[i].clientHeight)
1271 contH += this.body.childNodes[i].clientHeight;
1273 }, SED.relateDialog);
1274 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
1277 SED.relateDialog.setBody(ret.html);
1278 SED.relateDialog.render();
1279 SUGAR.util.evalScript(ret.html);
1280 SED.relateDialog.show();
1284 * DetailView callbacks
1286 AjaxObject.detailView.callback = {
1288 success : function(o) {
1290 var ret = JSON.parse(o.responseText);
1291 SUGAR.email2.detailView.consumeMetaDetail(ret);
1293 argument: [targetDiv],
1294 failure : AjaxObject.handleFailure,
1299 success : function(o) {
1301 var ret = JSON.parse(o.responseText);
1302 SUGAR.email2.detailView.consumeMetaPreview(ret);
1304 failure : AjaxObject.handleFailure,
1309 success : AjaxObject.detailView.displayPrintable,
1310 failure : AjaxObject.handleFailure,
1311 timeout : AjaxObject.timeout,
1315 success : AjaxObject.detailView.displayView,
1316 failure : AjaxObject.handleFailure,
1317 timeout : AjaxObject.timeout,
1326 AjaxObject.folders = {
1328 * check-mail post actions
1330 checkMailCleanup : function(o) {
1332 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
1334 // refresh focus ListView
1335 SE.listView.refreshGrid();
1336 SUGAR.email2.folders.startCheckTimer(); // resets the timer
1341 rebuildFolders : function(o) {
1344 var data = JSON.parse(o.responseText);
1346 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
1347 SUGAR.email2.folders.setSugarFolders();
1350 AjaxObject.folders.callback = {
1352 success : AjaxObject.folders.checkMailCleanup,
1353 failure : AjaxObject.handleFailure,
1354 timeout : 600000, // 5 mins
1359 AjaxObject.rules = {
1360 loadRulesForSettings : function(o) {
1361 document.getElementById("rulesListCell").innerHTML = o.responseText;
1362 // assume we have the class we need
1363 SUGAR.routing.getStrings();
1364 SUGAR.routing.getDependentDropdowns();
1367 //// END PER MODULE CALLBACK OBJECTS
1368 ///////////////////////////////////////////////////////////////////////////
1372 success : AjaxObject.handleSuccess,
1373 failure : AjaxObject.handleFailure,
1374 timeout : AjaxObject.timeout,
1377 var callbackAccount = {
1378 success : AjaxObject.ieSaveSuccess,
1379 failure : AjaxObject.handleFailure,
1380 timeout : AjaxObject.timeout,
1383 var callbackAccountDelete = {
1384 success : AjaxObject.ieDeleteSuccess,
1385 failure : AjaxObject.handleFailure,
1386 timeout : AjaxObject.timeout,
1389 var callbackOutboundTest = {
1390 success : AjaxObject.ieSendSuccess,
1391 failure : AjaxObject.handleFailure,
1392 timeout : AjaxObject.timeout,
1398 var callbackTeamInfoForSettings = {
1399 success : function (o) {
1400 var data = JSON.parse(o.responseText);
1401 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
1403 failure : AjaxObject.handleFailure,
1404 timeout : AjaxObject.timeout,
1409 var callbackStatusForImport = {
1410 success : function (o) {
1412 if (o.responseText != "") {
1413 var statusString = "";
1414 var data = JSON.parse(o.responseText);
1415 for(i=0; i<data.length; i++) {
1416 statusString = statusString + data[i] + '<br/>';
1418 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
1420 SE.listView.refreshGrid();
1423 failure : AjaxObject.handleFailure,
1424 timeout : AjaxObject.timeout,
1428 var callbackComposeCache = {
1429 success : AjaxObject.composeCache,
1430 failure : AjaxObject.handleFailure,
1431 timeout : AjaxObject.timeout,
1434 var callbackDelete = {
1435 success : AjaxObject.handleDeleteReturn,
1436 failure : AjaxObject.handleFailure,
1437 timeout : AjaxObject.timeout,
1440 var callbackEmailDetailMultiple = {
1441 success : function(o) {
1443 var retMulti = JSON.parse(o.responseText);
1444 var ret = new Object();
1446 for(var i=0; i<retMulti.length; i++) {
1449 SUGAR.email2._setDetailCache(ret);
1450 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
1453 failure : AjaxObject.handleFailure,
1457 var callbackListViewSortOrderChange = {
1458 success : AjaxObject.saveListViewSortOrderPart2,
1459 failure : AjaxObject.handleFailure,
1460 timeout : AjaxObject.timeout,
1462 argument : [ieId, ieName, focusFolder]
1464 var callbackEmptyTrash = {
1465 success : function(o) {
1467 AjaxObject.folderRenameCleanup;
1469 failure : AjaxObject.handleFailure,
1470 timeout : AjaxObject.timeout,
1473 var callbackClearCacheFiles = {
1474 success : function(o) {
1477 failure : AjaxObject.handleFailure,
1478 timeout : AjaxObject.timeout,
1481 var callbackFolderRename = {
1482 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
1483 failure : AjaxObject.handleFailure,
1484 timeout : AjaxObject.timeout,
1487 var callbackFolderDelete = {
1488 success : function(o) {
1489 var ret = JSON.parse(o.responseText);
1491 if (ret.folder_id) {
1492 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
1494 SUGAR.email2.tree.removeNode(node, true);
1495 } else if (ret.ieId && ret.mbox) {
1496 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
1498 SUGAR.email2.tree.removeNode(node, true);
1501 //SUGAR.email2.folders.loadSettingFolder();
1504 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
1507 failure : AjaxObject.handleFailure,
1508 timeout : AjaxObject.timeout,
1511 var callbackFolderSave = {
1512 success : function(o) {
1513 var ret = JSON.parse(o.responseText);
1515 switch(ret.action) {
1516 case 'newFolderSave':
1517 SUGAR.email2.folders.rebuildFolders();
1521 failure : AjaxObject.handleFailure,
1522 timeout : AjaxObject.timeout,
1525 var callbackFolderSubscriptions = {
1526 success : AjaxObject.updateFolderSubscriptions,
1527 failure : AjaxObject.handleFailure,
1528 timeout : AjaxObject.timeout,
1531 var callbackFolderUpdate = {
1532 success : AjaxObject.updateFrameFolder,
1533 failure : AjaxObject.handleFailure,
1534 timeout : AjaxObject.timeout,
1537 var callbackFolders = {
1538 success : AjaxObject.folders.rebuildFolders,
1539 //success : void(true),
1540 failure : AjaxObject.handleFailure,
1541 timeout : AjaxObject.timeout,
1544 var callbackFullSync = {
1545 success : AjaxObject.fullSyncCleanup,
1546 failure : AjaxObject.handleFailure,
1547 timeout : 9999999999999,
1550 var callbackGeneric = {
1551 success : function() {
1554 failure : AjaxObject.handleFailure,
1555 timeout : AjaxObject.timeout,
1558 var callbackIeAccountRetrieve = {
1559 success : function(o) {
1560 // return JSON encoding
1562 SUGAR.email2.accounts.fillIeAccount(o.responseText);
1563 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
1565 failure : AjaxObject.handleFailure,
1566 timeout : AjaxObject.timeout,
1569 var callbackImportOneEmail = {
1570 success : AjaxObject.detailView.showImportForm,
1571 failure : AjaxObject.handleFailure,
1572 timeout : AjaxObject.timeout,
1575 var callbackRelateEmail = {
1576 success : AjaxObject.detailView.showRelateForm,
1577 failure : AjaxObject.handleFailure,
1578 timeout : AjaxObject.timeout,
1581 var callbackEmailDetailView = {
1582 success : AjaxObject.detailView.showEmailDetailView,
1583 failure : AjaxObject.handleFailure,
1584 timeout : AjaxObject.timeout,
1587 var callbackAssignmentDialog = {
1588 success : AjaxObject.detailView.showAssignmentDialogWithData,
1589 failure : AjaxObject.handleFailure,
1590 timeout : AjaxObject.timeout,
1593 var callbackAssignmentAction = {
1594 success : function(o) {
1595 SE.listView.refreshGrid();
1597 if(o.responseText != '') {
1598 overlay('Assignment action result', o.responseText, 'alert');
1601 failure : AjaxObject.handleFailure,
1602 timeout : AjaxObject.timeout,
1605 var callbackMoveEmails = {
1606 success : function(o) {
1607 SE.listView.refreshGrid();
1609 if(o.responseText != '') {
1610 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
1613 failure : AjaxObject.handleFailure,
1614 timeout : AjaxObject.timeout,
1617 var callbackLoadAttachments = {
1618 success : AjaxObject.loadAttachments,
1619 failure : AjaxObject.handleFailure,
1620 timeout : AjaxObject.timeout,
1623 var callbackLoadRules = {
1624 success : AjaxObject.rules.loadRulesForSettings,
1625 failure : AjaxObject.handleFailure,
1626 timeout : AjaxObject.timeout,
1629 var callbackLoadSignature = {
1630 success : AjaxObject.loadSignature,
1631 failure : AjaxObject.handleFailure,
1632 timeout : AjaxObject.timeout,
1635 var callbackDeleteSignature = {
1636 success : AjaxObject.handleDeleteSignature,
1637 failure : AjaxObject.handleFailure,
1638 timeout : AjaxObject.timeout,
1641 /*var callbackMoveEmails = {
1642 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
1643 failure : AjaxObject.handleFailure,
1644 timeout : AjaxObject.timeout,
1647 var callbackOutboundSave = {
1648 success : AjaxObject.accounts.saveOutboundCleanup,
1649 failure : AjaxObject.handleFailure,
1650 timeout : AjaxObject.timeout,
1653 var callbackDefaultOutboundSave = {
1654 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
1655 failure : AjaxObject.handleFailure,
1656 timeout : AjaxObject.timeout,
1659 var callbackQuickCreate = {
1660 success : AjaxObject.detailView.showQuickCreateForm,
1661 failure : AjaxObject.handleFailure,
1662 timeout : AjaxObject.timeout,
1665 var callbackQuickCreateSave = {
1666 success : AjaxObject.detailView.saveQuickCreateForm,
1667 failure : AjaxObject.handleFailure,
1668 timeout : AjaxObject.timeout,
1671 var callbackQuickCreateSaveAndAddToAddressBook = {
1672 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
1673 failure : AjaxObject.handleFailure,
1674 timeout : AjaxObject.timeout,
1677 var callbackQuickCreateSaveAndReply = {
1678 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
1679 failure : AjaxObject.handleFailure,
1680 timeout : AjaxObject.timeout,
1683 var callbackQuickCreateSaveAndReplyCase = {
1684 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
1685 failure : AjaxObject.handleFailure,
1686 timeout : AjaxObject.timeout,
1689 var callbackRebuildShowAccountList = {
1690 success : AjaxObject.rebuildShowFolders,
1691 failure : AjaxObject.handleFailure,
1692 timeout : AjaxObject.timeout,
1696 var callbackRefreshSugarFolders = {
1697 success : function(o) {
1698 var t = JSON.parse(o.responseText);
1699 SUGAR.email2.folders.setSugarFoldersEnd(t);
1701 failure : AjaxObject.handleFailure,
1702 timeout : AjaxObject.timeout,
1705 var callbackReplyForward = {
1706 success : AjaxObject.handleReplyForward,
1707 finish : function(a, retryCount) {
1708 if (typeof(retryCount) == 'undefined') {
1713 var idx = SUGAR.email2.composeLayout.currentInstanceId;
1714 var t = tinyMCE.getInstanceById('htmleditor' + idx);
1716 var html = t.getContent();
1718 if (a.type != 'draft') {
1719 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
1720 html += " <div><hr></div>" + a.description;
1722 html = " <div><hr></div>" + a.description + html;
1725 html = a.description;
1728 t.setContent(html);//
1731 if (retryCount < 5) {
1732 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
1736 var tabArray = SUGAR.email2.innerLayout.get("tabs");
1737 if (tabArray != null && tabArray.length > 0) {
1738 for (i = 0 ; i < tabArray.length ; i++) {
1739 var tabObject = tabArray[i];
1740 if (tabObject.get("id") == ("composeTab" + idx)) {
1741 var tabLabel = a.name;
1742 if (tabLabel != null && tabLabel.length > 25) {
1743 tabLabel = tabLabel.substring(0, 25) + "...";
1745 tabObject.get("labelEl").firstChild.data = tabLabel;
1751 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
1752 if (a.parent_name != null && a.parent_name != "") {
1753 document.getElementById('data_parent_name' + idx).value = a.parent_name;
1755 if (a.parent_type != null && a.parent_type != "") {
1756 document.getElementById('data_parent_type' + idx).value = a.parent_type;
1758 if (a.parent_id != null && a.parent_id != "") {
1759 document.getElementById('data_parent_id' + idx).value = a.parent_id;
1761 if (a.fromAccounts.status) {
1762 var addressFrom = document.getElementById('addressFrom' + idx);
1763 SUGAR.email2.util.emptySelectOptions(addressFrom);
1764 var fromAccountOpts = a.fromAccounts.data;
1765 for(i=0; i<fromAccountOpts.length; i++) {
1766 var key = fromAccountOpts[i].value;
1767 var display = fromAccountOpts[i].text;
1768 var opt = new Option(display, key);
1769 if (fromAccountOpts[i].selected) {
1770 opt.selected = true;
1772 addressFrom.options.add(opt);
1778 failure : AjaxObject.handleFailure,
1779 timeout : AjaxObject.timeout,
1781 argument : [sendType]
1783 var callbackSendEmail = {
1784 success : AjaxObject.sendEmailCleanUp,
1785 failure : AjaxObject.handleFailure,
1786 timeout : AjaxObject.timeout,
1789 var callbackSettings = {
1790 success : AjaxObject.updateUserPrefs,
1791 failure : AjaxObject.handleFailure,
1792 timeout : AjaxObject.timeout,
1795 var callbackSettingsFolderRefresh = {
1796 success : AjaxObject.settingsFolderRefresh,
1797 failure : AjaxObject.handleFailure,
1798 timeout : AjaxObject.timeout,
1801 var callbackLoadSettingFolder = {
1802 success : function(o) {
1803 AjaxObject.settingsFolderRefresh(o);
1804 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
1806 failure : AjaxObject.handleFailure,
1807 timeout : AjaxObject.timeout,
1811 var callbackUploadAttachment = {
1812 success : AjaxObject.uploadAttachmentSuccessful,
1813 upload : AjaxObject.uploadAttachmentSuccessful,
1814 failure : AjaxObject.handleFailure,
1815 timeout : AjaxObject.timeout,
1818 var callbackUserPrefs = {
1819 success : function(o) {
1820 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
1822 failure : AjaxObject.handleFailure,
1823 timeout : AjaxObject.timeout,
1827 var callbackContextmenus = {
1829 success : AjaxObject.markEmailCleanup,
1830 failure : AjaxObject.handleFailure,
1831 timeout : AjaxObject.timeout,
1836 var callbackCheckEmail2 = {
1837 success : function(o) {
1838 var ret = JSON.parse(o.responseText);
1839 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
1843 failure : AjaxObject.handleFailure,
1844 timeout : AjaxObject.timeout,
1846 }// End of File modules/Emails/javascript/ajax.js
1848 /*********************************************************************************
1849 * SugarCRM Community Edition is a customer relationship management program developed by
1850 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
1852 * This program is free software; you can redistribute it and/or modify it under
1853 * the terms of the GNU Affero General Public License version 3 as published by the
1854 * Free Software Foundation with the addition of the following permission added
1855 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
1856 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
1857 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
1859 * This program is distributed in the hope that it will be useful, but WITHOUT
1860 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1861 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
1864 * You should have received a copy of the GNU Affero General Public License along with
1865 * this program; if not, see http://www.gnu.org/licenses or write to the Free
1866 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
1869 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
1870 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
1872 * The interactive user interfaces in modified source and object code versions
1873 * of this program must display Appropriate Legal Notices, as required under
1874 * Section 5 of the GNU Affero General Public License version 3.
1876 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
1877 * these Appropriate Legal Notices must retain the display of the "Powered by
1878 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
1879 * technical reasons, the Appropriate Legal Notices must display the words
1880 * "Powered by SugarCRM".
1881 ********************************************************************************/
1883 function gridInit() {
1884 if(SUGAR.email2.grid) {
1885 SUGAR.email2.grid.destroy();
1891 var Ck = YAHOO.util.Cookie;
1892 var widths = [ 10, 10, 150, 250, 175, 125 ];
1894 if (Ck.get("EmailGridWidths")) {
1895 for (var i=0; i < widths.length; i++) {
1896 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
1899 for (var i=0; i < widths.length; i++) {
1900 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
1904 // changes "F" to an icon
1905 function flaggedIcon(cell, record, column, value) {
1907 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
1910 // changes "A" to replied icon
1911 function repliedIcon(cell, record, column, value) {
1913 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
1916 function attachIcon(cell, record, column, value) {
1918 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
1925 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
1930 formatter: attachIcon,
1934 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
1939 formatter: flaggedIcon,
1943 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
1948 formatter: repliedIcon,
1952 label: app_strings.LBL_EMAIL_FROM,
1959 label: app_strings.LBL_EMAIL_SUBJECT,
1966 label: mod_strings.LBL_LIST_DATE,
1973 label: app_strings.LBL_EMAIL_TO,
2009 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2010 responseType: YAHOO.util.DataSource.TYPE_JSON,
2012 resultsList: 'Email',
2013 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
2014 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
2020 action : "EmailUIAjax",
2021 emailUIAction : "getMessageList",
2024 forceRefresh : "false"
2026 if(lazyLoadFolder != null) {
2027 params['mbox'] = lazyLoadFolder.folder;
2028 params['ieId'] = lazyLoadFolder.ieId;
2029 //Check if the folder is a Sugar Folder
2030 var test = new String(lazyLoadFolder.folder);
2031 if(test.match(/SUGAR\./)) {
2032 params['emailUIAction'] = 'getMessageListSugarFolders';
2033 params['mbox'] = test.substr(6);
2036 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
2039 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
2040 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2042 paginator: new YAHOO.widget.Paginator({
2043 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
2044 containers : ["dt-pag-nav"],
2045 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2046 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2047 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2048 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2049 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2051 initialRequest:SUGAR.util.paramsToUrl(params),
2058 //Override Paging request construction
2059 grid.set("generateRequest", function(oState, oSelf) {
2060 oState = oState || {pagination:null, sortedBy:null};
2061 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
2062 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2063 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2064 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2065 // Build the request
2067 SUGAR.util.paramsToUrl(oSelf.params) +
2070 "&start=" + startIndex +
2071 ((results !== null) ? "&limit=" + results : "");
2076 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2077 oPayload = oPayload || { };
2079 oPayload.totalRecords = oResponse.meta.total;
2080 oPayload.unreadRecords = oResponse.meta.unread;
2082 var tabObject = SE.innerLayout.get("tabs")[0];
2084 if (this.params.mbox != null) {
2085 mboxTitle = this.params.mbox;
2087 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
2088 tabObject.get("labelEl").firstChild.data = tabtext;
2091 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
2093 node.data.unseen = oResponse.meta.unread;
2094 SE.accounts.renderTree();
2100 var resize = grid.resizeGrid = function () {
2101 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
2102 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
2104 grid.convertDDRows = function() {
2105 var rowEl = this.getFirstTrEl();
2106 while (rowEl != null) {
2107 new this.DDRow(this, this.getRecord(rowEl), rowEl);
2108 rowEl = this.getNextTrEl(rowEl);
2113 grid.on("columnResizeEvent", function(o) {
2114 //Find the index of the column
2115 var colSet = SUGAR.email2.grid.getColumnSet().flat;
2116 for (var i=0; i < colSet.length; i++) {
2117 if (o.column == colSet[i]) {
2118 //Store it in the cookie
2119 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
2122 //this.resizeGrid();
2125 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
2126 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
2127 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
2129 SUGAR.email2.listViewLayout.on("render", resize);
2132 //Setup the default load parameters
2133 SUGAR.email2.grid.params = params;
2135 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
2136 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2137 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2144 function initRowDD() {
2145 var sg = SUGAR.email2.grid,
2146 Dom = YAHOO.util.Dom;
2147 sg.DDRow = function(oDataTable, oRecord, elTr) {
2148 if(oDataTable && oRecord && elTr) {
2149 this.ddtable = oDataTable;
2150 this.table = oDataTable.getTableEl();
2153 this.newIndex = null;
2155 this.initFrame(); // Needed for DDProxy
2156 this.invalidHandleTypes = {};
2160 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
2161 _resizeProxy: function() {
2162 this.constructor.superclass._resizeProxy.apply(this, arguments);
2163 var dragEl = this.getDragEl(),
2165 var xy = Dom.getXY(el);
2167 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
2168 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
2169 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
2170 Dom.setStyle(dragEl, 'display', "");
2173 startDrag: function(x, y) {
2174 //Check if we should be dragging a set of rows rather than just the one.
2175 var selectedRows = this.ddtable.getSelectedRows();
2176 var iSelected = false;
2177 for (var i in selectedRows) {
2178 if (this.rowEl.id == selectedRows[i]) {
2185 for (var i in selectedRows) {
2186 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
2189 this.rows = [this.row];
2190 this.ddtable.unselectAllRows();
2191 this.ddtable.selectRow(this.row);
2194 //Initialize the dragable proxy
2195 var dragEl = this.getDragEl();
2196 var clickEl = this.getEl();
2197 Dom.setStyle(clickEl, "opacity", "0.25");
2198 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
2199 Dom.addClass(dragEl, "yui-dt-liner");
2200 Dom.setStyle(dragEl, "opacity", "0.5");
2201 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
2202 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
2203 Dom.setStyle(dragEl, "border", "2px solid gray");
2206 clickValidator: function(e) {
2207 if (this.row.getData()[0] == " ")
2209 var target = YAHOO.util.Event.getTarget(e);
2210 return ( this.isValidHandleChild(target) &&
2211 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
2214 * This funciton checks that the target of the drag is a table row in this
2215 * DDGroup and simply moves the sourceEL to that location as a preview.
2217 onDragOver: function(ev, id) {
2218 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
2219 if (node && node != this.targetNode) {
2220 this.targetNode = node;
2221 SUGAR.email2.folders.unhighliteAll();
2226 onDragOut: function(e, id) {
2227 if (this.targetNode) {
2228 SUGAR.email2.folders.unhighliteAll();
2229 this.targetNode = false;
2232 endDrag: function() {
2233 Dom.setStyle(this.getEl(), "opacity", "");
2234 Dom.setStyle(this.getDragEl(), "display", "none");
2235 if (this.targetNode) {
2236 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
2238 SUGAR.email2.folders.unhighliteAll();
2244 function AddressSearchGridInit() {
2245 function moduleIcon(elCell, oRecord, oColumn, oData) {
2246 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
2248 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
2249 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
2251 var checkHeader = '<input type="checkbox" ';
2252 if (SUGAR.email2.util.isIe()) {
2253 checkHeader += 'style="top:-5px" ';
2255 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
2260 formatter: selectionCheckBox,
2264 label: mod_strings.LBL_LIST_TYPE,
2266 formatter: moduleIcon,
2270 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
2276 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
2282 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2283 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
2285 resultsList: 'Person',
2286 fields: ['name', 'email', 'bean_id', 'bean_module'],
2287 metaFields: {total: 'TotalCount'}
2289 //enable sorting on the server accross all data
2292 dataModel.params = {
2295 action : "EmailUIAjax",
2296 emailUIAction:"getAddressSearchResults"
2298 var rb = document.getElementById('hasRelatedBean').checked;
2300 var idx = SUGAR.email2.composeLayout.currentInstanceId;
2301 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2302 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2303 dataModel.params['related_bean_id'] = relatedBeanId;
2304 dataModel.params['related_bean_type'] = relatedBeanType;
2305 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
2307 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
2309 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
2310 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2312 paginator: new YAHOO.widget.Paginator({
2314 containers : ["dt-pag-nav-addressbook"],
2315 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2316 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2317 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2318 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2319 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2321 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
2325 //Override Paging request construction
2326 grid.set("generateRequest", function(oState, oSelf) {
2327 oState = oState || {pagination:null, sortedBy:null};
2328 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
2329 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2330 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2331 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2332 // Build the request
2334 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
2335 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
2336 ((results !== null) ? "&limit=" + results : "");
2340 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2341 oPayload = oPayload || { };
2342 oPayload.totalRecords = oResponse.meta.total;
2346 grid.clickToggleSelect= function(args) {
2347 var isIE = (args.event.target == null);
2348 var targetElement = isIE ? args.event.srcElement : args.event.target;
2349 if(targetElement.type == null || targetElement.type != 'checkbox') {
2350 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
2354 grid.reSelectRowsOnRender = function (){
2355 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2356 for (var i = 0; i < rows.length; i++)
2358 var emailAddress = rows[i].getData("email");
2359 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
2362 rows[i].setData("selected", true);
2363 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2367 rows[i].setData("selected", false);
2368 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
2372 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
2373 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
2374 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
2375 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
2378 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2379 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2381 grid.toggleSelectCheckbox = function(id,checked){
2382 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2383 row.setData("checked",checked);
2385 grid.toggleSelect = function(id, checked) {
2386 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2387 checked = row.getData("selected");
2390 SUGAR.email2.addressBook.grid.selectRow(row);
2391 SE.addressBook.insertContactRowToResultTable(id,null)
2394 SUGAR.email2.addressBook.grid.unselectRow(row);
2395 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
2397 row.setData("selected", !checked);
2400 grid.toggleSelectAll = function(checked) {
2401 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2402 for (var i = 0; i < rows.length; i++) {
2403 if (typeof(rows[i]) != "undefined")
2404 rows[i].setData("checked", checked);
2406 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2407 for (var i = 0; i < checkBoxes.length; i++) {
2408 checkBoxes[i].checked = checked;
2412 //Initialize the grid result table.
2413 AddressSearchResultsGridInit();
2419 * Initalize the results table for the address book selection.
2422 function AddressSearchResultsGridInit()
2425 /* Full name sort funciton to compare by last name if available */
2426 var fullNameSort = function(a, b, desc) {
2427 // Deal with empty values
2428 if(!YAHOO.lang.isValue(a))
2429 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
2430 else if(!YAHOO.lang.isValue(b))
2433 var aNames = a.getData("name").split(' ');
2434 var bNames = b.getData("name").split(' ');
2436 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
2437 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
2439 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
2443 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
2444 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
2445 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
2447 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})},
2448 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
2450 var myDataSource = new YAHOO.util.DataSource([]);
2451 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
2452 myDataSource.responseSchema = {
2453 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
2456 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
2457 width: "350px",height: "250px", MSG_EMPTY: " "});
2459 var highlightEditableCell = function(oArgs) {
2460 var elCell = oArgs.target;
2461 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
2462 this.highlightCell(elCell);
2466 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
2467 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
2468 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
2469 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
2470 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
2472 //Setup the context menus
2473 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
2474 var task = p_aArgs[1];
2477 var elRow = this.contextEventTarget;
2478 elRow = p_myDataTable.getTrEl(elRow);
2485 var oRecord = p_myDataTable.getRecord(elRow);
2486 p_myDataTable.deleteRow(elRow);
2487 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2492 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
2493 {trigger:gridResults.getTbodyEl()});
2494 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
2495 contextMenu.render("addrSearchResultGrid");
2496 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
2498 // End of File modules/Emails/javascript/grid.js
2500 /*********************************************************************************
2501 * SugarCRM Community Edition is a customer relationship management program developed by
2502 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
2504 * This program is free software; you can redistribute it and/or modify it under
2505 * the terms of the GNU Affero General Public License version 3 as published by the
2506 * Free Software Foundation with the addition of the following permission added
2507 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
2508 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
2509 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
2511 * This program is distributed in the hope that it will be useful, but WITHOUT
2512 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
2513 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
2516 * You should have received a copy of the GNU Affero General Public License along with
2517 * this program; if not, see http://www.gnu.org/licenses or write to the Free
2518 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
2521 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
2522 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
2524 * The interactive user interfaces in modified source and object code versions
2525 * of this program must display Appropriate Legal Notices, as required under
2526 * Section 5 of the GNU Affero General Public License version 3.
2528 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
2529 * these Appropriate Legal Notices must retain the display of the "Powered by
2530 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
2531 * technical reasons, the Appropriate Legal Notices must display the words
2532 * "Powered by SugarCRM".
2533 ********************************************************************************/
2536 var sw = YAHOO.SUGAR,
2537 Event = YAHOO.util.Event,
2538 Connect = YAHOO.util.Connect,
2539 Dom = YAHOO.util.Dom
2542 ///////////////////////////////////////////////////////////////////////////////
2545 _contactCache : new Array(), // cache of contacts
2546 _dd : new Array(), // filtered list, same format as _contactCache
2547 _ddLists : new Array(), // list of Lists
2548 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
2549 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
2550 clickBubble : true, // hack to get around onclick event bubbling
2552 relatedBeanType : '',
2555 itemSpacing : 'white-space:nowrap; padding:2px;',
2561 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
2563 initFixForDatatableSort: function () {
2564 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
2565 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
2566 var oColumn = this._oColumnSet.getColumn(column);
2569 // Validate TD element
2570 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
2572 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
2574 // Validate TH element
2576 elCell = this.getThEl(column);
2579 var allColumns = this._oColumnSet.flat;
2580 for(var i=0, len=allColumns.length; i<len; i++) {
2581 if(allColumns[i].getThEl().id === elCell.id) {
2582 oColumn = allColumns[i];
2593 cancelEdit : function() {
2594 if(this.editContactDialog)
2595 this.editContactDialog.hide();
2596 if(this.editMailingListDialog)
2597 this.editMailingListDialog.hide();
2601 * Clears filter form
2603 clear : function() {
2604 var t = document.getElementById('contactsFilter');
2610 * handle context-menu Compose-to call
2611 * @param string type 'contacts' or 'lists'
2613 composeTo : function(type, waited) {
2614 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
2615 if (activePanel.substring(0, 10) != "composeTab") {
2616 SE.composeLayout.c0_composeNewEmail();
2617 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
2618 SE.contextMenus.contactsContextMenu.hide();
2621 var idx = activePanel.substring(10);
2624 // determine if we have a selection to work with
2625 if(type == 'contacts') {
2626 var ids = SE.contactView.getSelectedRows();
2627 for (var i in ids) {
2628 rows[i] = SE.contactView.getRecord(ids[i]);
2630 removeHiddenNodes(rows, SE.contactView);
2634 if(rows.length > 0) {
2635 SE.composeLayout.handleDrop(
2636 (type == 'contacts') ? SE.contactView : SE.emailListsView,
2637 null, rows, 'addressTO' + idx );
2639 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
2643 editContact : function() {
2644 SE.contextMenus.contactsContextMenu.hide();
2645 var element = SE.contactView.getSelectedNodes()[0];
2647 if (element.className.indexOf('address-contact') > -1) {
2648 elementId = element.id;
2649 } else if (element.className.indexOf('address-exp-contact') > -1) {
2650 elementId = element.id.substring(2);
2656 * Filters contact entries based on user input
2658 filter : function(inputEl) {
2659 var ret = new Object();
2660 var re = new RegExp(inputEl.value, "gi");
2662 for(var i in this._contactCache) {
2663 if(this._contactCache[i].name.match(re)) {
2664 ret[i] = this._contactCache[i];
2668 this.buildContactList(ret);
2671 fullForm : function(id, module) {
2672 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
2676 * returns a formatted email address from the addressBook cache
2678 getFormattedAddress : function(id) {
2679 var o = this._contactCache[id];
2680 var primaryEmail = '';
2682 for(var i=0; i<o.email.length; i++) {
2683 var currentEmail = o.email[i].email_address;
2685 if(o.email[i].primary_address == 1) {
2686 primaryEmail = o.email[i].email_address;
2690 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
2691 var name = new String(o.name);
2692 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
2693 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
2699 * Sets up async call to query for matching contacts, users, etc.
2701 searchContacts : function() {
2702 var fn = document.getElementById('input_searchField').value;
2703 var pe = document.getElementById('input_searchPerson').value;
2705 var rb = document.getElementById('hasRelatedBean').checked;
2708 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2709 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2710 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2711 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2713 this.addressBookDataModel.params['related_bean_id'] = '';
2716 this.addressBookDataModel.params['search_field'] = fn;
2717 this.addressBookDataModel.params['person'] = pe;
2718 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
2719 this.grid._oDataSource = this.addressBookDataModel;
2720 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
2724 * Clear Search Crieteria For Addressbook
2726 clearAddressBookSearch : function() {
2727 document.getElementById('input_searchField').value = "";
2728 document.getElementById('input_searchPerson').selectedIndex = 0;
2732 * Opens modal select window to add contacts to addressbook
2734 selectContactsDialogue : function(destId) {
2735 if(!this.contactsDialogue) {
2736 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
2740 constraintoviewport: true,
2742 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
2743 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
2745 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
2747 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
2748 dlg.setBody(body.innerHTML);
2749 dlg.renderEvent.subscribe(function() {
2750 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
2751 if (iev && !SUGAR.isIE) {
2752 this.body.style.width = "950px";
2757 dlg.beforeRenderEvent.subscribe(function() {
2758 var dd = new YAHOO.util.DDProxy(dlg.element);
2759 dd.setHandleElId(dlg.header);
2760 dd.on('endDragEvent', function() {
2766 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
2768 var tabContent = SUGAR.util.getAndRemove("searchForm");
2769 tp.addTab(new YAHOO.widget.Tab({
2770 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
2772 content : tabContent.innerHTML,
2773 id : "addressSearchTab",
2777 var addListenerFields = ['input_searchPerson','input_searchField' ]
2778 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
2779 if (e.keyCode == 13) {
2780 YAHOO.util.Event.stopEvent(e);
2781 SUGAR.email2.addressBook.searchContacts();
2785 this.contactsDialogue.render();
2788 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
2789 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
2793 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
2794 var idx = activePanel.substring(10);
2796 SE.addressBook.idx = idx;
2799 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
2800 document.getElementById('relatedBeanColumn').style.display = '';
2801 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
2802 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2803 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2804 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
2805 SE.addressBook.relatedBeanType = relatedBeanType;
2807 document.getElementById('relatedBeanColumn').style.display = 'none';
2808 document.getElementById('hasRelatedBean').checked = false;
2811 if (!SE.addressBook.grid)
2813 if (hasRelatedBeanId) {
2814 document.getElementById('hasRelatedBean').checked = true;
2816 AddressSearchGridInit();
2817 SE.addressBook.relatedBeanId = relatedBeanId;
2821 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
2823 SE.addressBook.relatedBeanId = relatedBeanId;
2824 document.getElementById('hasRelatedBean').checked = true;
2826 if (document.getElementById('hasRelatedBean').checked == true)
2828 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2829 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2831 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
2832 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
2834 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
2835 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
2836 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
2839 //Remove any lingering rows in the result set table if the module was closed.
2840 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2842 SE.addressBook.populateResulstTableEmailAddresses();
2844 this.contactsDialogue.show();
2847 * Clear all email addresses from result table.
2850 clearAllEmailAddressFieldsFromResultTable: function () {
2851 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2852 //Unhighlight any rows currently selected if the emails were cleared.
2853 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
2854 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2857 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
2858 * results table. This function is called when the address book is displayed.
2860 populateResulstTableEmailAddresses: function () {
2862 var idx = SE.addressBook.idx;
2863 var emailFields = ['to','cc','bcc'];
2865 for(var k=0;k<emailFields.length;k++)
2867 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2868 var allEmails = document.getElementById(elKey).value;
2872 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
2874 for (var i=0; i<formatedEmails.length; i++)
2876 var t_name = formatedEmails[i].name;
2877 var t_emailAddr = formatedEmails[i].email_address;
2878 var displayEmail = t_name + ' <' + t_emailAddr + '>';
2880 t_name = displayEmail = t_emailAddr;
2882 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
2883 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
2884 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
2890 * Checks all entries in the result table against a particular email address, returning true
2891 * if the email address is found, false otherwise.
2893 doesEmailAdddressExistInResultTable: function(emailAddress)
2895 if(trim(emailAddress) == '')
2898 var emailAddressFound = false;
2899 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2900 for (var i=0; i < contacts.length; i++)
2902 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2903 //If we are adding to cc or bcc fields, make them visible.
2904 if(data.email_address == emailAddress)
2906 emailAddressFound = true;
2911 return emailAddressFound;
2914 * Takes all email addresses that the users wishes to add from the address book and populates the To
2915 * fields on the compose tab.
2917 populateEmailAddressFieldsFromResultTable: function()
2919 //Clear the fields first, all email addresses are stored in the address book
2920 var idx = SE.addressBook.idx;
2921 var emailFields = ['to','cc','bcc'];
2922 for(var k=0;k<emailFields.length;k++)
2924 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2925 document.getElementById(elKey).value = "";
2928 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2929 for (var i=0; i < contacts.length; i++)
2931 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2933 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
2934 //If we are adding to cc or bcc fields, make them visible.
2935 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
2936 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
2937 //Construct the target id
2938 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
2940 var target = document.getElementById(target_id);
2941 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
2944 //Delete all rows from the result set table
2945 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2948 SE.addressBook.contactsDialogue.hide()
2951 * Insert contacts into the result table.
2953 insertContactToResultTable : function(event,address_type) {
2955 var contactsDialogue = SE.addressBook.contactsDialogue;
2956 var contacts = SE.addressBook.grid.getSelectedRows();
2958 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2959 for (var i = 0; i < rows.length; i++)
2961 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
2963 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
2964 SE.addressBook.insertContactRowToResultTable(recId,address_type);
2965 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2966 rows[i].setData("selected",true);
2969 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2970 for (var i = 0; i < checkBoxes.length; i++) {
2971 checkBoxes[i].checked = false;
2977 insertContactRowToResultTable : function(rowId, addressType) {
2978 var data = SE.addressBook.grid.getRecord(rowId).getData();
2979 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
2981 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
2982 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
2983 if(addressType == null)
2984 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
2985 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});
2988 * Remove a row from the gridsResult table.
2990 removeRowFromGridResults : function(rowId,emailAddress)
2992 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2993 for (var i=0; i < contacts.length; i++)
2995 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
2996 var data = rec.getData();
2997 if(data.email_address == emailAddress)
2999 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
3004 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
3007 * Translates between the addressType To|Cc|Bcc labels/keys.
3009 translateAddresType: function(addressType,fromKey)
3011 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
3012 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
3013 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
3014 var mappingObject = {};
3017 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
3020 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
3021 mappingObject[displayCc] = 'cc';
3022 mappingObject[displayBcc] = 'bcc';
3025 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
3031 toggleSearchRowIcon : function(rowId,show)
3035 var idToShow = rowId + '_add_img';
3036 var idToHide = rowId + '_rm_img';
3040 var idToShow = rowId + '_rm_img';
3041 var idToHide = rowId + '_add_img';
3045 Dom.addClass(idToHide, "yui-hidden");
3046 Dom.removeClass(idToShow, "yui-hidden");
3049 * Determine if an entry has already been added to the grid results table to prevent duplicates.
3051 doesGridResultsEntryExist: function(emailAddrs)
3054 var contactExists = false;
3055 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
3056 for (var i=0; i < contacts.length; i++)
3058 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
3059 if(data.email_address == emailAddrs)
3061 contactExists = true;
3065 return contactExists;
3069 * adds an email address to a string, but first checks if it exists
3070 * @param string concat The string we are appending email addresses to
3071 * @param string addr Email address to add
3074 smartAddEmailAddressToComposeField : function(concat, addr) {
3075 var re = new RegExp(addr);
3077 if(!concat.match(re)) {
3079 concat += "; " + addr;
3088 //// END ADDRESS BOOK
3089 ///////////////////////////////////////////////////////////////////////////////
3093 ///////////////////////////////////////////////////////////////////////////////
3096 * Auto-complete object
3100 delimChar : [";", ","],
3104 prehighlightClassName : "yui-ac-prehighlight",
3107 instances : new Array(),
3110 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
3111 * @param object Contact from AddressBook
3114 getPrimaryAddress : function(contact) {
3115 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
3117 for(var eIndex in contact.email) {
3118 address = contact.email[eIndex].email_address;
3119 if(contact.email[eIndex].primary_address == 1) {
3120 return contact.email[eIndex].email_address;
3128 * initializes autocomplete widgets for a given compose view
3131 init : function(idx) {
3132 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
3133 "queryMatchContains" : false,
3134 "queryMatchSubset" : true
3137 this.instances[idx] = {
3144 // instantiate the autoComplete widgets
3145 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
3146 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
3147 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
3149 // enable hiding of interfering textareas
3150 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3151 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3152 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3154 // enable reshowing of hidden textareas
3155 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3156 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3157 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3159 // enable refreshes of contact lists
3160 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3161 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3162 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3165 refreshDataSource : function(sType, aArgs) {
3166 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
3168 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
3170 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
3171 idx = textBoxId.substr(9);
3173 idx = textBoxId.substr(10);
3176 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
3177 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
3178 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
3182 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
3184 returnDataSource : function(contacts) {
3185 var ret = new Array();
3186 for(var id in contacts) {
3187 if (contacts[id].name) {
3188 var primary = this.getPrimaryAddress(contacts[id]);
3190 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
3191 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
3193 for(var emailIndex in contacts[id].email) {
3194 ret[ret.length] = contacts[id].email[emailIndex].email_address;
3203 * Hides address textareas to prevent autocomplete dropdown from being obscured
3205 toggleTextareaHide : function(sType, aArgs) {
3206 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3210 if(textBoxId.indexOf("addressTO") > -1) {
3212 } else if(textBoxId.indexOf("addressCC") > -1) {
3215 idx = textBoxId.substr(9);
3217 // follow through if not BCC
3219 var cc = document.getElementById("addressCC" + idx);
3220 var bcc = document.getElementById("addressBCC" + idx);
3224 cc.style.visibility = 'hidden';
3226 bcc.style.visibility = 'hidden';
3233 * Redisplays the textareas after an address is commited
3235 toggleTextareaShow : function(sType, aArgs) {
3236 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3240 if(textBoxId.indexOf("addressTO") > -1) {
3242 } else if(textBoxId.indexOf("addressCC") > -1) {
3245 idx = textBoxId.substr(9);
3247 // follow through if not BCC
3249 document.getElementById("addressCC" + idx).style.visibility = 'visible';
3250 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
3255 //// END AUTOCOMPLETE
3256 ///////////////////////////////////////////////////////////////////////////////
3258 ///////////////////////////////////////////////////////////////////////////////
3261 * expands the options sidebar
3263 SE.composeLayout = {
3264 currentInstanceId : 0,
3267 outboundAccountErrors : null,
3268 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
3270 showAddressDetails : function(e) {
3271 var linkElement = document.getElementById("More"+e.id);
3272 var spanElement = document.getElementById("Detail"+e.id);
3273 var emailAddressList = e.value;
3274 if(e.value.length > 96)
3276 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
3277 var displayArray = [];
3278 for (var i=0; i<resultArray.length; i++)
3280 var t_name = resultArray[i].name;
3281 var t_emailAddr = resultArray[i].email_address;
3283 displayArray.push('<br/><' + t_emailAddr + '>');
3285 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
3288 var result = displayArray.join('<br/>');
3290 linkElement.style.display = "inline";
3291 linkElement.style.height="10px";
3292 linkElement.style.overflow="visible";
3293 spanElement.innerHTML = result;
3296 linkElement.style.display = "none";
3301 * Given a string of email address, return an array containing the name portion (if available)
3302 * and email portion.
3304 _getEmailArrayFromString : function (emailAddressList){
3307 while ((results = reg.exec(emailAddressList)) != null)
3309 orignial = results[0];
3310 parsedResult = results[0].replace(';', ':::::');
3311 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3315 while ((results = reg.exec(emailAddressList)) != null)
3317 orignial = results[0];
3318 parsedResult = results[0].replace(',', ':::::');
3319 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3321 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
3322 var emailArr = emailAddressList.split(":::::");
3323 var resultsArray = [];
3325 for (var i=0; i<emailArr.length; i++)
3327 var rposition = emailArr[i].indexOf('<');
3328 var lposition = emailArr[i].indexOf('>');
3330 if(trim(emailArr[i]) != '')
3332 if(rposition != -1 && lposition != -1)
3334 var t_name = emailArr[i].substr(0, rposition-1);
3335 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
3336 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
3340 resultsArray.push({'name':'', 'email_address': emailArr[i]});
3344 return resultsArray;
3346 ///////////////////////////////////////////////////////////////////////////
3349 * Prepare bucket DIV and yui-ext tab panels
3351 _0_yui : function() {
3352 var idx = this.currentInstanceId;
3354 var composeTab = new YAHOO.SUGAR.ClosableTab({
3355 label: mod_strings.LNK_NEW_SEND_EMAIL,
3357 content : "<div id='htmleditordiv" + idx + "'/>",
3358 id : "composeTab" + idx,
3359 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
3362 SE.innerLayout.addTab(composeTab);
3364 // get template engine with template
3365 if (!SE.composeLayout.composeTemplate) {
3366 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
3369 // create Tab inner layout
3370 var composePanel = this.getComposeLayout();
3371 composePanel.getUnitByPosition("right").collapse();
3372 composePanel.autoSize();
3376 * Generate the quick compose layout
3377 * @method getQuickComposeLayout
3378 * @param {Pannel} parentPanel Parent pannel
3379 * @param {Object} o Options
3382 getQuickComposeLayout : function (parentPanel,o) {
3383 var idx = SE.composeLayout.currentInstanceId;
3385 //Before rendering the parent pannel we need to initalize the grid layout
3386 parentPanel.beforeRenderEvent.subscribe(function() {
3388 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3389 SE.composeLayout._createComposeLayout(idx);
3390 SE.composeLayout[idx].set('height', 350);
3391 SE.composeLayout[idx].render();
3395 //Wait until the Compose Layout has rendered, then add the
3396 //options tab and perform the tiny initialization.
3397 parentPanel.renderEvent.subscribe(function() {
3399 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3400 SE.composeLayout._initComposeOptionTabs(idx);
3401 SE.composeLayout[idx].getUnitByPosition("right").collapse();
3402 //Initialize tinyMCE
3403 if (!SUGAR.util.isTouchScreen())
3404 SE.composeLayout._1_tiny();
3405 //Init templates and address book
3406 SE.composeLayout._2_final();
3408 SE.composeLayout.quickCreateComposePackage(o);
3413 //Check if we have the div override for the shortcut bar
3414 if(typeof o.menu_id != 'undefined') {
3415 parentPanel.render(o.menu_id);
3417 parentPanel.render(document.body);
3420 return SE.composeLayout[idx];
3423 * Fill in all fields into the quick compose layout.
3424 * @method quickCreateComposePackage
3425 * @param {Object} o Options
3428 quickCreateComposePackage: function(o)
3430 //If we have a compose package fill in defaults.
3431 if (typeof(o.composePackage) != 'undefined')
3433 composePackage = o.composePackage; //Set the compose data object
3434 //Hijack this method called by composePackage as it's not need for quick creates.
3435 SE.composeLayout.c0_composeNewEmail = function(){};
3436 SE.composeLayout.composePackage(); //Fill in defaults.
3439 getComposeLayout : function() {
3440 var idx = SE.composeLayout.currentInstanceId;
3442 this._createComposeLayout(idx);
3443 SE.composeLayout[idx].render();
3444 this._initComposeOptionTabs(idx);
3446 return SE.composeLayout[idx];
3450 * Create the layout manager for the compose window.
3452 _createComposeLayout : function(idx)
3454 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
3455 parent: SE.complexLayout,
3465 SE.composeLayout.composeTemplate.exec({
3466 'app_strings':app_strings,
3467 'mod_strings':mod_strings,
3469 'linkbeans_options' : linkBeans,
3470 'idx' : SE.composeLayout.currentInstanceId
3481 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
3484 header: app_strings.LBL_EMAIL_OPTIONS
3490 * Create compose tab which will populate the 'right' container in the compose window.
3492 _initComposeOptionTabs : function(idx)
3494 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
3495 var tab = new YAHOO.widget.Tab({
3496 label: app_strings.LBL_EMAIL_ATTACHMENT,
3498 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
3499 id : "divAttachments" + idx,
3503 tab.layout = SE.composeLayout[idx];
3505 tab.on("activeChange", function(o){
3507 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
3513 tab = new YAHOO.widget.Tab({
3514 label: app_strings.LBL_EMAIL_OPTIONS,
3516 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
3517 id : "divOptions" + idx,
3521 tab.layout = SE.composeLayout[idx];
3522 tab.on("activeChange", function(o){
3524 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
3529 SE.composeLayout[idx].autoSize = function() {
3530 var pEl = this.get("element").parentNode.parentNode.parentNode;
3531 this.set("height", pEl.clientHeight-30);
3535 SE.composeLayout[idx].rightTabs = cTabs;
3537 isParentTypeValid : function(idx) {
3538 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3539 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3540 if (trim(parentTypeValue) == ""){
3541 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
3547 isParentTypeAndNameValid : function(idx) {
3548 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3549 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3550 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
3551 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
3552 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
3553 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
3559 callopenpopupForEmail2 : function(idx,options) {
3561 var formName = 'emailCompose' + idx;
3563 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
3564 formName = options.form_name;
3566 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3567 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3568 if (!SE.composeLayout.isParentTypeValid(idx)) {
3571 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
3573 call_back_function:"SE.composeLayout.popupAddEmail",
3575 field_to_name_array:{
3576 id:'data_parent_id' + idx,
3577 name:'data_parent_name' + idx,
3582 popupAddEmail : function(o)
3584 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
3585 var data = o.name_to_value_array;
3586 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
3587 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
3589 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
3590 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
3597 _1_tiny : function() {
3598 var idx = SE.composeLayout.currentInstanceId;
3599 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
3600 SE.tinyInstances[elId] = { };
3601 SE.tinyInstances[elId].ready = false;
3602 var t = tinyMCE.getInstanceById(elId);
3604 if(typeof(t) == 'undefined') {
3605 tinyMCE.execCommand('mceAddControl', false, elId);
3606 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
3607 SE.composeLayout.resizeEditor(idx);
3608 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
3613 resizeEditor : function(idx)
3615 var cof = Dom.get('composeOverFrame' + idx);
3616 var head = Dom.get('composeHeaderTable' + idx);
3617 var targetHeight = cof.clientHeight - head.clientHeight;
3618 var instance = tinyMCE.get(SE.tinyInstances.currentHtmleditor);
3620 var parentEl = Dom.get(instance.editorId + '_parent');
3621 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
3622 var contentEl = instance.contentAreaContainer;
3623 var iFrame = contentEl.firstChild;
3624 var tinMceToolbarOffset = 18;
3625 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
3629 * Initializes d&d, auto-complete, email templates
3631 _2_final : function() {
3632 var idx = SE.composeLayout.currentInstanceId;
3634 if(this.emailTemplates) {
3635 this.setComposeOptions(idx);
3637 //populate email template cache
3638 AjaxObject.target = '';
3639 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
3642 // handle drop targets for addressBook
3643 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3644 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3645 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3646 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
3648 // auto-complete setup
3649 SE.autoComplete.init(idx);
3652 document.getElementById("addressTO" + idx).focus();
3656 * hide tinyMCE tool bar if send email as plaintext is checked
3658 renderTinyMCEToolBar : function (idx, hide) {
3660 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
3662 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
3666 c1_composeEmail : function(isReplyForward, retry) {
3670 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
3671 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
3676 if(isReplyForward) {
3677 this.replyForwardEmailStage2();
3683 * takes draft info and prepopulates
3685 c0_composeDraft : function() {
3686 this.getNewInstanceId();
3688 document.getElementById('_blank').innerHTML = '';
3689 var idx = SE.composeLayout.currentInstanceId;
3690 SE.composeLayout.draftObject = new Object();
3691 SE.composeLayout.draftObject.id = idx;
3692 SE.composeLayout.draftObject.isDraft = true;
3693 SE.composeLayout.currentInstanceId = idx;
3694 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
3695 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
3696 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
3698 SE.composeLayout._0_yui();
3699 SE.composeLayout._1_tiny();
3702 SE.composeLayout._2_final();
3704 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
3705 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
3709 * Strip & Prep editor hidden fields
3711 c0_composeNewEmail : function() {
3712 this.getNewInstanceId();
3713 this.c1_composeEmail(false);
3717 * Sends async request to get the compose view.
3718 * Requests come from "reply" or "forwards"
3720 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
3721 SE.composeLayout.replyForwardObj = new Object();
3722 SE.composeLayout.replyForwardObj.ieId = ieId;
3723 SE.composeLayout.replyForwardObj.uid = uid;
3724 SE.composeLayout.replyForwardObj.mbox = mbox;
3725 SE.composeLayout.replyForwardObj.type = type;
3727 if(mbox == 'sugar::Emails') {
3728 SE.composeLayout.replyForwardObj.sugarEmail = true;
3731 SE.composeLayout.getNewInstanceId();
3732 SE.composeLayout.c1_composeEmail(true);
3734 //// END COMPOSE FLOW
3735 ///////////////////////////////////////////////////////////////////////////
3738 * Called when a contact, email, or mailinglist is dropped
3739 * into one of the compose fields.
3741 handleDrop : function (source, event, data, target) {
3744 target = event.getTarget();
3746 data.nodes = [data.nodes];
3750 target = document.getElementById(target);
3754 if (target.id.indexOf('address') > -1) {
3755 // dropped onto email to/cc/bcc field
3756 for(var i in nodes) {
3757 var node = nodes[i].getData();
3759 if (node[1].indexOf('contact') > -1) {
3760 email = SE.addressBook.getFormattedAddress(node[0]);
3761 } else if (node[1].indexOf('address-email') > -1){
3762 email = node[3].replace(/ /gi, '');
3763 email = email.replace('<', '<').replace('>', '>');
3764 var tr = source.getTrEl(nodes[i]);
3765 while (tr && !Dom.hasClass(tr, "address-contact")) {
3766 tr = source.getPreviousTrEl(tr);
3768 var CID = source.getRecord(tr).getData()[0];
3769 var o = SE.addressBook._contactCache[CID];
3770 var name = new String(o.name);
3771 var finalName = name.replace(/(<([^>]+)>)/ig, "");
3772 email = finalName + email;
3774 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
3780 /*/////////////////////////////////////////////////////////////////////////////
3781 /// EMAIL TEMPLATE CODE
3783 applyEmailTemplate : function (idx, id) {
3786 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
3787 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
3788 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
3791 var to_addr = document.getElementById('addressTO'+idx);
3792 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
3794 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
3795 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
3798 // id is selected index of email template drop-down
3799 if(id == '' || id == "0") {
3800 YAHOO.SUGAR.MessageBox.show({
3805 if(btn=='no'){return;};
3806 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
3813 YAHOO.SUGAR.MessageBox.show({
3818 if(btn=='no'){return;};
3819 SUGAR.email2.composeLayout.processResult(idx, id);},
3825 processNoneResult : function(idx, id) {
3826 var tiny = SE.util.getTiny('htmleditor' + idx);
3827 var tinyHTML = tiny.getContent();
3828 var openTag = '<div><span><span>';
3829 var htmllow = tinyHTML.toLowerCase();
3830 var start = htmllow.indexOf(openTag);
3832 tinyHTML = tinyHTML.substr(start);
3833 tiny.setContent(tinyHTML);
3835 tiny.setContent('');
3839 processResult : function(idx , id){
3840 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
3842 // get attachments if any
3843 AjaxObject.target = '';
3844 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
3847 appendEmailTemplateJSON : function() {
3848 var idx = SE.composeLayout.currentInstanceId; // post increment
3850 // query based on template, contact_id0,related_to
3851 //jchi 09/10/2008 refix #7743
3852 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
3853 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
3856 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,'"');
3858 // cn: bug 14361 - text-only templates don't fill compose screen
3860 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/>");
3863 var tiny = SE.util.getTiny('htmleditor' + idx);
3864 var tinyHTML = tiny.getContent();
3865 var openTag = '<div><span><span>';
3866 var closeTag = '</span></span></div>';
3867 var htmllow = tinyHTML.toLowerCase();
3868 var start = htmllow.indexOf(openTag);
3870 var htmlPart2 = tinyHTML.substr(start);
3871 tinyHTML = text + htmlPart2;
3872 tiny.setContent(tinyHTML);
3874 tiny.setContent(text);
3879 * Writes out the signature in the email editor
3881 setSignature : function(idx) {
3884 var hide = document.getElementById('setEditor' + idx).checked;
3885 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
3886 //wait for signatures to load before trying to set them
3887 if (!SE.composeLayout.signatures) {
3888 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
3893 var sel = document.getElementById('signatures' + idx);
3895 var sel = document.getElementById('signature_id');
3896 idx = SE.tinyInstances.currentHtmleditor;
3899 //Ensure that the tinyMCE html has been rendered.
3900 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
3901 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
3908 signature = sel.options[sel.selectedIndex].value;
3913 var openTag = '<div><span><span>';
3914 var closeTag = '</span></span></div>';
3915 var t = SE.util.getTiny('htmleditor' + idx);
3917 if(typeof(t) != 'undefined')
3919 t.contentDocument = t.contentWindow.document;
3920 var html = t.getContent();
3925 var htmllow = html.toLowerCase();
3926 var start = htmllow.indexOf(openTag);
3927 var end = htmllow.indexOf(closeTag) + closeTag.length;
3929 // selected "none" - remove signature from email
3930 if(signature == '') {
3932 var htmlPart1 = html.substr(0, start);
3933 var htmlPart2 = html.substr(end, html.length);
3935 html = htmlPart1 + htmlPart2;
3938 SE.signatures.lastAttemptedLoad = '';
3942 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
3943 SE.signatures.lastAttemptedLoad = '';
3945 SE.signatures.lastAttemptedLoad = signature;
3947 if(typeof(SE.signatures[signature]) == 'undefined') {
3949 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
3950 SE.signatures.targetInstance = (idx) ? idx : "";
3951 AjaxObject.target = '';
3952 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
3954 var newSignature = this.prepareSignature(SE.signatures[signature]);
3956 // clear out old signature
3957 if(SE.signatures.lastAttemptedLoad && start > -1) {
3958 var htmlPart1 = html.substr(0, start);
3959 var htmlPart2 = html.substr(end, html.length);
3961 html = htmlPart1 + htmlPart2;
3965 start = html.indexOf('<div><hr></div>');
3966 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
3967 var htmlPart1 = html.substr(0, start);
3968 var htmlPart2 = html.substr(start, html.length);
3969 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
3970 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
3971 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
3973 var newHtml = html + openTag + newSignature + closeTag;
3975 //tinyMCE.setContent(newHtml);
3976 t.setContent(newHtml);
3980 prepareSignature : function(str) {
3981 var signature = new String(str);
3983 signature = signature.replace(/</gi, '<');
3984 signature = signature.replace(/>/gi, '>');
3990 showAttachmentPanel : function(idx) {
3991 var east = SE.composeLayout[idx].getUnitByPosition("right");
3992 var tabs = SE.composeLayout[idx].rightTabs;
3994 tabs.set("activeTab", tabs.getTab(0));
3998 * expands sidebar and displays options panel
4000 showOptionsPanel : function(idx) {
4001 var east = SE.composeLayout[idx].getUnitByPosition("right");
4002 var tabs = SE.composeLayout[idx].rightTabs;
4004 tabs.set("activeTab", tabs.getTab(1));
4008 * Selects the Contacts tab
4010 showContactsPanel : function() {
4011 SE.complexLayout.regions.west.showPanel("contactsTab");
4015 * Generates fields for Select Document
4017 addDocumentField : function(idx) {
4018 var basket = document.getElementById('addedDocuments' + idx);
4020 var index = (basket.childNodes.length / 7) - 1;
4027 var test = document.getElementById('documentId' + idx + index);
4029 while(test != null) {
4031 test = document.getElementById('documentId' + idx + index);
4034 var documentCup = document.createElement("div");
4035 documentCup.id = 'documentCup' + idx + index;
4036 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
4037 // document id field
4038 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
4039 // document name field
4040 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
4042 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
4043 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
4044 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
4046 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
4047 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
4048 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
4051 basket.appendChild(documentCup);
4052 //basket.innerHTML += out;
4057 * Makes async call to save a draft of the email
4058 * @param int Instance index
4060 saveDraft : function(tinyInstance) {
4061 this.sendEmail(tinyInstance, true);
4064 selectDocument : function(target) {
4065 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
4066 windowName = 'selectDocument';
4067 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
4069 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4071 // put the focus on the popup if the browser supports the focus() method
4077 * Modal popup for file attachment dialogue
4079 addFileField : function() {
4080 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
4081 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
4085 constraintoviewport: true,
4087 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
4088 fn:function(){SE.addFileDialog.hide();}
4091 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
4092 SE.addFileDialog.render();
4093 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
4095 Dom.removeClass("addFileDialog", "yui-hidden");
4097 SE.addFileDialog.show();
4101 * Async upload of file to temp dir
4103 uploadAttachment : function() {
4104 if(document.getElementById('email_attachment').value != "") {
4105 var formObject = document.getElementById('uploadAttachment');
4106 YAHOO.util.Connect.setForm(formObject, true, true);
4107 AjaxObject.target = '';
4108 AjaxObject.startRequest(callbackUploadAttachment, null);
4110 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
4115 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
4116 * @param string target in focus compose layout
4118 setDocument : function(idx, target, documentId, documentName, docRevId) {
4119 // fields are named/id'd [fieldName][instanceId][index]
4120 var addedDocs = document.getElementById("addedDocuments" + idx);
4121 var docId = document.getElementById('documentId' + idx + target);
4122 var docName = document.getElementById('documentName' + idx + target);
4123 var docRevisionId = document.getElementById('document' + idx + target);
4124 docId.value = documentId;
4125 docName.value = documentName;
4126 docRevisionId.value = docRevId;
4130 * Removes the bucket div containing the document input fields
4132 deleteDocumentField : function(documentCup) {
4133 var f0 = document.getElementById(documentCup);
4134 f0.parentNode.removeChild(f0);
4138 * Removes a Template Attachment field
4142 deleteTemplateAttachmentField : function(idx, index) {
4143 // create not-in-array values for removal filtering
4144 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
4150 r += document.getElementById('templateAttachmentId' + idx + index).value;
4151 document.getElementById("templateAttachmentsRemove" + idx).value = r;
4153 var target = 'templateAttachmentCup' + idx + index;
4154 d = document.getElementById(target);
4155 d.parentNode.removeChild(d);
4159 * Async removal of uploaded temp file
4160 * @param string index Should be a concatenation of idx and index
4163 deleteUploadAttachment : function(index, file) {
4164 var d = document.getElementById('email_attachment_bucket' + index);
4165 d.parentNode.removeChild(d);
4167 // make async call to delete cached file
4168 AjaxObject.target = '';
4169 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
4173 * Attaches files coming from Email Templates
4175 addTemplateAttachmentField : function(idx) {
4177 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
4179 var basket = document.getElementById('addedTemplateAttachments' + idx);
4182 var index = basket.childNodes.length;
4189 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
4191 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
4192 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
4193 idx + "\",\"" + index + "\");'/>" +
4195 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
4196 // templateAttachment field
4197 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
4199 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
4201 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
4202 "<br id='br" + index + "></br>" +
4203 "<br id='brdoc" + index + "></br>" +
4205 basket.innerHTML = basket.innerHTML + out;
4211 * Sends one email via async call
4212 * @param int idx Editor instance ID
4213 * @param bool isDraft
4215 sendEmail : function(idx, isDraft) {
4217 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
4218 var obAccountID = document.getElementById('addressFrom' + idx).value;
4220 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
4222 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
4227 var form = document.getElementById('emailCompose' + idx);
4228 var composeOptionsFormName = "composeOptionsForm" + idx;
4229 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
4230 var html = t.getContent();
4231 var subj = document.getElementById('emailSubject' + idx).value;
4232 var to = trim(document.getElementById('addressTO' + idx).value);
4233 var cc = trim(document.getElementById('addressCC' + idx).value);
4234 var bcc = trim(document.getElementById('addressBCC' + idx).value);
4235 var email_id = document.getElementById('email_id' + idx).value;
4236 var composeType = document.getElementById('composeType').value;
4237 var parent_type = document.getElementById("parent_type").value;
4238 var parent_id = document.getElementById("parent_id").value;
4240 var el_uid = document.getElementById("uid");
4241 var uid = (el_uid == null) ? '' : el_uid.value;
4243 var el_ieId = document.getElementById("ieId");
4244 var ieId = (el_ieId == null) ? '' : el_ieId.value;
4246 var el_mbox = document.getElementById("mbox");
4247 var mbox = (el_mbox == null) ? '' : el_mbox.value;
4249 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
4250 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
4254 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
4257 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
4258 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
4259 parent_id = parentIdValue;
4260 parent_type = parentTypeValue;
4262 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
4263 // baseline viability check
4265 if(to == "" && cc == '' && bcc == '' && !isDraft) {
4266 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
4268 } else if(subj == '' && !isDraft) {
4269 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
4272 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
4274 } else if(html == '' && !isDraft) {
4275 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
4280 SE.util.clearHiddenFieldValues('emailCompose' + idx);
4281 document.getElementById('data_parent_id' + idx).value = parentIdValue;
4282 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
4283 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
4284 html = html.replace(/</ig, "sugarLessThan");
4285 html = html.replace(/>/ig, "sugarGreaterThan");
4287 form.sendDescription.value = html;
4288 form.sendSubject.value = subj;
4289 form.sendTo.value = to;
4290 form.sendCc.value = cc;
4291 form.sendBcc.value = bcc;
4292 form.email_id.value = email_id;
4293 form.composeType.value = composeType;
4294 form.composeLayoutId.value = 'composeLayout' + idx;
4295 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
4296 form.saveToSugar.value = 1;
4297 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
4298 form.parent_type.value = parent_type;
4299 form.parent_id.value = parent_id;
4300 form.uid.value = uid;
4301 form.ieId.value = ieId;
4302 form.mbox.value = mbox;
4304 // email attachments
4305 var addedFiles = document.getElementById('addedFiles' + idx);
4307 for(i=0; i<addedFiles.childNodes.length; i++) {
4308 var bucket = addedFiles.childNodes[i];
4310 for(j=0; j<bucket.childNodes.length; j++) {
4311 var node = bucket.childNodes[j];
4312 var nName = new String(node.name);
4314 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
4315 if(form.attachments.value != '') {
4316 form.attachments.value += "::";
4318 form.attachments.value += node.value;
4325 var addedDocs = document.getElementById('addedDocuments' + idx);
4327 for(i=0; i<addedDocs.childNodes.length; i++) {
4328 var cNode = addedDocs.childNodes[i];
4329 for(j=0; j<cNode.childNodes.length; j++) {
4330 var node = cNode.childNodes[j];
4331 var nName = new String(node.name);
4332 if(node.type == 'hidden' && nName.match(/documentId/)) {
4333 if(form.documents.value != '') {
4334 form.documents.value += "::";
4336 form.documents.value += node.value;
4342 // template attachments
4343 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
4344 if(addedTemplateAttachments) {
4345 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
4346 var cNode = addedTemplateAttachments.childNodes[i];
4347 for(j=0; j<cNode.childNodes.length; j++) {
4348 var node = cNode.childNodes[j];
4349 var nName = new String(node.name);
4350 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
4351 if(form.templateAttachments.value != "") {
4352 form.templateAttachments.value += "::";
4354 form.templateAttachments.value += node.value;
4360 // remove attachments
4361 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
4363 YAHOO.util.Connect.setForm(form);
4365 AjaxObject.target = 'frameFlex';
4367 // sending a draft email
4368 if(!isDraft && in_draft) {
4370 SE.listView.removeRowByUid(email_id);
4373 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
4374 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
4376 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
4380 * Handles clicking the email address link from a given view
4382 composePackage : function() {
4383 if(composePackage != null) {
4384 SE.composeLayout.c0_composeNewEmail();
4387 if(composePackage.to_email_addrs) {
4388 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
4390 if (composePackage.subject != null && composePackage.subject.length > 0) {
4391 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
4394 //If no parent fields are set in the composePackage, ensure they are cleared.
4395 var parentFields = ['parent_type','parent_name','parent_id'];
4396 for(var i=0;i<parentFields.length;i++)
4398 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
4399 composePackage[parentFields[i]] = "";
4402 document.getElementById("parent_type").value = composePackage.parent_type;
4403 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
4404 document.getElementById("parent_id").value = composePackage.parent_id;
4405 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
4406 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
4408 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
4409 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
4411 if (composePackage.body != null && composePackage.body.length > 0) {
4412 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4413 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
4414 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
4416 if (composePackage.attachments != null) {
4417 SE.composeLayout.loadAttachments(composePackage.attachments);
4420 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
4421 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
4422 SE.util.emptySelectOptions(addressFrom);
4423 var fromAccountOpts = composePackage.fromAccounts.data;
4424 for(i=0; i<fromAccountOpts.length; i++) {
4425 var key = fromAccountOpts[i].value;
4426 var display = fromAccountOpts[i].text;
4427 var opt = new Option(display, key);
4428 if (fromAccountOpts[i].selected) {
4429 opt.selected = true;
4431 addressFrom.options.add(opt);
4438 setContentOnThisTiny : function() {
4439 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4440 var tinyHTML = tiny.getContent();
4441 composePackage.body = decodeURI(encodeURI(composePackage.body));
4442 // cn: bug 14361 - text-only templates don't fill compose screen
4443 if(composePackage.body == '') {
4444 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4446 //Flag determines if we should clear the tiny contents or just append
4447 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
4448 SE.composeLayout.tinyHTML = '';
4450 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
4452 tiny.setContent(SE.composeLayout.tinyHTML);
4453 //Indicate that the contents has been loaded successfully.
4454 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
4457 * Confirms closure of a compose screen if "x" is clicked
4459 confirmClose : function(panel) {
4460 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
4461 SE.composeLayout.closeCompose(panel.id);
4469 * forces close of a compose screen
4471 forceCloseCompose : function(id) {
4472 SE.composeLayout.closeCompose(id);
4474 // handle flow back to originating view
4475 if(composePackage) {
4476 // check if it's a module we need to return to
4477 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
4478 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
4479 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
4480 window.location = url;
4487 * closes the editor that just sent email
4488 * @param string id ID of composeLayout tab
4490 closeCompose : function(id) {
4491 // destroy tinyMCE instance
4492 var idx = id.substr(13, id.length);
4493 var instanceId = "htmleditor" + idx;
4494 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
4496 // nullify DOM and namespace values.
4498 SE.composeLayout[idx] = null;
4499 SE.tinyInstances[instanceId] = null;
4500 var tabsArray = SE.innerLayout.get("tabs");
4501 for (i = 0 ; i < tabsArray.length ; i++) {
4502 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
4503 tabsArray[i].close();
4507 //SE.innerLayout.getTab(idx).close();
4511 * Enable the quick search for the compose relate field or search tab
4513 enableQuickSearchRelate: function(idx,overides){
4515 if(typeof overides != 'undefined')
4517 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
4518 var newModule = document.getElementById(newModuleID).value;
4519 var formName = overides['formName'];
4520 var fieldName = overides['fieldName'];
4521 var fieldId = overides['fieldId'];
4522 var fullName = formName + "_" + fieldName;
4523 var postBlurFunction = null;
4527 var newModule = document.getElementById('data_parent_type'+idx).value;
4528 var formName = 'emailCompose'+idx;
4529 var fieldName = 'data_parent_name'+idx;
4530 var fieldId = 'data_parent_id'+idx;
4531 var fullName = formName + "_" + fieldName;
4532 var postBlurFunction = "SE.composeLayout.qsAddAddress";
4535 if(typeof sqs_objects == 'undefined')
4536 window['sqs_objects'] = new Array;
4538 window['sqs_objects'][fullName] = {
4541 modules:[newModule],
4543 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
4544 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
4545 post_onblur_function: postBlurFunction,
4546 order:"name","limit":"30","no_match_text":"No Match"};
4549 if(typeof QSProcessedFieldsArray != 'undefined')
4550 QSProcessedFieldsArray[fullName] = false;
4551 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
4552 QSFieldsArray[fullName].destroy();
4553 delete QSFieldsArray[fullName];
4555 if (Dom.get(fullName + "_results")) {
4556 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
4562 qsAddAddress : function(o) {
4563 if (o.name != "" && o.email1 != "")
4565 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
4566 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
4570 * Returns a new instance ID, 0-index
4572 getNewInstanceId : function() {
4573 this.currentInstanceId = this.currentInstanceId + 1;
4574 return this.currentInstanceId;
4578 * 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.
4580 loadAttachments : function(result) {
4581 var idx = SE.composeLayout.currentInstanceId;
4583 if(typeof(result) == 'object') {
4584 //jchi #20680. Clean the former template attachments;
4585 var basket = document.getElementById('addedTemplateAttachments' + idx);
4586 if(basket.innerHTML != ''){
4587 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
4589 basket.innerHTML = '';
4594 if(typeof result[i] == 'object') {
4595 var index = SE.composeLayout.addTemplateAttachmentField(idx);
4596 var bean = result[i];
4597 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
4598 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
4605 * fills drop-down values for email templates and signatures
4607 setComposeOptions : function(idx) {
4608 // send from accounts
4609 var addressFrom = document.getElementById('addressFrom' + idx);
4611 if (addressFrom.options.length <= 0) {
4612 SE.util.emptySelectOptions(addressFrom);
4613 var fromAccountOpts = SE.composeLayout.fromAccounts;
4614 for (id = 0 ; id < fromAccountOpts.length ; id++) {
4615 var key = fromAccountOpts[id].value;
4616 var display = fromAccountOpts[id].text;
4617 var is_default = false;
4618 if(key == SUGAR.default_inbound_accnt_id)
4620 var opt = new Option(display, key);
4621 addressFrom.options.add(opt);
4622 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
4627 var et = document.getElementById('email_template' + idx);
4628 SE.util.emptySelectOptions(et);
4630 for(var key in this.emailTemplates) { // iterate through assoc array
4631 var display = this.emailTemplates[key];
4632 var opt = new Option(display, key);
4633 et.options.add(opt);
4637 var sigs = document.getElementById('signatures' + idx);
4638 SE.util.emptySelectOptions(sigs);
4640 for(var key in this.signatures) { // iterate through assoc array
4641 var display = this.signatures[key];
4642 var opt = new Option(display, key);
4644 if(key == SE.userPrefs.signatures.signature_default) {
4645 opt.selected = true;
4648 sigs.options.add(opt);
4651 // html/plain email?
4652 var htmlEmail = document.getElementById('setEditor' + idx);
4653 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
4654 htmlEmail.checked = true;
4656 htmlEmail.checked = false;
4659 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
4663 * After compose screen is rendered, async call to get email body from Sugar
4665 replyForwardEmailStage2 : function() {
4666 SE.util.clearHiddenFieldValues('emailUIForm');
4667 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
4669 var ieId = SE.composeLayout.replyForwardObj.ieId;
4670 var uid = SE.composeLayout.replyForwardObj.uid;
4671 var mbox = SE.composeLayout.replyForwardObj.mbox;
4672 var type = SE.composeLayout.replyForwardObj.type;
4673 var idx = SE.composeLayout.currentInstanceId;
4675 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
4677 document.getElementById('emailSubject' + idx).value = type;
4678 document.getElementById('emailUIAction').value = 'composeEmail';
4679 document.getElementById('composeType').value = type;
4680 document.getElementById('ieId').value = ieId;
4681 document.getElementById('uid').value = uid;
4682 document.getElementById('mbox').value = mbox;
4683 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
4684 var formObject = document.getElementById('emailUIForm');
4685 YAHOO.util.Connect.setForm(formObject);
4687 var sendType = type;
4688 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
4692 * Show the hidden cc or bcc fields
4694 showHiddenAddress: function(addrType,idx){
4696 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
4697 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
4698 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
4699 this[addrType+'Hidden'+idx] = false;
4701 //After bcc or cc is added, move options below last addr field
4702 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4704 //If both cc and bcc hidden, remove the empty row containing text.
4705 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
4706 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
4707 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
4709 SE.composeLayout.resizeEditor(idx);
4712 * Hide the cc and bcc fields if they were shown.
4714 hideHiddenAddresses: function(idx){
4716 var addrTypes = ['cc','bcc'];
4717 for(var i = 0;i<addrTypes.length;i++)
4719 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
4720 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
4721 this[addrTypes[i] + 'Hidden'+idx] = true
4724 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
4725 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
4726 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4730 //// END SE.composeLayout
4731 ///////////////////////////////////////////////////////////////////////////////
4732 ///////////////////////////////////////////////////////////////////////////////
4736 * Cleans serialized UID lists of duplicates
4740 cleanUids : function(str) {
4741 var seen = new Object();
4743 var arr = new String(str).split(",");
4745 for(var i=0; i<arr.length; i++) {
4750 clean += (clean != "") ? "," : "";
4752 seen[arr[i]] = true;
4759 * Clears hidden field values
4760 * @param string id ID of form element to clear
4762 clearHiddenFieldValues : function(id) {
4763 var form = document.getElementById(id);
4765 for(i=0; i<form.elements.length; i++) {
4766 if(form.elements[i].type == 'hidden') {
4767 var e = form.elements[i];
4768 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
4776 * Reduces a SELECT drop-down to 0 items to prepare for new ones
4778 emptySelectOptions : function(el) {
4780 for(i=el.childNodes.length - 1; i >= 0; i--) {
4781 if(el.childNodes[i]) {
4782 el.removeChild(el.childNodes[i]);
4789 * Returns the MBOX path in the manner php_imap expects:
4790 * ie: INBOX.DEBUG.test
4791 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
4793 generateMboxPath : function(str) {
4794 var ex = str.split("::");
4796 /* we have a serialized MBOX path */
4800 for(var i=0; i<ex.length; i++) {
4801 if(ex[i] == 'INBOX') {
4813 /* we have a Sugar folder GUID - do nothing */
4821 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
4822 * @param HTMLElement el
4823 * @return string GUID of found element or empty on failure
4825 getGuidFromElement : function(el) {
4831 for(var i=0; i<iterations; i++) {
4833 if(el.id.match(SE.reGUID)) {
4845 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
4848 getPanelId : function() {
4849 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
4853 * wrapper to handle weirdness with IE
4854 * @param string instanceId
4855 * @return tinyMCE Controller object
4857 getTiny : function(instanceId) {
4858 if(instanceId == '') {
4862 var t = tinyMCE.getInstanceById(instanceId);
4866 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
4872 * Simple check for MSIE browser
4876 var nav = new String(navigator.appVersion);
4877 if(nav.match(/MSIE/)) {
4884 * Recursively removes an element from the DOM
4885 * @param HTMLElement
4887 removeElementRecursive : function(el) {
4888 this.emptySelectOptions(el);
4895 sleep : function(secs) {
4896 setTimeout("void(0);", secs);
4900 * Converts a <select> element to an Ext.form.combobox
4902 convertSelect : function(select) {
4903 alert('in convertSelect');
4904 if (typeof(select) == "string") {
4905 select = document.getElementById(select);
4909 findChildNode : function (parent, property, value) {
4910 for (i in parent.children) {
4911 var child = parent.children[i];
4912 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
4914 var searchChild = SE.util.findChildNode(child, property, value);
4921 cascadeNodes : function (parent, fn, scope, args) {
4922 for (i in parent.children) {
4923 var child = parent.children[i];
4924 var s = scope ? scope : child;
4925 var a = args ? args : child;
4927 SE.util.cascadeNodes(child, fn, scope, args);
4934 ///////////////////////////////////////////////////////////////////////////////
4937 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
4939 /*********************************************************************************
4940 * SugarCRM Community Edition is a customer relationship management program developed by
4941 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4943 * This program is free software; you can redistribute it and/or modify it under
4944 * the terms of the GNU Affero General Public License version 3 as published by the
4945 * Free Software Foundation with the addition of the following permission added
4946 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4947 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4948 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4950 * This program is distributed in the hope that it will be useful, but WITHOUT
4951 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4952 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4955 * You should have received a copy of the GNU Affero General Public License along with
4956 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4957 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4960 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4961 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4963 * The interactive user interfaces in modified source and object code versions
4964 * of this program must display Appropriate Legal Notices, as required under
4965 * Section 5 of the GNU Affero General Public License version 3.
4967 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4968 * these Appropriate Legal Notices must retain the display of the "Powered by
4969 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4970 * technical reasons, the Appropriate Legal Notices must display the words
4971 * "Powered by SugarCRM".
4972 ********************************************************************************/
4974 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
4975 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
4976 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
4977 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
4978 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
4979 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
4980 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
4981 ' <input type="hidden" id="type{idx}" name="type" value="">' +
4982 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
4983 ' <input type="hidden" id="composeType" name="composeType">' +
4984 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
4985 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
4986 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
4987 ' <input type="hidden" id="sendTo" name="sendTo">' +
4988 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
4989 ' <input type="hidden" id="sendCc" name="sendCc">' +
4990 ' <input type="hidden" id="setEditor" name="setEditor">' +
4991 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
4992 ' <input type="hidden" id="parent_id" name="parent_id">' +
4993 ' <input type="hidden" id="parent_type" name="parent_type">' +
4994 ' <input type="hidden" id="attachments" name="attachments">' +
4995 ' <input type="hidden" id="documents" name="documents">' +
4996 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
4997 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
4998 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
4999 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
5001 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
5002 ' <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>' +
5003 ' <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>' +
5004 ' <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>' +
5005 ' <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>' +
5006 '</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>' +
5007 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
5008 '<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>' +
5009 ' </td></tr></tbody></table></th>' +
5013 ' <div style="margin:5px;">' +
5014 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
5016 ' <td class="emailUILabel" NOWRAP >' +
5017 ' {app_strings.LBL_EMAIL_FROM}:' +
5019 ' <td class="emailUIField" NOWRAP>' +
5021 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
5026 ' <td class="emailUILabel" NOWRAP>' +
5027 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
5028 ' {app_strings.LBL_EMAIL_TO}:' +
5031 ' <td class="emailUIField" NOWRAP>' +
5032 ' <div class="ac_autocomplete">' +
5033 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5034 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
5035 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
5039 ' <tr id="add_addr_options_tr{idx}">' +
5040 ' <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>'+
5042 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
5043 ' <td class="emailUILabel" NOWRAP>' +
5044 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
5045 ' {app_strings.LBL_EMAIL_CC}:' +
5048 ' <td class="emailUIField" NOWRAP>' +
5049 ' <div class="ac_autocomplete">' +
5050 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5051 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
5052 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
5056 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
5057 ' <td class="emailUILabel" NOWRAP>' +
5058 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
5059 ' {app_strings.LBL_EMAIL_BCC}:' +
5062 ' <td class="emailUIField" NOWRAP>' +
5063 ' <div class="ac_autocomplete">' +
5064 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5065 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
5066 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
5071 ' <td class="emailUILabel" NOWRAP width="1%">' +
5072 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
5074 ' <td class="emailUIField" NOWRAP width="99%">' +
5075 ' <div class="ac_autocomplete">' +
5076 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
5085 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
5086 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
5087 ' <div style="padding:5px;">' +
5088 ' <table cellpadding="2" cellspacing="0" border="0">' +
5091 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
5098 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
5099 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
5111 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
5118 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
5119 ' <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>' +
5131 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
5138 ' <div id="addedTemplateAttachments{idx}"></div>' +
5145 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
5146 ' <div style="padding:5px;">' +
5147 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
5148 ' <table border="0" width="100%">' +
5150 ' <td NOWRAP style="padding:2px;">' +
5151 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
5155 ' <td NOWRAP style="padding:2px;">' +
5156 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
5161 ' <table border="0" width="100%">' +
5163 ' <td NOWRAP style="padding:2px;">' +
5164 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
5168 ' <td NOWRAP style="padding:2px;">' +
5169 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
5173 ' <table border="0" width="100%">' +
5175 ' <td NOWRAP style="padding:2px;">' +
5176 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
5177 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
5185 // End of File modules/Emails/javascript/composeEmailTemplate.js
5187 /*********************************************************************************
5188 * SugarCRM Community Edition is a customer relationship management program developed by
5189 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5191 * This program is free software; you can redistribute it and/or modify it under
5192 * the terms of the GNU Affero General Public License version 3 as published by the
5193 * Free Software Foundation with the addition of the following permission added
5194 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
5195 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
5196 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
5198 * This program is distributed in the hope that it will be useful, but WITHOUT
5199 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
5200 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
5203 * You should have received a copy of the GNU Affero General Public License along with
5204 * this program; if not, see http://www.gnu.org/licenses or write to the Free
5205 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
5208 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
5209 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
5211 * The interactive user interfaces in modified source and object code versions
5212 * of this program must display Appropriate Legal Notices, as required under
5213 * Section 5 of the GNU Affero General Public License version 3.
5215 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
5216 * these Appropriate Legal Notices must retain the display of the "Powered by
5217 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
5218 * technical reasons, the Appropriate Legal Notices must display the words
5219 * "Powered by SugarCRM".
5220 ********************************************************************************/
5225 function complexLayoutInit() {
5226 var se = SUGAR.email2;
5227 var Dom = YAHOO.util.Dom;
5229 getInnerLayout : function(rows) {
5230 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
5231 parent: se.complexLayout,
5237 scroll:false, // grid should autoScroll itself
5239 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
5247 body: "<div id='listBottom' />"
5255 body: "<div id='listRight' />",
5256 titlebar: false //,header: "right"
5259 se.complexLayout.on("render", function(){
5260 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
5261 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5262 SUGAR.email2.listViewLayout.set("height", height);
5263 SUGAR.email2.listViewLayout.render();
5265 se.listViewLayout.render();
5267 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
5268 var rp = se.listViewLayout.resizePreview = function() {
5269 var pre = Dom.get("displayEmailFramePreview");
5271 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
5272 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
5275 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
5276 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
5277 se.e2Layout.setPreviewPanel(rows);
5278 se.previewLayout = se.listViewLayout;
5279 return se.listViewLayout;
5282 getInnerLayout2Rows : function() {
5283 return this.getInnerLayout(true);
5285 getInnerLayout2Columns : function() {
5286 return this.getInnerLayout(false);
5290 // initialize state manager, we will use cookies
5291 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
5292 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
5293 se.complexLayout = new YAHOO.widget.Layout("container", {
5296 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
5297 width: Dom.getViewportWidth() - 40,
5301 body: "<div id='emailtabs'></div>"
5306 body: "<div id='lefttabs'></div>",
5316 header: Dom.get('footerLinks').innerHTML,
5323 se.complexLayout.render();
5324 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
5325 tp.addTab(new YAHOO.widget.Tab({
5328 content : "<div id='listViewDiv'/>",
5332 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
5333 tp.appendTo(centerEl);
5335 tp.get("element").style.borderRight = "1px solid #666"
5337 var listV = this.getInnerLayout2Rows();
5338 listV.set("height", tp.get("element").clientHeight - 25);
5341 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
5342 var folderTab = new YAHOO.widget.Tab({
5343 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
5345 content : "<div id='emailtree'/>",
5349 folderTab.on("activeChange", function(o){
5351 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
5354 se.leftTabs.addTab(folderTab);
5356 var tabContent = SUGAR.util.getAndRemove("searchTab");
5357 var searchTab = new YAHOO.widget.Tab({
5358 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
5360 content : tabContent.innerHTML,
5363 searchTab.on("activeChange", function(o){
5366 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
5367 //Setup the calendars if needed
5368 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
5369 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
5371 //Initalize sqs object for assigned user name
5372 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
5374 //Attach event handler for when the relate module option is selected for the correct sqs object
5375 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
5376 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
5377 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
5378 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
5380 //If enter key is pressed, perform search
5381 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
5382 for(var i=0; i < addKeyPressFields.length;i++)
5384 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
5385 if (e.keyCode == 13) {
5386 YAHOO.util.Event.stopEvent(e);
5387 SUGAR.email2.search.searchAdvanced();
5391 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
5393 //Clear parent values if selecting another parent type.
5394 YAHOO.util.Event.addListener('data_parent_type_search','change',
5396 document.getElementById('data_parent_id_search').value ='';
5397 document.getElementById('data_parent_name_search').value ='';
5402 se.leftTabs.addTab(searchTab);
5404 var resizeTabBody = function() {
5405 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
5406 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5409 se.complexLayout.on("render", resizeTabBody);
5410 se.leftTabs.on("activeTabChange", resizeTabBody);
5411 //hack to allow left pane scroll bar to fully show
5412 var lefttabsDiv = document.getElementById('lefttabs');
5413 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
5414 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
5415 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
5418 initSQSObject: function(formName,fieldName)
5420 var fullFieldName = formName + '_' + fieldName; //SQS Convention
5421 var resultName = fullFieldName + '_' + 'results';
5423 if (QSFieldsArray[fullFieldName] != null)
5425 QSFieldsArray[fullFieldName].destroy();
5426 delete QSFieldsArray[fullFieldName];
5428 if (QSProcessedFieldsArray[fullFieldName])
5429 QSProcessedFieldsArray[fullFieldName] = false;
5431 if( Dom.get(resultName) )
5433 var obj = document.getElementById(resultName);
5434 obj.parentNode.removeChild(obj);
5437 setPreviewPanel: function(rows) {
5439 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
5440 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
5441 Dom.get("listRight").innerHTML = "";
5442 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
5444 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
5445 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
5446 Dom.get("listBottom").innerHTML = "";
5447 Dom.get("listRight").innerHTML = "<div id='_blank' />";
5454 var myBufferedListenerObject = new Object();
5455 myBufferedListenerObject.refit = function() {
5456 if(SUGAR.email2.grid) {
5457 SUGAR.email2.grid.autoSize();
5460 // End of File modules/Emails/javascript/complexLayout.js