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;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];for(var i in properties)
127 {if(e[properties[i]])
128 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
129 newNode[properties[i]]=e[properties[i]];}}
131 {for(var i in e.childNodes)
132 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
133 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
134 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
136 /*********************************************************************************
137 * SugarCRM Community Edition is a customer relationship management program developed by
138 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
140 * This program is free software; you can redistribute it and/or modify it under
141 * the terms of the GNU Affero General Public License version 3 as published by the
142 * Free Software Foundation with the addition of the following permission added
143 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
144 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
145 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
147 * This program is distributed in the hope that it will be useful, but WITHOUT
148 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
149 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
152 * You should have received a copy of the GNU Affero General Public License along with
153 * this program; if not, see http://www.gnu.org/licenses or write to the Free
154 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
157 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
158 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
160 * The interactive user interfaces in modified source and object code versions
161 * of this program must display Appropriate Legal Notices, as required under
162 * Section 5 of the GNU Affero General Public License version 3.
164 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
165 * these Appropriate Legal Notices must retain the display of the "Powered by
166 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
167 * technical reasons, the Appropriate Legal Notices must display the words
168 * "Powered by SugarCRM".
169 ********************************************************************************/
172 cache : new Object(),
173 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
174 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
177 currentHtmleditor : ''
181 * preserves hits from email server
183 _setDetailCache : function(ret) {
185 var compKey = ret.meta.mbox + ret.meta.uid;
187 if(!SUGAR.email2.cache[compKey]) {
188 SUGAR.email2.cache[compKey] = ret;
193 autoSetLayout : function() {
194 var c = document.getElementById('container');
195 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
196 //Ensure a minimum height.
197 tHeight = Math.max(tHeight, 550);
198 c.style.height = tHeight + "px";
199 SUGAR.email2.complexLayout.set('height', tHeight);
200 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
201 SUGAR.email2.complexLayout.render();
202 SUGAR.email2.listViewLayout.resizePreview();
207 * Shows overlay progress message
209 function overlayModal(title, body) {
210 overlay(title, body);
212 function overlay(reqtitle, body, type, additconfig) {
214 if (typeof(additconfig) == "object") {
215 var config = additconfig;
218 config.title = reqtitle;
220 YAHOO.SUGAR.MessageBox.show(config);
223 function hideOverlay() {
224 YAHOO.SUGAR.MessageBox.hide();
226 // End of File modules/Emails/javascript/EmailUIShared.js
228 /*********************************************************************************
229 * SugarCRM Community Edition is a customer relationship management program developed by
230 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
232 * This program is free software; you can redistribute it and/or modify it under
233 * the terms of the GNU Affero General Public License version 3 as published by the
234 * Free Software Foundation with the addition of the following permission added
235 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
236 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
237 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
239 * This program is distributed in the hope that it will be useful, but WITHOUT
240 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
241 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
244 * You should have received a copy of the GNU Affero General Public License along with
245 * this program; if not, see http://www.gnu.org/licenses or write to the Free
246 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
249 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
250 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
252 * The interactive user interfaces in modified source and object code versions
253 * of this program must display Appropriate Legal Notices, as required under
254 * Section 5 of the GNU Affero General Public License version 3.
256 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
257 * these Appropriate Legal Notices must retain the display of the "Powered by
258 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
259 * technical reasons, the Appropriate Legal Notices must display the words
260 * "Powered by SugarCRM".
261 ********************************************************************************/
264 if (typeof console == "undefined")
265 console = { log: function(o) {alert(o)} };
269 currentRequestObject : null,
270 //timeout : 30000, // 30 second timeout default
271 timeout : 9999999999, // 30 second timeout default
277 _reset : function() {
278 this.timeout = 30000;
279 this.forceAbort = false;
282 folderRenameCleanup : function() {
283 SUGAR.email2.folders.setSugarFolders();
286 fullSyncCleanup : function(o) {
287 this.folders.checkMailCleanup(o);
288 SUGAR.email2.settings.settingsDialog.hide();
293 composeCache : function(o) {
294 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
295 // get email templates and user signatures
296 var ret = JSON.parse(o.responseText);
298 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
299 SUGAR.email2.composeLayout.signatures = ret.signatures;
300 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
302 SUGAR.email2.composeLayout.setComposeOptions(idx);
304 //Set the error array so we can notify the user when they try to hit send if any errors
305 //are present. We will also notify them now (after hitting compose button).
306 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
309 //if error element is returning an array, then check the length to make sure we have error messages
310 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
311 //add error messages for display
312 for(i in ret.errorArray)
313 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
314 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
315 //if error element is returning an object, and the object value is not empty or null, then display error message
316 for(i in ret.errorArray)
317 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
320 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
322 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
324 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
330 handleDeleteSignature : function(o) {
332 var ret = JSON.parse(o.responseText);
333 SUGAR.email2.composeLayout.signatures = ret.signatures;
334 var field = document.getElementById('signature_id');
335 SUGAR.email2.util.emptySelectOptions(field);
337 for(var i in ret.signatures) { // iterate through assoc array
338 var opt = new Option(ret.signatures[i], i);
339 field.options.add(opt);
341 setSigEditButtonVisibility();
346 handleDeleteReturn : function(o) {
347 // force refresh ListView
349 if(document.getElementById('focusEmailMbox')) {
350 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
353 // need to display success message before calling next async call?
354 document.getElementById(this.target).innerHTML = o.responseText;
359 handleFailure : function(o) {
361 overlay('Exception occurred...', o.statusText, 'alert');
362 if(document.getElementById('saveButton')) {
363 document.getElementById('saveButton').disabled = false;
367 handleReplyForward : function(o) {
368 var a = JSON.parse(o.responseText);
370 var idx = SUGAR.email2.composeLayout.currentInstanceId;
372 document.getElementById('email_id' + idx).value = a.uid;
373 document.getElementById('emailSubject' + idx).value = a.name;
374 document.getElementById('addressTO' + idx).value = a.from;
375 document.getElementById('uid' + idx).value = a.uid;
377 document.getElementById('addressCC' + idx).value = a.cc;
378 SE.composeLayout.showHiddenAddress('cc', idx);
382 document.getElementById('type' + idx).value = a.type;
385 // apply attachment values
386 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
388 setTimeout("callbackReplyForward.finish(globalA);", 500);
391 handleReplyForwardForDraft : function(o) {
392 var a = JSON.parse(o.responseText);
394 var idx = SUGAR.email2.composeLayout.currentInstanceId;
396 document.getElementById('email_id' + idx).value = a.uid;
397 document.getElementById('emailSubject' + idx).value = a.name;
398 document.getElementById('addressTO' + idx).value = a.to;
401 document.getElementById('addressCC' + idx).value = a.cc;
402 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
406 document.getElementById('addressBCC' + idx).value = a.bcc;
407 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
412 document.getElementById('type' + idx).value = a.type;
416 // apply attachment values
417 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
419 setTimeout("callbackReplyForward.finish(globalA);", 500);
424 handleSuccess : function(o) {
425 document.getElementById(this.target).innerHTML = o.responseText;
431 ieDeleteSuccess : function(o) {
434 var ret = JSON.parse(o.responseText);
436 SUGAR.email2.accounts.refreshInboundAccountTable();
437 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
438 SUGAR.email2.accounts.rebuildFolderList();
444 ieSaveSuccess : function(o) {
445 document.getElementById('saveButton').disabled = false;
446 var a = JSON.parse(o.responseText);
449 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
450 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
452 resp = JSON.parse(o.responseText);
453 SUGAR.email2.accounts.refreshInboundAccountTable();
454 SUGAR.email2.accounts.refreshOuboundAccountTable();
455 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
456 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
460 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
467 loadAttachments : function(o) {
468 var result = JSON.parse(o.responseText);
470 SUGAR.email2.composeLayout.loadAttachments(result);
475 loadSignature : function(o) {
476 var ret = JSON.parse(o.responseText);
477 SUGAR.email2.signatures[ret.id] = ret.signature_html;
478 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
482 * Follow up to mark email read|unread|flagged
484 markEmailCleanup : function(o) {
485 var ret = JSON.parse(o.responseText);
486 if (!ret['status']) {
488 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
490 SUGAR.email2.contextMenus.markEmailCleanup();
496 rebuildShowFolders : function(o) {
497 var t = JSON.parse(o.responseText);
498 var show = document.getElementById('ieAccountListShow');
500 SUGAR.email2.util.emptySelectOptions(show);
502 for(i=0; i<t.length; i++) { // iterate through assoc array
503 var opt = new Option(t[i].text, t[i].value, t[i].selected);
504 opt.selected = t[i].selected;
505 show.options.add(opt);
508 SUGAR.email2.accounts.renderTree();
512 saveListViewSortOrderPart2 : function() {
513 // create the JSON string the func expects
514 focusFolderPath = '[ "Home", "' + ieName + '"';
516 var f = new String(focusFolder);
517 var fEx = f.split('.');
519 for(i=0; i<fEx.length; i++) {
520 focusFolderPath += ', "' + fEx[i] +'"'
523 focusFolderPath += ']';
525 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
526 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
532 sendEmailCleanUp : function(o) {
534 var ret = JSON.parse(o.responseText);
536 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
537 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
538 } else if (o.responseText) {
539 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
542 if (typeof(SE.grid) != 'undefined')
543 SE.listView.refreshGrid();
544 //Disabled while address book is disabled
546 //If this call back was initiated by quick compose from a Detail View page, refresh the
547 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
548 //close the shortcut bar menu
549 if ( (typeof(action_sugar_grp1) != 'undefined')) {
550 if(action_sugar_grp1 == 'DetailView') {
551 showSubPanel('history',null,true);
552 } else if(action_sugar_grp1 == 'quickcreate') {
559 ieSendSuccess : function(o) {
561 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
566 settingsFolderRefresh : function(o) {
567 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
568 var ret = JSON.parse(o.responseText);
569 var user = document.getElementById('userFolders');
571 SUGAR.email2.util.emptySelectOptions(user);
573 for(i=0; i<ret.userFolders.length; i++) {
574 var display = ret.userFolders[i].name;
575 var value = ret.userFolders[i].id;
576 var selected = (ret.userFolders[i].selected != "") ? true : false;
577 var opt = new Option(display, value, selected);
578 opt.selected = selected;
579 user.options.add(opt);
585 startRequest : function(callback, args, forceAbort) {
586 if(this.currentRequestObject != null) {
587 if(this.forceAbort == true) {
588 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
591 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
595 requestInProgress : function() {
596 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
601 updateFolderSubscriptions : function() {
602 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
603 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
609 updateFrameFolder : function() {
610 SUGAR.email2.folders.checkEmailAccounts();
615 updateUserPrefs : function(o) {
616 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
617 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
622 uploadAttachmentSuccessful : function(o) {
624 document.getElementById('email_attachment').value = '';
626 var ret = JSON.parse(o.responseText);
627 var idx = SUGAR.email2.composeLayout.currentInstanceId;
628 var overall = document.getElementById('addedFiles' + idx);
629 var index = overall.childNodes.length;
631 "<div id='email_attachment_bucket" + idx + index + "'>" +
633 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
634 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
635 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
637 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
638 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
640 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
642 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
645 overall.innerHTML += out;
646 if(SUGAR.email2.util.isIe()) {
647 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
651 SUGAR.email2.addFileDialog.hide();
653 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
658 ///////////////////////////////////////////////////////////////////////////
659 //// PER MODULE CALLBACK OBJECTS
660 AjaxObject.accounts = {
661 saveOutboundCleanup : function(o) {
662 SUGAR.email2.accounts.refreshOuboundAccountTable();
663 SUGAR.email2.accounts.outboundDialog.hide();
664 var id = o.responseText;
665 SUGAR.email2.accounts.newAddedOutboundId = id;
667 saveDefaultOutboundCleanup: function(o){
670 callbackEditOutbound : {
671 success : function(o)
673 var ret = JSON.parse(o.responseText);
675 SUGAR.email2.accounts.showAddSmtp();
678 document.getElementById("mail_id").value = ret.id;
679 document.getElementById("type").value = ret.type;
680 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
681 document.getElementById("mail_name").value = ret.name;
682 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
683 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
684 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
685 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
686 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
687 SUGAR.email2.accounts.smtp_authenticate_field_display();
688 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
690 if(ret.type == 'system-override') {
691 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
692 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
695 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
696 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
698 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
701 failure : AjaxObject.handleFailure,
702 timeout : AjaxObject.timeout,
705 callbackDeleteOutbound : {
706 success : function(o) {
707 var ret = JSON.parse(o.responseText);
710 if(confirm(ret.error_message))
712 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
713 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
721 SUGAR.email2.accounts.refreshOuboundAccountTable();
725 failure : AjaxObject.handleFailure,
726 timeout : AjaxObject.timeout,
730 callbackCheckMailProgress : {
731 success : function(o) {
732 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
733 SUGAR.email2.accounts.totalMsgCount = -1;
736 //Check for server timeout / errors
737 var ret = JSON.parse(o.responseText);
740 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
742 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
743 SUGAR.email2.accounts.totalMsgCount = -1;
744 //SUGAR.email2.folders.rebuildFolders();
748 var currIeId = ret['ieid'];
751 var serverCount = ret.count;
753 if (ret['status'] == 'done') {
754 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
755 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
759 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
761 currIeId = SUGAR.email2.accounts.ieIds[i+1];
763 SUGAR.email2.accounts.totalMsgCount = -1;
768 else if (ret.mbox && ret.totalcount && ret.count) {
769 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
770 if (ret.count >= ret.totalcount) {
773 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
774 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
777 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
778 SUGAR.email2.accounts.totalMsgCount = -1;
783 SUGAR.email2.accounts.totalMsgCount = -1;
785 SUGAR.email2.folders.rebuildFolders();
786 SE.listView.refreshGrid();
787 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
788 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
789 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
790 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
792 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
793 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
794 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
795 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
796 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
799 failure : AjaxObject.handleFailure,
800 timeout : AjaxObject.timeout,
805 ///////////////////////////////////////////////////////////////////////////////
807 AjaxObject.composeLayout = {
809 * Populates the record id
811 saveDraftCleanup : function(o) {
813 var ret = JSON.parse(o.responseText);
815 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
816 else if (o.responseText)
817 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
821 AjaxObject.composeLayout.callback = {
823 success : AjaxObject.composeLayout.saveDraftCleanup,
824 failure : AjaxObject.handleFailure,
825 timeout : AjaxObject.timeout,
830 AjaxObject.detailView = {
832 * Pops-up a printable view of an email
834 displayPrintable : function(o) {
835 var ret = JSON.parse(o.responseText);
836 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
837 // 2 below must be in global context
839 meta['panelId'] = SUGAR.email2.util.getPanelId();
840 email = ret.meta.email;
841 if (typeof(email.cc) == 'undefined') {
845 var out = displayTemplate.exec({
846 'app_strings' : app_strings,
854 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
855 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
857 popup.document.write(out);
858 popup.document.close();
862 * Takes formatted response and creates a modal pop-over containing a title and content
864 displayView : function(o) {
865 var SED = SUGAR.email2.detailView;
866 var ret = JSON.parse(o.responseText);
868 if(!SED.viewDialog) {
869 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
873 constraintoviewport: true,
876 SED.viewDialog.renderEvent.subscribe(function() {
877 var content = this.body.firstChild;
878 var viewH = YAHOO.util.Dom.getViewportHeight();
880 this.body.style.overflow = "auto";
881 this.body.style.width = "800px";
882 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
886 SED.viewDialog.setHeader(ret.title);
887 SED.viewDialog.setBody(ret.html);
888 SED.viewDialog.render();
889 SED.viewDialog.show();
893 * Generates a modal popup to populate with the contents of bean's full EditView
895 showQuickCreateForm : function(o) {
896 var SED = SUGAR.email2.detailView;
897 var ret = JSON.parse(o.responseText);
899 if(!SED.quickCreateDialog) {
900 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
904 constraintoviewport: true,
908 SED.quickCreateDialog.renderEvent.subscribe(function() {
909 var viewH = YAHOO.util.Dom.getViewportHeight();
911 for (var i in this.body.childNodes) {
912 if (this.body.childNodes[i].clientHeight) {
913 contH += this.body.childNodes[i].clientHeight;
914 } else if (this.body.childNodes[i].offsetHeight) {
915 contH += this.body.childNodes[i].offsetHeight;
918 this.body.style.width = "800px";
919 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
920 this.body.style.overflow = "auto";
921 }, SED.quickCreateDialog);
923 SED.quickCreateDialog.hideEvent.subscribe(function(){
924 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
925 /*for(var qsField in qsFields){
926 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
927 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
930 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
933 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
935 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
936 SED.quickCreateDialog.render();
937 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
939 SED.quickCreateDialog.ieId = ret.ieId;
940 SED.quickCreateDialog.uid = ret.uid;
941 SED.quickCreateDialog.mbox = ret.mbox;
942 SED.quickCreateDialog.qcmodule = ret.module;
944 SED.quickCreateDialog.show();
946 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
948 editForm.module.value = 'Emails';
949 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
950 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
951 var instId = ret.module + count;
952 SED.quickCreateEmailsToAdd = ret.emailAddress;
953 SED.quickCreateEmailCallback = function(instId, tableId) {
954 var eaw = SUGAR.EmailAddressWidget.instances[instId];
955 if (typeof(eaw) == "undefined")
956 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
957 + instId + "','" + tableId + "');", 100);
958 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
960 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
961 + instId + "','" + tableId + "');", 100);
965 saveQuickCreateForm : function(o) {
967 SUGAR.email2.detailView.quickCreateDialog.hide();
968 validate['EditView'] = [ ];
971 saveQuickCreateFormAndReply : function(o) {
973 var ret = JSON.parse(o.responseText);
974 SUGAR.email2.detailView.quickCreateDialog.hide();
975 var qcd = SUGAR.email2.detailView.quickCreateDialog;
976 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
978 var emailID = ret.id;
979 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
981 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
983 //Cean the validate cache to prevent errors on the next call
984 validate['EditView'] = [ ];
987 saveQuickCreateFormAndAddToAddressBook : function(o) {
989 SUGAR.email2.detailView.quickCreateDialog.hide();
990 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
991 validate['EditView'] = [ ];
994 handleAssignmentDialogAssignAction : function() {
997 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
1003 var found_teams = false;
1004 var warning_message = mod_strings.LBL_WARN_NO_USERS;
1005 if(!found_teams && assign_user_id == '' )
1007 alert(warning_message);
1011 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1013 for(i=0; i<emailUids.length; i++) {
1015 uids += app_strings.LBL_EMAIL_DELIMITER;
1017 uids += emailUids[i];
1020 var row = SUGAR.email2.grid.getSelectedRows()[0];
1021 var data = SUGAR.email2.grid.getRecord(row).getData();
1022 var ieid = data.ieId;
1023 var mbox = data.mbox;
1024 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
1025 SUGAR.email2.contextMenus.assignToDialogue.hide();
1026 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
1030 handleAssignmentDialogDeleteAction : function() {
1031 // TO pass list of UIDS/emailIds
1032 var uids = SUGAR.email2.listView.getUidsFromSelection();
1033 var row = SUGAR.email2.grid.getSelections()[0];
1034 var ieid = row.data.ieId;
1035 var mbox = row.data.mbox;
1036 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
1037 SUGAR.email2.contextMenus.assignmentDialog.hide();
1038 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1044 showEmailDetailView : function(o) {
1046 var SED = SUGAR.email2.detailView;
1047 var ret = JSON.parse(o.responseText);
1049 if(!SED.quickCreateDialog) {
1050 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
1054 constraintoviewport: true,
1056 autofillheight: "body",
1059 SED.quickCreateDialog.renderEvent.subscribe(function() {
1060 var viewHeight = YAHOO.util.Dom.getViewportHeight();
1062 for (var i in this.body.childNodes) {
1063 if (this.body.childNodes[i].offsetHeight)
1064 contH += this.body.childNodes[i].offsetHeight;
1066 this.body.style.overflow = "auto";
1067 this.body.style.width = "800px";
1068 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
1070 }, SED.quickCreateDialog);
1072 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
1073 SED.quickCreateDialog.setBody(ret.html);
1074 SED.quickCreateDialog.render();
1075 SUGAR.util.evalScript(ret.html);
1076 SED.quickCreateDialog.show();
1079 showAssignmentDialogWithData : function(o) {
1080 var SEC = SUGAR.email2.contextMenus;
1082 var ret = JSON.parse(o.responseText);
1083 if (!SEC.assignmentDialog) {
1084 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
1087 constraintoviewport: true,
1090 SEC.assignmentDialog.setBody("");
1091 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
1092 SEC.assignmentDialog.renderEvent.subscribe(function() {
1093 var iev = YAHOO.util.Dom.get("Distribute");
1095 this.body.style.width = "700px";
1097 }, SEC.assignmentDialog);
1098 SEC.assignmentDialog.render();
1100 SEC.assignmentDialog.setBody(ret);
1101 SEC.assignmentDialog.render();
1103 SEC.assignmentDialog.show();
1104 SUGAR.util.evalScript(ret);
1107 showImportForm : function(o) {
1108 var SED = SUGAR.email2.detailView;
1109 var ret = JSON.parse(o.responseText);
1111 document.getElementById('quickCreateContent').innerHTML = "";
1117 if(!SED.importDialog) {
1118 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
1122 constraintoviewport: true,
1124 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
1125 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
1129 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
1130 SED.importDialog.setBody("");
1131 SED.importDialog.hideEvent.subscribe(function(){
1132 for(var i in QSFieldsArray) {
1133 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
1134 QSFieldsArray[i].destroy();
1135 delete QSFieldsArray[i];
1137 if (QSProcessedFieldsArray[i]) {
1138 QSProcessedFieldsArray[i] = false;
1142 SED.importDialog.renderEvent.subscribe(function() {
1143 var iev = YAHOO.util.Dom.get("ImportEditView");
1145 //this.body.style.height = (iev.clientHeight + 10) + "px";
1146 this.body.style.width = "600px";
1148 }, SED.importDialog);
1149 SED.importDialog.render();
1151 SED.importDialog.setBody(ret.html);
1152 SED.importDialog.ret = ret;
1153 SUGAR.util.evalScript(ret.html);
1154 SED.importDialog.render();
1156 SED.importDialog.show();
1157 SED.importDialog.focusFirstButton();
1159 getImportAction : function(ret) {
1160 if (!check_form('ImportEditView')) return false;
1161 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
1162 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
1166 var editView = document.getElementById('ImportEditView');
1167 if (editView.assigned_user_id != null) {
1168 get = get + "&user_id=" + editView.assigned_user_id.value
1169 //var user_id = editView.assigned_user_id.value;
1171 var parent_id = editView.parent_id.value;
1172 var parent_type = editView.parent_type.value;
1173 var row = SUGAR.email2.grid.getSelectedRows()[0];
1174 row = SUGAR.email2.grid.getRecord(row);
1175 var data = row.getData();
1176 var ieId = data.ieId;
1177 var mbox = data.mbox;
1178 var serverDelete = editView.serverDelete.checked;
1179 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1181 for(i=0; i<emailUids.length; i++) {
1183 uids += app_strings.LBL_EMAIL_DELIMITER;
1185 uids += emailUids[i];
1188 var action = 'importEmail&uid=';
1190 action = 'moveEmails';
1191 action = action + '&sourceFolder=' + ret['srcFolder'];
1192 action = action + '&sourceIeId=' + ret['srcIeId'];
1193 action = action + '&destinationFolder=' + ret['dstFolder'];
1194 action = action + '&destinationIeId=' + ret['dstIeId'];
1195 action = action + '&emailUids=';
1197 if (action.search(/importEmail/) != -1) {
1198 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
1200 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
1203 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
1204 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
1205 SUGAR.email2.detailView.importDialog.hide();
1206 document.getElementById('importDialogContent').innerHTML = "";
1209 showRelateForm : function(o) {
1210 var SED = SUGAR.email2.detailView;
1211 var ret = JSON.parse(o.responseText);
1212 document.getElementById('quickCreateContent').innerHTML = "";
1217 dialog_loaded = true;
1219 if(!SED.relateDialog) {
1220 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
1225 constraintoviewport: true,
1227 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
1228 if (!check_form('RelateEditView')) return false;
1230 var editView = document.getElementById('RelateEditView');
1231 var parent_id = editView.parent_id.value;
1232 var parent_type = editView.parent_type.value;
1233 var row = SUGAR.email2.grid.getSelectedRows()[0];
1234 row = SUGAR.email2.grid.getRecord(row);
1235 var ieId = row.getData().ieId;
1236 var mbox = row.getData().mbox;
1237 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1239 for(i=0; i<emailUids.length; i++) {
1241 uids += app_strings.LBL_EMAIL_DELIMITER;
1243 uids += emailUids[i];
1245 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1246 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
1247 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
1248 SED.relateDialog.hide();
1249 document.getElementById('relateDialogContent').innerHTML = "";
1254 SED.relateDialog.hideEvent.subscribe(function(){
1255 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
1256 QSFieldsArray['ImportEditView_parent_name'].destroy();
1257 delete QSFieldsArray['ImportEditView_parent_name'];
1259 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
1260 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
1264 SED.relateDialog.renderEvent.subscribe(function() {
1265 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
1267 for (var i in this.body.childNodes) {
1268 if (this.body.childNodes[i].clientHeight)
1269 contH += this.body.childNodes[i].clientHeight;
1271 }, SED.relateDialog);
1272 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
1275 SED.relateDialog.setBody(ret.html);
1276 SED.relateDialog.render();
1277 SUGAR.util.evalScript(ret.html);
1278 SED.relateDialog.show();
1282 * DetailView callbacks
1284 AjaxObject.detailView.callback = {
1286 success : function(o) {
1288 var ret = JSON.parse(o.responseText);
1289 SUGAR.email2.detailView.consumeMetaDetail(ret);
1291 argument: [targetDiv],
1292 failure : AjaxObject.handleFailure,
1297 success : function(o) {
1299 var ret = JSON.parse(o.responseText);
1300 SUGAR.email2.detailView.consumeMetaPreview(ret);
1302 failure : AjaxObject.handleFailure,
1307 success : AjaxObject.detailView.displayPrintable,
1308 failure : AjaxObject.handleFailure,
1309 timeout : AjaxObject.timeout,
1313 success : AjaxObject.detailView.displayView,
1314 failure : AjaxObject.handleFailure,
1315 timeout : AjaxObject.timeout,
1324 AjaxObject.folders = {
1326 * check-mail post actions
1328 checkMailCleanup : function(o) {
1330 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
1332 // refresh focus ListView
1333 SE.listView.refreshGrid();
1334 SUGAR.email2.folders.startCheckTimer(); // resets the timer
1339 rebuildFolders : function(o) {
1342 var data = JSON.parse(o.responseText);
1344 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
1345 SUGAR.email2.folders.setSugarFolders();
1348 AjaxObject.folders.callback = {
1350 success : AjaxObject.folders.checkMailCleanup,
1351 failure : AjaxObject.handleFailure,
1352 timeout : 600000, // 5 mins
1357 AjaxObject.rules = {
1358 loadRulesForSettings : function(o) {
1359 document.getElementById("rulesListCell").innerHTML = o.responseText;
1360 // assume we have the class we need
1361 SUGAR.routing.getStrings();
1362 SUGAR.routing.getDependentDropdowns();
1365 //// END PER MODULE CALLBACK OBJECTS
1366 ///////////////////////////////////////////////////////////////////////////
1370 success : AjaxObject.handleSuccess,
1371 failure : AjaxObject.handleFailure,
1372 timeout : AjaxObject.timeout,
1375 var callbackAccount = {
1376 success : AjaxObject.ieSaveSuccess,
1377 failure : AjaxObject.handleFailure,
1378 timeout : AjaxObject.timeout,
1381 var callbackAccountDelete = {
1382 success : AjaxObject.ieDeleteSuccess,
1383 failure : AjaxObject.handleFailure,
1384 timeout : AjaxObject.timeout,
1387 var callbackOutboundTest = {
1388 success : AjaxObject.ieSendSuccess,
1389 failure : AjaxObject.handleFailure,
1390 timeout : AjaxObject.timeout,
1396 var callbackTeamInfoForSettings = {
1397 success : function (o) {
1398 var data = JSON.parse(o.responseText);
1399 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
1401 failure : AjaxObject.handleFailure,
1402 timeout : AjaxObject.timeout,
1407 var callbackStatusForImport = {
1408 success : function (o) {
1410 if (o.responseText != "") {
1411 var statusString = "";
1412 var data = JSON.parse(o.responseText);
1413 for(i=0; i<data.length; i++) {
1414 statusString = statusString + data[i] + '<br/>';
1416 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
1418 SE.listView.refreshGrid();
1421 failure : AjaxObject.handleFailure,
1422 timeout : AjaxObject.timeout,
1426 var callbackComposeCache = {
1427 success : AjaxObject.composeCache,
1428 failure : AjaxObject.handleFailure,
1429 timeout : AjaxObject.timeout,
1432 var callbackDelete = {
1433 success : AjaxObject.handleDeleteReturn,
1434 failure : AjaxObject.handleFailure,
1435 timeout : AjaxObject.timeout,
1438 var callbackEmailDetailMultiple = {
1439 success : function(o) {
1441 var retMulti = JSON.parse(o.responseText);
1442 var ret = new Object();
1444 for(var i=0; i<retMulti.length; i++) {
1447 SUGAR.email2._setDetailCache(ret);
1448 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
1451 failure : AjaxObject.handleFailure,
1455 var callbackListViewSortOrderChange = {
1456 success : AjaxObject.saveListViewSortOrderPart2,
1457 failure : AjaxObject.handleFailure,
1458 timeout : AjaxObject.timeout,
1460 argument : [ieId, ieName, focusFolder]
1462 var callbackEmptyTrash = {
1463 success : function(o) {
1465 AjaxObject.folderRenameCleanup;
1467 failure : AjaxObject.handleFailure,
1468 timeout : AjaxObject.timeout,
1471 var callbackClearCacheFiles = {
1472 success : function(o) {
1475 failure : AjaxObject.handleFailure,
1476 timeout : AjaxObject.timeout,
1479 var callbackFolderRename = {
1480 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
1481 failure : AjaxObject.handleFailure,
1482 timeout : AjaxObject.timeout,
1485 var callbackFolderDelete = {
1486 success : function(o) {
1487 var ret = JSON.parse(o.responseText);
1489 if (ret.folder_id) {
1490 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
1492 SUGAR.email2.tree.removeNode(node, true);
1493 } else if (ret.ieId && ret.mbox) {
1494 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
1496 SUGAR.email2.tree.removeNode(node, true);
1499 //SUGAR.email2.folders.loadSettingFolder();
1502 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
1505 failure : AjaxObject.handleFailure,
1506 timeout : AjaxObject.timeout,
1509 var callbackFolderSave = {
1510 success : function(o) {
1511 var ret = JSON.parse(o.responseText);
1513 switch(ret.action) {
1514 case 'newFolderSave':
1515 SUGAR.email2.folders.rebuildFolders();
1519 failure : AjaxObject.handleFailure,
1520 timeout : AjaxObject.timeout,
1523 var callbackFolderSubscriptions = {
1524 success : AjaxObject.updateFolderSubscriptions,
1525 failure : AjaxObject.handleFailure,
1526 timeout : AjaxObject.timeout,
1529 var callbackFolderUpdate = {
1530 success : AjaxObject.updateFrameFolder,
1531 failure : AjaxObject.handleFailure,
1532 timeout : AjaxObject.timeout,
1535 var callbackFolders = {
1536 success : AjaxObject.folders.rebuildFolders,
1537 //success : void(true),
1538 failure : AjaxObject.handleFailure,
1539 timeout : AjaxObject.timeout,
1542 var callbackFullSync = {
1543 success : AjaxObject.fullSyncCleanup,
1544 failure : AjaxObject.handleFailure,
1545 timeout : 9999999999999,
1548 var callbackGeneric = {
1549 success : function() {
1552 failure : AjaxObject.handleFailure,
1553 timeout : AjaxObject.timeout,
1556 var callbackIeAccountRetrieve = {
1557 success : function(o) {
1558 // return JSON encoding
1560 SUGAR.email2.accounts.fillIeAccount(o.responseText);
1561 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
1563 failure : AjaxObject.handleFailure,
1564 timeout : AjaxObject.timeout,
1567 var callbackImportOneEmail = {
1568 success : AjaxObject.detailView.showImportForm,
1569 failure : AjaxObject.handleFailure,
1570 timeout : AjaxObject.timeout,
1573 var callbackRelateEmail = {
1574 success : AjaxObject.detailView.showRelateForm,
1575 failure : AjaxObject.handleFailure,
1576 timeout : AjaxObject.timeout,
1579 var callbackEmailDetailView = {
1580 success : AjaxObject.detailView.showEmailDetailView,
1581 failure : AjaxObject.handleFailure,
1582 timeout : AjaxObject.timeout,
1585 var callbackAssignmentDialog = {
1586 success : AjaxObject.detailView.showAssignmentDialogWithData,
1587 failure : AjaxObject.handleFailure,
1588 timeout : AjaxObject.timeout,
1591 var callbackAssignmentAction = {
1592 success : function(o) {
1593 SE.listView.refreshGrid();
1595 if(o.responseText != '') {
1596 overlay('Assignment action result', o.responseText, 'alert');
1599 failure : AjaxObject.handleFailure,
1600 timeout : AjaxObject.timeout,
1603 var callbackMoveEmails = {
1604 success : function(o) {
1605 SE.listView.refreshGrid();
1607 if(o.responseText != '') {
1608 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
1611 failure : AjaxObject.handleFailure,
1612 timeout : AjaxObject.timeout,
1615 var callbackLoadAttachments = {
1616 success : AjaxObject.loadAttachments,
1617 failure : AjaxObject.handleFailure,
1618 timeout : AjaxObject.timeout,
1621 var callbackLoadRules = {
1622 success : AjaxObject.rules.loadRulesForSettings,
1623 failure : AjaxObject.handleFailure,
1624 timeout : AjaxObject.timeout,
1627 var callbackLoadSignature = {
1628 success : AjaxObject.loadSignature,
1629 failure : AjaxObject.handleFailure,
1630 timeout : AjaxObject.timeout,
1633 var callbackDeleteSignature = {
1634 success : AjaxObject.handleDeleteSignature,
1635 failure : AjaxObject.handleFailure,
1636 timeout : AjaxObject.timeout,
1639 /*var callbackMoveEmails = {
1640 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
1641 failure : AjaxObject.handleFailure,
1642 timeout : AjaxObject.timeout,
1645 var callbackOutboundSave = {
1646 success : AjaxObject.accounts.saveOutboundCleanup,
1647 failure : AjaxObject.handleFailure,
1648 timeout : AjaxObject.timeout,
1651 var callbackDefaultOutboundSave = {
1652 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
1653 failure : AjaxObject.handleFailure,
1654 timeout : AjaxObject.timeout,
1657 var callbackQuickCreate = {
1658 success : AjaxObject.detailView.showQuickCreateForm,
1659 failure : AjaxObject.handleFailure,
1660 timeout : AjaxObject.timeout,
1663 var callbackQuickCreateSave = {
1664 success : AjaxObject.detailView.saveQuickCreateForm,
1665 failure : AjaxObject.handleFailure,
1666 timeout : AjaxObject.timeout,
1669 var callbackQuickCreateSaveAndAddToAddressBook = {
1670 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
1671 failure : AjaxObject.handleFailure,
1672 timeout : AjaxObject.timeout,
1675 var callbackQuickCreateSaveAndReply = {
1676 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
1677 failure : AjaxObject.handleFailure,
1678 timeout : AjaxObject.timeout,
1681 var callbackQuickCreateSaveAndReplyCase = {
1682 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
1683 failure : AjaxObject.handleFailure,
1684 timeout : AjaxObject.timeout,
1687 var callbackRebuildShowAccountList = {
1688 success : AjaxObject.rebuildShowFolders,
1689 failure : AjaxObject.handleFailure,
1690 timeout : AjaxObject.timeout,
1694 var callbackRefreshSugarFolders = {
1695 success : function(o) {
1696 var t = JSON.parse(o.responseText);
1697 SUGAR.email2.folders.setSugarFoldersEnd(t);
1699 failure : AjaxObject.handleFailure,
1700 timeout : AjaxObject.timeout,
1703 var callbackReplyForward = {
1704 success : AjaxObject.handleReplyForward,
1705 finish : function(a, retryCount) {
1706 if (typeof(retryCount) == 'undefined') {
1711 var idx = SUGAR.email2.composeLayout.currentInstanceId;
1712 var t = tinyMCE.getInstanceById('htmleditor' + idx);
1714 var html = t.getContent();
1716 if (a.type != 'draft') {
1717 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
1718 html += " <div><hr></div>" + a.description;
1720 html = " <div><hr></div>" + a.description + html;
1723 html = a.description;
1726 t.setContent(html);//
1729 if (retryCount < 5) {
1730 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
1734 var tabArray = SUGAR.email2.innerLayout.get("tabs");
1735 if (tabArray != null && tabArray.length > 0) {
1736 for (i = 0 ; i < tabArray.length ; i++) {
1737 var tabObject = tabArray[i];
1738 if (tabObject.get("id") == ("composeTab" + idx)) {
1739 var tabLabel = a.name;
1740 if (tabLabel != null && tabLabel.length > 25) {
1741 tabLabel = tabLabel.substring(0, 25) + "...";
1743 tabObject.get("labelEl").firstChild.data = tabLabel;
1749 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
1750 if (a.parent_name != null && a.parent_name != "") {
1751 document.getElementById('data_parent_name' + idx).value = a.parent_name;
1753 if (a.parent_type != null && a.parent_type != "") {
1754 document.getElementById('data_parent_type' + idx).value = a.parent_type;
1756 if (a.parent_id != null && a.parent_id != "") {
1757 document.getElementById('data_parent_id' + idx).value = a.parent_id;
1759 if (a.fromAccounts.status) {
1760 var addressFrom = document.getElementById('addressFrom' + idx);
1761 SUGAR.email2.util.emptySelectOptions(addressFrom);
1762 var fromAccountOpts = a.fromAccounts.data;
1763 for(i=0; i<fromAccountOpts.length; i++) {
1764 var key = fromAccountOpts[i].value;
1765 var display = fromAccountOpts[i].text;
1766 var opt = new Option(display, key);
1767 if (fromAccountOpts[i].selected) {
1768 opt.selected = true;
1770 addressFrom.options.add(opt);
1776 failure : AjaxObject.handleFailure,
1777 timeout : AjaxObject.timeout,
1779 argument : [sendType]
1781 var callbackSendEmail = {
1782 success : AjaxObject.sendEmailCleanUp,
1783 failure : AjaxObject.handleFailure,
1784 timeout : AjaxObject.timeout,
1787 var callbackSettings = {
1788 success : AjaxObject.updateUserPrefs,
1789 failure : AjaxObject.handleFailure,
1790 timeout : AjaxObject.timeout,
1793 var callbackSettingsFolderRefresh = {
1794 success : AjaxObject.settingsFolderRefresh,
1795 failure : AjaxObject.handleFailure,
1796 timeout : AjaxObject.timeout,
1799 var callbackLoadSettingFolder = {
1800 success : function(o) {
1801 AjaxObject.settingsFolderRefresh(o);
1802 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
1804 failure : AjaxObject.handleFailure,
1805 timeout : AjaxObject.timeout,
1809 var callbackUploadAttachment = {
1810 success : AjaxObject.uploadAttachmentSuccessful,
1811 upload : AjaxObject.uploadAttachmentSuccessful,
1812 failure : AjaxObject.handleFailure,
1813 timeout : AjaxObject.timeout,
1816 var callbackUserPrefs = {
1817 success : function(o) {
1818 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
1820 failure : AjaxObject.handleFailure,
1821 timeout : AjaxObject.timeout,
1825 var callbackContextmenus = {
1827 success : AjaxObject.markEmailCleanup,
1828 failure : AjaxObject.handleFailure,
1829 timeout : AjaxObject.timeout,
1834 var callbackCheckEmail2 = {
1835 success : function(o) {
1836 var ret = JSON.parse(o.responseText);
1837 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
1841 failure : AjaxObject.handleFailure,
1842 timeout : AjaxObject.timeout,
1844 }// End of File modules/Emails/javascript/ajax.js
1846 /*********************************************************************************
1847 * SugarCRM Community Edition is a customer relationship management program developed by
1848 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
1850 * This program is free software; you can redistribute it and/or modify it under
1851 * the terms of the GNU Affero General Public License version 3 as published by the
1852 * Free Software Foundation with the addition of the following permission added
1853 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
1854 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
1855 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
1857 * This program is distributed in the hope that it will be useful, but WITHOUT
1858 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1859 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
1862 * You should have received a copy of the GNU Affero General Public License along with
1863 * this program; if not, see http://www.gnu.org/licenses or write to the Free
1864 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
1867 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
1868 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
1870 * The interactive user interfaces in modified source and object code versions
1871 * of this program must display Appropriate Legal Notices, as required under
1872 * Section 5 of the GNU Affero General Public License version 3.
1874 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
1875 * these Appropriate Legal Notices must retain the display of the "Powered by
1876 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
1877 * technical reasons, the Appropriate Legal Notices must display the words
1878 * "Powered by SugarCRM".
1879 ********************************************************************************/
1881 function gridInit() {
1882 if(SUGAR.email2.grid) {
1883 SUGAR.email2.grid.destroy();
1889 var Ck = YAHOO.util.Cookie;
1890 var widths = [ 10, 10, 150, 250, 175, 125 ];
1892 if (Ck.get("EmailGridWidths")) {
1893 for (var i=0; i < widths.length; i++) {
1894 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
1897 for (var i=0; i < widths.length; i++) {
1898 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
1902 // changes "F" to an icon
1903 function flaggedIcon(cell, record, column, value) {
1905 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
1908 // changes "A" to replied icon
1909 function repliedIcon(cell, record, column, value) {
1911 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
1914 function attachIcon(cell, record, column, value) {
1916 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
1923 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
1928 formatter: attachIcon,
1932 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
1937 formatter: flaggedIcon,
1941 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
1946 formatter: repliedIcon,
1950 label: app_strings.LBL_EMAIL_FROM,
1957 label: app_strings.LBL_EMAIL_SUBJECT,
1964 label: mod_strings.LBL_LIST_DATE,
1971 label: app_strings.LBL_EMAIL_TO,
2007 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2008 responseType: YAHOO.util.DataSource.TYPE_JSON,
2010 resultsList: 'Email',
2011 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
2012 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
2018 action : "EmailUIAjax",
2019 emailUIAction : "getMessageList",
2022 forceRefresh : "false"
2024 if(lazyLoadFolder != null) {
2025 params['mbox'] = lazyLoadFolder.folder;
2026 params['ieId'] = lazyLoadFolder.ieId;
2027 //Check if the folder is a Sugar Folder
2028 var test = new String(lazyLoadFolder.folder);
2029 if(test.match(/SUGAR\./)) {
2030 params['emailUIAction'] = 'getMessageListSugarFolders';
2031 params['mbox'] = test.substr(6);
2034 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
2037 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
2038 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2040 paginator: new YAHOO.widget.Paginator({
2041 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
2042 containers : ["dt-pag-nav"],
2043 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2044 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2045 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2046 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2047 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2049 initialRequest:SUGAR.util.paramsToUrl(params),
2056 //Override Paging request construction
2057 grid.set("generateRequest", function(oState, oSelf) {
2058 oState = oState || {pagination:null, sortedBy:null};
2059 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
2060 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2061 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2062 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2063 // Build the request
2065 SUGAR.util.paramsToUrl(oSelf.params) +
2068 "&start=" + startIndex +
2069 ((results !== null) ? "&limit=" + results : "");
2074 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2075 oPayload = oPayload || { };
2077 oPayload.totalRecords = oResponse.meta.total;
2078 oPayload.unreadRecords = oResponse.meta.unread;
2080 var tabObject = SE.innerLayout.get("tabs")[0];
2082 if (this.params.mbox != null) {
2083 mboxTitle = this.params.mbox;
2085 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
2086 tabObject.get("labelEl").firstChild.data = tabtext;
2089 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
2091 node.data.unseen = oResponse.meta.unread;
2092 SE.accounts.renderTree();
2098 var resize = grid.resizeGrid = function () {
2099 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
2100 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
2102 grid.convertDDRows = function() {
2103 var rowEl = this.getFirstTrEl();
2104 while (rowEl != null) {
2105 new this.DDRow(this, this.getRecord(rowEl), rowEl);
2106 rowEl = this.getNextTrEl(rowEl);
2111 grid.on("columnResizeEvent", function(o) {
2112 //Find the index of the column
2113 var colSet = SUGAR.email2.grid.getColumnSet().flat;
2114 for (var i=0; i < colSet.length; i++) {
2115 if (o.column == colSet[i]) {
2116 //Store it in the cookie
2117 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
2120 //this.resizeGrid();
2123 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
2124 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
2125 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
2127 SUGAR.email2.listViewLayout.on("render", resize);
2130 //Setup the default load parameters
2131 SUGAR.email2.grid.params = params;
2133 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
2134 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2135 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2142 function initRowDD() {
2143 var sg = SUGAR.email2.grid,
2144 Dom = YAHOO.util.Dom;
2145 sg.DDRow = function(oDataTable, oRecord, elTr) {
2146 if(oDataTable && oRecord && elTr) {
2147 this.ddtable = oDataTable;
2148 this.table = oDataTable.getTableEl();
2151 this.newIndex = null;
2153 this.initFrame(); // Needed for DDProxy
2154 this.invalidHandleTypes = {};
2158 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
2159 _resizeProxy: function() {
2160 this.constructor.superclass._resizeProxy.apply(this, arguments);
2161 var dragEl = this.getDragEl(),
2163 var xy = Dom.getXY(el);
2165 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
2166 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
2167 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
2168 Dom.setStyle(dragEl, 'display', "");
2171 startDrag: function(x, y) {
2172 //Check if we should be dragging a set of rows rather than just the one.
2173 var selectedRows = this.ddtable.getSelectedRows();
2174 var iSelected = false;
2175 for (var i in selectedRows) {
2176 if (this.rowEl.id == selectedRows[i]) {
2183 for (var i in selectedRows) {
2184 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
2187 this.rows = [this.row];
2188 this.ddtable.unselectAllRows();
2189 this.ddtable.selectRow(this.row);
2192 //Initialize the dragable proxy
2193 var dragEl = this.getDragEl();
2194 var clickEl = this.getEl();
2195 Dom.setStyle(clickEl, "opacity", "0.25");
2196 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
2197 Dom.addClass(dragEl, "yui-dt-liner");
2198 Dom.setStyle(dragEl, "opacity", "0.5");
2199 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
2200 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
2201 Dom.setStyle(dragEl, "border", "2px solid gray");
2204 clickValidator: function(e) {
2205 if (this.row.getData()[0] == " ")
2207 var target = YAHOO.util.Event.getTarget(e);
2208 return ( this.isValidHandleChild(target) &&
2209 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
2212 * This funciton checks that the target of the drag is a table row in this
2213 * DDGroup and simply moves the sourceEL to that location as a preview.
2215 onDragOver: function(ev, id) {
2216 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
2217 if (node && node != this.targetNode) {
2218 this.targetNode = node;
2219 SUGAR.email2.folders.unhighliteAll();
2224 onDragOut: function(e, id) {
2225 if (this.targetNode) {
2226 SUGAR.email2.folders.unhighliteAll();
2227 this.targetNode = false;
2230 endDrag: function() {
2231 Dom.setStyle(this.getEl(), "opacity", "");
2232 Dom.setStyle(this.getDragEl(), "display", "none");
2233 if (this.targetNode) {
2234 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
2236 SUGAR.email2.folders.unhighliteAll();
2242 function AddressSearchGridInit() {
2243 function moduleIcon(elCell, oRecord, oColumn, oData) {
2244 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
2246 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
2247 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
2249 var checkHeader = '<input type="checkbox" ';
2250 if (SUGAR.email2.util.isIe()) {
2251 checkHeader += 'style="top:-5px" ';
2253 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
2258 formatter: selectionCheckBox,
2262 label: mod_strings.LBL_LIST_TYPE,
2264 formatter: moduleIcon,
2268 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
2274 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
2280 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2281 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
2283 resultsList: 'Person',
2284 fields: ['name', 'email', 'bean_id', 'bean_module'],
2285 metaFields: {total: 'TotalCount'}
2287 //enable sorting on the server accross all data
2290 dataModel.params = {
2293 action : "EmailUIAjax",
2294 emailUIAction:"getAddressSearchResults"
2296 var rb = document.getElementById('hasRelatedBean').checked;
2298 var idx = SUGAR.email2.composeLayout.currentInstanceId;
2299 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2300 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2301 dataModel.params['related_bean_id'] = relatedBeanId;
2302 dataModel.params['related_bean_type'] = relatedBeanType;
2303 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
2305 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
2307 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
2308 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2310 paginator: new YAHOO.widget.Paginator({
2312 containers : ["dt-pag-nav-addressbook"],
2313 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2314 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2315 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2316 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2317 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2319 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
2323 //Override Paging request construction
2324 grid.set("generateRequest", function(oState, oSelf) {
2325 oState = oState || {pagination:null, sortedBy:null};
2326 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
2327 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2328 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2329 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2330 // Build the request
2332 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
2333 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
2334 ((results !== null) ? "&limit=" + results : "");
2338 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2339 oPayload = oPayload || { };
2340 oPayload.totalRecords = oResponse.meta.total;
2344 grid.clickToggleSelect= function(args) {
2345 var isIE = (args.event.target == null);
2346 var targetElement = isIE ? args.event.srcElement : args.event.target;
2347 if(targetElement.type == null || targetElement.type != 'checkbox') {
2348 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
2352 grid.reSelectRowsOnRender = function (){
2353 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2354 for (var i = 0; i < rows.length; i++)
2356 var emailAddress = rows[i].getData("email");
2357 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
2360 rows[i].setData("selected", true);
2361 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2365 rows[i].setData("selected", false);
2366 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
2370 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
2371 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
2372 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
2373 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
2376 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2377 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2379 grid.toggleSelectCheckbox = function(id,checked){
2380 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2381 row.setData("checked",checked);
2383 grid.toggleSelect = function(id, checked) {
2384 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2385 checked = row.getData("selected");
2388 SUGAR.email2.addressBook.grid.selectRow(row);
2389 SE.addressBook.insertContactRowToResultTable(id,null)
2392 SUGAR.email2.addressBook.grid.unselectRow(row);
2393 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
2395 row.setData("selected", !checked);
2398 grid.toggleSelectAll = function(checked) {
2399 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2400 for (var i = 0; i < rows.length; i++) {
2401 if (typeof(rows[i]) != "undefined")
2402 rows[i].setData("checked", checked);
2404 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2405 for (var i = 0; i < checkBoxes.length; i++) {
2406 checkBoxes[i].checked = checked;
2410 //Initialize the grid result table.
2411 AddressSearchResultsGridInit();
2417 * Initalize the results table for the address book selection.
2420 function AddressSearchResultsGridInit()
2423 /* Full name sort funciton to compare by last name if available */
2424 var fullNameSort = function(a, b, desc) {
2425 // Deal with empty values
2426 if(!YAHOO.lang.isValue(a))
2427 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
2428 else if(!YAHOO.lang.isValue(b))
2431 var aNames = a.getData("name").split(' ');
2432 var bNames = b.getData("name").split(' ');
2434 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
2435 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
2437 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
2441 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
2442 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
2443 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
2445 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})},
2446 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
2448 var myDataSource = new YAHOO.util.DataSource([]);
2449 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
2450 myDataSource.responseSchema = {
2451 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
2454 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
2455 width: "350px",height: "250px", MSG_EMPTY: " "});
2457 var highlightEditableCell = function(oArgs) {
2458 var elCell = oArgs.target;
2459 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
2460 this.highlightCell(elCell);
2464 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
2465 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
2466 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
2467 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
2468 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
2470 //Setup the context menus
2471 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
2472 var task = p_aArgs[1];
2475 var elRow = this.contextEventTarget;
2476 elRow = p_myDataTable.getTrEl(elRow);
2483 var oRecord = p_myDataTable.getRecord(elRow);
2484 p_myDataTable.deleteRow(elRow);
2485 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2490 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
2491 {trigger:gridResults.getTbodyEl()});
2492 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
2493 contextMenu.render("addrSearchResultGrid");
2494 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
2496 // End of File modules/Emails/javascript/grid.js
2498 /*********************************************************************************
2499 * SugarCRM Community Edition is a customer relationship management program developed by
2500 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
2502 * This program is free software; you can redistribute it and/or modify it under
2503 * the terms of the GNU Affero General Public License version 3 as published by the
2504 * Free Software Foundation with the addition of the following permission added
2505 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
2506 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
2507 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
2509 * This program is distributed in the hope that it will be useful, but WITHOUT
2510 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
2511 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
2514 * You should have received a copy of the GNU Affero General Public License along with
2515 * this program; if not, see http://www.gnu.org/licenses or write to the Free
2516 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
2519 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
2520 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
2522 * The interactive user interfaces in modified source and object code versions
2523 * of this program must display Appropriate Legal Notices, as required under
2524 * Section 5 of the GNU Affero General Public License version 3.
2526 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
2527 * these Appropriate Legal Notices must retain the display of the "Powered by
2528 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
2529 * technical reasons, the Appropriate Legal Notices must display the words
2530 * "Powered by SugarCRM".
2531 ********************************************************************************/
2534 var sw = YAHOO.SUGAR,
2535 Event = YAHOO.util.Event,
2536 Connect = YAHOO.util.Connect,
2537 Dom = YAHOO.util.Dom
2540 ///////////////////////////////////////////////////////////////////////////////
2543 _contactCache : new Array(), // cache of contacts
2544 _dd : new Array(), // filtered list, same format as _contactCache
2545 _ddLists : new Array(), // list of Lists
2546 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
2547 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
2548 clickBubble : true, // hack to get around onclick event bubbling
2550 relatedBeanType : '',
2553 itemSpacing : 'white-space:nowrap; padding:2px;',
2559 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
2561 initFixForDatatableSort: function () {
2562 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
2563 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
2564 var oColumn = this._oColumnSet.getColumn(column);
2567 // Validate TD element
2568 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
2570 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
2572 // Validate TH element
2574 elCell = this.getThEl(column);
2577 var allColumns = this._oColumnSet.flat;
2578 for(var i=0, len=allColumns.length; i<len; i++) {
2579 if(allColumns[i].getThEl().id === elCell.id) {
2580 oColumn = allColumns[i];
2591 cancelEdit : function() {
2592 if(this.editContactDialog)
2593 this.editContactDialog.hide();
2594 if(this.editMailingListDialog)
2595 this.editMailingListDialog.hide();
2599 * Clears filter form
2601 clear : function() {
2602 var t = document.getElementById('contactsFilter');
2608 * handle context-menu Compose-to call
2609 * @param string type 'contacts' or 'lists'
2611 composeTo : function(type, waited) {
2612 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
2613 if (activePanel.substring(0, 10) != "composeTab") {
2614 SE.composeLayout.c0_composeNewEmail();
2615 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
2616 SE.contextMenus.contactsContextMenu.hide();
2619 var idx = activePanel.substring(10);
2622 // determine if we have a selection to work with
2623 if(type == 'contacts') {
2624 var ids = SE.contactView.getSelectedRows();
2625 for (var i in ids) {
2626 rows[i] = SE.contactView.getRecord(ids[i]);
2628 removeHiddenNodes(rows, SE.contactView);
2632 if(rows.length > 0) {
2633 SE.composeLayout.handleDrop(
2634 (type == 'contacts') ? SE.contactView : SE.emailListsView,
2635 null, rows, 'addressTO' + idx );
2637 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
2641 editContact : function() {
2642 SE.contextMenus.contactsContextMenu.hide();
2643 var element = SE.contactView.getSelectedNodes()[0];
2645 if (element.className.indexOf('address-contact') > -1) {
2646 elementId = element.id;
2647 } else if (element.className.indexOf('address-exp-contact') > -1) {
2648 elementId = element.id.substring(2);
2654 * Filters contact entries based on user input
2656 filter : function(inputEl) {
2657 var ret = new Object();
2658 var re = new RegExp(inputEl.value, "gi");
2660 for(var i in this._contactCache) {
2661 if(this._contactCache[i].name.match(re)) {
2662 ret[i] = this._contactCache[i];
2666 this.buildContactList(ret);
2669 fullForm : function(id, module) {
2670 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
2674 * returns a formatted email address from the addressBook cache
2676 getFormattedAddress : function(id) {
2677 var o = this._contactCache[id];
2678 var primaryEmail = '';
2680 for(var i=0; i<o.email.length; i++) {
2681 var currentEmail = o.email[i].email_address;
2683 if(o.email[i].primary_address == 1) {
2684 primaryEmail = o.email[i].email_address;
2688 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
2689 var name = new String(o.name);
2690 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
2691 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
2697 * Sets up async call to query for matching contacts, users, etc.
2699 searchContacts : function() {
2700 var fn = document.getElementById('input_searchField').value;
2701 var pe = document.getElementById('input_searchPerson').value;
2703 var rb = document.getElementById('hasRelatedBean').checked;
2706 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2707 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2708 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2709 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2711 this.addressBookDataModel.params['related_bean_id'] = '';
2714 this.addressBookDataModel.params['search_field'] = fn;
2715 this.addressBookDataModel.params['person'] = pe;
2716 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
2717 this.grid._oDataSource = this.addressBookDataModel;
2718 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
2722 * Clear Search Crieteria For Addressbook
2724 clearAddressBookSearch : function() {
2725 document.getElementById('input_searchField').value = "";
2726 document.getElementById('input_searchPerson').selectedIndex = 0;
2730 * Opens modal select window to add contacts to addressbook
2732 selectContactsDialogue : function(destId) {
2733 if(!this.contactsDialogue) {
2734 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
2738 constraintoviewport: true,
2740 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
2741 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
2743 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
2745 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
2746 dlg.setBody(body.innerHTML);
2747 dlg.renderEvent.subscribe(function() {
2748 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
2749 if (iev && !SUGAR.isIE) {
2750 this.body.style.width = "950px";
2755 dlg.beforeRenderEvent.subscribe(function() {
2756 var dd = new YAHOO.util.DDProxy(dlg.element);
2757 dd.setHandleElId(dlg.header);
2758 dd.on('endDragEvent', function() {
2764 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
2766 var tabContent = SUGAR.util.getAndRemove("searchForm");
2767 tp.addTab(new YAHOO.widget.Tab({
2768 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
2770 content : tabContent.innerHTML,
2771 id : "addressSearchTab",
2775 var addListenerFields = ['input_searchPerson','input_searchField' ]
2776 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
2777 if (e.keyCode == 13) {
2778 YAHOO.util.Event.stopEvent(e);
2779 SUGAR.email2.addressBook.searchContacts();
2783 this.contactsDialogue.render();
2786 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
2787 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
2791 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
2792 var idx = activePanel.substring(10);
2794 SE.addressBook.idx = idx;
2797 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
2798 document.getElementById('relatedBeanColumn').style.display = '';
2799 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
2800 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2801 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2802 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
2803 SE.addressBook.relatedBeanType = relatedBeanType;
2805 document.getElementById('relatedBeanColumn').style.display = 'none';
2806 document.getElementById('hasRelatedBean').checked = false;
2809 if (!SE.addressBook.grid)
2811 if (hasRelatedBeanId) {
2812 document.getElementById('hasRelatedBean').checked = true;
2814 AddressSearchGridInit();
2815 SE.addressBook.relatedBeanId = relatedBeanId;
2819 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
2821 SE.addressBook.relatedBeanId = relatedBeanId;
2822 document.getElementById('hasRelatedBean').checked = true;
2824 if (document.getElementById('hasRelatedBean').checked == true)
2826 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2827 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2829 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
2830 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
2832 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
2833 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
2834 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
2837 //Remove any lingering rows in the result set table if the module was closed.
2838 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2840 SE.addressBook.populateResulstTableEmailAddresses();
2842 this.contactsDialogue.show();
2845 * Clear all email addresses from result table.
2848 clearAllEmailAddressFieldsFromResultTable: function () {
2849 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2850 //Unhighlight any rows currently selected if the emails were cleared.
2851 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
2852 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2855 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
2856 * results table. This function is called when the address book is displayed.
2858 populateResulstTableEmailAddresses: function () {
2860 var idx = SE.addressBook.idx;
2861 var emailFields = ['to','cc','bcc'];
2863 for(var k=0;k<emailFields.length;k++)
2865 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2866 var allEmails = document.getElementById(elKey).value;
2870 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
2872 for (var i=0; i<formatedEmails.length; i++)
2874 var t_name = formatedEmails[i].name;
2875 var t_emailAddr = formatedEmails[i].email_address;
2876 var displayEmail = t_name + ' <' + t_emailAddr + '>';
2878 t_name = displayEmail = t_emailAddr;
2880 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
2881 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
2882 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
2888 * Checks all entries in the result table against a particular email address, returning true
2889 * if the email address is found, false otherwise.
2891 doesEmailAdddressExistInResultTable: function(emailAddress)
2893 if(trim(emailAddress) == '')
2896 var emailAddressFound = false;
2897 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2898 for (var i=0; i < contacts.length; i++)
2900 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2901 //If we are adding to cc or bcc fields, make them visible.
2902 if(data.email_address == emailAddress)
2904 emailAddressFound = true;
2909 return emailAddressFound;
2912 * Takes all email addresses that the users wishes to add from the address book and populates the To
2913 * fields on the compose tab.
2915 populateEmailAddressFieldsFromResultTable: function()
2917 //Clear the fields first, all email addresses are stored in the address book
2918 var idx = SE.addressBook.idx;
2919 var emailFields = ['to','cc','bcc'];
2920 for(var k=0;k<emailFields.length;k++)
2922 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2923 document.getElementById(elKey).value = "";
2926 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2927 for (var i=0; i < contacts.length; i++)
2929 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2931 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
2932 //If we are adding to cc or bcc fields, make them visible.
2933 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
2934 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
2935 //Construct the target id
2936 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
2938 var target = document.getElementById(target_id);
2939 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
2942 //Delete all rows from the result set table
2943 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2946 SE.addressBook.contactsDialogue.hide()
2949 * Insert contacts into the result table.
2951 insertContactToResultTable : function(event,address_type) {
2953 var contactsDialogue = SE.addressBook.contactsDialogue;
2954 var contacts = SE.addressBook.grid.getSelectedRows();
2956 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2957 for (var i = 0; i < rows.length; i++)
2959 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
2961 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
2962 SE.addressBook.insertContactRowToResultTable(recId,address_type);
2963 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2964 rows[i].setData("selected",true);
2967 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2968 for (var i = 0; i < checkBoxes.length; i++) {
2969 checkBoxes[i].checked = false;
2975 insertContactRowToResultTable : function(rowId, addressType) {
2976 var data = SE.addressBook.grid.getRecord(rowId).getData();
2977 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
2979 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
2980 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
2981 if(addressType == null)
2982 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
2983 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});
2986 * Remove a row from the gridsResult table.
2988 removeRowFromGridResults : function(rowId,emailAddress)
2990 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2991 for (var i=0; i < contacts.length; i++)
2993 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
2994 var data = rec.getData();
2995 if(data.email_address == emailAddress)
2997 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
3002 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
3005 * Translates between the addressType To|Cc|Bcc labels/keys.
3007 translateAddresType: function(addressType,fromKey)
3009 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
3010 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
3011 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
3012 var mappingObject = {};
3015 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
3018 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
3019 mappingObject[displayCc] = 'cc';
3020 mappingObject[displayBcc] = 'bcc';
3023 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
3029 toggleSearchRowIcon : function(rowId,show)
3033 var idToShow = rowId + '_add_img';
3034 var idToHide = rowId + '_rm_img';
3038 var idToShow = rowId + '_rm_img';
3039 var idToHide = rowId + '_add_img';
3043 Dom.addClass(idToHide, "yui-hidden");
3044 Dom.removeClass(idToShow, "yui-hidden");
3047 * Determine if an entry has already been added to the grid results table to prevent duplicates.
3049 doesGridResultsEntryExist: function(emailAddrs)
3052 var contactExists = false;
3053 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
3054 for (var i=0; i < contacts.length; i++)
3056 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
3057 if(data.email_address == emailAddrs)
3059 contactExists = true;
3063 return contactExists;
3067 * adds an email address to a string, but first checks if it exists
3068 * @param string concat The string we are appending email addresses to
3069 * @param string addr Email address to add
3072 smartAddEmailAddressToComposeField : function(concat, addr) {
3073 var re = new RegExp(addr);
3075 if(!concat.match(re)) {
3077 concat += "; " + addr;
3086 //// END ADDRESS BOOK
3087 ///////////////////////////////////////////////////////////////////////////////
3091 ///////////////////////////////////////////////////////////////////////////////
3094 * Auto-complete object
3098 delimChar : [";", ","],
3102 prehighlightClassName : "yui-ac-prehighlight",
3105 instances : new Array(),
3108 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
3109 * @param object Contact from AddressBook
3112 getPrimaryAddress : function(contact) {
3113 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
3115 for(var eIndex in contact.email) {
3116 address = contact.email[eIndex].email_address;
3117 if(contact.email[eIndex].primary_address == 1) {
3118 return contact.email[eIndex].email_address;
3126 * initializes autocomplete widgets for a given compose view
3129 init : function(idx) {
3130 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
3131 "queryMatchContains" : false,
3132 "queryMatchSubset" : true
3135 this.instances[idx] = {
3142 // instantiate the autoComplete widgets
3143 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
3144 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
3145 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
3147 // enable hiding of interfering textareas
3148 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3149 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3150 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3152 // enable reshowing of hidden textareas
3153 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3154 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3155 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3157 // enable refreshes of contact lists
3158 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3159 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3160 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3163 refreshDataSource : function(sType, aArgs) {
3164 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
3166 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
3168 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
3169 idx = textBoxId.substr(9);
3171 idx = textBoxId.substr(10);
3174 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
3175 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
3176 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
3180 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
3182 returnDataSource : function(contacts) {
3183 var ret = new Array();
3184 for(var id in contacts) {
3185 if (contacts[id].name) {
3186 var primary = this.getPrimaryAddress(contacts[id]);
3188 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
3189 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
3191 for(var emailIndex in contacts[id].email) {
3192 ret[ret.length] = contacts[id].email[emailIndex].email_address;
3201 * Hides address textareas to prevent autocomplete dropdown from being obscured
3203 toggleTextareaHide : function(sType, aArgs) {
3204 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3208 if(textBoxId.indexOf("addressTO") > -1) {
3210 } else if(textBoxId.indexOf("addressCC") > -1) {
3213 idx = textBoxId.substr(9);
3215 // follow through if not BCC
3217 var cc = document.getElementById("addressCC" + idx);
3218 var bcc = document.getElementById("addressBCC" + idx);
3222 cc.style.visibility = 'hidden';
3224 bcc.style.visibility = 'hidden';
3231 * Redisplays the textareas after an address is commited
3233 toggleTextareaShow : function(sType, aArgs) {
3234 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3238 if(textBoxId.indexOf("addressTO") > -1) {
3240 } else if(textBoxId.indexOf("addressCC") > -1) {
3243 idx = textBoxId.substr(9);
3245 // follow through if not BCC
3247 document.getElementById("addressCC" + idx).style.visibility = 'visible';
3248 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
3253 //// END AUTOCOMPLETE
3254 ///////////////////////////////////////////////////////////////////////////////
3256 ///////////////////////////////////////////////////////////////////////////////
3259 * expands the options sidebar
3261 SE.composeLayout = {
3262 currentInstanceId : 0,
3265 outboundAccountErrors : null,
3266 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
3268 showAddressDetails : function(e) {
3269 var linkElement = document.getElementById("More"+e.id);
3270 var spanElement = document.getElementById("Detail"+e.id);
3271 var emailAddressList = e.value;
3272 if(e.value.length > 96)
3274 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
3275 var displayArray = [];
3276 for (var i=0; i<resultArray.length; i++)
3278 var t_name = resultArray[i].name;
3279 var t_emailAddr = resultArray[i].email_address;
3281 displayArray.push('<br/><' + t_emailAddr + '>');
3283 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
3286 var result = displayArray.join('<br/>');
3288 linkElement.style.display = "inline";
3289 linkElement.style.height="10px";
3290 linkElement.style.overflow="visible";
3291 spanElement.innerHTML = result;
3294 linkElement.style.display = "none";
3299 * Given a string of email address, return an array containing the name portion (if available)
3300 * and email portion.
3302 _getEmailArrayFromString : function (emailAddressList){
3305 while ((results = reg.exec(emailAddressList)) != null)
3307 orignial = results[0];
3308 parsedResult = results[0].replace(';', ':::::');
3309 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3313 while ((results = reg.exec(emailAddressList)) != null)
3315 orignial = results[0];
3316 parsedResult = results[0].replace(',', ':::::');
3317 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3319 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
3320 var emailArr = emailAddressList.split(":::::");
3321 var resultsArray = [];
3323 for (var i=0; i<emailArr.length; i++)
3325 var rposition = emailArr[i].indexOf('<');
3326 var lposition = emailArr[i].indexOf('>');
3328 if(trim(emailArr[i]) != '')
3330 if(rposition != -1 && lposition != -1)
3332 var t_name = emailArr[i].substr(0, rposition-1);
3333 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
3334 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
3338 resultsArray.push({'name':'', 'email_address': emailArr[i]});
3342 return resultsArray;
3344 ///////////////////////////////////////////////////////////////////////////
3347 * Prepare bucket DIV and yui-ext tab panels
3349 _0_yui : function() {
3350 var idx = this.currentInstanceId;
3352 var composeTab = new YAHOO.SUGAR.ClosableTab({
3353 label: mod_strings.LNK_NEW_SEND_EMAIL,
3355 content : "<div id='htmleditordiv" + idx + "'/>",
3356 id : "composeTab" + idx,
3357 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
3360 SE.innerLayout.addTab(composeTab);
3362 // get template engine with template
3363 if (!SE.composeLayout.composeTemplate) {
3364 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
3367 // create Tab inner layout
3368 var composePanel = this.getComposeLayout();
3369 composePanel.getUnitByPosition("right").collapse();
3370 composePanel.autoSize();
3374 * Generate the quick compose layout
3375 * @method getQuickComposeLayout
3376 * @param {Pannel} parentPanel Parent pannel
3377 * @param {Object} o Options
3380 getQuickComposeLayout : function (parentPanel,o) {
3381 var idx = SE.composeLayout.currentInstanceId;
3383 //Before rendering the parent pannel we need to initalize the grid layout
3384 parentPanel.beforeRenderEvent.subscribe(function() {
3386 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3387 SE.composeLayout._createComposeLayout(idx);
3388 SE.composeLayout[idx].set('height', 350);
3389 SE.composeLayout[idx].render();
3393 //Wait until the Compose Layout has rendered, then add the
3394 //options tab and perform the tiny initialization.
3395 parentPanel.renderEvent.subscribe(function() {
3397 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3398 SE.composeLayout._initComposeOptionTabs(idx);
3399 SE.composeLayout[idx].getUnitByPosition("right").collapse();
3400 //Initialize tinyMCE
3401 if (!SUGAR.util.isTouchScreen())
3402 SE.composeLayout._1_tiny();
3403 //Init templates and address book
3404 SE.composeLayout._2_final();
3406 SE.composeLayout.quickCreateComposePackage(o);
3411 //Check if we have the div override for the shortcut bar
3412 if(typeof o.menu_id != 'undefined') {
3413 parentPanel.render(o.menu_id);
3415 parentPanel.render(document.body);
3418 return SE.composeLayout[idx];
3421 * Fill in all fields into the quick compose layout.
3422 * @method quickCreateComposePackage
3423 * @param {Object} o Options
3426 quickCreateComposePackage: function(o)
3428 //If we have a compose package fill in defaults.
3429 if (typeof(o.composePackage) != 'undefined')
3431 composePackage = o.composePackage; //Set the compose data object
3432 //Hijack this method called by composePackage as it's not need for quick creates.
3433 SE.composeLayout.c0_composeNewEmail = function(){};
3434 SE.composeLayout.composePackage(); //Fill in defaults.
3437 getComposeLayout : function() {
3438 var idx = SE.composeLayout.currentInstanceId;
3440 this._createComposeLayout(idx);
3441 SE.composeLayout[idx].render();
3442 this._initComposeOptionTabs(idx);
3444 return SE.composeLayout[idx];
3448 * Create the layout manager for the compose window.
3450 _createComposeLayout : function(idx)
3452 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
3453 parent: SE.complexLayout,
3463 SE.composeLayout.composeTemplate.exec({
3464 'app_strings':app_strings,
3465 'mod_strings':mod_strings,
3467 'linkbeans_options' : linkBeans,
3468 'idx' : SE.composeLayout.currentInstanceId
3479 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
3482 header: app_strings.LBL_EMAIL_OPTIONS
3488 * Create compose tab which will populate the 'right' container in the compose window.
3490 _initComposeOptionTabs : function(idx)
3492 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
3493 var tab = new YAHOO.widget.Tab({
3494 label: app_strings.LBL_EMAIL_ATTACHMENT,
3496 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
3497 id : "divAttachments" + idx,
3501 tab.layout = SE.composeLayout[idx];
3503 tab.on("activeChange", function(o){
3505 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
3511 tab = new YAHOO.widget.Tab({
3512 label: app_strings.LBL_EMAIL_OPTIONS,
3514 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
3515 id : "divOptions" + idx,
3519 tab.layout = SE.composeLayout[idx];
3520 tab.on("activeChange", function(o){
3522 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
3527 SE.composeLayout[idx].autoSize = function() {
3528 var pEl = this.get("element").parentNode.parentNode.parentNode;
3529 this.set("height", pEl.clientHeight-30);
3533 SE.composeLayout[idx].rightTabs = cTabs;
3535 isParentTypeValid : function(idx) {
3536 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3537 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3538 if (trim(parentTypeValue) == ""){
3539 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
3545 isParentTypeAndNameValid : function(idx) {
3546 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3547 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3548 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
3549 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
3550 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
3551 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
3557 callopenpopupForEmail2 : function(idx,options) {
3559 var formName = 'emailCompose' + idx;
3561 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
3562 formName = options.form_name;
3564 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3565 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3566 if (!SE.composeLayout.isParentTypeValid(idx)) {
3569 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
3571 call_back_function:"SE.composeLayout.popupAddEmail",
3573 field_to_name_array:{
3574 id:'data_parent_id' + idx,
3575 name:'data_parent_name' + idx,
3580 popupAddEmail : function(o)
3582 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
3583 var data = o.name_to_value_array;
3584 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
3585 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
3587 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
3588 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
3595 _1_tiny : function() {
3596 var idx = SE.composeLayout.currentInstanceId;
3597 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
3598 SE.tinyInstances[elId] = { };
3599 SE.tinyInstances[elId].ready = false;
3600 var t = tinyMCE.getInstanceById(elId);
3602 if(typeof(t) == 'undefined') {
3603 tinyMCE.execCommand('mceAddControl', false, elId);
3604 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
3605 SE.composeLayout.resizeEditor(idx);
3606 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
3611 resizeEditor : function(idx)
3613 var cof = Dom.get('composeOverFrame' + idx);
3614 var head = Dom.get('composeHeaderTable' + idx);
3615 var targetHeight = cof.clientHeight - head.clientHeight;
3616 var instance = tinyMCE.get(SE.tinyInstances.currentHtmleditor);
3618 var parentEl = Dom.get(instance.editorId + '_parent');
3619 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
3620 var contentEl = instance.contentAreaContainer;
3621 var iFrame = contentEl.firstChild;
3622 var tinMceToolbarOffset = 18;
3623 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
3627 * Initializes d&d, auto-complete, email templates
3629 _2_final : function() {
3630 var idx = SE.composeLayout.currentInstanceId;
3632 if(this.emailTemplates) {
3633 this.setComposeOptions(idx);
3635 //populate email template cache
3636 AjaxObject.target = '';
3637 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
3640 // handle drop targets for addressBook
3641 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3642 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3643 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3644 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
3646 // auto-complete setup
3647 SE.autoComplete.init(idx);
3650 document.getElementById("addressTO" + idx).focus();
3654 * hide tinyMCE tool bar if send email as plaintext is checked
3656 renderTinyMCEToolBar : function (idx, hide) {
3658 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
3660 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
3664 c1_composeEmail : function(isReplyForward, retry) {
3668 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
3669 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
3674 if(isReplyForward) {
3675 this.replyForwardEmailStage2();
3681 * takes draft info and prepopulates
3683 c0_composeDraft : function() {
3684 this.getNewInstanceId();
3686 document.getElementById('_blank').innerHTML = '';
3687 var idx = SE.composeLayout.currentInstanceId;
3688 SE.composeLayout.draftObject = new Object();
3689 SE.composeLayout.draftObject.id = idx;
3690 SE.composeLayout.draftObject.isDraft = true;
3691 SE.composeLayout.currentInstanceId = idx;
3692 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
3693 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
3694 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
3696 SE.composeLayout._0_yui();
3697 SE.composeLayout._1_tiny();
3700 SE.composeLayout._2_final();
3702 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
3703 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
3707 * Strip & Prep editor hidden fields
3709 c0_composeNewEmail : function() {
3710 this.getNewInstanceId();
3711 this.c1_composeEmail(false);
3715 * Sends async request to get the compose view.
3716 * Requests come from "reply" or "forwards"
3718 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
3719 SE.composeLayout.replyForwardObj = new Object();
3720 SE.composeLayout.replyForwardObj.ieId = ieId;
3721 SE.composeLayout.replyForwardObj.uid = uid;
3722 SE.composeLayout.replyForwardObj.mbox = mbox;
3723 SE.composeLayout.replyForwardObj.type = type;
3725 if(mbox == 'sugar::Emails') {
3726 SE.composeLayout.replyForwardObj.sugarEmail = true;
3729 SE.composeLayout.getNewInstanceId();
3730 SE.composeLayout.c1_composeEmail(true);
3732 //// END COMPOSE FLOW
3733 ///////////////////////////////////////////////////////////////////////////
3736 * Called when a contact, email, or mailinglist is dropped
3737 * into one of the compose fields.
3739 handleDrop : function (source, event, data, target) {
3742 target = event.getTarget();
3744 data.nodes = [data.nodes];
3748 target = document.getElementById(target);
3752 if (target.id.indexOf('address') > -1) {
3753 // dropped onto email to/cc/bcc field
3754 for(var i in nodes) {
3755 var node = nodes[i].getData();
3757 if (node[1].indexOf('contact') > -1) {
3758 email = SE.addressBook.getFormattedAddress(node[0]);
3759 } else if (node[1].indexOf('address-email') > -1){
3760 email = node[3].replace(/ /gi, '');
3761 email = email.replace('<', '<').replace('>', '>');
3762 var tr = source.getTrEl(nodes[i]);
3763 while (tr && !Dom.hasClass(tr, "address-contact")) {
3764 tr = source.getPreviousTrEl(tr);
3766 var CID = source.getRecord(tr).getData()[0];
3767 var o = SE.addressBook._contactCache[CID];
3768 var name = new String(o.name);
3769 var finalName = name.replace(/(<([^>]+)>)/ig, "");
3770 email = finalName + email;
3772 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
3778 /*/////////////////////////////////////////////////////////////////////////////
3779 /// EMAIL TEMPLATE CODE
3781 applyEmailTemplate : function (idx, id) {
3784 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
3785 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
3786 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
3789 var to_addr = document.getElementById('addressTO'+idx);
3790 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
3792 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
3793 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
3796 // id is selected index of email template drop-down
3797 if(id == '' || id == "0") {
3798 YAHOO.SUGAR.MessageBox.show({
3803 if(btn=='no'){return;};
3804 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
3811 YAHOO.SUGAR.MessageBox.show({
3816 if(btn=='no'){return;};
3817 SUGAR.email2.composeLayout.processResult(idx, id);},
3823 processNoneResult : function(idx, id) {
3824 var tiny = SE.util.getTiny('htmleditor' + idx);
3825 var tinyHTML = tiny.getContent();
3826 var openTag = '<div><span><span>';
3827 var htmllow = tinyHTML.toLowerCase();
3828 var start = htmllow.indexOf(openTag);
3830 tinyHTML = tinyHTML.substr(start);
3831 tiny.setContent(tinyHTML);
3833 tiny.setContent('');
3837 processResult : function(idx , id){
3838 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
3840 // get attachments if any
3841 AjaxObject.target = '';
3842 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
3845 appendEmailTemplateJSON : function() {
3846 var idx = SE.composeLayout.currentInstanceId; // post increment
3848 // query based on template, contact_id0,related_to
3849 //jchi 09/10/2008 refix #7743
3850 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
3851 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
3854 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,'"');
3856 // cn: bug 14361 - text-only templates don't fill compose screen
3858 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/>");
3861 var tiny = SE.util.getTiny('htmleditor' + idx);
3862 var tinyHTML = tiny.getContent();
3863 var openTag = '<div><span><span>';
3864 var closeTag = '</span></span></div>';
3865 var htmllow = tinyHTML.toLowerCase();
3866 var start = htmllow.indexOf(openTag);
3868 var htmlPart2 = tinyHTML.substr(start);
3869 tinyHTML = text + htmlPart2;
3870 tiny.setContent(tinyHTML);
3872 tiny.setContent(text);
3877 * Writes out the signature in the email editor
3879 setSignature : function(idx) {
3882 var hide = document.getElementById('setEditor' + idx).checked;
3883 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
3884 //wait for signatures to load before trying to set them
3885 if (!SE.composeLayout.signatures) {
3886 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
3891 var sel = document.getElementById('signatures' + idx);
3893 var sel = document.getElementById('signature_id');
3894 idx = SE.tinyInstances.currentHtmleditor;
3897 //Ensure that the tinyMCE html has been rendered.
3898 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
3899 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
3906 signature = sel.options[sel.selectedIndex].value;
3911 var openTag = '<div><span><span>';
3912 var closeTag = '</span></span></div>';
3913 var t = SE.util.getTiny('htmleditor' + idx);
3915 if(typeof(t) != 'undefined')
3917 t.contentDocument = t.contentWindow.document;
3918 var html = t.getContent();
3923 var htmllow = html.toLowerCase();
3924 var start = htmllow.indexOf(openTag);
3925 var end = htmllow.indexOf(closeTag) + closeTag.length;
3927 // selected "none" - remove signature from email
3928 if(signature == '') {
3930 var htmlPart1 = html.substr(0, start);
3931 var htmlPart2 = html.substr(end, html.length);
3933 html = htmlPart1 + htmlPart2;
3936 SE.signatures.lastAttemptedLoad = '';
3940 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
3941 SE.signatures.lastAttemptedLoad = '';
3943 SE.signatures.lastAttemptedLoad = signature;
3945 if(typeof(SE.signatures[signature]) == 'undefined') {
3947 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
3948 SE.signatures.targetInstance = (idx) ? idx : "";
3949 AjaxObject.target = '';
3950 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
3952 var newSignature = this.prepareSignature(SE.signatures[signature]);
3954 // clear out old signature
3955 if(SE.signatures.lastAttemptedLoad && start > -1) {
3956 var htmlPart1 = html.substr(0, start);
3957 var htmlPart2 = html.substr(end, html.length);
3959 html = htmlPart1 + htmlPart2;
3963 start = html.indexOf('<div><hr></div>');
3964 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
3965 var htmlPart1 = html.substr(0, start);
3966 var htmlPart2 = html.substr(start, html.length);
3967 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
3968 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
3969 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
3971 var newHtml = html + openTag + newSignature + closeTag;
3973 //tinyMCE.setContent(newHtml);
3974 t.setContent(newHtml);
3978 prepareSignature : function(str) {
3979 var signature = new String(str);
3981 signature = signature.replace(/</gi, '<');
3982 signature = signature.replace(/>/gi, '>');
3988 showAttachmentPanel : function(idx) {
3989 var east = SE.composeLayout[idx].getUnitByPosition("right");
3990 var tabs = SE.composeLayout[idx].rightTabs;
3992 tabs.set("activeTab", tabs.getTab(0));
3996 * expands sidebar and displays options panel
3998 showOptionsPanel : function(idx) {
3999 var east = SE.composeLayout[idx].getUnitByPosition("right");
4000 var tabs = SE.composeLayout[idx].rightTabs;
4002 tabs.set("activeTab", tabs.getTab(1));
4006 * Selects the Contacts tab
4008 showContactsPanel : function() {
4009 SE.complexLayout.regions.west.showPanel("contactsTab");
4013 * Generates fields for Select Document
4015 addDocumentField : function(idx) {
4016 var basket = document.getElementById('addedDocuments' + idx);
4018 var index = (basket.childNodes.length / 7) - 1;
4025 var test = document.getElementById('documentId' + idx + index);
4027 while(test != null) {
4029 test = document.getElementById('documentId' + idx + index);
4032 var documentCup = document.createElement("div");
4033 documentCup.id = 'documentCup' + idx + index;
4034 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
4035 // document id field
4036 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
4037 // document name field
4038 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
4040 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
4041 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
4042 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
4044 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
4045 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
4046 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
4049 basket.appendChild(documentCup);
4050 //basket.innerHTML += out;
4055 * Makes async call to save a draft of the email
4056 * @param int Instance index
4058 saveDraft : function(tinyInstance) {
4059 this.sendEmail(tinyInstance, true);
4062 selectDocument : function(target) {
4063 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
4064 windowName = 'selectDocument';
4065 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
4067 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4069 // put the focus on the popup if the browser supports the focus() method
4075 * Modal popup for file attachment dialogue
4077 addFileField : function() {
4078 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
4079 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
4083 constraintoviewport: true,
4085 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
4086 fn:function(){SE.addFileDialog.hide();}
4089 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
4090 SE.addFileDialog.render();
4091 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
4093 Dom.removeClass("addFileDialog", "yui-hidden");
4095 SE.addFileDialog.show();
4099 * Async upload of file to temp dir
4101 uploadAttachment : function() {
4102 if(document.getElementById('email_attachment').value != "") {
4103 var formObject = document.getElementById('uploadAttachment');
4104 YAHOO.util.Connect.setForm(formObject, true, true);
4105 AjaxObject.target = '';
4106 AjaxObject.startRequest(callbackUploadAttachment, null);
4108 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
4113 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
4114 * @param string target in focus compose layout
4116 setDocument : function(idx, target, documentId, documentName, docRevId) {
4117 // fields are named/id'd [fieldName][instanceId][index]
4118 var addedDocs = document.getElementById("addedDocuments" + idx);
4119 var docId = document.getElementById('documentId' + idx + target);
4120 var docName = document.getElementById('documentName' + idx + target);
4121 var docRevisionId = document.getElementById('document' + idx + target);
4122 docId.value = documentId;
4123 docName.value = documentName;
4124 docRevisionId.value = docRevId;
4128 * Removes the bucket div containing the document input fields
4130 deleteDocumentField : function(documentCup) {
4131 var f0 = document.getElementById(documentCup);
4132 f0.parentNode.removeChild(f0);
4136 * Removes a Template Attachment field
4140 deleteTemplateAttachmentField : function(idx, index) {
4141 // create not-in-array values for removal filtering
4142 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
4148 r += document.getElementById('templateAttachmentId' + idx + index).value;
4149 document.getElementById("templateAttachmentsRemove" + idx).value = r;
4151 var target = 'templateAttachmentCup' + idx + index;
4152 d = document.getElementById(target);
4153 d.parentNode.removeChild(d);
4157 * Async removal of uploaded temp file
4158 * @param string index Should be a concatenation of idx and index
4161 deleteUploadAttachment : function(index, file) {
4162 var d = document.getElementById('email_attachment_bucket' + index);
4163 d.parentNode.removeChild(d);
4165 // make async call to delete cached file
4166 AjaxObject.target = '';
4167 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
4171 * Attaches files coming from Email Templates
4173 addTemplateAttachmentField : function(idx) {
4175 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
4177 var basket = document.getElementById('addedTemplateAttachments' + idx);
4180 var index = basket.childNodes.length;
4187 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
4189 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
4190 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
4191 idx + "\",\"" + index + "\");'/>" +
4193 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
4194 // templateAttachment field
4195 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
4197 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
4199 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
4200 "<br id='br" + index + "></br>" +
4201 "<br id='brdoc" + index + "></br>" +
4203 basket.innerHTML = basket.innerHTML + out;
4209 * Sends one email via async call
4210 * @param int idx Editor instance ID
4211 * @param bool isDraft
4213 sendEmail : function(idx, isDraft) {
4215 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
4216 var obAccountID = document.getElementById('addressFrom' + idx).value;
4218 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
4220 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
4225 var form = document.getElementById('emailCompose' + idx);
4226 var composeOptionsFormName = "composeOptionsForm" + idx;
4227 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
4228 var html = t.getContent();
4229 var subj = document.getElementById('emailSubject' + idx).value;
4230 var to = trim(document.getElementById('addressTO' + idx).value);
4231 var cc = trim(document.getElementById('addressCC' + idx).value);
4232 var bcc = trim(document.getElementById('addressBCC' + idx).value);
4233 var email_id = document.getElementById('email_id' + idx).value;
4234 var composeType = document.getElementById('composeType').value;
4235 var parent_type = document.getElementById("parent_type").value;
4236 var parent_id = document.getElementById("parent_id").value;
4238 var el_uid = document.getElementById("uid");
4239 var uid = (el_uid == null) ? '' : el_uid.value;
4241 var el_ieId = document.getElementById("ieId");
4242 var ieId = (el_ieId == null) ? '' : el_ieId.value;
4244 var el_mbox = document.getElementById("mbox");
4245 var mbox = (el_mbox == null) ? '' : el_mbox.value;
4247 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
4248 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
4252 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
4255 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
4256 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
4257 parent_id = parentIdValue;
4258 parent_type = parentTypeValue;
4260 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
4261 // baseline viability check
4263 if(to == "" && cc == '' && bcc == '' && !isDraft) {
4264 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
4266 } else if(subj == '' && !isDraft) {
4267 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
4270 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
4272 } else if(html == '' && !isDraft) {
4273 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
4278 SE.util.clearHiddenFieldValues('emailCompose' + idx);
4279 document.getElementById('data_parent_id' + idx).value = parentIdValue;
4280 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
4281 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
4282 html = html.replace(/</ig, "sugarLessThan");
4283 html = html.replace(/>/ig, "sugarGreaterThan");
4285 form.sendDescription.value = html;
4286 form.sendSubject.value = subj;
4287 form.sendTo.value = to;
4288 form.sendCc.value = cc;
4289 form.sendBcc.value = bcc;
4290 form.email_id.value = email_id;
4291 form.composeType.value = composeType;
4292 form.composeLayoutId.value = 'composeLayout' + idx;
4293 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
4294 form.saveToSugar.value = 1;
4295 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
4296 form.parent_type.value = parent_type;
4297 form.parent_id.value = parent_id;
4298 form.uid.value = uid;
4299 form.ieId.value = ieId;
4300 form.mbox.value = mbox;
4302 // email attachments
4303 var addedFiles = document.getElementById('addedFiles' + idx);
4305 for(i=0; i<addedFiles.childNodes.length; i++) {
4306 var bucket = addedFiles.childNodes[i];
4308 for(j=0; j<bucket.childNodes.length; j++) {
4309 var node = bucket.childNodes[j];
4310 var nName = new String(node.name);
4312 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
4313 if(form.attachments.value != '') {
4314 form.attachments.value += "::";
4316 form.attachments.value += node.value;
4323 var addedDocs = document.getElementById('addedDocuments' + idx);
4325 for(i=0; i<addedDocs.childNodes.length; i++) {
4326 var cNode = addedDocs.childNodes[i];
4327 for(j=0; j<cNode.childNodes.length; j++) {
4328 var node = cNode.childNodes[j];
4329 var nName = new String(node.name);
4330 if(node.type == 'hidden' && nName.match(/documentId/)) {
4331 if(form.documents.value != '') {
4332 form.documents.value += "::";
4334 form.documents.value += node.value;
4340 // template attachments
4341 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
4342 if(addedTemplateAttachments) {
4343 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
4344 var cNode = addedTemplateAttachments.childNodes[i];
4345 for(j=0; j<cNode.childNodes.length; j++) {
4346 var node = cNode.childNodes[j];
4347 var nName = new String(node.name);
4348 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
4349 if(form.templateAttachments.value != "") {
4350 form.templateAttachments.value += "::";
4352 form.templateAttachments.value += node.value;
4358 // remove attachments
4359 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
4361 YAHOO.util.Connect.setForm(form);
4363 AjaxObject.target = 'frameFlex';
4365 // sending a draft email
4366 if(!isDraft && in_draft) {
4368 SE.listView.removeRowByUid(email_id);
4371 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
4372 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
4374 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
4378 * Handles clicking the email address link from a given view
4380 composePackage : function() {
4381 if(composePackage != null) {
4382 SE.composeLayout.c0_composeNewEmail();
4385 if(composePackage.to_email_addrs) {
4386 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
4388 if (composePackage.subject != null && composePackage.subject.length > 0) {
4389 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
4392 //If no parent fields are set in the composePackage, ensure they are cleared.
4393 var parentFields = ['parent_type','parent_name','parent_id'];
4394 for(var i=0;i<parentFields.length;i++)
4396 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
4397 composePackage[parentFields[i]] = "";
4400 document.getElementById("parent_type").value = composePackage.parent_type;
4401 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
4402 document.getElementById("parent_id").value = composePackage.parent_id;
4403 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
4404 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
4406 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
4407 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
4409 if (composePackage.body != null && composePackage.body.length > 0) {
4410 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4411 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
4412 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
4414 if (composePackage.attachments != null) {
4415 SE.composeLayout.loadAttachments(composePackage.attachments);
4418 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
4419 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
4420 SE.util.emptySelectOptions(addressFrom);
4421 var fromAccountOpts = composePackage.fromAccounts.data;
4422 for(i=0; i<fromAccountOpts.length; i++) {
4423 var key = fromAccountOpts[i].value;
4424 var display = fromAccountOpts[i].text;
4425 var opt = new Option(display, key);
4426 if (fromAccountOpts[i].selected) {
4427 opt.selected = true;
4429 addressFrom.options.add(opt);
4436 setContentOnThisTiny : function() {
4437 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4438 var tinyHTML = tiny.getContent();
4439 composePackage.body = decodeURI(encodeURI(composePackage.body));
4440 // cn: bug 14361 - text-only templates don't fill compose screen
4441 if(composePackage.body == '') {
4442 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4444 //Flag determines if we should clear the tiny contents or just append
4445 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
4446 SE.composeLayout.tinyHTML = '';
4448 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
4450 tiny.setContent(SE.composeLayout.tinyHTML);
4451 //Indicate that the contents has been loaded successfully.
4452 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
4455 * Confirms closure of a compose screen if "x" is clicked
4457 confirmClose : function(panel) {
4458 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
4459 SE.composeLayout.closeCompose(panel.id);
4467 * forces close of a compose screen
4469 forceCloseCompose : function(id) {
4470 SE.composeLayout.closeCompose(id);
4472 // handle flow back to originating view
4473 if(composePackage) {
4474 // check if it's a module we need to return to
4475 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
4476 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
4477 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
4478 window.location = url;
4485 * closes the editor that just sent email
4486 * @param string id ID of composeLayout tab
4488 closeCompose : function(id) {
4489 // destroy tinyMCE instance
4490 var idx = id.substr(13, id.length);
4491 var instanceId = "htmleditor" + idx;
4492 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
4494 // nullify DOM and namespace values.
4496 SE.composeLayout[idx] = null;
4497 SE.tinyInstances[instanceId] = null;
4498 var tabsArray = SE.innerLayout.get("tabs");
4499 for (i = 0 ; i < tabsArray.length ; i++) {
4500 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
4501 tabsArray[i].close();
4505 //SE.innerLayout.getTab(idx).close();
4509 * Enable the quick search for the compose relate field or search tab
4511 enableQuickSearchRelate: function(idx,overides){
4513 if(typeof overides != 'undefined')
4515 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
4516 var newModule = document.getElementById(newModuleID).value;
4517 var formName = overides['formName'];
4518 var fieldName = overides['fieldName'];
4519 var fieldId = overides['fieldId'];
4520 var fullName = formName + "_" + fieldName;
4521 var postBlurFunction = null;
4525 var newModule = document.getElementById('data_parent_type'+idx).value;
4526 var formName = 'emailCompose'+idx;
4527 var fieldName = 'data_parent_name'+idx;
4528 var fieldId = 'data_parent_id'+idx;
4529 var fullName = formName + "_" + fieldName;
4530 var postBlurFunction = "SE.composeLayout.qsAddAddress";
4533 if(typeof sqs_objects == 'undefined')
4534 window['sqs_objects'] = new Array;
4536 window['sqs_objects'][fullName] = {
4539 modules:[newModule],
4541 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
4542 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
4543 post_onblur_function: postBlurFunction,
4544 order:"name","limit":"30","no_match_text":"No Match"};
4547 if(typeof QSProcessedFieldsArray != 'undefined')
4548 QSProcessedFieldsArray[fullName] = false;
4549 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
4550 QSFieldsArray[fullName].destroy();
4551 delete QSFieldsArray[fullName];
4553 if (Dom.get(fullName + "_results")) {
4554 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
4560 qsAddAddress : function(o) {
4561 if (o.name != "" && o.email1 != "")
4563 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
4564 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
4568 * Returns a new instance ID, 0-index
4570 getNewInstanceId : function() {
4571 this.currentInstanceId = this.currentInstanceId + 1;
4572 return this.currentInstanceId;
4576 * 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.
4578 loadAttachments : function(result) {
4579 var idx = SE.composeLayout.currentInstanceId;
4581 if(typeof(result) == 'object') {
4582 //jchi #20680. Clean the former template attachments;
4583 var basket = document.getElementById('addedTemplateAttachments' + idx);
4584 if(basket.innerHTML != ''){
4585 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
4587 basket.innerHTML = '';
4592 if(typeof result[i] == 'object') {
4593 var index = SE.composeLayout.addTemplateAttachmentField(idx);
4594 var bean = result[i];
4595 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
4596 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
4603 * fills drop-down values for email templates and signatures
4605 setComposeOptions : function(idx) {
4606 // send from accounts
4607 var addressFrom = document.getElementById('addressFrom' + idx);
4609 if (addressFrom.options.length <= 0) {
4610 SE.util.emptySelectOptions(addressFrom);
4611 var fromAccountOpts = SE.composeLayout.fromAccounts;
4612 for (id = 0 ; id < fromAccountOpts.length ; id++) {
4613 var key = fromAccountOpts[id].value;
4614 var display = fromAccountOpts[id].text;
4615 var is_default = false;
4616 if(key == SUGAR.default_inbound_accnt_id)
4618 var opt = new Option(display, key);
4619 addressFrom.options.add(opt);
4620 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
4625 var et = document.getElementById('email_template' + idx);
4626 SE.util.emptySelectOptions(et);
4628 for(var key in this.emailTemplates) { // iterate through assoc array
4629 var display = this.emailTemplates[key];
4630 var opt = new Option(display, key);
4631 et.options.add(opt);
4635 var sigs = document.getElementById('signatures' + idx);
4636 SE.util.emptySelectOptions(sigs);
4638 for(var key in this.signatures) { // iterate through assoc array
4639 var display = this.signatures[key];
4640 var opt = new Option(display, key);
4642 if(key == SE.userPrefs.signatures.signature_default) {
4643 opt.selected = true;
4646 sigs.options.add(opt);
4649 // html/plain email?
4650 var htmlEmail = document.getElementById('setEditor' + idx);
4651 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
4652 htmlEmail.checked = true;
4654 htmlEmail.checked = false;
4657 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
4661 * After compose screen is rendered, async call to get email body from Sugar
4663 replyForwardEmailStage2 : function() {
4664 SE.util.clearHiddenFieldValues('emailUIForm');
4665 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
4667 var ieId = SE.composeLayout.replyForwardObj.ieId;
4668 var uid = SE.composeLayout.replyForwardObj.uid;
4669 var mbox = SE.composeLayout.replyForwardObj.mbox;
4670 var type = SE.composeLayout.replyForwardObj.type;
4671 var idx = SE.composeLayout.currentInstanceId;
4673 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
4675 document.getElementById('emailSubject' + idx).value = type;
4676 document.getElementById('emailUIAction').value = 'composeEmail';
4677 document.getElementById('composeType').value = type;
4678 document.getElementById('ieId').value = ieId;
4679 document.getElementById('uid').value = uid;
4680 document.getElementById('mbox').value = mbox;
4681 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
4682 var formObject = document.getElementById('emailUIForm');
4683 YAHOO.util.Connect.setForm(formObject);
4685 var sendType = type;
4686 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
4690 * Show the hidden cc or bcc fields
4692 showHiddenAddress: function(addrType,idx){
4694 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
4695 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
4696 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
4697 this[addrType+'Hidden'+idx] = false;
4699 //After bcc or cc is added, move options below last addr field
4700 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4702 //If both cc and bcc hidden, remove the empty row containing text.
4703 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
4704 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
4705 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
4707 SE.composeLayout.resizeEditor(idx);
4710 * Hide the cc and bcc fields if they were shown.
4712 hideHiddenAddresses: function(idx){
4714 var addrTypes = ['cc','bcc'];
4715 for(var i = 0;i<addrTypes.length;i++)
4717 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
4718 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
4719 this[addrTypes[i] + 'Hidden'+idx] = true
4722 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
4723 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
4724 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4728 //// END SE.composeLayout
4729 ///////////////////////////////////////////////////////////////////////////////
4730 ///////////////////////////////////////////////////////////////////////////////
4734 * Cleans serialized UID lists of duplicates
4738 cleanUids : function(str) {
4739 var seen = new Object();
4741 var arr = new String(str).split(",");
4743 for(var i=0; i<arr.length; i++) {
4748 clean += (clean != "") ? "," : "";
4750 seen[arr[i]] = true;
4757 * Clears hidden field values
4758 * @param string id ID of form element to clear
4760 clearHiddenFieldValues : function(id) {
4761 var form = document.getElementById(id);
4763 for(i=0; i<form.elements.length; i++) {
4764 if(form.elements[i].type == 'hidden') {
4765 var e = form.elements[i];
4766 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
4774 * Reduces a SELECT drop-down to 0 items to prepare for new ones
4776 emptySelectOptions : function(el) {
4778 for(i=el.childNodes.length - 1; i >= 0; i--) {
4779 if(el.childNodes[i]) {
4780 el.removeChild(el.childNodes[i]);
4787 * Returns the MBOX path in the manner php_imap expects:
4788 * ie: INBOX.DEBUG.test
4789 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
4791 generateMboxPath : function(str) {
4792 var ex = str.split("::");
4794 /* we have a serialized MBOX path */
4798 for(var i=0; i<ex.length; i++) {
4799 if(ex[i] == 'INBOX') {
4811 /* we have a Sugar folder GUID - do nothing */
4819 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
4820 * @param HTMLElement el
4821 * @return string GUID of found element or empty on failure
4823 getGuidFromElement : function(el) {
4829 for(var i=0; i<iterations; i++) {
4831 if(el.id.match(SE.reGUID)) {
4843 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
4846 getPanelId : function() {
4847 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
4851 * wrapper to handle weirdness with IE
4852 * @param string instanceId
4853 * @return tinyMCE Controller object
4855 getTiny : function(instanceId) {
4856 if(instanceId == '') {
4860 var t = tinyMCE.getInstanceById(instanceId);
4864 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
4870 * Simple check for MSIE browser
4874 var nav = new String(navigator.appVersion);
4875 if(nav.match(/MSIE/)) {
4882 * Recursively removes an element from the DOM
4883 * @param HTMLElement
4885 removeElementRecursive : function(el) {
4886 this.emptySelectOptions(el);
4893 sleep : function(secs) {
4894 setTimeout("void(0);", secs);
4898 * Converts a <select> element to an Ext.form.combobox
4900 convertSelect : function(select) {
4901 alert('in convertSelect');
4902 if (typeof(select) == "string") {
4903 select = document.getElementById(select);
4907 findChildNode : function (parent, property, value) {
4908 for (i in parent.children) {
4909 var child = parent.children[i];
4910 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
4912 var searchChild = SE.util.findChildNode(child, property, value);
4919 cascadeNodes : function (parent, fn, scope, args) {
4920 for (i in parent.children) {
4921 var child = parent.children[i];
4922 var s = scope ? scope : child;
4923 var a = args ? args : child;
4925 SE.util.cascadeNodes(child, fn, scope, args);
4932 ///////////////////////////////////////////////////////////////////////////////
4935 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
4937 /*********************************************************************************
4938 * SugarCRM Community Edition is a customer relationship management program developed by
4939 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4941 * This program is free software; you can redistribute it and/or modify it under
4942 * the terms of the GNU Affero General Public License version 3 as published by the
4943 * Free Software Foundation with the addition of the following permission added
4944 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4945 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4946 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4948 * This program is distributed in the hope that it will be useful, but WITHOUT
4949 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4950 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4953 * You should have received a copy of the GNU Affero General Public License along with
4954 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4955 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4958 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4959 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4961 * The interactive user interfaces in modified source and object code versions
4962 * of this program must display Appropriate Legal Notices, as required under
4963 * Section 5 of the GNU Affero General Public License version 3.
4965 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4966 * these Appropriate Legal Notices must retain the display of the "Powered by
4967 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4968 * technical reasons, the Appropriate Legal Notices must display the words
4969 * "Powered by SugarCRM".
4970 ********************************************************************************/
4972 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
4973 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
4974 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
4975 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
4976 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
4977 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
4978 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
4979 ' <input type="hidden" id="type{idx}" name="type" value="">' +
4980 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
4981 ' <input type="hidden" id="composeType" name="composeType">' +
4982 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
4983 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
4984 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
4985 ' <input type="hidden" id="sendTo" name="sendTo">' +
4986 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
4987 ' <input type="hidden" id="sendCc" name="sendCc">' +
4988 ' <input type="hidden" id="setEditor" name="setEditor">' +
4989 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
4990 ' <input type="hidden" id="parent_id" name="parent_id">' +
4991 ' <input type="hidden" id="parent_type" name="parent_type">' +
4992 ' <input type="hidden" id="attachments" name="attachments">' +
4993 ' <input type="hidden" id="documents" name="documents">' +
4994 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
4995 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
4996 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
4997 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
4999 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
5000 ' <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>' +
5001 ' <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>' +
5002 ' <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>' +
5003 ' <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>' +
5004 '</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>' +
5005 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
5006 '<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>' +
5007 ' </td></tr></tbody></table></th>' +
5011 ' <div style="margin:5px;">' +
5012 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
5014 ' <td class="emailUILabel" NOWRAP >' +
5015 ' {app_strings.LBL_EMAIL_FROM}:' +
5017 ' <td class="emailUIField" NOWRAP>' +
5019 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
5024 ' <td class="emailUILabel" NOWRAP>' +
5025 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
5026 ' {app_strings.LBL_EMAIL_TO}:' +
5029 ' <td class="emailUIField" NOWRAP>' +
5030 ' <div class="ac_autocomplete">' +
5031 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5032 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
5033 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
5037 ' <tr id="add_addr_options_tr{idx}">' +
5038 ' <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>'+
5040 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
5041 ' <td class="emailUILabel" NOWRAP>' +
5042 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
5043 ' {app_strings.LBL_EMAIL_CC}:' +
5046 ' <td class="emailUIField" NOWRAP>' +
5047 ' <div class="ac_autocomplete">' +
5048 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5049 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
5050 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
5054 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
5055 ' <td class="emailUILabel" NOWRAP>' +
5056 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
5057 ' {app_strings.LBL_EMAIL_BCC}:' +
5060 ' <td class="emailUIField" NOWRAP>' +
5061 ' <div class="ac_autocomplete">' +
5062 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5063 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
5064 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
5069 ' <td class="emailUILabel" NOWRAP width="1%">' +
5070 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
5072 ' <td class="emailUIField" NOWRAP width="99%">' +
5073 ' <div class="ac_autocomplete">' +
5074 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
5083 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
5084 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
5085 ' <div style="padding:5px;">' +
5086 ' <table cellpadding="2" cellspacing="0" border="0">' +
5089 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
5096 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
5097 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
5109 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
5116 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
5117 ' <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>' +
5129 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
5136 ' <div id="addedTemplateAttachments{idx}"></div>' +
5143 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
5144 ' <div style="padding:5px;">' +
5145 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
5146 ' <table border="0" width="100%">' +
5148 ' <td NOWRAP style="padding:2px;">' +
5149 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
5153 ' <td NOWRAP style="padding:2px;">' +
5154 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
5159 ' <table border="0" width="100%">' +
5161 ' <td NOWRAP style="padding:2px;">' +
5162 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
5166 ' <td NOWRAP style="padding:2px;">' +
5167 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
5171 ' <table border="0" width="100%">' +
5173 ' <td NOWRAP style="padding:2px;">' +
5174 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
5175 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
5183 // End of File modules/Emails/javascript/composeEmailTemplate.js
5185 /*********************************************************************************
5186 * SugarCRM Community Edition is a customer relationship management program developed by
5187 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5189 * This program is free software; you can redistribute it and/or modify it under
5190 * the terms of the GNU Affero General Public License version 3 as published by the
5191 * Free Software Foundation with the addition of the following permission added
5192 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
5193 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
5194 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
5196 * This program is distributed in the hope that it will be useful, but WITHOUT
5197 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
5198 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
5201 * You should have received a copy of the GNU Affero General Public License along with
5202 * this program; if not, see http://www.gnu.org/licenses or write to the Free
5203 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
5206 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
5207 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
5209 * The interactive user interfaces in modified source and object code versions
5210 * of this program must display Appropriate Legal Notices, as required under
5211 * Section 5 of the GNU Affero General Public License version 3.
5213 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
5214 * these Appropriate Legal Notices must retain the display of the "Powered by
5215 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
5216 * technical reasons, the Appropriate Legal Notices must display the words
5217 * "Powered by SugarCRM".
5218 ********************************************************************************/
5223 function complexLayoutInit() {
5224 var se = SUGAR.email2;
5225 var Dom = YAHOO.util.Dom;
5227 getInnerLayout : function(rows) {
5228 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
5229 parent: se.complexLayout,
5235 scroll:false, // grid should autoScroll itself
5237 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
5245 body: "<div id='listBottom' />"
5253 body: "<div id='listRight' />",
5254 titlebar: false //,header: "right"
5257 se.complexLayout.on("render", function(){
5258 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
5259 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5260 SUGAR.email2.listViewLayout.set("height", height);
5261 SUGAR.email2.listViewLayout.render();
5263 se.listViewLayout.render();
5265 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
5266 var rp = se.listViewLayout.resizePreview = function() {
5267 var pre = Dom.get("displayEmailFramePreview");
5269 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
5270 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
5273 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
5274 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
5275 se.e2Layout.setPreviewPanel(rows);
5276 se.previewLayout = se.listViewLayout;
5277 return se.listViewLayout;
5280 getInnerLayout2Rows : function() {
5281 return this.getInnerLayout(true);
5283 getInnerLayout2Columns : function() {
5284 return this.getInnerLayout(false);
5288 // initialize state manager, we will use cookies
5289 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
5290 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
5291 se.complexLayout = new YAHOO.widget.Layout("container", {
5294 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
5295 width: Dom.getViewportWidth() - 40,
5299 body: "<div id='emailtabs'></div>"
5304 body: "<div id='lefttabs'></div>",
5314 header: Dom.get('footerLinks').innerHTML,
5321 se.complexLayout.render();
5322 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
5323 tp.addTab(new YAHOO.widget.Tab({
5326 content : "<div id='listViewDiv'/>",
5330 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
5331 tp.appendTo(centerEl);
5333 tp.get("element").style.borderRight = "1px solid #666"
5335 var listV = this.getInnerLayout2Rows();
5336 listV.set("height", tp.get("element").clientHeight - 25);
5339 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
5340 var folderTab = new YAHOO.widget.Tab({
5341 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
5343 content : "<div id='emailtree'/>",
5347 folderTab.on("activeChange", function(o){
5349 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
5352 se.leftTabs.addTab(folderTab);
5354 var tabContent = SUGAR.util.getAndRemove("searchTab");
5355 var searchTab = new YAHOO.widget.Tab({
5356 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
5358 content : tabContent.innerHTML,
5361 searchTab.on("activeChange", function(o){
5364 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
5365 //Setup the calendars if needed
5366 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
5367 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
5369 //Initalize sqs object for assigned user name
5370 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
5372 //Attach event handler for when the relate module option is selected for the correct sqs object
5373 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
5374 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
5375 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
5376 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
5378 //If enter key is pressed, perform search
5379 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
5380 for(var i=0; i < addKeyPressFields.length;i++)
5382 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
5383 if (e.keyCode == 13) {
5384 YAHOO.util.Event.stopEvent(e);
5385 SUGAR.email2.search.searchAdvanced();
5389 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
5391 //Clear parent values if selecting another parent type.
5392 YAHOO.util.Event.addListener('data_parent_type_search','change',
5394 document.getElementById('data_parent_id_search').value ='';
5395 document.getElementById('data_parent_name_search').value ='';
5400 se.leftTabs.addTab(searchTab);
5402 var resizeTabBody = function() {
5403 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
5404 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5407 se.complexLayout.on("render", resizeTabBody);
5408 se.leftTabs.on("activeTabChange", resizeTabBody);
5409 //hack to allow left pane scroll bar to fully show
5410 var lefttabsDiv = document.getElementById('lefttabs');
5411 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
5412 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
5413 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
5416 initSQSObject: function(formName,fieldName)
5418 var fullFieldName = formName + '_' + fieldName; //SQS Convention
5419 var resultName = fullFieldName + '_' + 'results';
5421 if (QSFieldsArray[fullFieldName] != null)
5423 QSFieldsArray[fullFieldName].destroy();
5424 delete QSFieldsArray[fullFieldName];
5426 if (QSProcessedFieldsArray[fullFieldName])
5427 QSProcessedFieldsArray[fullFieldName] = false;
5429 if( Dom.get(resultName) )
5431 var obj = document.getElementById(resultName);
5432 obj.parentNode.removeChild(obj);
5435 setPreviewPanel: function(rows) {
5437 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
5438 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
5439 Dom.get("listRight").innerHTML = "";
5440 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
5442 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
5443 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
5444 Dom.get("listBottom").innerHTML = "";
5445 Dom.get("listRight").innerHTML = "<div id='_blank' />";
5452 var myBufferedListenerObject = new Object();
5453 myBufferedListenerObject.refit = function() {
5454 if(SUGAR.email2.grid) {
5455 SUGAR.email2.grid.autoSize();
5458 // End of File modules/Emails/javascript/complexLayout.js