1 /*********************************************************************************
2 * SugarCRM is a customer relationship management program developed by
3 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5 * This program is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU Affero General Public License version 3 as published by the
7 * Free Software Foundation with the addition of the following permission added
8 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
17 * You should have received a copy of the GNU Affero General Public License along with
18 * this program; if not, see http://www.gnu.org/licenses or write to the Free
19 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
23 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25 * The interactive user interfaces in modified source and object code versions
26 * of this program must display Appropriate Legal Notices, as required under
27 * Section 5 of the GNU Affero General Public License version 3.
29 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
30 * these Appropriate Legal Notices must retain the display of the "Powered by
31 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
32 * technical reasons, the Appropriate Legal Notices must display the words
33 * "Powered by SugarCRM".
34 ********************************************************************************/
38 var flexContentOld = "";
39 var forcePreview = false;
40 var inCompose = false;
42 /* globals for Callback functions */
43 var email; // AjaxObject.showEmailPreview
47 var meta; // AjaxObject.showEmailPreview
50 var urlBase = 'index.php';
51 var urlStandard = 'sugar_body_only=true&to_pdf=true&module=Emails&action=EmailUIAjax';
53 var lazyLoadFolder = null;// End of File modules/Emails/javascript/vars.js
55 /*********************************************************************************
56 * SugarCRM is a customer relationship management program developed by
57 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
59 * This program is free software; you can redistribute it and/or modify it under
60 * the terms of the GNU Affero General Public License version 3 as published by the
61 * Free Software Foundation with the addition of the following permission added
62 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
63 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
64 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
66 * This program is distributed in the hope that it will be useful, but WITHOUT
67 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
68 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
71 * You should have received a copy of the GNU Affero General Public License along with
72 * this program; if not, see http://www.gnu.org/licenses or write to the Free
73 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
76 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
77 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
79 * The interactive user interfaces in modified source and object code versions
80 * of this program must display Appropriate Legal Notices, as required under
81 * Section 5 of the GNU Affero General Public License version 3.
83 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
84 * these Appropriate Legal Notices must retain the display of the "Powered by
85 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
86 * technical reasons, the Appropriate Legal Notices must display the words
87 * "Powered by SugarCRM".
88 ********************************************************************************/
89 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
90 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
91 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
92 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
93 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
94 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
95 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
96 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
97 this.js_more();this.js_more();}
98 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
99 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
100 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
101 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
102 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&¤tNode.tagName=='SPAN'){currentNode.id=/_input/.test(currentNode.id)?this.field_element_name+'_input_div_'+this.fields_count:this.field_element_name+'_radio_div_'+this.fields_count;if(/_input/.test(currentNode.id)){currentNode.name='teamset_div';}
103 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
104 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
105 currentNode.name=new_name;currentNode.id=new_name;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_name;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
106 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
107 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
109 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
111 if(!has_primary){return false;}
113 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
114 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
115 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
116 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
117 if(noAdd){enableQS(false);}
118 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_collection_"+i);var id_field=document.getElementById("id_"+this.field+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].id==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
120 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
121 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
123 SUGAR.collection.safe_clone=function(e,recursive)
124 {if(e.nodeName=="#text")
125 {return document.createTextNode(e.data);}
126 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];for(var i in properties)
127 {if(e[properties[i]])
128 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
129 newNode[properties[i]]=e[properties[i]];}}
131 {for(var i in e.childNodes)
132 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
133 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
134 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
136 /*********************************************************************************
137 * SugarCRM is a customer relationship management program developed by
138 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
140 * This program is free software; you can redistribute it and/or modify it under
141 * the terms of the GNU Affero General Public License version 3 as published by the
142 * Free Software Foundation with the addition of the following permission added
143 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
144 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
145 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
147 * This program is distributed in the hope that it will be useful, but WITHOUT
148 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
149 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
152 * You should have received a copy of the GNU Affero General Public License along with
153 * this program; if not, see http://www.gnu.org/licenses or write to the Free
154 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
157 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
158 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
160 * The interactive user interfaces in modified source and object code versions
161 * of this program must display Appropriate Legal Notices, as required under
162 * Section 5 of the GNU Affero General Public License version 3.
164 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
165 * these Appropriate Legal Notices must retain the display of the "Powered by
166 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
167 * technical reasons, the Appropriate Legal Notices must display the words
168 * "Powered by SugarCRM".
169 ********************************************************************************/
172 cache : new Object(),
173 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
174 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
177 currentHtmleditor : ''
181 * preserves hits from email server
183 _setDetailCache : function(ret) {
185 var compKey = ret.meta.mbox + ret.meta.uid;
187 if(!SUGAR.email2.cache[compKey]) {
188 SUGAR.email2.cache[compKey] = ret;
193 autoSetLayout : function() {
194 var c = document.getElementById('container');
195 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
196 //Ensure a minimum height.
197 tHeight = Math.max(tHeight, 550);
198 c.style.height = tHeight + "px";
199 SUGAR.email2.complexLayout.set('height', tHeight);
200 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
201 SUGAR.email2.complexLayout.render();
202 SUGAR.email2.listViewLayout.resizePreview();
207 * Shows overlay progress message
209 function overlayModal(title, body) {
210 overlay(title, body);
212 function overlay(reqtitle, body, type, additconfig) {
214 if (typeof(additconfig) == "object") {
215 var config = additconfig;
218 config.title = reqtitle;
220 YAHOO.SUGAR.MessageBox.show(config);
223 function hideOverlay() {
224 YAHOO.SUGAR.MessageBox.hide();
226 // End of File modules/Emails/javascript/EmailUIShared.js
228 /*********************************************************************************
229 * SugarCRM is a customer relationship management program developed by
230 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
232 * This program is free software; you can redistribute it and/or modify it under
233 * the terms of the GNU Affero General Public License version 3 as published by the
234 * Free Software Foundation with the addition of the following permission added
235 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
236 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
237 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
239 * This program is distributed in the hope that it will be useful, but WITHOUT
240 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
241 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
244 * You should have received a copy of the GNU Affero General Public License along with
245 * this program; if not, see http://www.gnu.org/licenses or write to the Free
246 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
249 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
250 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
252 * The interactive user interfaces in modified source and object code versions
253 * of this program must display Appropriate Legal Notices, as required under
254 * Section 5 of the GNU Affero General Public License version 3.
256 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
257 * these Appropriate Legal Notices must retain the display of the "Powered by
258 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
259 * technical reasons, the Appropriate Legal Notices must display the words
260 * "Powered by SugarCRM".
261 ********************************************************************************/
264 if (typeof console == "undefined")
265 console = { log: function(o) {alert(o)} };
269 currentRequestObject : null,
270 //timeout : 30000, // 30 second timeout default
271 timeout : 9999999999, // 30 second timeout default
277 _reset : function() {
278 this.timeout = 30000;
279 this.forceAbort = false;
282 folderRenameCleanup : function() {
283 SUGAR.email2.folders.setSugarFolders();
286 fullSyncCleanup : function(o) {
287 this.folders.checkMailCleanup(o);
288 SUGAR.email2.settings.settingsDialog.hide();
293 composeCache : function(o) {
294 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
295 // get email templates and user signatures
296 var ret = JSON.parse(o.responseText);
298 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
299 SUGAR.email2.composeLayout.signatures = ret.signatures;
300 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
302 SUGAR.email2.composeLayout.setComposeOptions(idx);
304 //Set the error array so we can notify the user when they try to hit send if any errors
305 //are present. We will also notify them now (after hitting compose button).
306 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
309 //if error element is returning an array, then check the length to make sure we have error messages
310 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
311 //add error messages for display
312 for(i in ret.errorArray)
313 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
314 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
315 //if error element is returning an object, and the object value is not empty or null, then display error message
316 for(i in ret.errorArray)
317 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
320 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
322 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
324 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
330 handleDeleteSignature : function(o) {
332 var ret = JSON.parse(o.responseText);
333 SUGAR.email2.composeLayout.signatures = ret.signatures;
334 var field = document.getElementById('signature_id');
335 SUGAR.email2.util.emptySelectOptions(field);
337 for(var i in ret.signatures) { // iterate through assoc array
338 var opt = new Option(ret.signatures[i], i);
339 field.options.add(opt);
341 setSigEditButtonVisibility();
346 handleDeleteReturn : function(o) {
347 // force refresh ListView
349 if(document.getElementById('focusEmailMbox')) {
350 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
353 // need to display success message before calling next async call?
354 document.getElementById(this.target).innerHTML = o.responseText;
359 handleFailure : function(o) {
361 overlay('Exception occurred...', o.statusText, 'alert');
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_smtppass").value = ret.mail_smtppass;
687 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
688 SUGAR.email2.accounts.smtp_authenticate_field_display();
689 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
691 if(ret.type == 'system-override') {
692 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
693 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
696 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
697 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
702 failure : AjaxObject.handleFailure,
703 timeout : AjaxObject.timeout,
706 callbackDeleteOutbound : {
707 success : function(o) {
708 var ret = JSON.parse(o.responseText);
711 if(confirm(ret.error_message))
713 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
714 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
722 SUGAR.email2.accounts.refreshOuboundAccountTable();
726 failure : AjaxObject.handleFailure,
727 timeout : AjaxObject.timeout,
731 callbackCheckMailProgress : {
732 success : function(o) {
733 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
734 SUGAR.email2.accounts.totalMsgCount = -1;
737 //Check for server timeout / errors
738 var ret = JSON.parse(o.responseText);
741 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
743 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
744 SUGAR.email2.accounts.totalMsgCount = -1;
745 //SUGAR.email2.folders.rebuildFolders();
749 var currIeId = ret['ieid'];
752 var serverCount = ret.count;
754 if (ret['status'] == 'done') {
755 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
756 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
760 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
762 currIeId = SUGAR.email2.accounts.ieIds[i+1];
764 SUGAR.email2.accounts.totalMsgCount = -1;
769 else if (ret.mbox && ret.totalcount && ret.count) {
770 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
771 if (ret.count >= ret.totalcount) {
774 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
775 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
778 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
779 SUGAR.email2.accounts.totalMsgCount = -1;
784 SUGAR.email2.accounts.totalMsgCount = -1;
786 SUGAR.email2.folders.rebuildFolders();
787 SE.listView.refreshGrid();
788 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
789 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
790 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
791 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
793 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
794 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
795 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
796 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
797 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
800 failure : AjaxObject.handleFailure,
801 timeout : AjaxObject.timeout,
806 ///////////////////////////////////////////////////////////////////////////////
808 AjaxObject.composeLayout = {
810 * Populates the record id
812 saveDraftCleanup : function(o) {
814 var ret = JSON.parse(o.responseText);
816 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
817 else if (o.responseText)
818 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
822 AjaxObject.composeLayout.callback = {
824 success : AjaxObject.composeLayout.saveDraftCleanup,
825 failure : AjaxObject.handleFailure,
826 timeout : AjaxObject.timeout,
831 AjaxObject.detailView = {
833 * Pops-up a printable view of an email
835 displayPrintable : function(o) {
836 var ret = JSON.parse(o.responseText);
837 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
838 // 2 below must be in global context
840 meta['panelId'] = SUGAR.email2.util.getPanelId();
841 email = ret.meta.email;
842 if (typeof(email.cc) == 'undefined') {
846 var out = displayTemplate.exec({
847 'app_strings' : app_strings,
855 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
856 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
858 popup.document.write(out);
859 popup.document.close();
863 * Takes formatted response and creates a modal pop-over containing a title and content
865 displayView : function(o) {
866 var SED = SUGAR.email2.detailView;
867 var ret = JSON.parse(o.responseText);
869 if(!SED.viewDialog) {
870 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
874 constraintoviewport: true,
877 SED.viewDialog.renderEvent.subscribe(function() {
878 var content = this.body.firstChild;
879 var viewH = YAHOO.util.Dom.getViewportHeight();
881 this.body.style.overflow = "auto";
882 this.body.style.width = "800px";
883 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
887 SED.viewDialog.setHeader(ret.title);
888 SED.viewDialog.setBody(ret.html);
889 SED.viewDialog.render();
890 SED.viewDialog.show();
894 * Generates a modal popup to populate with the contents of bean's full EditView
896 showQuickCreateForm : function(o) {
897 var SED = SUGAR.email2.detailView;
898 var ret = JSON.parse(o.responseText);
900 if(!SED.quickCreateDialog) {
901 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
905 constraintoviewport: true,
909 SED.quickCreateDialog.renderEvent.subscribe(function() {
910 var viewH = YAHOO.util.Dom.getViewportHeight();
912 for (var i in this.body.childNodes) {
913 if (this.body.childNodes[i].clientHeight) {
914 contH += this.body.childNodes[i].clientHeight;
915 } else if (this.body.childNodes[i].offsetHeight) {
916 contH += this.body.childNodes[i].offsetHeight;
919 this.body.style.width = "800px";
920 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
921 this.body.style.overflow = "auto";
922 }, SED.quickCreateDialog);
924 SED.quickCreateDialog.hideEvent.subscribe(function(){
925 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
926 /*for(var qsField in qsFields){
927 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
928 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
931 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
934 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
936 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
937 SED.quickCreateDialog.render();
938 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
940 SED.quickCreateDialog.ieId = ret.ieId;
941 SED.quickCreateDialog.uid = ret.uid;
942 SED.quickCreateDialog.mbox = ret.mbox;
943 SED.quickCreateDialog.qcmodule = ret.module;
945 SED.quickCreateDialog.show();
947 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
949 editForm.module.value = 'Emails';
950 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
951 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
952 var instId = ret.module + count;
953 SED.quickCreateEmailsToAdd = ret.emailAddress;
954 SED.quickCreateEmailCallback = function(instId, tableId) {
955 var eaw = SUGAR.EmailAddressWidget.instances[instId];
956 if (typeof(eaw) == "undefined")
957 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
958 + instId + "','" + tableId + "');", 100);
959 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
961 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
962 + instId + "','" + tableId + "');", 100);
966 saveQuickCreateForm : function(o) {
968 SUGAR.email2.detailView.quickCreateDialog.hide();
969 validate['EditView'] = [ ];
972 saveQuickCreateFormAndReply : function(o) {
974 var ret = JSON.parse(o.responseText);
975 SUGAR.email2.detailView.quickCreateDialog.hide();
976 var qcd = SUGAR.email2.detailView.quickCreateDialog;
977 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
979 var emailID = ret.id;
980 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
982 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
984 //Cean the validate cache to prevent errors on the next call
985 validate['EditView'] = [ ];
988 saveQuickCreateFormAndAddToAddressBook : function(o) {
990 SUGAR.email2.detailView.quickCreateDialog.hide();
991 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
992 validate['EditView'] = [ ];
995 handleAssignmentDialogAssignAction : function() {
998 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
1000 var dist = 'direct';
1004 var found_teams = false;
1005 var warning_message = mod_strings.LBL_WARN_NO_USERS;
1006 if(!found_teams && assign_user_id == '' )
1008 alert(warning_message);
1012 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1014 for(i=0; i<emailUids.length; i++) {
1016 uids += app_strings.LBL_EMAIL_DELIMITER;
1018 uids += emailUids[i];
1021 var row = SUGAR.email2.grid.getSelectedRows()[0];
1022 var data = SUGAR.email2.grid.getRecord(row).getData();
1023 var ieid = data.ieId;
1024 var mbox = data.mbox;
1025 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
1026 SUGAR.email2.contextMenus.assignToDialogue.hide();
1027 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
1031 handleAssignmentDialogDeleteAction : function() {
1032 // TO pass list of UIDS/emailIds
1033 var uids = SUGAR.email2.listView.getUidsFromSelection();
1034 var row = SUGAR.email2.grid.getSelections()[0];
1035 var ieid = row.data.ieId;
1036 var mbox = row.data.mbox;
1037 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
1038 SUGAR.email2.contextMenus.assignmentDialog.hide();
1039 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1045 showEmailDetailView : function(o) {
1047 var SED = SUGAR.email2.detailView;
1048 var ret = JSON.parse(o.responseText);
1050 if(!SED.quickCreateDialog) {
1051 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
1055 constraintoviewport: true,
1057 autofillheight: "body",
1060 SED.quickCreateDialog.renderEvent.subscribe(function() {
1061 var viewHeight = YAHOO.util.Dom.getViewportHeight();
1063 for (var i in this.body.childNodes) {
1064 if (this.body.childNodes[i].offsetHeight)
1065 contH += this.body.childNodes[i].offsetHeight;
1067 this.body.style.overflow = "auto";
1068 this.body.style.width = "800px";
1069 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
1071 }, SED.quickCreateDialog);
1073 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
1074 SED.quickCreateDialog.setBody(ret.html);
1075 SED.quickCreateDialog.render();
1076 SUGAR.util.evalScript(ret.html);
1077 SED.quickCreateDialog.show();
1080 showAssignmentDialogWithData : function(o) {
1081 var SEC = SUGAR.email2.contextMenus;
1083 var ret = JSON.parse(o.responseText);
1084 if (!SEC.assignmentDialog) {
1085 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
1088 constraintoviewport: true,
1091 SEC.assignmentDialog.setBody("");
1092 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
1093 SEC.assignmentDialog.renderEvent.subscribe(function() {
1094 var iev = YAHOO.util.Dom.get("Distribute");
1096 this.body.style.width = "700px";
1098 }, SEC.assignmentDialog);
1099 SEC.assignmentDialog.render();
1101 SEC.assignmentDialog.setBody(ret);
1102 SEC.assignmentDialog.render();
1104 SEC.assignmentDialog.show();
1105 SUGAR.util.evalScript(ret);
1108 showImportForm : function(o) {
1109 var SED = SUGAR.email2.detailView;
1110 var ret = JSON.parse(o.responseText);
1112 document.getElementById('quickCreateContent').innerHTML = "";
1118 if(!SED.importDialog) {
1119 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
1123 constraintoviewport: true,
1125 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
1126 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
1130 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
1131 SED.importDialog.setBody("");
1132 SED.importDialog.hideEvent.subscribe(function(){
1133 for(var i in QSFieldsArray) {
1134 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
1135 QSFieldsArray[i].destroy();
1136 delete QSFieldsArray[i];
1138 if (QSProcessedFieldsArray[i]) {
1139 QSProcessedFieldsArray[i] = false;
1143 SED.importDialog.renderEvent.subscribe(function() {
1144 var iev = YAHOO.util.Dom.get("ImportEditView");
1146 //this.body.style.height = (iev.clientHeight + 10) + "px";
1147 this.body.style.width = "600px";
1149 }, SED.importDialog);
1150 SED.importDialog.render();
1152 SED.importDialog.setBody(ret.html);
1153 SED.importDialog.ret = ret;
1154 SUGAR.util.evalScript(ret.html);
1155 SED.importDialog.render();
1157 SED.importDialog.show();
1158 SED.importDialog.focusFirstButton();
1160 getImportAction : function(ret) {
1161 if (!check_form('ImportEditView')) return false;
1162 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
1163 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
1167 var editView = document.getElementById('ImportEditView');
1168 if (editView.assigned_user_id != null) {
1169 get = get + "&user_id=" + editView.assigned_user_id.value
1170 //var user_id = editView.assigned_user_id.value;
1172 var parent_id = editView.parent_id.value;
1173 var parent_type = editView.parent_type.value;
1174 var row = SUGAR.email2.grid.getSelectedRows()[0];
1175 row = SUGAR.email2.grid.getRecord(row);
1176 var data = row.getData();
1177 var ieId = data.ieId;
1178 var mbox = data.mbox;
1179 var serverDelete = editView.serverDelete.checked;
1180 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1182 for(i=0; i<emailUids.length; i++) {
1184 uids += app_strings.LBL_EMAIL_DELIMITER;
1186 uids += emailUids[i];
1189 var action = 'importEmail&uid=';
1191 action = 'moveEmails';
1192 action = action + '&sourceFolder=' + ret['srcFolder'];
1193 action = action + '&sourceIeId=' + ret['srcIeId'];
1194 action = action + '&destinationFolder=' + ret['dstFolder'];
1195 action = action + '&destinationIeId=' + ret['dstIeId'];
1196 action = action + '&emailUids=';
1198 if (action.search(/importEmail/) != -1) {
1199 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
1201 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
1204 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
1205 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
1206 SUGAR.email2.detailView.importDialog.hide();
1207 document.getElementById('importDialogContent').innerHTML = "";
1210 showRelateForm : function(o) {
1211 var SED = SUGAR.email2.detailView;
1212 var ret = JSON.parse(o.responseText);
1213 document.getElementById('quickCreateContent').innerHTML = "";
1218 dialog_loaded = true;
1220 if(!SED.relateDialog) {
1221 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
1226 constraintoviewport: true,
1228 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
1229 if (!check_form('RelateEditView')) return false;
1231 var editView = document.getElementById('RelateEditView');
1232 var parent_id = editView.parent_id.value;
1233 var parent_type = editView.parent_type.value;
1234 var row = SUGAR.email2.grid.getSelectedRows()[0];
1235 row = SUGAR.email2.grid.getRecord(row);
1236 var ieId = row.getData().ieId;
1237 var mbox = row.getData().mbox;
1238 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1240 for(i=0; i<emailUids.length; i++) {
1242 uids += app_strings.LBL_EMAIL_DELIMITER;
1244 uids += emailUids[i];
1246 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1247 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
1248 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
1249 SED.relateDialog.hide();
1250 document.getElementById('relateDialogContent').innerHTML = "";
1255 SED.relateDialog.hideEvent.subscribe(function(){
1256 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
1257 QSFieldsArray['ImportEditView_parent_name'].destroy();
1258 delete QSFieldsArray['ImportEditView_parent_name'];
1260 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
1261 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
1265 SED.relateDialog.renderEvent.subscribe(function() {
1266 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
1268 for (var i in this.body.childNodes) {
1269 if (this.body.childNodes[i].clientHeight)
1270 contH += this.body.childNodes[i].clientHeight;
1272 }, SED.relateDialog);
1273 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
1276 SED.relateDialog.setBody(ret.html);
1277 SED.relateDialog.render();
1278 SUGAR.util.evalScript(ret.html);
1279 SED.relateDialog.show();
1283 * DetailView callbacks
1285 AjaxObject.detailView.callback = {
1287 success : function(o) {
1289 var ret = JSON.parse(o.responseText);
1290 SUGAR.email2.detailView.consumeMetaDetail(ret);
1292 argument: [targetDiv],
1293 failure : AjaxObject.handleFailure,
1298 success : function(o) {
1300 var ret = JSON.parse(o.responseText);
1301 SUGAR.email2.detailView.consumeMetaPreview(ret);
1303 failure : AjaxObject.handleFailure,
1308 success : AjaxObject.detailView.displayPrintable,
1309 failure : AjaxObject.handleFailure,
1310 timeout : AjaxObject.timeout,
1314 success : AjaxObject.detailView.displayView,
1315 failure : AjaxObject.handleFailure,
1316 timeout : AjaxObject.timeout,
1325 AjaxObject.folders = {
1327 * check-mail post actions
1329 checkMailCleanup : function(o) {
1331 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
1333 // refresh focus ListView
1334 SE.listView.refreshGrid();
1335 SUGAR.email2.folders.startCheckTimer(); // resets the timer
1340 rebuildFolders : function(o) {
1343 var data = JSON.parse(o.responseText);
1345 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
1346 SUGAR.email2.folders.setSugarFolders();
1349 AjaxObject.folders.callback = {
1351 success : AjaxObject.folders.checkMailCleanup,
1352 failure : AjaxObject.handleFailure,
1353 timeout : 600000, // 5 mins
1358 AjaxObject.rules = {
1359 loadRulesForSettings : function(o) {
1360 document.getElementById("rulesListCell").innerHTML = o.responseText;
1361 // assume we have the class we need
1362 SUGAR.routing.getStrings();
1363 SUGAR.routing.getDependentDropdowns();
1366 //// END PER MODULE CALLBACK OBJECTS
1367 ///////////////////////////////////////////////////////////////////////////
1371 success : AjaxObject.handleSuccess,
1372 failure : AjaxObject.handleFailure,
1373 timeout : AjaxObject.timeout,
1376 var callbackAccount = {
1377 success : AjaxObject.ieSaveSuccess,
1378 failure : AjaxObject.handleFailure,
1379 timeout : AjaxObject.timeout,
1382 var callbackAccountDelete = {
1383 success : AjaxObject.ieDeleteSuccess,
1384 failure : AjaxObject.handleFailure,
1385 timeout : AjaxObject.timeout,
1388 var callbackOutboundTest = {
1389 success : AjaxObject.ieSendSuccess,
1390 failure : AjaxObject.handleFailure,
1391 timeout : AjaxObject.timeout,
1397 var callbackTeamInfoForSettings = {
1398 success : function (o) {
1399 var data = JSON.parse(o.responseText);
1400 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
1402 failure : AjaxObject.handleFailure,
1403 timeout : AjaxObject.timeout,
1408 var callbackStatusForImport = {
1409 success : function (o) {
1411 if (o.responseText != "") {
1412 var statusString = "";
1413 var data = JSON.parse(o.responseText);
1414 for(i=0; i<data.length; i++) {
1415 statusString = statusString + data[i] + '<br/>';
1417 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
1419 SE.listView.refreshGrid();
1422 failure : AjaxObject.handleFailure,
1423 timeout : AjaxObject.timeout,
1427 var callbackComposeCache = {
1428 success : AjaxObject.composeCache,
1429 failure : AjaxObject.handleFailure,
1430 timeout : AjaxObject.timeout,
1433 var callbackDelete = {
1434 success : AjaxObject.handleDeleteReturn,
1435 failure : AjaxObject.handleFailure,
1436 timeout : AjaxObject.timeout,
1439 var callbackEmailDetailMultiple = {
1440 success : function(o) {
1442 var retMulti = JSON.parse(o.responseText);
1443 var ret = new Object();
1445 for(var i=0; i<retMulti.length; i++) {
1448 SUGAR.email2._setDetailCache(ret);
1449 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
1452 failure : AjaxObject.handleFailure,
1456 var callbackListViewSortOrderChange = {
1457 success : AjaxObject.saveListViewSortOrderPart2,
1458 failure : AjaxObject.handleFailure,
1459 timeout : AjaxObject.timeout,
1461 argument : [ieId, ieName, focusFolder]
1463 var callbackEmptyTrash = {
1464 success : function(o) {
1466 AjaxObject.folderRenameCleanup;
1468 failure : AjaxObject.handleFailure,
1469 timeout : AjaxObject.timeout,
1472 var callbackClearCacheFiles = {
1473 success : function(o) {
1476 failure : AjaxObject.handleFailure,
1477 timeout : AjaxObject.timeout,
1480 var callbackFolderRename = {
1481 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
1482 failure : AjaxObject.handleFailure,
1483 timeout : AjaxObject.timeout,
1486 var callbackFolderDelete = {
1487 success : function(o) {
1488 var ret = JSON.parse(o.responseText);
1490 if (ret.folder_id) {
1491 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
1493 SUGAR.email2.tree.removeNode(node, true);
1494 } else if (ret.ieId && ret.mbox) {
1495 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
1497 SUGAR.email2.tree.removeNode(node, true);
1500 //SUGAR.email2.folders.loadSettingFolder();
1503 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
1506 failure : AjaxObject.handleFailure,
1507 timeout : AjaxObject.timeout,
1510 var callbackFolderSave = {
1511 success : function(o) {
1512 var ret = JSON.parse(o.responseText);
1514 switch(ret.action) {
1515 case 'newFolderSave':
1516 SUGAR.email2.folders.rebuildFolders();
1520 failure : AjaxObject.handleFailure,
1521 timeout : AjaxObject.timeout,
1524 var callbackFolderSubscriptions = {
1525 success : AjaxObject.updateFolderSubscriptions,
1526 failure : AjaxObject.handleFailure,
1527 timeout : AjaxObject.timeout,
1530 var callbackFolderUpdate = {
1531 success : AjaxObject.updateFrameFolder,
1532 failure : AjaxObject.handleFailure,
1533 timeout : AjaxObject.timeout,
1536 var callbackFolders = {
1537 success : AjaxObject.folders.rebuildFolders,
1538 //success : void(true),
1539 failure : AjaxObject.handleFailure,
1540 timeout : AjaxObject.timeout,
1543 var callbackFullSync = {
1544 success : AjaxObject.fullSyncCleanup,
1545 failure : AjaxObject.handleFailure,
1546 timeout : 9999999999999,
1549 var callbackGeneric = {
1550 success : function() {
1553 failure : AjaxObject.handleFailure,
1554 timeout : AjaxObject.timeout,
1557 var callbackIeAccountRetrieve = {
1558 success : function(o) {
1559 // return JSON encoding
1561 SUGAR.email2.accounts.fillIeAccount(o.responseText);
1562 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
1564 failure : AjaxObject.handleFailure,
1565 timeout : AjaxObject.timeout,
1568 var callbackImportOneEmail = {
1569 success : AjaxObject.detailView.showImportForm,
1570 failure : AjaxObject.handleFailure,
1571 timeout : AjaxObject.timeout,
1574 var callbackRelateEmail = {
1575 success : AjaxObject.detailView.showRelateForm,
1576 failure : AjaxObject.handleFailure,
1577 timeout : AjaxObject.timeout,
1580 var callbackEmailDetailView = {
1581 success : AjaxObject.detailView.showEmailDetailView,
1582 failure : AjaxObject.handleFailure,
1583 timeout : AjaxObject.timeout,
1586 var callbackAssignmentDialog = {
1587 success : AjaxObject.detailView.showAssignmentDialogWithData,
1588 failure : AjaxObject.handleFailure,
1589 timeout : AjaxObject.timeout,
1592 var callbackAssignmentAction = {
1593 success : function(o) {
1594 SE.listView.refreshGrid();
1596 if(o.responseText != '') {
1597 overlay('Assignment action result', o.responseText, 'alert');
1600 failure : AjaxObject.handleFailure,
1601 timeout : AjaxObject.timeout,
1604 var callbackMoveEmails = {
1605 success : function(o) {
1606 SE.listView.refreshGrid();
1608 if(o.responseText != '') {
1609 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
1612 failure : AjaxObject.handleFailure,
1613 timeout : AjaxObject.timeout,
1616 var callbackLoadAttachments = {
1617 success : AjaxObject.loadAttachments,
1618 failure : AjaxObject.handleFailure,
1619 timeout : AjaxObject.timeout,
1622 var callbackLoadRules = {
1623 success : AjaxObject.rules.loadRulesForSettings,
1624 failure : AjaxObject.handleFailure,
1625 timeout : AjaxObject.timeout,
1628 var callbackLoadSignature = {
1629 success : AjaxObject.loadSignature,
1630 failure : AjaxObject.handleFailure,
1631 timeout : AjaxObject.timeout,
1634 var callbackDeleteSignature = {
1635 success : AjaxObject.handleDeleteSignature,
1636 failure : AjaxObject.handleFailure,
1637 timeout : AjaxObject.timeout,
1640 /*var callbackMoveEmails = {
1641 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
1642 failure : AjaxObject.handleFailure,
1643 timeout : AjaxObject.timeout,
1646 var callbackOutboundSave = {
1647 success : AjaxObject.accounts.saveOutboundCleanup,
1648 failure : AjaxObject.handleFailure,
1649 timeout : AjaxObject.timeout,
1652 var callbackDefaultOutboundSave = {
1653 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
1654 failure : AjaxObject.handleFailure,
1655 timeout : AjaxObject.timeout,
1658 var callbackQuickCreate = {
1659 success : AjaxObject.detailView.showQuickCreateForm,
1660 failure : AjaxObject.handleFailure,
1661 timeout : AjaxObject.timeout,
1664 var callbackQuickCreateSave = {
1665 success : AjaxObject.detailView.saveQuickCreateForm,
1666 failure : AjaxObject.handleFailure,
1667 timeout : AjaxObject.timeout,
1670 var callbackQuickCreateSaveAndAddToAddressBook = {
1671 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
1672 failure : AjaxObject.handleFailure,
1673 timeout : AjaxObject.timeout,
1676 var callbackQuickCreateSaveAndReply = {
1677 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
1678 failure : AjaxObject.handleFailure,
1679 timeout : AjaxObject.timeout,
1682 var callbackQuickCreateSaveAndReplyCase = {
1683 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
1684 failure : AjaxObject.handleFailure,
1685 timeout : AjaxObject.timeout,
1688 var callbackRebuildShowAccountList = {
1689 success : AjaxObject.rebuildShowFolders,
1690 failure : AjaxObject.handleFailure,
1691 timeout : AjaxObject.timeout,
1695 var callbackRefreshSugarFolders = {
1696 success : function(o) {
1697 var t = JSON.parse(o.responseText);
1698 SUGAR.email2.folders.setSugarFoldersEnd(t);
1700 failure : AjaxObject.handleFailure,
1701 timeout : AjaxObject.timeout,
1704 var callbackReplyForward = {
1705 success : AjaxObject.handleReplyForward,
1706 finish : function(a, retryCount) {
1707 if (typeof(retryCount) == 'undefined') {
1712 var idx = SUGAR.email2.composeLayout.currentInstanceId;
1713 var t = tinyMCE.getInstanceById('htmleditor' + idx);
1715 var html = t.getContent();
1717 if (a.type != 'draft') {
1718 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
1719 html += " <div><hr></div>" + a.description;
1721 html = " <div><hr></div>" + a.description + html;
1724 html = a.description;
1727 t.setContent(html);//
1730 if (retryCount < 5) {
1731 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
1735 var tabArray = SUGAR.email2.innerLayout.get("tabs");
1736 if (tabArray != null && tabArray.length > 0) {
1737 for (i = 0 ; i < tabArray.length ; i++) {
1738 var tabObject = tabArray[i];
1739 if (tabObject.get("id") == ("composeTab" + idx)) {
1740 var tabLabel = a.name;
1741 if (tabLabel != null && tabLabel.length > 25) {
1742 tabLabel = tabLabel.substring(0, 25) + "...";
1744 tabObject.get("labelEl").firstChild.data = tabLabel;
1750 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
1751 if (a.parent_name != null && a.parent_name != "") {
1752 document.getElementById('data_parent_name' + idx).value = a.parent_name;
1754 if (a.parent_type != null && a.parent_type != "") {
1755 document.getElementById('data_parent_type' + idx).value = a.parent_type;
1757 if (a.parent_id != null && a.parent_id != "") {
1758 document.getElementById('data_parent_id' + idx).value = a.parent_id;
1760 if (a.fromAccounts.status) {
1761 var addressFrom = document.getElementById('addressFrom' + idx);
1762 SUGAR.email2.util.emptySelectOptions(addressFrom);
1763 var fromAccountOpts = a.fromAccounts.data;
1764 for(i=0; i<fromAccountOpts.length; i++) {
1765 var key = fromAccountOpts[i].value;
1766 var display = fromAccountOpts[i].text;
1767 var opt = new Option(display, key);
1768 if (fromAccountOpts[i].selected) {
1769 opt.selected = true;
1771 addressFrom.options.add(opt);
1777 failure : AjaxObject.handleFailure,
1778 timeout : AjaxObject.timeout,
1780 argument : [sendType]
1782 var callbackSendEmail = {
1783 success : AjaxObject.sendEmailCleanUp,
1784 failure : AjaxObject.handleFailure,
1785 timeout : AjaxObject.timeout,
1788 var callbackSettings = {
1789 success : AjaxObject.updateUserPrefs,
1790 failure : AjaxObject.handleFailure,
1791 timeout : AjaxObject.timeout,
1794 var callbackSettingsFolderRefresh = {
1795 success : AjaxObject.settingsFolderRefresh,
1796 failure : AjaxObject.handleFailure,
1797 timeout : AjaxObject.timeout,
1800 var callbackLoadSettingFolder = {
1801 success : function(o) {
1802 AjaxObject.settingsFolderRefresh(o);
1803 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
1805 failure : AjaxObject.handleFailure,
1806 timeout : AjaxObject.timeout,
1810 var callbackUploadAttachment = {
1811 success : AjaxObject.uploadAttachmentSuccessful,
1812 upload : AjaxObject.uploadAttachmentSuccessful,
1813 failure : AjaxObject.handleFailure,
1814 timeout : AjaxObject.timeout,
1817 var callbackUserPrefs = {
1818 success : function(o) {
1819 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
1821 failure : AjaxObject.handleFailure,
1822 timeout : AjaxObject.timeout,
1826 var callbackContextmenus = {
1828 success : AjaxObject.markEmailCleanup,
1829 failure : AjaxObject.handleFailure,
1830 timeout : AjaxObject.timeout,
1835 var callbackCheckEmail2 = {
1836 success : function(o) {
1837 var ret = JSON.parse(o.responseText);
1838 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
1842 failure : AjaxObject.handleFailure,
1843 timeout : AjaxObject.timeout,
1845 }// End of File modules/Emails/javascript/ajax.js
1847 /*********************************************************************************
1848 * SugarCRM is a customer relationship management program developed by
1849 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
1851 * This program is free software; you can redistribute it and/or modify it under
1852 * the terms of the GNU Affero General Public License version 3 as published by the
1853 * Free Software Foundation with the addition of the following permission added
1854 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
1855 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
1856 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
1858 * This program is distributed in the hope that it will be useful, but WITHOUT
1859 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1860 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
1863 * You should have received a copy of the GNU Affero General Public License along with
1864 * this program; if not, see http://www.gnu.org/licenses or write to the Free
1865 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
1868 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
1869 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
1871 * The interactive user interfaces in modified source and object code versions
1872 * of this program must display Appropriate Legal Notices, as required under
1873 * Section 5 of the GNU Affero General Public License version 3.
1875 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
1876 * these Appropriate Legal Notices must retain the display of the "Powered by
1877 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
1878 * technical reasons, the Appropriate Legal Notices must display the words
1879 * "Powered by SugarCRM".
1880 ********************************************************************************/
1882 function gridInit() {
1883 if(SUGAR.email2.grid) {
1884 SUGAR.email2.grid.destroy();
1890 var Ck = YAHOO.util.Cookie;
1891 var widths = [ 10, 10, 150, 250, 175, 125 ];
1893 if (Ck.get("EmailGridWidths")) {
1894 for (var i=0; i < widths.length; i++) {
1895 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
1898 for (var i=0; i < widths.length; i++) {
1899 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
1903 // changes "F" to an icon
1904 function flaggedIcon(cell, record, column, value) {
1906 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
1909 // changes "A" to replied icon
1910 function repliedIcon(cell, record, column, value) {
1912 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
1915 function attachIcon(cell, record, column, value) {
1917 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
1924 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
1929 formatter: attachIcon,
1933 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
1938 formatter: flaggedIcon,
1942 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
1947 formatter: repliedIcon,
1951 label: app_strings.LBL_EMAIL_FROM,
1958 label: app_strings.LBL_EMAIL_SUBJECT,
1965 label: mod_strings.LBL_LIST_DATE,
1972 label: app_strings.LBL_EMAIL_TO,
2008 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2009 responseType: YAHOO.util.DataSource.TYPE_JSON,
2011 resultsList: 'Email',
2012 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
2013 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
2019 action : "EmailUIAjax",
2020 emailUIAction : "getMessageList",
2023 forceRefresh : "false"
2025 if(lazyLoadFolder != null) {
2026 params['mbox'] = lazyLoadFolder.folder;
2027 params['ieId'] = lazyLoadFolder.ieId;
2028 //Check if the folder is a Sugar Folder
2029 var test = new String(lazyLoadFolder.folder);
2030 if(test.match(/SUGAR\./)) {
2031 params['emailUIAction'] = 'getMessageListSugarFolders';
2032 params['mbox'] = test.substr(6);
2035 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
2038 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
2039 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2041 paginator: new YAHOO.widget.Paginator({
2042 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
2043 containers : ["dt-pag-nav"],
2044 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2045 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2046 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2047 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2048 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2050 initialRequest:SUGAR.util.paramsToUrl(params),
2057 //Override Paging request construction
2058 grid.set("generateRequest", function(oState, oSelf) {
2059 oState = oState || {pagination:null, sortedBy:null};
2060 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
2061 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2062 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2063 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2064 // Build the request
2066 SUGAR.util.paramsToUrl(oSelf.params) +
2069 "&start=" + startIndex +
2070 ((results !== null) ? "&limit=" + results : "");
2075 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2076 oPayload = oPayload || { };
2078 oPayload.totalRecords = oResponse.meta.total;
2079 oPayload.unreadRecords = oResponse.meta.unread;
2081 var tabObject = SE.innerLayout.get("tabs")[0];
2083 if (this.params.mbox != null) {
2084 mboxTitle = this.params.mbox;
2086 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
2087 tabObject.get("labelEl").firstChild.data = tabtext;
2090 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
2092 node.data.unseen = oResponse.meta.unread;
2093 SE.accounts.renderTree();
2099 var resize = grid.resizeGrid = function () {
2100 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
2101 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
2103 grid.convertDDRows = function() {
2104 var rowEl = this.getFirstTrEl();
2105 while (rowEl != null) {
2106 new this.DDRow(this, this.getRecord(rowEl), rowEl);
2107 rowEl = this.getNextTrEl(rowEl);
2112 grid.on("columnResizeEvent", function(o) {
2113 //Find the index of the column
2114 var colSet = SUGAR.email2.grid.getColumnSet().flat;
2115 for (var i=0; i < colSet.length; i++) {
2116 if (o.column == colSet[i]) {
2117 //Store it in the cookie
2118 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
2121 //this.resizeGrid();
2124 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
2125 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
2126 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
2128 SUGAR.email2.listViewLayout.on("render", resize);
2131 //Setup the default load parameters
2132 SUGAR.email2.grid.params = params;
2134 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
2135 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2136 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2143 function initRowDD() {
2144 var sg = SUGAR.email2.grid,
2145 Dom = YAHOO.util.Dom;
2146 sg.DDRow = function(oDataTable, oRecord, elTr) {
2147 if(oDataTable && oRecord && elTr) {
2148 this.ddtable = oDataTable;
2149 this.table = oDataTable.getTableEl();
2152 this.newIndex = null;
2154 this.initFrame(); // Needed for DDProxy
2155 this.invalidHandleTypes = {};
2159 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
2160 _resizeProxy: function() {
2161 this.constructor.superclass._resizeProxy.apply(this, arguments);
2162 var dragEl = this.getDragEl(),
2164 var xy = Dom.getXY(el);
2166 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
2167 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
2168 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
2169 Dom.setStyle(dragEl, 'display', "");
2172 startDrag: function(x, y) {
2173 //Check if we should be dragging a set of rows rather than just the one.
2174 var selectedRows = this.ddtable.getSelectedRows();
2175 var iSelected = false;
2176 for (var i in selectedRows) {
2177 if (this.rowEl.id == selectedRows[i]) {
2184 for (var i in selectedRows) {
2185 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
2188 this.rows = [this.row];
2189 this.ddtable.unselectAllRows();
2190 this.ddtable.selectRow(this.row);
2193 //Initialize the dragable proxy
2194 var dragEl = this.getDragEl();
2195 var clickEl = this.getEl();
2196 Dom.setStyle(clickEl, "opacity", "0.25");
2197 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
2198 Dom.addClass(dragEl, "yui-dt-liner");
2199 Dom.setStyle(dragEl, "opacity", "0.5");
2200 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
2201 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
2202 Dom.setStyle(dragEl, "border", "2px solid gray");
2205 clickValidator: function(e) {
2206 if (this.row.getData()[0] == " ")
2208 var target = YAHOO.util.Event.getTarget(e);
2209 return ( this.isValidHandleChild(target) &&
2210 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
2213 * This funciton checks that the target of the drag is a table row in this
2214 * DDGroup and simply moves the sourceEL to that location as a preview.
2216 onDragOver: function(ev, id) {
2217 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
2218 if (node && node != this.targetNode) {
2219 this.targetNode = node;
2220 SUGAR.email2.folders.unhighliteAll();
2225 onDragOut: function(e, id) {
2226 if (this.targetNode) {
2227 SUGAR.email2.folders.unhighliteAll();
2228 this.targetNode = false;
2231 endDrag: function() {
2232 Dom.setStyle(this.getEl(), "opacity", "");
2233 Dom.setStyle(this.getDragEl(), "display", "none");
2234 if (this.targetNode) {
2235 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
2237 SUGAR.email2.folders.unhighliteAll();
2243 function AddressSearchGridInit() {
2244 function moduleIcon(elCell, oRecord, oColumn, oData) {
2245 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
2247 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
2248 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
2250 var checkHeader = '<input type="checkbox" ';
2251 if (SUGAR.email2.util.isIe()) {
2252 checkHeader += 'style="top:-5px" ';
2254 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
2259 formatter: selectionCheckBox,
2263 label: mod_strings.LBL_LIST_TYPE,
2265 formatter: moduleIcon,
2269 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
2275 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
2281 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2282 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
2284 resultsList: 'Person',
2285 fields: ['name', 'email', 'bean_id', 'bean_module'],
2286 metaFields: {total: 'TotalCount'}
2288 //enable sorting on the server accross all data
2291 dataModel.params = {
2294 action : "EmailUIAjax",
2295 emailUIAction:"getAddressSearchResults"
2297 var rb = document.getElementById('hasRelatedBean').checked;
2299 var idx = SUGAR.email2.composeLayout.currentInstanceId;
2300 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2301 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2302 dataModel.params['related_bean_id'] = relatedBeanId;
2303 dataModel.params['related_bean_type'] = relatedBeanType;
2304 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
2306 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
2308 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
2309 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2311 paginator: new YAHOO.widget.Paginator({
2313 containers : ["dt-pag-nav-addressbook"],
2314 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2315 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2316 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2317 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2318 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2320 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
2324 //Override Paging request construction
2325 grid.set("generateRequest", function(oState, oSelf) {
2326 oState = oState || {pagination:null, sortedBy:null};
2327 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
2328 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2329 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2330 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2331 // Build the request
2333 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
2334 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
2335 ((results !== null) ? "&limit=" + results : "");
2339 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2340 oPayload = oPayload || { };
2341 oPayload.totalRecords = oResponse.meta.total;
2345 grid.clickToggleSelect= function(args) {
2346 var isIE = (args.event.target == null);
2347 var targetElement = isIE ? args.event.srcElement : args.event.target;
2348 if(targetElement.type == null || targetElement.type != 'checkbox') {
2349 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
2353 grid.reSelectRowsOnRender = function (){
2354 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2355 for (var i = 0; i < rows.length; i++)
2357 var emailAddress = rows[i].getData("email");
2358 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
2361 rows[i].setData("selected", true);
2362 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2366 rows[i].setData("selected", false);
2367 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
2371 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
2372 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
2373 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
2374 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
2377 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2378 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2380 grid.toggleSelectCheckbox = function(id,checked){
2381 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2382 row.setData("checked",checked);
2384 grid.toggleSelect = function(id, checked) {
2385 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2386 checked = row.getData("selected");
2389 SUGAR.email2.addressBook.grid.selectRow(row);
2390 SE.addressBook.insertContactRowToResultTable(id,null)
2393 SUGAR.email2.addressBook.grid.unselectRow(row);
2394 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
2396 row.setData("selected", !checked);
2399 grid.toggleSelectAll = function(checked) {
2400 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2401 for (var i = 0; i < rows.length; i++) {
2402 if (typeof(rows[i]) != "undefined")
2403 rows[i].setData("checked", checked);
2405 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2406 for (var i = 0; i < checkBoxes.length; i++) {
2407 checkBoxes[i].checked = checked;
2411 //Initialize the grid result table.
2412 AddressSearchResultsGridInit();
2418 * Initalize the results table for the address book selection.
2421 function AddressSearchResultsGridInit()
2424 /* Full name sort funciton to compare by last name if available */
2425 var fullNameSort = function(a, b, desc) {
2426 // Deal with empty values
2427 if(!YAHOO.lang.isValue(a))
2428 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
2429 else if(!YAHOO.lang.isValue(b))
2432 var aNames = a.getData("name").split(' ');
2433 var bNames = b.getData("name").split(' ');
2435 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
2436 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
2438 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
2442 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
2443 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
2444 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
2446 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})},
2447 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
2449 var myDataSource = new YAHOO.util.DataSource([]);
2450 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
2451 myDataSource.responseSchema = {
2452 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
2455 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
2456 width: "350px",height: "250px", MSG_EMPTY: " "});
2458 var highlightEditableCell = function(oArgs) {
2459 var elCell = oArgs.target;
2460 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
2461 this.highlightCell(elCell);
2465 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
2466 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
2467 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
2468 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
2469 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
2471 //Setup the context menus
2472 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
2473 var task = p_aArgs[1];
2476 var elRow = this.contextEventTarget;
2477 elRow = p_myDataTable.getTrEl(elRow);
2484 var oRecord = p_myDataTable.getRecord(elRow);
2485 p_myDataTable.deleteRow(elRow);
2486 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2491 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
2492 {trigger:gridResults.getTbodyEl()});
2493 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
2494 contextMenu.render("addrSearchResultGrid");
2495 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
2497 // End of File modules/Emails/javascript/grid.js
2499 /*********************************************************************************
2500 * SugarCRM is a customer relationship management program developed by
2501 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
2503 * This program is free software; you can redistribute it and/or modify it under
2504 * the terms of the GNU Affero General Public License version 3 as published by the
2505 * Free Software Foundation with the addition of the following permission added
2506 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
2507 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
2508 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
2510 * This program is distributed in the hope that it will be useful, but WITHOUT
2511 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
2512 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
2515 * You should have received a copy of the GNU Affero General Public License along with
2516 * this program; if not, see http://www.gnu.org/licenses or write to the Free
2517 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
2520 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
2521 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
2523 * The interactive user interfaces in modified source and object code versions
2524 * of this program must display Appropriate Legal Notices, as required under
2525 * Section 5 of the GNU Affero General Public License version 3.
2527 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
2528 * these Appropriate Legal Notices must retain the display of the "Powered by
2529 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
2530 * technical reasons, the Appropriate Legal Notices must display the words
2531 * "Powered by SugarCRM".
2532 ********************************************************************************/
2535 var sw = YAHOO.SUGAR,
2536 Event = YAHOO.util.Event,
2537 Connect = YAHOO.util.Connect,
2538 Dom = YAHOO.util.Dom
2541 ///////////////////////////////////////////////////////////////////////////////
2544 _contactCache : new Array(), // cache of contacts
2545 _dd : new Array(), // filtered list, same format as _contactCache
2546 _ddLists : new Array(), // list of Lists
2547 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
2548 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
2549 clickBubble : true, // hack to get around onclick event bubbling
2551 relatedBeanType : '',
2554 itemSpacing : 'white-space:nowrap; padding:2px;',
2560 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
2562 initFixForDatatableSort: function () {
2563 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
2564 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
2565 var oColumn = this._oColumnSet.getColumn(column);
2568 // Validate TD element
2569 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
2571 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
2573 // Validate TH element
2575 elCell = this.getThEl(column);
2578 var allColumns = this._oColumnSet.flat;
2579 for(var i=0, len=allColumns.length; i<len; i++) {
2580 if(allColumns[i].getThEl().id === elCell.id) {
2581 oColumn = allColumns[i];
2592 cancelEdit : function() {
2593 if(this.editContactDialog)
2594 this.editContactDialog.hide();
2595 if(this.editMailingListDialog)
2596 this.editMailingListDialog.hide();
2600 * Clears filter form
2602 clear : function() {
2603 var t = document.getElementById('contactsFilter');
2609 * handle context-menu Compose-to call
2610 * @param string type 'contacts' or 'lists'
2612 composeTo : function(type, waited) {
2613 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
2614 if (activePanel.substring(0, 10) != "composeTab") {
2615 SE.composeLayout.c0_composeNewEmail();
2616 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
2617 SE.contextMenus.contactsContextMenu.hide();
2620 var idx = activePanel.substring(10);
2623 // determine if we have a selection to work with
2624 if(type == 'contacts') {
2625 var ids = SE.contactView.getSelectedRows();
2626 for (var i in ids) {
2627 rows[i] = SE.contactView.getRecord(ids[i]);
2629 removeHiddenNodes(rows, SE.contactView);
2633 if(rows.length > 0) {
2634 SE.composeLayout.handleDrop(
2635 (type == 'contacts') ? SE.contactView : SE.emailListsView,
2636 null, rows, 'addressTO' + idx );
2638 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
2642 editContact : function() {
2643 SE.contextMenus.contactsContextMenu.hide();
2644 var element = SE.contactView.getSelectedNodes()[0];
2646 if (element.className.indexOf('address-contact') > -1) {
2647 elementId = element.id;
2648 } else if (element.className.indexOf('address-exp-contact') > -1) {
2649 elementId = element.id.substring(2);
2655 * Filters contact entries based on user input
2657 filter : function(inputEl) {
2658 var ret = new Object();
2659 var re = new RegExp(inputEl.value, "gi");
2661 for(var i in this._contactCache) {
2662 if(this._contactCache[i].name.match(re)) {
2663 ret[i] = this._contactCache[i];
2667 this.buildContactList(ret);
2670 fullForm : function(id, module) {
2671 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
2675 * returns a formatted email address from the addressBook cache
2677 getFormattedAddress : function(id) {
2678 var o = this._contactCache[id];
2679 var primaryEmail = '';
2681 for(var i=0; i<o.email.length; i++) {
2682 var currentEmail = o.email[i].email_address;
2684 if(o.email[i].primary_address == 1) {
2685 primaryEmail = o.email[i].email_address;
2689 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
2690 var name = new String(o.name);
2691 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
2692 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
2698 * Sets up async call to query for matching contacts, users, etc.
2700 searchContacts : function() {
2701 var fn = document.getElementById('input_searchField').value;
2702 var pe = document.getElementById('input_searchPerson').value;
2704 var rb = document.getElementById('hasRelatedBean').checked;
2707 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2708 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2709 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2710 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2712 this.addressBookDataModel.params['related_bean_id'] = '';
2715 this.addressBookDataModel.params['search_field'] = fn;
2716 this.addressBookDataModel.params['person'] = pe;
2717 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
2718 this.grid._oDataSource = this.addressBookDataModel;
2719 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
2723 * Clear Search Crieteria For Addressbook
2725 clearAddressBookSearch : function() {
2726 document.getElementById('input_searchField').value = "";
2727 document.getElementById('input_searchPerson').selectedIndex = 0;
2731 * Opens modal select window to add contacts to addressbook
2733 selectContactsDialogue : function(destId) {
2734 if(!this.contactsDialogue) {
2735 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
2739 constraintoviewport: true,
2741 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
2742 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
2744 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
2746 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
2747 dlg.setBody(body.innerHTML);
2748 dlg.renderEvent.subscribe(function() {
2749 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
2750 if (iev && !SUGAR.isIE) {
2751 this.body.style.width = "950px";
2756 dlg.beforeRenderEvent.subscribe(function() {
2757 var dd = new YAHOO.util.DDProxy(dlg.element);
2758 dd.setHandleElId(dlg.header);
2759 dd.on('endDragEvent', function() {
2765 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
2767 var tabContent = SUGAR.util.getAndRemove("searchForm");
2768 tp.addTab(new YAHOO.widget.Tab({
2769 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
2771 content : tabContent.innerHTML,
2772 id : "addressSearchTab",
2776 var addListenerFields = ['input_searchPerson','input_searchField' ]
2777 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
2778 if (e.keyCode == 13) {
2779 YAHOO.util.Event.stopEvent(e);
2780 SUGAR.email2.addressBook.searchContacts();
2784 this.contactsDialogue.render();
2787 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
2788 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
2792 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
2793 var idx = activePanel.substring(10);
2795 SE.addressBook.idx = idx;
2798 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
2799 document.getElementById('relatedBeanColumn').style.display = '';
2800 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
2801 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2802 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2803 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
2804 SE.addressBook.relatedBeanType = relatedBeanType;
2806 document.getElementById('relatedBeanColumn').style.display = 'none';
2807 document.getElementById('hasRelatedBean').checked = false;
2810 if (!SE.addressBook.grid)
2812 if (hasRelatedBeanId) {
2813 document.getElementById('hasRelatedBean').checked = true;
2815 AddressSearchGridInit();
2816 SE.addressBook.relatedBeanId = relatedBeanId;
2820 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
2822 SE.addressBook.relatedBeanId = relatedBeanId;
2823 document.getElementById('hasRelatedBean').checked = true;
2825 if (document.getElementById('hasRelatedBean').checked == true)
2827 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2828 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2830 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
2831 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
2833 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
2834 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
2835 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
2838 //Remove any lingering rows in the result set table if the module was closed.
2839 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2841 SE.addressBook.populateResulstTableEmailAddresses();
2843 this.contactsDialogue.show();
2846 * Clear all email addresses from result table.
2849 clearAllEmailAddressFieldsFromResultTable: function () {
2850 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2851 //Unhighlight any rows currently selected if the emails were cleared.
2852 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
2853 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2856 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
2857 * results table. This function is called when the address book is displayed.
2859 populateResulstTableEmailAddresses: function () {
2861 var idx = SE.addressBook.idx;
2862 var emailFields = ['to','cc','bcc'];
2864 for(var k=0;k<emailFields.length;k++)
2866 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2867 var allEmails = document.getElementById(elKey).value;
2871 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
2873 for (var i=0; i<formatedEmails.length; i++)
2875 var t_name = formatedEmails[i].name;
2876 var t_emailAddr = formatedEmails[i].email_address;
2877 var displayEmail = t_name + ' <' + t_emailAddr + '>';
2879 t_name = displayEmail = t_emailAddr;
2881 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
2882 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
2883 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
2889 * Checks all entries in the result table against a particular email address, returning true
2890 * if the email address is found, false otherwise.
2892 doesEmailAdddressExistInResultTable: function(emailAddress)
2894 if(trim(emailAddress) == '')
2897 var emailAddressFound = false;
2898 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2899 for (var i=0; i < contacts.length; i++)
2901 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2902 //If we are adding to cc or bcc fields, make them visible.
2903 if(data.email_address == emailAddress)
2905 emailAddressFound = true;
2910 return emailAddressFound;
2913 * Takes all email addresses that the users wishes to add from the address book and populates the To
2914 * fields on the compose tab.
2916 populateEmailAddressFieldsFromResultTable: function()
2918 //Clear the fields first, all email addresses are stored in the address book
2919 var idx = SE.addressBook.idx;
2920 var emailFields = ['to','cc','bcc'];
2921 for(var k=0;k<emailFields.length;k++)
2923 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2924 document.getElementById(elKey).value = "";
2927 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2928 for (var i=0; i < contacts.length; i++)
2930 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2932 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
2933 //If we are adding to cc or bcc fields, make them visible.
2934 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
2935 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
2936 //Construct the target id
2937 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
2939 var target = document.getElementById(target_id);
2940 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
2943 //Delete all rows from the result set table
2944 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2947 SE.addressBook.contactsDialogue.hide()
2950 * Insert contacts into the result table.
2952 insertContactToResultTable : function(event,address_type) {
2954 var contactsDialogue = SE.addressBook.contactsDialogue;
2955 var contacts = SE.addressBook.grid.getSelectedRows();
2957 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2958 for (var i = 0; i < rows.length; i++)
2960 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
2962 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
2963 SE.addressBook.insertContactRowToResultTable(recId,address_type);
2964 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2965 rows[i].setData("selected",true);
2968 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2969 for (var i = 0; i < checkBoxes.length; i++) {
2970 checkBoxes[i].checked = false;
2976 insertContactRowToResultTable : function(rowId, addressType) {
2977 var data = SE.addressBook.grid.getRecord(rowId).getData();
2978 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
2980 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
2981 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
2982 if(addressType == null)
2983 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
2984 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});
2987 * Remove a row from the gridsResult table.
2989 removeRowFromGridResults : function(rowId,emailAddress)
2991 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2992 for (var i=0; i < contacts.length; i++)
2994 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
2995 var data = rec.getData();
2996 if(data.email_address == emailAddress)
2998 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
3003 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
3006 * Translates between the addressType To|Cc|Bcc labels/keys.
3008 translateAddresType: function(addressType,fromKey)
3010 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
3011 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
3012 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
3013 var mappingObject = {};
3016 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
3019 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
3020 mappingObject[displayCc] = 'cc';
3021 mappingObject[displayBcc] = 'bcc';
3024 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
3030 toggleSearchRowIcon : function(rowId,show)
3034 var idToShow = rowId + '_add_img';
3035 var idToHide = rowId + '_rm_img';
3039 var idToShow = rowId + '_rm_img';
3040 var idToHide = rowId + '_add_img';
3044 Dom.addClass(idToHide, "yui-hidden");
3045 Dom.removeClass(idToShow, "yui-hidden");
3048 * Determine if an entry has already been added to the grid results table to prevent duplicates.
3050 doesGridResultsEntryExist: function(emailAddrs)
3053 var contactExists = false;
3054 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
3055 for (var i=0; i < contacts.length; i++)
3057 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
3058 if(data.email_address == emailAddrs)
3060 contactExists = true;
3064 return contactExists;
3068 * adds an email address to a string, but first checks if it exists
3069 * @param string concat The string we are appending email addresses to
3070 * @param string addr Email address to add
3073 smartAddEmailAddressToComposeField : function(concat, addr) {
3074 var re = new RegExp(addr);
3076 if(!concat.match(re)) {
3078 concat += "; " + addr;
3087 //// END ADDRESS BOOK
3088 ///////////////////////////////////////////////////////////////////////////////
3092 ///////////////////////////////////////////////////////////////////////////////
3095 * Auto-complete object
3099 delimChar : [";", ","],
3103 prehighlightClassName : "yui-ac-prehighlight",
3106 instances : new Array(),
3109 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
3110 * @param object Contact from AddressBook
3113 getPrimaryAddress : function(contact) {
3114 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
3116 for(var eIndex in contact.email) {
3117 address = contact.email[eIndex].email_address;
3118 if(contact.email[eIndex].primary_address == 1) {
3119 return contact.email[eIndex].email_address;
3127 * initializes autocomplete widgets for a given compose view
3130 init : function(idx) {
3131 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
3132 "queryMatchContains" : false,
3133 "queryMatchSubset" : true
3136 this.instances[idx] = {
3143 // instantiate the autoComplete widgets
3144 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
3145 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
3146 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
3148 // enable hiding of interfering textareas
3149 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3150 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3151 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3153 // enable reshowing of hidden textareas
3154 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3155 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3156 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3158 // enable refreshes of contact lists
3159 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3160 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3161 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3164 refreshDataSource : function(sType, aArgs) {
3165 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
3167 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
3169 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
3170 idx = textBoxId.substr(9);
3172 idx = textBoxId.substr(10);
3175 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
3176 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
3177 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
3181 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
3183 returnDataSource : function(contacts) {
3184 var ret = new Array();
3185 for(var id in contacts) {
3186 if (contacts[id].name) {
3187 var primary = this.getPrimaryAddress(contacts[id]);
3189 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
3190 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
3192 for(var emailIndex in contacts[id].email) {
3193 ret[ret.length] = contacts[id].email[emailIndex].email_address;
3202 * Hides address textareas to prevent autocomplete dropdown from being obscured
3204 toggleTextareaHide : function(sType, aArgs) {
3205 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3209 if(textBoxId.indexOf("addressTO") > -1) {
3211 } else if(textBoxId.indexOf("addressCC") > -1) {
3214 idx = textBoxId.substr(9);
3216 // follow through if not BCC
3218 var cc = document.getElementById("addressCC" + idx);
3219 var bcc = document.getElementById("addressBCC" + idx);
3223 cc.style.visibility = 'hidden';
3225 bcc.style.visibility = 'hidden';
3232 * Redisplays the textareas after an address is commited
3234 toggleTextareaShow : function(sType, aArgs) {
3235 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3239 if(textBoxId.indexOf("addressTO") > -1) {
3241 } else if(textBoxId.indexOf("addressCC") > -1) {
3244 idx = textBoxId.substr(9);
3246 // follow through if not BCC
3248 document.getElementById("addressCC" + idx).style.visibility = 'visible';
3249 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
3254 //// END AUTOCOMPLETE
3255 ///////////////////////////////////////////////////////////////////////////////
3257 ///////////////////////////////////////////////////////////////////////////////
3260 * expands the options sidebar
3262 SE.composeLayout = {
3263 currentInstanceId : 0,
3266 outboundAccountErrors : null,
3267 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
3269 showAddressDetails : function(e) {
3270 var linkElement = document.getElementById("More"+e.id);
3271 var spanElement = document.getElementById("Detail"+e.id);
3272 var emailAddressList = e.value;
3273 if(e.value.length > 96)
3275 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
3276 var displayArray = [];
3277 for (var i=0; i<resultArray.length; i++)
3279 var t_name = resultArray[i].name;
3280 var t_emailAddr = resultArray[i].email_address;
3282 displayArray.push('<br/><' + t_emailAddr + '>');
3284 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
3287 var result = displayArray.join('<br/>');
3289 linkElement.style.display = "inline";
3290 linkElement.style.height="10px";
3291 linkElement.style.overflow="visible";
3292 spanElement.innerHTML = result;
3295 linkElement.style.display = "none";
3300 * Given a string of email address, return an array containing the name portion (if available)
3301 * and email portion.
3303 _getEmailArrayFromString : function (emailAddressList){
3306 while ((results = reg.exec(emailAddressList)) != null)
3308 orignial = results[0];
3309 parsedResult = results[0].replace(';', ':::::');
3310 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3314 while ((results = reg.exec(emailAddressList)) != null)
3316 orignial = results[0];
3317 parsedResult = results[0].replace(',', ':::::');
3318 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3320 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
3321 var emailArr = emailAddressList.split(":::::");
3322 var resultsArray = [];
3324 for (var i=0; i<emailArr.length; i++)
3326 var rposition = emailArr[i].indexOf('<');
3327 var lposition = emailArr[i].indexOf('>');
3329 if(trim(emailArr[i]) != '')
3331 if(rposition != -1 && lposition != -1)
3333 var t_name = emailArr[i].substr(0, rposition-1);
3334 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
3335 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
3339 resultsArray.push({'name':'', 'email_address': emailArr[i]});
3343 return resultsArray;
3345 ///////////////////////////////////////////////////////////////////////////
3348 * Prepare bucket DIV and yui-ext tab panels
3350 _0_yui : function() {
3351 var idx = this.currentInstanceId;
3353 var composeTab = new YAHOO.SUGAR.ClosableTab({
3354 label: mod_strings.LNK_NEW_SEND_EMAIL,
3356 content : "<div id='htmleditordiv" + idx + "'/>",
3357 id : "composeTab" + idx,
3358 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
3361 SE.innerLayout.addTab(composeTab);
3363 // get template engine with template
3364 if (!SE.composeLayout.composeTemplate) {
3365 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
3368 // create Tab inner layout
3369 var composePanel = this.getComposeLayout();
3370 composePanel.getUnitByPosition("right").collapse();
3371 composePanel.autoSize();
3375 * Generate the quick compose layout
3376 * @method getQuickComposeLayout
3377 * @param {Pannel} parentPanel Parent pannel
3378 * @param {Object} o Options
3381 getQuickComposeLayout : function (parentPanel,o) {
3382 var idx = SE.composeLayout.currentInstanceId;
3384 //Before rendering the parent pannel we need to initalize the grid layout
3385 parentPanel.beforeRenderEvent.subscribe(function() {
3387 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3388 SE.composeLayout._createComposeLayout(idx);
3389 SE.composeLayout[idx].set('height', 350);
3390 SE.composeLayout[idx].render();
3394 //Wait until the Compose Layout has rendered, then add the
3395 //options tab and perform the tiny initialization.
3396 parentPanel.renderEvent.subscribe(function() {
3398 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3399 SE.composeLayout._initComposeOptionTabs(idx);
3400 SE.composeLayout[idx].getUnitByPosition("right").collapse();
3401 //Initialize tinyMCE
3402 if (!SUGAR.util.isTouchScreen())
3403 SE.composeLayout._1_tiny();
3404 //Init templates and address book
3405 SE.composeLayout._2_final();
3407 SE.composeLayout.quickCreateComposePackage(o);
3412 //Check if we have the div override for the shortcut bar
3413 if(typeof o.menu_id != 'undefined') {
3414 parentPanel.render(o.menu_id);
3416 parentPanel.render(document.body);
3419 return SE.composeLayout[idx];
3422 * Fill in all fields into the quick compose layout.
3423 * @method quickCreateComposePackage
3424 * @param {Object} o Options
3427 quickCreateComposePackage: function(o)
3429 //If we have a compose package fill in defaults.
3430 if (typeof(o.composePackage) != 'undefined')
3432 composePackage = o.composePackage; //Set the compose data object
3433 //Hijack this method called by composePackage as it's not need for quick creates.
3434 SE.composeLayout.c0_composeNewEmail = function(){};
3435 SE.composeLayout.composePackage(); //Fill in defaults.
3438 getComposeLayout : function() {
3439 var idx = SE.composeLayout.currentInstanceId;
3441 this._createComposeLayout(idx);
3442 SE.composeLayout[idx].render();
3443 this._initComposeOptionTabs(idx);
3445 return SE.composeLayout[idx];
3449 * Create the layout manager for the compose window.
3451 _createComposeLayout : function(idx)
3453 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
3454 parent: SE.complexLayout,
3464 SE.composeLayout.composeTemplate.exec({
3465 'app_strings':app_strings,
3466 'mod_strings':mod_strings,
3468 'linkbeans_options' : linkBeans,
3469 'idx' : SE.composeLayout.currentInstanceId
3480 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
3483 header: app_strings.LBL_EMAIL_OPTIONS
3489 * Create compose tab which will populate the 'right' container in the compose window.
3491 _initComposeOptionTabs : function(idx)
3493 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
3494 var tab = new YAHOO.widget.Tab({
3495 label: app_strings.LBL_EMAIL_ATTACHMENT,
3497 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
3498 id : "divAttachments" + idx,
3502 tab.layout = SE.composeLayout[idx];
3504 tab.on("activeChange", function(o){
3506 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
3512 tab = new YAHOO.widget.Tab({
3513 label: app_strings.LBL_EMAIL_OPTIONS,
3515 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
3516 id : "divOptions" + idx,
3520 tab.layout = SE.composeLayout[idx];
3521 tab.on("activeChange", function(o){
3523 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
3528 SE.composeLayout[idx].autoSize = function() {
3529 var pEl = this.get("element").parentNode.parentNode.parentNode;
3530 this.set("height", pEl.clientHeight-30);
3534 SE.composeLayout[idx].rightTabs = cTabs;
3536 isParentTypeValid : function(idx) {
3537 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3538 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3539 if (trim(parentTypeValue) == ""){
3540 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
3546 isParentTypeAndNameValid : function(idx) {
3547 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3548 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3549 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
3550 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
3551 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
3552 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
3558 callopenpopupForEmail2 : function(idx,options) {
3560 var formName = 'emailCompose' + idx;
3562 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
3563 formName = options.form_name;
3565 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3566 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3567 if (!SE.composeLayout.isParentTypeValid(idx)) {
3570 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
3572 call_back_function:"SE.composeLayout.popupAddEmail",
3574 field_to_name_array:{
3575 id:'data_parent_id' + idx,
3576 name:'data_parent_name' + idx,
3581 popupAddEmail : function(o)
3583 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
3584 var data = o.name_to_value_array;
3585 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
3586 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
3588 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
3589 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
3596 _1_tiny : function() {
3597 var idx = SE.composeLayout.currentInstanceId;
3598 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
3599 SE.tinyInstances[elId] = { };
3600 SE.tinyInstances[elId].ready = false;
3601 var t = tinyMCE.getInstanceById(elId);
3603 if(typeof(t) == 'undefined') {
3604 tinyMCE.execCommand('mceAddControl', false, elId);
3605 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
3606 SE.composeLayout.resizeEditor(idx);
3607 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
3612 resizeEditor : function(idx)
3614 var cof = Dom.get('composeOverFrame' + idx);
3615 var head = Dom.get('composeHeaderTable' + idx);
3616 var targetHeight = cof.clientHeight - head.clientHeight;
3617 var instance = tinyMCE.get(SE.tinyInstances.currentHtmleditor);
3619 var parentEl = Dom.get(instance.editorId + '_parent');
3620 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
3621 var contentEl = instance.contentAreaContainer;
3622 var iFrame = contentEl.firstChild;
3623 var tinMceToolbarOffset = 18;
3624 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
3628 * Initializes d&d, auto-complete, email templates
3630 _2_final : function() {
3631 var idx = SE.composeLayout.currentInstanceId;
3633 if(this.emailTemplates) {
3634 this.setComposeOptions(idx);
3636 //populate email template cache
3637 AjaxObject.target = '';
3638 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
3641 // handle drop targets for addressBook
3642 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3643 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3644 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3645 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
3647 // auto-complete setup
3648 SE.autoComplete.init(idx);
3651 document.getElementById("addressTO" + idx).focus();
3655 * hide tinyMCE tool bar if send email as plaintext is checked
3657 renderTinyMCEToolBar : function (idx, hide) {
3659 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
3661 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
3665 c1_composeEmail : function(isReplyForward, retry) {
3669 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
3670 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
3675 if(isReplyForward) {
3676 this.replyForwardEmailStage2();
3682 * takes draft info and prepopulates
3684 c0_composeDraft : function() {
3685 this.getNewInstanceId();
3687 document.getElementById('_blank').innerHTML = '';
3688 var idx = SE.composeLayout.currentInstanceId;
3689 SE.composeLayout.draftObject = new Object();
3690 SE.composeLayout.draftObject.id = idx;
3691 SE.composeLayout.draftObject.isDraft = true;
3692 SE.composeLayout.currentInstanceId = idx;
3693 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
3694 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
3695 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
3697 SE.composeLayout._0_yui();
3698 SE.composeLayout._1_tiny();
3701 SE.composeLayout._2_final();
3703 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
3704 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
3708 * Strip & Prep editor hidden fields
3710 c0_composeNewEmail : function() {
3711 this.getNewInstanceId();
3712 this.c1_composeEmail(false);
3716 * Sends async request to get the compose view.
3717 * Requests come from "reply" or "forwards"
3719 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
3720 SE.composeLayout.replyForwardObj = new Object();
3721 SE.composeLayout.replyForwardObj.ieId = ieId;
3722 SE.composeLayout.replyForwardObj.uid = uid;
3723 SE.composeLayout.replyForwardObj.mbox = mbox;
3724 SE.composeLayout.replyForwardObj.type = type;
3726 if(mbox == 'sugar::Emails') {
3727 SE.composeLayout.replyForwardObj.sugarEmail = true;
3730 SE.composeLayout.getNewInstanceId();
3731 SE.composeLayout.c1_composeEmail(true);
3733 //// END COMPOSE FLOW
3734 ///////////////////////////////////////////////////////////////////////////
3737 * Called when a contact, email, or mailinglist is dropped
3738 * into one of the compose fields.
3740 handleDrop : function (source, event, data, target) {
3743 target = event.getTarget();
3745 data.nodes = [data.nodes];
3749 target = document.getElementById(target);
3753 if (target.id.indexOf('address') > -1) {
3754 // dropped onto email to/cc/bcc field
3755 for(var i in nodes) {
3756 var node = nodes[i].getData();
3758 if (node[1].indexOf('contact') > -1) {
3759 email = SE.addressBook.getFormattedAddress(node[0]);
3760 } else if (node[1].indexOf('address-email') > -1){
3761 email = node[3].replace(/ /gi, '');
3762 email = email.replace('<', '<').replace('>', '>');
3763 var tr = source.getTrEl(nodes[i]);
3764 while (tr && !Dom.hasClass(tr, "address-contact")) {
3765 tr = source.getPreviousTrEl(tr);
3767 var CID = source.getRecord(tr).getData()[0];
3768 var o = SE.addressBook._contactCache[CID];
3769 var name = new String(o.name);
3770 var finalName = name.replace(/(<([^>]+)>)/ig, "");
3771 email = finalName + email;
3773 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
3779 /*/////////////////////////////////////////////////////////////////////////////
3780 /// EMAIL TEMPLATE CODE
3782 applyEmailTemplate : function (idx, id) {
3785 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
3786 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
3787 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) {
3791 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
3792 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
3795 // id is selected index of email template drop-down
3796 if(id == '' || id == "0") {
3797 YAHOO.SUGAR.MessageBox.show({
3802 if(btn=='no'){return;};
3803 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
3810 YAHOO.SUGAR.MessageBox.show({
3815 if(btn=='no'){return;};
3816 SUGAR.email2.composeLayout.processResult(idx, id);},
3822 processNoneResult : function(idx, id) {
3823 var tiny = SE.util.getTiny('htmleditor' + idx);
3824 var tinyHTML = tiny.getContent();
3825 var openTag = '<div><span><span>';
3826 var htmllow = tinyHTML.toLowerCase();
3827 var start = htmllow.indexOf(openTag);
3829 tinyHTML = tinyHTML.substr(start);
3830 tiny.setContent(tinyHTML);
3832 tiny.setContent('');
3836 processResult : function(idx , id){
3837 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
3839 // get attachments if any
3840 AjaxObject.target = '';
3841 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
3844 appendEmailTemplateJSON : function() {
3845 var idx = SE.composeLayout.currentInstanceId; // post increment
3847 // query based on template, contact_id0,related_to
3848 //jchi 09/10/2008 refix #7743
3849 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
3850 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
3853 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,'"');
3855 // cn: bug 14361 - text-only templates don't fill compose screen
3857 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/>");
3860 var tiny = SE.util.getTiny('htmleditor' + idx);
3861 var tinyHTML = tiny.getContent();
3862 var openTag = '<div><span><span>';
3863 var closeTag = '</span></span></div>';
3864 var htmllow = tinyHTML.toLowerCase();
3865 var start = htmllow.indexOf(openTag);
3867 var htmlPart2 = tinyHTML.substr(start);
3868 tinyHTML = text + htmlPart2;
3869 tiny.setContent(tinyHTML);
3871 tiny.setContent(text);
3876 * Writes out the signature in the email editor
3878 setSignature : function(idx) {
3881 var hide = document.getElementById('setEditor' + idx).checked;
3882 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
3883 //wait for signatures to load before trying to set them
3884 if (!SE.composeLayout.signatures) {
3885 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
3890 var sel = document.getElementById('signatures' + idx);
3892 var sel = document.getElementById('signature_id');
3893 idx = SE.tinyInstances.currentHtmleditor;
3896 //Ensure that the tinyMCE html has been rendered.
3897 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
3898 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
3905 signature = sel.options[sel.selectedIndex].value;
3910 var openTag = '<div><span><span>';
3911 var closeTag = '</span></span></div>';
3912 var t = SE.util.getTiny('htmleditor' + idx);
3914 if(typeof(t) != 'undefined')
3916 t.contentDocument = t.contentWindow.document;
3917 var html = t.getContent();
3922 var htmllow = html.toLowerCase();
3923 var start = htmllow.indexOf(openTag);
3924 var end = htmllow.indexOf(closeTag) + closeTag.length;
3926 // selected "none" - remove signature from email
3927 if(signature == '') {
3929 var htmlPart1 = html.substr(0, start);
3930 var htmlPart2 = html.substr(end, html.length);
3932 html = htmlPart1 + htmlPart2;
3935 SE.signatures.lastAttemptedLoad = '';
3939 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
3940 SE.signatures.lastAttemptedLoad = '';
3942 SE.signatures.lastAttemptedLoad = signature;
3944 if(typeof(SE.signatures[signature]) == 'undefined') {
3946 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
3947 SE.signatures.targetInstance = (idx) ? idx : "";
3948 AjaxObject.target = '';
3949 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
3951 var newSignature = this.prepareSignature(SE.signatures[signature]);
3953 // clear out old signature
3954 if(SE.signatures.lastAttemptedLoad && start > -1) {
3955 var htmlPart1 = html.substr(0, start);
3956 var htmlPart2 = html.substr(end, html.length);
3958 html = htmlPart1 + htmlPart2;
3962 start = html.indexOf('<div><hr></div>');
3963 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
3964 var htmlPart1 = html.substr(0, start);
3965 var htmlPart2 = html.substr(start, html.length);
3966 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
3967 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
3968 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
3970 var newHtml = html + openTag + newSignature + closeTag;
3972 //tinyMCE.setContent(newHtml);
3973 t.setContent(newHtml);
3977 prepareSignature : function(str) {
3978 var signature = new String(str);
3980 signature = signature.replace(/</gi, '<');
3981 signature = signature.replace(/>/gi, '>');
3987 showAttachmentPanel : function(idx) {
3988 var east = SE.composeLayout[idx].getUnitByPosition("right");
3989 var tabs = SE.composeLayout[idx].rightTabs;
3991 tabs.set("activeTab", tabs.getTab(0));
3995 * expands sidebar and displays options panel
3997 showOptionsPanel : function(idx) {
3998 var east = SE.composeLayout[idx].getUnitByPosition("right");
3999 var tabs = SE.composeLayout[idx].rightTabs;
4001 tabs.set("activeTab", tabs.getTab(1));
4005 * Selects the Contacts tab
4007 showContactsPanel : function() {
4008 SE.complexLayout.regions.west.showPanel("contactsTab");
4012 * Generates fields for Select Document
4014 addDocumentField : function(idx) {
4015 var basket = document.getElementById('addedDocuments' + idx);
4017 var index = (basket.childNodes.length / 7) - 1;
4024 var test = document.getElementById('documentId' + idx + index);
4026 while(test != null) {
4028 test = document.getElementById('documentId' + idx + index);
4031 var documentCup = document.createElement("div");
4032 documentCup.id = 'documentCup' + idx + index;
4033 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
4034 // document id field
4035 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
4036 // document name field
4037 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
4039 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
4040 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
4041 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
4043 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
4044 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
4045 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
4048 basket.appendChild(documentCup);
4049 //basket.innerHTML += out;
4054 * Makes async call to save a draft of the email
4055 * @param int Instance index
4057 saveDraft : function(tinyInstance) {
4058 this.sendEmail(tinyInstance, true);
4061 selectDocument : function(target) {
4062 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
4063 windowName = 'selectDocument';
4064 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
4066 win = window.open(URL, windowName, windowFeatures);
4068 // put the focus on the popup if the browser supports the focus() method
4074 * Modal popup for file attachment dialogue
4076 addFileField : function() {
4077 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
4078 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
4082 constraintoviewport: true,
4084 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
4085 fn:function(){SE.addFileDialog.hide();}
4088 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
4089 SE.addFileDialog.render();
4090 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
4092 Dom.removeClass("addFileDialog", "yui-hidden");
4094 SE.addFileDialog.show();
4098 * Async upload of file to temp dir
4100 uploadAttachment : function() {
4101 if(document.getElementById('email_attachment').value != "") {
4102 var formObject = document.getElementById('uploadAttachment');
4103 YAHOO.util.Connect.setForm(formObject, true, true);
4104 AjaxObject.target = '';
4105 AjaxObject.startRequest(callbackUploadAttachment, null);
4107 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
4112 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
4113 * @param string target in focus compose layout
4115 setDocument : function(idx, target, documentId, documentName, docRevId) {
4116 // fields are named/id'd [fieldName][instanceId][index]
4117 var addedDocs = document.getElementById("addedDocuments" + idx);
4118 var docId = document.getElementById('documentId' + idx + target);
4119 var docName = document.getElementById('documentName' + idx + target);
4120 var docRevisionId = document.getElementById('document' + idx + target);
4121 docId.value = documentId;
4122 docName.value = documentName;
4123 docRevisionId.value = docRevId;
4127 * Removes the bucket div containing the document input fields
4129 deleteDocumentField : function(documentCup) {
4130 var f0 = document.getElementById(documentCup);
4131 f0.parentNode.removeChild(f0);
4135 * Removes a Template Attachment field
4139 deleteTemplateAttachmentField : function(idx, index) {
4140 // create not-in-array values for removal filtering
4141 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
4147 r += document.getElementById('templateAttachmentId' + idx + index).value;
4148 document.getElementById("templateAttachmentsRemove" + idx).value = r;
4150 var target = 'templateAttachmentCup' + idx + index;
4151 d = document.getElementById(target);
4152 d.parentNode.removeChild(d);
4156 * Async removal of uploaded temp file
4157 * @param string index Should be a concatenation of idx and index
4160 deleteUploadAttachment : function(index, file) {
4161 var d = document.getElementById('email_attachment_bucket' + index);
4162 d.parentNode.removeChild(d);
4164 // make async call to delete cached file
4165 AjaxObject.target = '';
4166 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
4170 * Attaches files coming from Email Templates
4172 addTemplateAttachmentField : function(idx) {
4174 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
4176 var basket = document.getElementById('addedTemplateAttachments' + idx);
4179 var index = basket.childNodes.length;
4186 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
4188 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
4189 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
4190 idx + "\",\"" + index + "\");'/>" +
4192 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
4193 // templateAttachment field
4194 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
4196 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
4198 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
4199 "<br id='br" + index + "></br>" +
4200 "<br id='brdoc" + index + "></br>" +
4202 basket.innerHTML = basket.innerHTML + out;
4208 * Sends one email via async call
4209 * @param int idx Editor instance ID
4210 * @param bool isDraft
4212 sendEmail : function(idx, isDraft) {
4214 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
4215 var obAccountID = document.getElementById('addressFrom' + idx).value;
4217 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
4219 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
4224 var form = document.getElementById('emailCompose' + idx);
4225 var composeOptionsFormName = "composeOptionsForm" + idx;
4226 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
4227 var html = t.getContent();
4228 var subj = document.getElementById('emailSubject' + idx).value;
4229 var to = trim(document.getElementById('addressTO' + idx).value);
4230 var cc = trim(document.getElementById('addressCC' + idx).value);
4231 var bcc = trim(document.getElementById('addressBCC' + idx).value);
4232 var email_id = document.getElementById('email_id' + idx).value;
4233 var composeType = document.getElementById('composeType').value;
4234 var parent_type = document.getElementById("parent_type").value;
4235 var parent_id = document.getElementById("parent_id").value;
4237 var el_uid = document.getElementById("uid");
4238 var uid = (el_uid == null) ? '' : el_uid.value;
4240 var el_ieId = document.getElementById("ieId");
4241 var ieId = (el_ieId == null) ? '' : el_ieId.value;
4243 var el_mbox = document.getElementById("mbox");
4244 var mbox = (el_mbox == null) ? '' : el_mbox.value;
4246 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
4247 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
4251 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
4254 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
4255 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
4256 parent_id = parentIdValue;
4257 parent_type = parentTypeValue;
4259 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
4260 // baseline viability check
4262 if(to == "" && cc == '' && bcc == '' && !isDraft) {
4263 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
4265 } else if(subj == '' && !isDraft) {
4266 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
4269 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
4271 } else if(html == '' && !isDraft) {
4272 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
4277 SE.util.clearHiddenFieldValues('emailCompose' + idx);
4278 document.getElementById('data_parent_id' + idx).value = parentIdValue;
4279 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
4280 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
4281 html = html.replace(/</ig, "sugarLessThan");
4282 html = html.replace(/>/ig, "sugarGreaterThan");
4284 form.sendDescription.value = html;
4285 form.sendSubject.value = subj;
4286 form.sendTo.value = to;
4287 form.sendCc.value = cc;
4288 form.sendBcc.value = bcc;
4289 form.email_id.value = email_id;
4290 form.composeType.value = composeType;
4291 form.composeLayoutId.value = 'composeLayout' + idx;
4292 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
4293 form.saveToSugar.value = 1;
4294 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
4295 form.parent_type.value = parent_type;
4296 form.parent_id.value = parent_id;
4297 form.uid.value = uid;
4298 form.ieId.value = ieId;
4299 form.mbox.value = mbox;
4301 // email attachments
4302 var addedFiles = document.getElementById('addedFiles' + idx);
4304 for(i=0; i<addedFiles.childNodes.length; i++) {
4305 var bucket = addedFiles.childNodes[i];
4307 for(j=0; j<bucket.childNodes.length; j++) {
4308 var node = bucket.childNodes[j];
4309 var nName = new String(node.name);
4311 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
4312 if(form.attachments.value != '') {
4313 form.attachments.value += "::";
4315 form.attachments.value += node.value;
4322 var addedDocs = document.getElementById('addedDocuments' + idx);
4324 for(i=0; i<addedDocs.childNodes.length; i++) {
4325 var cNode = addedDocs.childNodes[i];
4326 for(j=0; j<cNode.childNodes.length; j++) {
4327 var node = cNode.childNodes[j];
4328 var nName = new String(node.name);
4329 if(node.type == 'hidden' && nName.match(/documentId/)) {
4330 if(form.documents.value != '') {
4331 form.documents.value += "::";
4333 form.documents.value += node.value;
4339 // template attachments
4340 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
4341 if(addedTemplateAttachments) {
4342 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
4343 var cNode = addedTemplateAttachments.childNodes[i];
4344 for(j=0; j<cNode.childNodes.length; j++) {
4345 var node = cNode.childNodes[j];
4346 var nName = new String(node.name);
4347 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
4348 if(form.templateAttachments.value != "") {
4349 form.templateAttachments.value += "::";
4351 form.templateAttachments.value += node.value;
4357 // remove attachments
4358 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
4360 YAHOO.util.Connect.setForm(form);
4362 AjaxObject.target = 'frameFlex';
4364 // sending a draft email
4365 if(!isDraft && in_draft) {
4367 SE.listView.removeRowByUid(email_id);
4370 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
4371 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
4373 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
4377 * Handles clicking the email address link from a given view
4379 composePackage : function() {
4380 if(composePackage != null) {
4381 SE.composeLayout.c0_composeNewEmail();
4384 if(composePackage.to_email_addrs) {
4385 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
4387 if (composePackage.subject != null && composePackage.subject.length > 0) {
4388 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
4391 //If no parent fields are set in the composePackage, ensure they are cleared.
4392 var parentFields = ['parent_type','parent_name','parent_id'];
4393 for(var i=0;i<parentFields.length;i++)
4395 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
4396 composePackage[parentFields[i]] = "";
4399 document.getElementById("parent_type").value = composePackage.parent_type;
4400 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
4401 document.getElementById("parent_id").value = composePackage.parent_id;
4402 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
4403 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
4405 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
4406 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
4408 if (composePackage.body != null && composePackage.body.length > 0) {
4409 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4410 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
4411 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
4413 if (composePackage.attachments != null) {
4414 SE.composeLayout.loadAttachments(composePackage.attachments);
4417 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
4418 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
4419 SE.util.emptySelectOptions(addressFrom);
4420 var fromAccountOpts = composePackage.fromAccounts.data;
4421 for(i=0; i<fromAccountOpts.length; i++) {
4422 var key = fromAccountOpts[i].value;
4423 var display = fromAccountOpts[i].text;
4424 var opt = new Option(display, key);
4425 if (fromAccountOpts[i].selected) {
4426 opt.selected = true;
4428 addressFrom.options.add(opt);
4435 setContentOnThisTiny : function() {
4436 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4437 var tinyHTML = tiny.getContent();
4438 composePackage.body = decodeURI(encodeURI(composePackage.body));
4439 // cn: bug 14361 - text-only templates don't fill compose screen
4440 if(composePackage.body == '') {
4441 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4443 //Flag determines if we should clear the tiny contents or just append
4444 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
4445 SE.composeLayout.tinyHTML = '';
4447 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
4449 tiny.setContent(SE.composeLayout.tinyHTML);
4450 //Indicate that the contents has been loaded successfully.
4451 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
4454 * Confirms closure of a compose screen if "x" is clicked
4456 confirmClose : function(panel) {
4457 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
4458 SE.composeLayout.closeCompose(panel.id);
4466 * forces close of a compose screen
4468 forceCloseCompose : function(id) {
4469 SE.composeLayout.closeCompose(id);
4471 // handle flow back to originating view
4472 if(composePackage) {
4473 // check if it's a module we need to return to
4474 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
4475 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
4476 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
4477 window.location = url;
4484 * closes the editor that just sent email
4485 * @param string id ID of composeLayout tab
4487 closeCompose : function(id) {
4488 // destroy tinyMCE instance
4489 var idx = id.substr(13, id.length);
4490 var instanceId = "htmleditor" + idx;
4491 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
4493 // nullify DOM and namespace values.
4495 SE.composeLayout[idx] = null;
4496 SE.tinyInstances[instanceId] = null;
4497 var tabsArray = SE.innerLayout.get("tabs");
4498 for (i = 0 ; i < tabsArray.length ; i++) {
4499 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
4500 tabsArray[i].close();
4504 //SE.innerLayout.getTab(idx).close();
4508 * Enable the quick search for the compose relate field or search tab
4510 enableQuickSearchRelate: function(idx,overides){
4512 if(typeof overides != 'undefined')
4514 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
4515 var newModule = document.getElementById(newModuleID).value;
4516 var formName = overides['formName'];
4517 var fieldName = overides['fieldName'];
4518 var fieldId = overides['fieldId'];
4519 var fullName = formName + "_" + fieldName;
4520 var postBlurFunction = null;
4524 var newModule = document.getElementById('data_parent_type'+idx).value;
4525 var formName = 'emailCompose'+idx;
4526 var fieldName = 'data_parent_name'+idx;
4527 var fieldId = 'data_parent_id'+idx;
4528 var fullName = formName + "_" + fieldName;
4529 var postBlurFunction = "SE.composeLayout.qsAddAddress";
4532 if(typeof sqs_objects == 'undefined')
4533 window['sqs_objects'] = new Array;
4535 window['sqs_objects'][fullName] = {
4538 modules:[newModule],
4540 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
4541 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
4542 post_onblur_function: postBlurFunction,
4543 order:"name","limit":"30","no_match_text":"No Match"};
4546 if(typeof QSProcessedFieldsArray != 'undefined')
4547 QSProcessedFieldsArray[fullName] = false;
4548 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
4549 QSFieldsArray[fullName].destroy();
4550 delete QSFieldsArray[fullName];
4552 if (Dom.get(fullName + "_results")) {
4553 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
4559 qsAddAddress : function(o) {
4560 if (o.name != "" && o.email1 != "")
4562 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
4563 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
4567 * Returns a new instance ID, 0-index
4569 getNewInstanceId : function() {
4570 this.currentInstanceId = this.currentInstanceId + 1;
4571 return this.currentInstanceId;
4575 * 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.
4577 loadAttachments : function(result) {
4578 var idx = SE.composeLayout.currentInstanceId;
4580 if(typeof(result) == 'object') {
4581 //jchi #20680. Clean the former template attachments;
4582 var basket = document.getElementById('addedTemplateAttachments' + idx);
4583 if(basket.innerHTML != ''){
4584 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
4586 basket.innerHTML = '';
4591 if(typeof result[i] == 'object') {
4592 var index = SE.composeLayout.addTemplateAttachmentField(idx);
4593 var bean = result[i];
4594 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
4595 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
4602 * fills drop-down values for email templates and signatures
4604 setComposeOptions : function(idx) {
4605 // send from accounts
4606 var addressFrom = document.getElementById('addressFrom' + idx);
4608 if (addressFrom.options.length <= 0) {
4609 SE.util.emptySelectOptions(addressFrom);
4610 var fromAccountOpts = SE.composeLayout.fromAccounts;
4611 for (id = 0 ; id < fromAccountOpts.length ; id++) {
4612 var key = fromAccountOpts[id].value;
4613 var display = fromAccountOpts[id].text;
4614 var is_default = false;
4615 if(key == SUGAR.default_inbound_accnt_id)
4617 var opt = new Option(display, key);
4618 addressFrom.options.add(opt);
4619 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
4624 var et = document.getElementById('email_template' + idx);
4625 SE.util.emptySelectOptions(et);
4627 for(var key in this.emailTemplates) { // iterate through assoc array
4628 var display = this.emailTemplates[key];
4629 var opt = new Option(display, key);
4630 et.options.add(opt);
4634 var sigs = document.getElementById('signatures' + idx);
4635 SE.util.emptySelectOptions(sigs);
4637 for(var key in this.signatures) { // iterate through assoc array
4638 var display = this.signatures[key];
4639 var opt = new Option(display, key);
4641 if(key == SE.userPrefs.signatures.signature_default) {
4642 opt.selected = true;
4645 sigs.options.add(opt);
4648 // html/plain email?
4649 var htmlEmail = document.getElementById('setEditor' + idx);
4650 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
4651 htmlEmail.checked = true;
4653 htmlEmail.checked = false;
4656 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
4660 * After compose screen is rendered, async call to get email body from Sugar
4662 replyForwardEmailStage2 : function() {
4663 SE.util.clearHiddenFieldValues('emailUIForm');
4664 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
4666 var ieId = SE.composeLayout.replyForwardObj.ieId;
4667 var uid = SE.composeLayout.replyForwardObj.uid;
4668 var mbox = SE.composeLayout.replyForwardObj.mbox;
4669 var type = SE.composeLayout.replyForwardObj.type;
4670 var idx = SE.composeLayout.currentInstanceId;
4672 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
4674 document.getElementById('emailSubject' + idx).value = type;
4675 document.getElementById('emailUIAction').value = 'composeEmail';
4676 document.getElementById('composeType').value = type;
4677 document.getElementById('ieId').value = ieId;
4678 document.getElementById('uid').value = uid;
4679 document.getElementById('mbox').value = mbox;
4680 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
4681 var formObject = document.getElementById('emailUIForm');
4682 YAHOO.util.Connect.setForm(formObject);
4684 var sendType = type;
4685 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
4689 * Show the hidden cc or bcc fields
4691 showHiddenAddress: function(addrType,idx){
4693 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
4694 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
4695 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
4696 this[addrType+'Hidden'+idx] = false;
4698 //After bcc or cc is added, move options below last addr field
4699 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4701 //If both cc and bcc hidden, remove the empty row containing text.
4702 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
4703 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
4704 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
4706 SE.composeLayout.resizeEditor(idx);
4709 * Hide the cc and bcc fields if they were shown.
4711 hideHiddenAddresses: function(idx){
4713 var addrTypes = ['cc','bcc'];
4714 for(var i = 0;i<addrTypes.length;i++)
4716 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
4717 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
4718 this[addrTypes[i] + 'Hidden'+idx] = true
4721 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
4722 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
4723 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4727 //// END SE.composeLayout
4728 ///////////////////////////////////////////////////////////////////////////////
4729 ///////////////////////////////////////////////////////////////////////////////
4733 * Cleans serialized UID lists of duplicates
4737 cleanUids : function(str) {
4738 var seen = new Object();
4740 var arr = new String(str).split(",");
4742 for(var i=0; i<arr.length; i++) {
4747 clean += (clean != "") ? "," : "";
4749 seen[arr[i]] = true;
4756 * Clears hidden field values
4757 * @param string id ID of form element to clear
4759 clearHiddenFieldValues : function(id) {
4760 var form = document.getElementById(id);
4762 for(i=0; i<form.elements.length; i++) {
4763 if(form.elements[i].type == 'hidden') {
4764 var e = form.elements[i];
4765 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
4773 * Reduces a SELECT drop-down to 0 items to prepare for new ones
4775 emptySelectOptions : function(el) {
4777 for(i=el.childNodes.length - 1; i >= 0; i--) {
4778 if(el.childNodes[i]) {
4779 el.removeChild(el.childNodes[i]);
4786 * Returns the MBOX path in the manner php_imap expects:
4787 * ie: INBOX.DEBUG.test
4788 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
4790 generateMboxPath : function(str) {
4791 var ex = str.split("::");
4793 /* we have a serialized MBOX path */
4797 for(var i=0; i<ex.length; i++) {
4798 if(ex[i] == 'INBOX') {
4810 /* we have a Sugar folder GUID - do nothing */
4818 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
4819 * @param HTMLElement el
4820 * @return string GUID of found element or empty on failure
4822 getGuidFromElement : function(el) {
4828 for(var i=0; i<iterations; i++) {
4830 if(el.id.match(SE.reGUID)) {
4842 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
4845 getPanelId : function() {
4846 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
4850 * wrapper to handle weirdness with IE
4851 * @param string instanceId
4852 * @return tinyMCE Controller object
4854 getTiny : function(instanceId) {
4855 if(instanceId == '') {
4859 var t = tinyMCE.getInstanceById(instanceId);
4863 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
4869 * Simple check for MSIE browser
4873 var nav = new String(navigator.appVersion);
4874 if(nav.match(/MSIE/)) {
4881 * Recursively removes an element from the DOM
4882 * @param HTMLElement
4884 removeElementRecursive : function(el) {
4885 this.emptySelectOptions(el);
4892 sleep : function(secs) {
4893 setTimeout("void(0);", secs);
4897 * Converts a <select> element to an Ext.form.combobox
4899 convertSelect : function(select) {
4900 alert('in convertSelect');
4901 if (typeof(select) == "string") {
4902 select = document.getElementById(select);
4906 findChildNode : function (parent, property, value) {
4907 for (i in parent.children) {
4908 var child = parent.children[i];
4909 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
4911 var searchChild = SE.util.findChildNode(child, property, value);
4918 cascadeNodes : function (parent, fn, scope, args) {
4919 for (i in parent.children) {
4920 var child = parent.children[i];
4921 var s = scope ? scope : child;
4922 var a = args ? args : child;
4924 SE.util.cascadeNodes(child, fn, scope, args);
4931 ///////////////////////////////////////////////////////////////////////////////
4934 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
4936 /*********************************************************************************
4937 * SugarCRM is a customer relationship management program developed by
4938 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4940 * This program is free software; you can redistribute it and/or modify it under
4941 * the terms of the GNU Affero General Public License version 3 as published by the
4942 * Free Software Foundation with the addition of the following permission added
4943 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4944 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4945 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4947 * This program is distributed in the hope that it will be useful, but WITHOUT
4948 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4949 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4952 * You should have received a copy of the GNU Affero General Public License along with
4953 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4954 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4957 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4958 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4960 * The interactive user interfaces in modified source and object code versions
4961 * of this program must display Appropriate Legal Notices, as required under
4962 * Section 5 of the GNU Affero General Public License version 3.
4964 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4965 * these Appropriate Legal Notices must retain the display of the "Powered by
4966 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4967 * technical reasons, the Appropriate Legal Notices must display the words
4968 * "Powered by SugarCRM".
4969 ********************************************************************************/
4971 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
4972 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
4973 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
4974 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
4975 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
4976 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
4977 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
4978 ' <input type="hidden" id="type{idx}" name="type" value="">' +
4979 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
4980 ' <input type="hidden" id="composeType" name="composeType">' +
4981 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
4982 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
4983 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
4984 ' <input type="hidden" id="sendTo" name="sendTo">' +
4985 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
4986 ' <input type="hidden" id="sendCc" name="sendCc">' +
4987 ' <input type="hidden" id="setEditor" name="setEditor">' +
4988 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
4989 ' <input type="hidden" id="parent_id" name="parent_id">' +
4990 ' <input type="hidden" id="parent_type" name="parent_type">' +
4991 ' <input type="hidden" id="attachments" name="attachments">' +
4992 ' <input type="hidden" id="documents" name="documents">' +
4993 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
4994 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
4995 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
4996 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
4998 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
4999 ' <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>' +
5000 ' <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>' +
5001 ' <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>' +
5002 ' <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>' +
5003 '</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>' +
5004 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
5005 '<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>' +
5006 ' </td></tr></tbody></table></th>' +
5010 ' <div style="margin:5px;">' +
5011 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
5013 ' <td class="emailUILabel" NOWRAP >' +
5014 ' {app_strings.LBL_EMAIL_FROM}:' +
5016 ' <td class="emailUIField" NOWRAP>' +
5018 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
5023 ' <td class="emailUILabel" NOWRAP>' +
5024 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
5025 ' {app_strings.LBL_EMAIL_TO}:' +
5028 ' <td class="emailUIField" NOWRAP>' +
5029 ' <div class="ac_autocomplete">' +
5030 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5031 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
5032 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
5036 ' <tr id="add_addr_options_tr{idx}">' +
5037 ' <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>'+
5039 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
5040 ' <td class="emailUILabel" NOWRAP>' +
5041 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
5042 ' {app_strings.LBL_EMAIL_CC}:' +
5045 ' <td class="emailUIField" NOWRAP>' +
5046 ' <div class="ac_autocomplete">' +
5047 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5048 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
5049 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
5053 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
5054 ' <td class="emailUILabel" NOWRAP>' +
5055 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
5056 ' {app_strings.LBL_EMAIL_BCC}:' +
5059 ' <td class="emailUIField" NOWRAP>' +
5060 ' <div class="ac_autocomplete">' +
5061 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5062 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
5063 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
5068 ' <td class="emailUILabel" NOWRAP width="1%">' +
5069 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
5071 ' <td class="emailUIField" NOWRAP width="99%">' +
5072 ' <div class="ac_autocomplete">' +
5073 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
5082 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
5083 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
5084 ' <div style="padding:5px;">' +
5085 ' <table cellpadding="2" cellspacing="0" border="0">' +
5088 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
5095 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
5096 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
5108 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
5115 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
5116 ' <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>' +
5128 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
5135 ' <div id="addedTemplateAttachments{idx}"></div>' +
5142 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
5143 ' <div style="padding:5px;">' +
5144 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
5145 ' <table border="0" width="100%">' +
5147 ' <td NOWRAP style="padding:2px;">' +
5148 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
5152 ' <td NOWRAP style="padding:2px;">' +
5153 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
5158 ' <table border="0" width="100%">' +
5160 ' <td NOWRAP style="padding:2px;">' +
5161 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
5165 ' <td NOWRAP style="padding:2px;">' +
5166 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
5170 ' <table border="0" width="100%">' +
5172 ' <td NOWRAP style="padding:2px;">' +
5173 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
5174 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
5182 // End of File modules/Emails/javascript/composeEmailTemplate.js
5184 /*********************************************************************************
5185 * SugarCRM is a customer relationship management program developed by
5186 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5188 * This program is free software; you can redistribute it and/or modify it under
5189 * the terms of the GNU Affero General Public License version 3 as published by the
5190 * Free Software Foundation with the addition of the following permission added
5191 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
5192 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
5193 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
5195 * This program is distributed in the hope that it will be useful, but WITHOUT
5196 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
5197 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
5200 * You should have received a copy of the GNU Affero General Public License along with
5201 * this program; if not, see http://www.gnu.org/licenses or write to the Free
5202 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
5205 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
5206 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
5208 * The interactive user interfaces in modified source and object code versions
5209 * of this program must display Appropriate Legal Notices, as required under
5210 * Section 5 of the GNU Affero General Public License version 3.
5212 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
5213 * these Appropriate Legal Notices must retain the display of the "Powered by
5214 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
5215 * technical reasons, the Appropriate Legal Notices must display the words
5216 * "Powered by SugarCRM".
5217 ********************************************************************************/
5222 function complexLayoutInit() {
5223 var se = SUGAR.email2;
5224 var Dom = YAHOO.util.Dom;
5226 getInnerLayout : function(rows) {
5227 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
5228 parent: se.complexLayout,
5234 scroll:false, // grid should autoScroll itself
5236 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
5244 body: "<div id='listBottom' />"
5252 body: "<div id='listRight' />",
5253 titlebar: false //,header: "right"
5256 se.complexLayout.on("render", function(){
5257 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
5258 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5259 SUGAR.email2.listViewLayout.set("height", height);
5260 SUGAR.email2.listViewLayout.render();
5262 se.listViewLayout.render();
5264 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
5265 var rp = se.listViewLayout.resizePreview = function() {
5266 var pre = Dom.get("displayEmailFramePreview");
5268 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
5269 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
5272 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
5273 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
5274 se.e2Layout.setPreviewPanel(rows);
5275 se.previewLayout = se.listViewLayout;
5276 return se.listViewLayout;
5279 getInnerLayout2Rows : function() {
5280 return this.getInnerLayout(true);
5282 getInnerLayout2Columns : function() {
5283 return this.getInnerLayout(false);
5287 // initialize state manager, we will use cookies
5288 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
5289 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
5290 se.complexLayout = new YAHOO.widget.Layout("container", {
5293 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
5294 width: Dom.getViewportWidth() - 40,
5298 body: "<div id='emailtabs'></div>"
5303 body: "<div id='lefttabs'></div>",
5313 header: Dom.get('footerLinks').innerHTML,
5320 se.complexLayout.render();
5321 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
5322 tp.addTab(new YAHOO.widget.Tab({
5325 content : "<div id='listViewDiv'/>",
5329 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
5330 tp.appendTo(centerEl);
5332 tp.get("element").style.borderRight = "1px solid #666"
5334 var listV = this.getInnerLayout2Rows();
5335 listV.set("height", tp.get("element").clientHeight - 25);
5338 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
5339 var folderTab = new YAHOO.widget.Tab({
5340 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
5342 content : "<div id='emailtree'/>",
5346 folderTab.on("activeChange", function(o){
5348 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
5351 se.leftTabs.addTab(folderTab);
5353 var tabContent = SUGAR.util.getAndRemove("searchTab");
5354 var searchTab = new YAHOO.widget.Tab({
5355 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
5357 content : tabContent.innerHTML,
5360 searchTab.on("activeChange", function(o){
5363 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
5364 //Setup the calendars if needed
5365 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
5366 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
5368 //Initalize sqs object for assigned user name
5369 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
5371 //Attach event handler for when the relate module option is selected for the correct sqs object
5372 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
5373 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
5374 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
5375 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
5377 //If enter key is pressed, perform search
5378 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
5379 for(var i=0; i < addKeyPressFields.length;i++)
5381 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
5382 if (e.keyCode == 13) {
5383 YAHOO.util.Event.stopEvent(e);
5384 SUGAR.email2.search.searchAdvanced();
5388 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
5390 //Clear parent values if selecting another parent type.
5391 YAHOO.util.Event.addListener('data_parent_type_search','change',
5393 document.getElementById('data_parent_id_search').value ='';
5394 document.getElementById('data_parent_name_search').value ='';
5399 se.leftTabs.addTab(searchTab);
5401 var resizeTabBody = function() {
5402 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
5403 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5406 se.complexLayout.on("render", resizeTabBody);
5407 se.leftTabs.on("activeTabChange", resizeTabBody);
5408 //hack to allow left pane scroll bar to fully show
5409 var lefttabsDiv = document.getElementById('lefttabs');
5410 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
5411 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
5412 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
5415 initSQSObject: function(formName,fieldName)
5417 var fullFieldName = formName + '_' + fieldName; //SQS Convention
5418 var resultName = fullFieldName + '_' + 'results';
5420 if (QSFieldsArray[fullFieldName] != null)
5422 QSFieldsArray[fullFieldName].destroy();
5423 delete QSFieldsArray[fullFieldName];
5425 if (QSProcessedFieldsArray[fullFieldName])
5426 QSProcessedFieldsArray[fullFieldName] = false;
5428 if( Dom.get(resultName) )
5430 var obj = document.getElementById(resultName);
5431 obj.parentNode.removeChild(obj);
5434 setPreviewPanel: function(rows) {
5436 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
5437 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
5438 Dom.get("listRight").innerHTML = "";
5439 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
5441 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
5442 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
5443 Dom.get("listBottom").innerHTML = "";
5444 Dom.get("listRight").innerHTML = "<div id='_blank' />";
5451 var myBufferedListenerObject = new Object();
5452 myBufferedListenerObject.refit = function() {
5453 if(SUGAR.email2.grid) {
5454 SUGAR.email2.grid.autoSize();
5457 // End of File modules/Emails/javascript/complexLayout.js