1 /*********************************************************************************
2 * SugarCRM is a customer relationship management program developed by
3 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5 * This program is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU Affero General Public License version 3 as published by the
7 * Free Software Foundation with the addition of the following permission added
8 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
17 * You should have received a copy of the GNU Affero General Public License along with
18 * this program; if not, see http://www.gnu.org/licenses or write to the Free
19 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
23 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25 * The interactive user interfaces in modified source and object code versions
26 * of this program must display Appropriate Legal Notices, as required under
27 * Section 5 of the GNU Affero General Public License version 3.
29 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
30 * these Appropriate Legal Notices must retain the display of the "Powered by
31 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
32 * technical reasons, the Appropriate Legal Notices must display the words
33 * "Powered by SugarCRM".
34 ********************************************************************************/
38 var flexContentOld = "";
39 var forcePreview = false;
40 var inCompose = false;
42 /* globals for Callback functions */
43 var email; // AjaxObject.showEmailPreview
47 var meta; // AjaxObject.showEmailPreview
50 var urlBase = 'index.php';
51 var urlStandard = 'sugar_body_only=true&to_pdf=true&module=Emails&action=EmailUIAjax';
53 var lazyLoadFolder = null;// End of File modules/Emails/javascript/vars.js
55 /*********************************************************************************
56 * SugarCRM is a customer relationship management program developed by
57 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
59 * This program is free software; you can redistribute it and/or modify it under
60 * the terms of the GNU Affero General Public License version 3 as published by the
61 * Free Software Foundation with the addition of the following permission added
62 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
63 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
64 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
66 * This program is distributed in the hope that it will be useful, but WITHOUT
67 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
68 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
71 * You should have received a copy of the GNU Affero General Public License along with
72 * this program; if not, see http://www.gnu.org/licenses or write to the Free
73 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
76 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
77 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
79 * The interactive user interfaces in modified source and object code versions
80 * of this program must display Appropriate Legal Notices, as required under
81 * Section 5 of the GNU Affero General Public License version 3.
83 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
84 * these Appropriate Legal Notices must retain the display of the "Powered by
85 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
86 * technical reasons, the Appropriate Legal Notices must display the words
87 * "Powered by SugarCRM".
88 ********************************************************************************/
89 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
90 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
91 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
92 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
93 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
94 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
95 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
96 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
97 this.js_more();this.js_more();}
98 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
99 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
100 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
101 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
102 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&¤tNode.tagName=='SPAN'){currentNode.id=/_input/.test(currentNode.id)?this.field_element_name+'_input_div_'+this.fields_count:this.field_element_name+'_radio_div_'+this.fields_count;if(/_input/.test(currentNode.id)){currentNode.name='teamset_div';}
103 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
104 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
105 currentNode.name=new_name;currentNode.id=new_name;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_name;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
106 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
107 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
109 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
111 if(!has_primary){return false;}
113 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
114 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
115 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
116 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
117 if(noAdd){enableQS(false);}
118 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_collection_"+i);var id_field=document.getElementById("id_"+this.field+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].id==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
120 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
121 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
123 SUGAR.collection.safe_clone=function(e,recursive)
124 {if(e.nodeName=="#text")
125 {return document.createTextNode(e.data);}
126 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];for(var i in properties)
127 {if(e[properties[i]])
128 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
129 newNode[properties[i]]=e[properties[i]];}}
131 {for(var i in e.childNodes)
132 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
133 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
134 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
136 /*********************************************************************************
137 * SugarCRM is a customer relationship management program developed by
138 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
140 * This program is free software; you can redistribute it and/or modify it under
141 * the terms of the GNU Affero General Public License version 3 as published by the
142 * Free Software Foundation with the addition of the following permission added
143 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
144 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
145 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
147 * This program is distributed in the hope that it will be useful, but WITHOUT
148 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
149 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
152 * You should have received a copy of the GNU Affero General Public License along with
153 * this program; if not, see http://www.gnu.org/licenses or write to the Free
154 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
157 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
158 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
160 * The interactive user interfaces in modified source and object code versions
161 * of this program must display Appropriate Legal Notices, as required under
162 * Section 5 of the GNU Affero General Public License version 3.
164 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
165 * these Appropriate Legal Notices must retain the display of the "Powered by
166 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
167 * technical reasons, the Appropriate Legal Notices must display the words
168 * "Powered by SugarCRM".
169 ********************************************************************************/
172 cache : new Object(),
173 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
174 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
177 currentHtmleditor : ''
181 * preserves hits from email server
183 _setDetailCache : function(ret) {
185 var compKey = ret.meta.mbox + ret.meta.uid;
187 if(!SUGAR.email2.cache[compKey]) {
188 SUGAR.email2.cache[compKey] = ret;
193 autoSetLayout : function() {
194 var c = document.getElementById('container');
195 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
196 //Ensure a minimum height.
197 tHeight = Math.max(tHeight, 550);
198 c.style.height = tHeight + "px";
199 SUGAR.email2.complexLayout.set('height', tHeight);
200 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
201 SUGAR.email2.complexLayout.render();
202 SUGAR.email2.listViewLayout.resizePreview();
207 * Shows overlay progress message
209 function overlayModal(title, body) {
210 overlay(title, body);
212 function overlay(reqtitle, body, type, additconfig) {
214 if (typeof(additconfig) == "object") {
215 var config = additconfig;
218 config.title = reqtitle;
220 YAHOO.SUGAR.MessageBox.show(config);
223 function hideOverlay() {
224 YAHOO.SUGAR.MessageBox.hide();
226 // End of File modules/Emails/javascript/EmailUIShared.js
228 /*********************************************************************************
229 * SugarCRM is a customer relationship management program developed by
230 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
232 * This program is free software; you can redistribute it and/or modify it under
233 * the terms of the GNU Affero General Public License version 3 as published by the
234 * Free Software Foundation with the addition of the following permission added
235 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
236 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
237 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
239 * This program is distributed in the hope that it will be useful, but WITHOUT
240 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
241 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
244 * You should have received a copy of the GNU Affero General Public License along with
245 * this program; if not, see http://www.gnu.org/licenses or write to the Free
246 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
249 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
250 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
252 * The interactive user interfaces in modified source and object code versions
253 * of this program must display Appropriate Legal Notices, as required under
254 * Section 5 of the GNU Affero General Public License version 3.
256 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
257 * these Appropriate Legal Notices must retain the display of the "Powered by
258 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
259 * technical reasons, the Appropriate Legal Notices must display the words
260 * "Powered by SugarCRM".
261 ********************************************************************************/
264 if (typeof console == "undefined")
265 console = { log: function(o) {alert(o)} };
269 currentRequestObject : null,
270 //timeout : 30000, // 30 second timeout default
271 timeout : 9999999999, // 30 second timeout default
277 _reset : function() {
278 this.timeout = 30000;
279 this.forceAbort = false;
282 folderRenameCleanup : function() {
283 SUGAR.email2.folders.setSugarFolders();
286 fullSyncCleanup : function(o) {
287 this.folders.checkMailCleanup(o);
288 SUGAR.email2.settings.settingsDialog.hide();
293 composeCache : function(o) {
294 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
295 // get email templates and user signatures
296 var ret = JSON.parse(o.responseText);
298 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
299 SUGAR.email2.composeLayout.signatures = ret.signatures;
300 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
302 SUGAR.email2.composeLayout.setComposeOptions(idx);
304 //Set the error array so we can notify the user when they try to hit send if any errors
305 //are present. We will also notify them now (after hitting compose button).
306 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
309 //if error element is returning an array, then check the length to make sure we have error messages
310 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
311 //add error messages for display
312 for(i in ret.errorArray)
313 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
314 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
315 //if error element is returning an object, and the object value is not empty or null, then display error message
316 for(i in ret.errorArray)
317 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
320 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
322 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
324 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
330 handleDeleteSignature : function(o) {
332 var ret = JSON.parse(o.responseText);
333 SUGAR.email2.composeLayout.signatures = ret.signatures;
334 var field = document.getElementById('signature_id');
335 SUGAR.email2.util.emptySelectOptions(field);
337 for(var i in ret.signatures) { // iterate through assoc array
338 var opt = new Option(ret.signatures[i], i);
339 field.options.add(opt);
341 setSigEditButtonVisibility();
346 handleDeleteReturn : function(o) {
347 // force refresh ListView
349 if(document.getElementById('focusEmailMbox')) {
350 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
353 // need to display success message before calling next async call?
354 document.getElementById(this.target).innerHTML = o.responseText;
359 handleFailure : function(o) {
361 overlay('Exception occurred...', o.statusText, 'alert');
364 handleReplyForward : function(o) {
365 var a = JSON.parse(o.responseText);
367 var idx = SUGAR.email2.composeLayout.currentInstanceId;
369 document.getElementById('email_id' + idx).value = a.uid;
370 document.getElementById('emailSubject' + idx).value = a.name;
371 document.getElementById('addressTO' + idx).value = a.from;
372 document.getElementById('uid' + idx).value = a.uid;
374 document.getElementById('addressCC' + idx).value = a.cc;
375 SE.composeLayout.showHiddenAddress('cc', idx);
379 document.getElementById('type' + idx).value = a.type;
382 // apply attachment values
383 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
385 setTimeout("callbackReplyForward.finish(globalA);", 500);
388 handleReplyForwardForDraft : function(o) {
389 var a = JSON.parse(o.responseText);
391 var idx = SUGAR.email2.composeLayout.currentInstanceId;
393 document.getElementById('email_id' + idx).value = a.uid;
394 document.getElementById('emailSubject' + idx).value = a.name;
395 document.getElementById('addressTO' + idx).value = a.to;
398 document.getElementById('addressCC' + idx).value = a.cc;
399 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
403 document.getElementById('addressBCC' + idx).value = a.bcc;
404 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
409 document.getElementById('type' + idx).value = a.type;
413 // apply attachment values
414 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
416 setTimeout("callbackReplyForward.finish(globalA);", 500);
421 handleSuccess : function(o) {
422 document.getElementById(this.target).innerHTML = o.responseText;
428 ieDeleteSuccess : function(o) {
431 var ret = JSON.parse(o.responseText);
433 SUGAR.email2.accounts.refreshInboundAccountTable();
434 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
435 SUGAR.email2.accounts.rebuildFolderList();
441 ieSaveSuccess : function(o) {
442 document.getElementById('saveButton').disabled = false;
443 var a = JSON.parse(o.responseText);
446 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
447 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
449 resp = JSON.parse(o.responseText);
450 SUGAR.email2.accounts.refreshInboundAccountTable();
451 SUGAR.email2.accounts.refreshOuboundAccountTable();
452 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
453 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
457 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
464 loadAttachments : function(o) {
465 var result = JSON.parse(o.responseText);
467 SUGAR.email2.composeLayout.loadAttachments(result);
472 loadSignature : function(o) {
473 var ret = JSON.parse(o.responseText);
474 SUGAR.email2.signatures[ret.id] = ret.signature_html;
475 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
479 * Follow up to mark email read|unread|flagged
481 markEmailCleanup : function(o) {
482 var ret = JSON.parse(o.responseText);
483 if (!ret['status']) {
485 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
487 SUGAR.email2.contextMenus.markEmailCleanup();
493 rebuildShowFolders : function(o) {
494 var t = JSON.parse(o.responseText);
495 var show = document.getElementById('ieAccountListShow');
497 SUGAR.email2.util.emptySelectOptions(show);
499 for(i=0; i<t.length; i++) { // iterate through assoc array
500 var opt = new Option(t[i].text, t[i].value, t[i].selected);
501 opt.selected = t[i].selected;
502 show.options.add(opt);
505 SUGAR.email2.accounts.renderTree();
509 saveListViewSortOrderPart2 : function() {
510 // create the JSON string the func expects
511 focusFolderPath = '[ "Home", "' + ieName + '"';
513 var f = new String(focusFolder);
514 var fEx = f.split('.');
516 for(i=0; i<fEx.length; i++) {
517 focusFolderPath += ', "' + fEx[i] +'"'
520 focusFolderPath += ']';
522 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
523 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
529 sendEmailCleanUp : function(o) {
531 var ret = JSON.parse(o.responseText);
533 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
534 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
535 } else if (o.responseText) {
536 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
539 if (typeof(SE.grid) != 'undefined')
540 SE.listView.refreshGrid();
541 //Disabled while address book is disabled
543 //If this call back was initiated by quick compose from a Detail View page, refresh the
544 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
545 //close the shortcut bar menu
546 if ( (typeof(action_sugar_grp1) != 'undefined')) {
547 if(action_sugar_grp1 == 'DetailView') {
548 showSubPanel('history',null,true);
549 } else if(action_sugar_grp1 == 'quickcreate') {
556 ieSendSuccess : function(o) {
558 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
563 settingsFolderRefresh : function(o) {
564 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
565 var ret = JSON.parse(o.responseText);
566 var user = document.getElementById('userFolders');
568 SUGAR.email2.util.emptySelectOptions(user);
570 for(i=0; i<ret.userFolders.length; i++) {
571 var display = ret.userFolders[i].name;
572 var value = ret.userFolders[i].id;
573 var selected = (ret.userFolders[i].selected != "") ? true : false;
574 var opt = new Option(display, value, selected);
575 opt.selected = selected;
576 user.options.add(opt);
582 startRequest : function(callback, args, forceAbort) {
583 if(this.currentRequestObject != null) {
584 if(this.forceAbort == true) {
585 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
588 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
592 requestInProgress : function() {
593 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
598 updateFolderSubscriptions : function() {
599 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
600 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
606 updateFrameFolder : function() {
607 SUGAR.email2.folders.checkEmailAccounts();
612 updateUserPrefs : function(o) {
613 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
614 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
619 uploadAttachmentSuccessful : function(o) {
621 document.getElementById('email_attachment').value = '';
623 var ret = JSON.parse(o.responseText);
624 var idx = SUGAR.email2.composeLayout.currentInstanceId;
625 var overall = document.getElementById('addedFiles' + idx);
626 var index = overall.childNodes.length;
628 "<div id='email_attachment_bucket" + idx + index + "'>" +
630 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
631 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
632 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
634 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
635 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
637 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
639 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
642 overall.innerHTML += out;
643 if(SUGAR.email2.util.isIe()) {
644 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
648 SUGAR.email2.addFileDialog.hide();
650 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
655 ///////////////////////////////////////////////////////////////////////////
656 //// PER MODULE CALLBACK OBJECTS
657 AjaxObject.accounts = {
658 saveOutboundCleanup : function(o) {
659 SUGAR.email2.accounts.refreshOuboundAccountTable();
660 SUGAR.email2.accounts.outboundDialog.hide();
661 var id = o.responseText;
662 SUGAR.email2.accounts.newAddedOutboundId = id;
664 saveDefaultOutboundCleanup: function(o){
667 callbackEditOutbound : {
668 success : function(o)
670 var ret = JSON.parse(o.responseText);
672 SUGAR.email2.accounts.showAddSmtp();
675 document.getElementById("mail_id").value = ret.id;
676 document.getElementById("type").value = ret.type;
677 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
678 document.getElementById("mail_name").value = ret.name;
679 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
680 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
681 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
682 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
683 document.getElementById("mail_smtppass").value = ret.mail_smtppass;
684 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
685 SUGAR.email2.accounts.smtp_authenticate_field_display();
686 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
688 if(ret.type == 'system-override') {
689 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
690 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
693 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
694 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
699 failure : AjaxObject.handleFailure,
700 timeout : AjaxObject.timeout,
703 callbackDeleteOutbound : {
704 success : function(o) {
705 var ret = JSON.parse(o.responseText);
708 if(confirm(ret.error_message))
710 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
711 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
719 SUGAR.email2.accounts.refreshOuboundAccountTable();
723 failure : AjaxObject.handleFailure,
724 timeout : AjaxObject.timeout,
728 callbackCheckMailProgress : {
729 success : function(o) {
730 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
731 SUGAR.email2.accounts.totalMsgCount = -1;
734 //Check for server timeout / errors
735 var ret = JSON.parse(o.responseText);
738 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
740 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
741 SUGAR.email2.accounts.totalMsgCount = -1;
742 //SUGAR.email2.folders.rebuildFolders();
746 var currIeId = ret['ieid'];
749 var serverCount = ret.count;
751 if (ret['status'] == 'done') {
752 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
753 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
757 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
759 currIeId = SUGAR.email2.accounts.ieIds[i+1];
761 SUGAR.email2.accounts.totalMsgCount = -1;
766 else if (ret.mbox && ret.totalcount && ret.count) {
767 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
768 if (ret.count >= ret.totalcount) {
771 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
772 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
775 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
776 SUGAR.email2.accounts.totalMsgCount = -1;
781 SUGAR.email2.accounts.totalMsgCount = -1;
783 SUGAR.email2.folders.rebuildFolders();
784 SE.listView.refreshGrid();
785 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
786 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
787 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
788 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
790 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
791 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
792 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
793 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
794 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
797 failure : AjaxObject.handleFailure,
798 timeout : AjaxObject.timeout,
803 ///////////////////////////////////////////////////////////////////////////////
805 AjaxObject.composeLayout = {
807 * Populates the record id
809 saveDraftCleanup : function(o) {
811 var ret = JSON.parse(o.responseText);
813 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
814 else if (o.responseText)
815 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
819 AjaxObject.composeLayout.callback = {
821 success : AjaxObject.composeLayout.saveDraftCleanup,
822 failure : AjaxObject.handleFailure,
823 timeout : AjaxObject.timeout,
828 AjaxObject.detailView = {
830 * Pops-up a printable view of an email
832 displayPrintable : function(o) {
833 var ret = JSON.parse(o.responseText);
834 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
835 // 2 below must be in global context
837 meta['panelId'] = SUGAR.email2.util.getPanelId();
838 email = ret.meta.email;
839 if (typeof(email.cc) == 'undefined') {
843 var out = displayTemplate.exec({
844 'app_strings' : app_strings,
852 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
853 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
855 popup.document.write(out);
856 popup.document.close();
860 * Takes formatted response and creates a modal pop-over containing a title and content
862 displayView : function(o) {
863 var SED = SUGAR.email2.detailView;
864 var ret = JSON.parse(o.responseText);
866 if(!SED.viewDialog) {
867 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
871 constraintoviewport: true,
874 SED.viewDialog.renderEvent.subscribe(function() {
875 var content = this.body.firstChild;
876 var viewH = YAHOO.util.Dom.getViewportHeight();
878 this.body.style.overflow = "auto";
879 this.body.style.width = "800px";
880 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
884 SED.viewDialog.setHeader(ret.title);
885 SED.viewDialog.setBody(ret.html);
886 SED.viewDialog.render();
887 SED.viewDialog.show();
891 * Generates a modal popup to populate with the contents of bean's full EditView
893 showQuickCreateForm : function(o) {
894 var SED = SUGAR.email2.detailView;
895 var ret = JSON.parse(o.responseText);
897 if(!SED.quickCreateDialog) {
898 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
902 constraintoviewport: true,
906 SED.quickCreateDialog.renderEvent.subscribe(function() {
907 var viewH = YAHOO.util.Dom.getViewportHeight();
909 for (var i in this.body.childNodes) {
910 if (this.body.childNodes[i].clientHeight) {
911 contH += this.body.childNodes[i].clientHeight;
912 } else if (this.body.childNodes[i].offsetHeight) {
913 contH += this.body.childNodes[i].offsetHeight;
916 this.body.style.width = "800px";
917 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
918 this.body.style.overflow = "auto";
919 }, SED.quickCreateDialog);
921 SED.quickCreateDialog.hideEvent.subscribe(function(){
922 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
923 /*for(var qsField in qsFields){
924 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
925 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
928 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
931 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
933 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
934 SED.quickCreateDialog.render();
935 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
937 SED.quickCreateDialog.ieId = ret.ieId;
938 SED.quickCreateDialog.uid = ret.uid;
939 SED.quickCreateDialog.mbox = ret.mbox;
940 SED.quickCreateDialog.qcmodule = ret.module;
942 SED.quickCreateDialog.show();
944 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
946 editForm.module.value = 'Emails';
947 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
948 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
949 var instId = ret.module + count;
950 SED.quickCreateEmailsToAdd = ret.emailAddress;
951 SED.quickCreateEmailCallback = function(instId, tableId) {
952 var eaw = SUGAR.EmailAddressWidget.instances[instId];
953 if (typeof(eaw) == "undefined")
954 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
955 + instId + "','" + tableId + "');", 100);
956 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
958 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
959 + instId + "','" + tableId + "');", 100);
963 saveQuickCreateForm : function(o) {
965 SUGAR.email2.detailView.quickCreateDialog.hide();
966 validate['EditView'] = [ ];
969 saveQuickCreateFormAndReply : function(o) {
971 var ret = JSON.parse(o.responseText);
972 SUGAR.email2.detailView.quickCreateDialog.hide();
973 var qcd = SUGAR.email2.detailView.quickCreateDialog;
974 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
976 var emailID = ret.id;
977 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
979 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
981 //Cean the validate cache to prevent errors on the next call
982 validate['EditView'] = [ ];
985 saveQuickCreateFormAndAddToAddressBook : function(o) {
987 SUGAR.email2.detailView.quickCreateDialog.hide();
988 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
989 validate['EditView'] = [ ];
992 handleAssignmentDialogAssignAction : function() {
995 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
1001 var found_teams = false;
1002 var warning_message = mod_strings.LBL_WARN_NO_USERS;
1003 if(!found_teams && assign_user_id == '' )
1005 alert(warning_message);
1009 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1011 for(i=0; i<emailUids.length; i++) {
1013 uids += app_strings.LBL_EMAIL_DELIMITER;
1015 uids += emailUids[i];
1018 var row = SUGAR.email2.grid.getSelectedRows()[0];
1019 var data = SUGAR.email2.grid.getRecord(row).getData();
1020 var ieid = data.ieId;
1021 var mbox = data.mbox;
1022 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
1023 SUGAR.email2.contextMenus.assignToDialogue.hide();
1024 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
1028 handleAssignmentDialogDeleteAction : function() {
1029 // TO pass list of UIDS/emailIds
1030 var uids = SUGAR.email2.listView.getUidsFromSelection();
1031 var row = SUGAR.email2.grid.getSelections()[0];
1032 var ieid = row.data.ieId;
1033 var mbox = row.data.mbox;
1034 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
1035 SUGAR.email2.contextMenus.assignmentDialog.hide();
1036 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1042 showEmailDetailView : function(o) {
1044 var SED = SUGAR.email2.detailView;
1045 var ret = JSON.parse(o.responseText);
1047 if(!SED.quickCreateDialog) {
1048 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
1052 constraintoviewport: true,
1054 autofillheight: "body",
1057 SED.quickCreateDialog.renderEvent.subscribe(function() {
1058 var viewHeight = YAHOO.util.Dom.getViewportHeight();
1060 for (var i in this.body.childNodes) {
1061 if (this.body.childNodes[i].offsetHeight)
1062 contH += this.body.childNodes[i].offsetHeight;
1064 this.body.style.overflow = "auto";
1065 this.body.style.width = "800px";
1066 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
1068 }, SED.quickCreateDialog);
1070 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
1071 SED.quickCreateDialog.setBody(ret.html);
1072 SED.quickCreateDialog.render();
1073 SUGAR.util.evalScript(ret.html);
1074 SED.quickCreateDialog.show();
1077 showAssignmentDialogWithData : function(o) {
1078 var SEC = SUGAR.email2.contextMenus;
1080 var ret = JSON.parse(o.responseText);
1081 if (!SEC.assignmentDialog) {
1082 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
1085 constraintoviewport: true,
1088 SEC.assignmentDialog.setBody("");
1089 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
1090 SEC.assignmentDialog.renderEvent.subscribe(function() {
1091 var iev = YAHOO.util.Dom.get("Distribute");
1093 this.body.style.width = "700px";
1095 }, SEC.assignmentDialog);
1096 SEC.assignmentDialog.render();
1098 SEC.assignmentDialog.setBody(ret);
1099 SEC.assignmentDialog.render();
1101 SEC.assignmentDialog.show();
1102 SUGAR.util.evalScript(ret);
1105 showImportForm : function(o) {
1106 var SED = SUGAR.email2.detailView;
1107 var ret = JSON.parse(o.responseText);
1109 document.getElementById('quickCreateContent').innerHTML = "";
1115 if(!SED.importDialog) {
1116 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
1120 constraintoviewport: true,
1122 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
1123 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
1127 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
1128 SED.importDialog.setBody("");
1129 SED.importDialog.hideEvent.subscribe(function(){
1130 for(var i in QSFieldsArray) {
1131 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
1132 QSFieldsArray[i].destroy();
1133 delete QSFieldsArray[i];
1135 if (QSProcessedFieldsArray[i]) {
1136 QSProcessedFieldsArray[i] = false;
1140 SED.importDialog.renderEvent.subscribe(function() {
1141 var iev = YAHOO.util.Dom.get("ImportEditView");
1143 //this.body.style.height = (iev.clientHeight + 10) + "px";
1144 this.body.style.width = "600px";
1146 }, SED.importDialog);
1147 SED.importDialog.render();
1149 SED.importDialog.setBody(ret.html);
1150 SED.importDialog.ret = ret;
1151 SUGAR.util.evalScript(ret.html);
1152 SED.importDialog.render();
1154 SED.importDialog.show();
1155 SED.importDialog.focusFirstButton();
1157 getImportAction : function(ret) {
1158 if (!check_form('ImportEditView')) return false;
1159 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
1160 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
1164 var editView = document.getElementById('ImportEditView');
1165 if (editView.assigned_user_id != null) {
1166 get = get + "&user_id=" + editView.assigned_user_id.value
1167 //var user_id = editView.assigned_user_id.value;
1169 var parent_id = editView.parent_id.value;
1170 var parent_type = editView.parent_type.value;
1171 var row = SUGAR.email2.grid.getSelectedRows()[0];
1172 row = SUGAR.email2.grid.getRecord(row);
1173 var data = row.getData();
1174 var ieId = data.ieId;
1175 var mbox = data.mbox;
1176 var serverDelete = editView.serverDelete.checked;
1177 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1179 for(i=0; i<emailUids.length; i++) {
1181 uids += app_strings.LBL_EMAIL_DELIMITER;
1183 uids += emailUids[i];
1186 var action = 'importEmail&uid=';
1188 action = 'moveEmails';
1189 action = action + '&sourceFolder=' + ret['srcFolder'];
1190 action = action + '&sourceIeId=' + ret['srcIeId'];
1191 action = action + '&destinationFolder=' + ret['dstFolder'];
1192 action = action + '&destinationIeId=' + ret['dstIeId'];
1193 action = action + '&emailUids=';
1195 if (action.search(/importEmail/) != -1) {
1196 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
1198 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
1201 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
1202 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
1203 SUGAR.email2.detailView.importDialog.hide();
1204 document.getElementById('importDialogContent').innerHTML = "";
1207 showRelateForm : function(o) {
1208 var SED = SUGAR.email2.detailView;
1209 var ret = JSON.parse(o.responseText);
1210 document.getElementById('quickCreateContent').innerHTML = "";
1215 dialog_loaded = true;
1217 if(!SED.relateDialog) {
1218 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
1223 constraintoviewport: true,
1225 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
1226 if (!check_form('RelateEditView')) return false;
1228 var editView = document.getElementById('RelateEditView');
1229 var parent_id = editView.parent_id.value;
1230 var parent_type = editView.parent_type.value;
1231 var row = SUGAR.email2.grid.getSelectedRows()[0];
1232 row = SUGAR.email2.grid.getRecord(row);
1233 var ieId = row.getData().ieId;
1234 var mbox = row.getData().mbox;
1235 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1237 for(i=0; i<emailUids.length; i++) {
1239 uids += app_strings.LBL_EMAIL_DELIMITER;
1241 uids += emailUids[i];
1243 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1244 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
1245 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
1246 SED.relateDialog.hide();
1247 document.getElementById('relateDialogContent').innerHTML = "";
1252 SED.relateDialog.hideEvent.subscribe(function(){
1253 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
1254 QSFieldsArray['ImportEditView_parent_name'].destroy();
1255 delete QSFieldsArray['ImportEditView_parent_name'];
1257 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
1258 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
1262 SED.relateDialog.renderEvent.subscribe(function() {
1263 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
1265 for (var i in this.body.childNodes) {
1266 if (this.body.childNodes[i].clientHeight)
1267 contH += this.body.childNodes[i].clientHeight;
1269 }, SED.relateDialog);
1270 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
1273 SED.relateDialog.setBody(ret.html);
1274 SED.relateDialog.render();
1275 SUGAR.util.evalScript(ret.html);
1276 SED.relateDialog.show();
1280 * DetailView callbacks
1282 AjaxObject.detailView.callback = {
1284 success : function(o) {
1286 var ret = JSON.parse(o.responseText);
1287 SUGAR.email2.detailView.consumeMetaDetail(ret);
1289 argument: [targetDiv],
1290 failure : AjaxObject.handleFailure,
1295 success : function(o) {
1297 var ret = JSON.parse(o.responseText);
1298 SUGAR.email2.detailView.consumeMetaPreview(ret);
1300 failure : AjaxObject.handleFailure,
1305 success : AjaxObject.detailView.displayPrintable,
1306 failure : AjaxObject.handleFailure,
1307 timeout : AjaxObject.timeout,
1311 success : AjaxObject.detailView.displayView,
1312 failure : AjaxObject.handleFailure,
1313 timeout : AjaxObject.timeout,
1322 AjaxObject.folders = {
1324 * check-mail post actions
1326 checkMailCleanup : function(o) {
1328 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
1330 // refresh focus ListView
1331 SE.listView.refreshGrid();
1332 SUGAR.email2.folders.startCheckTimer(); // resets the timer
1337 rebuildFolders : function(o) {
1340 var data = JSON.parse(o.responseText);
1342 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
1343 SUGAR.email2.folders.setSugarFolders();
1346 AjaxObject.folders.callback = {
1348 success : AjaxObject.folders.checkMailCleanup,
1349 failure : AjaxObject.handleFailure,
1350 timeout : 600000, // 5 mins
1355 AjaxObject.rules = {
1356 loadRulesForSettings : function(o) {
1357 document.getElementById("rulesListCell").innerHTML = o.responseText;
1358 // assume we have the class we need
1359 SUGAR.routing.getStrings();
1360 SUGAR.routing.getDependentDropdowns();
1363 //// END PER MODULE CALLBACK OBJECTS
1364 ///////////////////////////////////////////////////////////////////////////
1368 success : AjaxObject.handleSuccess,
1369 failure : AjaxObject.handleFailure,
1370 timeout : AjaxObject.timeout,
1373 var callbackAccount = {
1374 success : AjaxObject.ieSaveSuccess,
1375 failure : AjaxObject.handleFailure,
1376 timeout : AjaxObject.timeout,
1379 var callbackAccountDelete = {
1380 success : AjaxObject.ieDeleteSuccess,
1381 failure : AjaxObject.handleFailure,
1382 timeout : AjaxObject.timeout,
1385 var callbackOutboundTest = {
1386 success : AjaxObject.ieSendSuccess,
1387 failure : AjaxObject.handleFailure,
1388 timeout : AjaxObject.timeout,
1394 var callbackTeamInfoForSettings = {
1395 success : function (o) {
1396 var data = JSON.parse(o.responseText);
1397 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
1399 failure : AjaxObject.handleFailure,
1400 timeout : AjaxObject.timeout,
1405 var callbackStatusForImport = {
1406 success : function (o) {
1408 if (o.responseText != "") {
1409 var statusString = "";
1410 var data = JSON.parse(o.responseText);
1411 for(i=0; i<data.length; i++) {
1412 statusString = statusString + data[i] + '<br/>';
1414 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
1416 SE.listView.refreshGrid();
1419 failure : AjaxObject.handleFailure,
1420 timeout : AjaxObject.timeout,
1424 var callbackComposeCache = {
1425 success : AjaxObject.composeCache,
1426 failure : AjaxObject.handleFailure,
1427 timeout : AjaxObject.timeout,
1430 var callbackDelete = {
1431 success : AjaxObject.handleDeleteReturn,
1432 failure : AjaxObject.handleFailure,
1433 timeout : AjaxObject.timeout,
1436 var callbackEmailDetailMultiple = {
1437 success : function(o) {
1439 var retMulti = JSON.parse(o.responseText);
1440 var ret = new Object();
1442 for(var i=0; i<retMulti.length; i++) {
1445 SUGAR.email2._setDetailCache(ret);
1446 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
1449 failure : AjaxObject.handleFailure,
1453 var callbackListViewSortOrderChange = {
1454 success : AjaxObject.saveListViewSortOrderPart2,
1455 failure : AjaxObject.handleFailure,
1456 timeout : AjaxObject.timeout,
1458 argument : [ieId, ieName, focusFolder]
1460 var callbackEmptyTrash = {
1461 success : function(o) {
1463 AjaxObject.folderRenameCleanup;
1465 failure : AjaxObject.handleFailure,
1466 timeout : AjaxObject.timeout,
1469 var callbackClearCacheFiles = {
1470 success : function(o) {
1473 failure : AjaxObject.handleFailure,
1474 timeout : AjaxObject.timeout,
1477 var callbackFolderRename = {
1478 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
1479 failure : AjaxObject.handleFailure,
1480 timeout : AjaxObject.timeout,
1483 var callbackFolderDelete = {
1484 success : function(o) {
1485 var ret = JSON.parse(o.responseText);
1487 if (ret.folder_id) {
1488 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
1490 SUGAR.email2.tree.removeNode(node, true);
1491 } else if (ret.ieId && ret.mbox) {
1492 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
1494 SUGAR.email2.tree.removeNode(node, true);
1497 //SUGAR.email2.folders.loadSettingFolder();
1500 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
1503 failure : AjaxObject.handleFailure,
1504 timeout : AjaxObject.timeout,
1507 var callbackFolderSave = {
1508 success : function(o) {
1509 var ret = JSON.parse(o.responseText);
1511 switch(ret.action) {
1512 case 'newFolderSave':
1513 SUGAR.email2.folders.rebuildFolders();
1517 failure : AjaxObject.handleFailure,
1518 timeout : AjaxObject.timeout,
1521 var callbackFolderSubscriptions = {
1522 success : AjaxObject.updateFolderSubscriptions,
1523 failure : AjaxObject.handleFailure,
1524 timeout : AjaxObject.timeout,
1527 var callbackFolderUpdate = {
1528 success : AjaxObject.updateFrameFolder,
1529 failure : AjaxObject.handleFailure,
1530 timeout : AjaxObject.timeout,
1533 var callbackFolders = {
1534 success : AjaxObject.folders.rebuildFolders,
1535 //success : void(true),
1536 failure : AjaxObject.handleFailure,
1537 timeout : AjaxObject.timeout,
1540 var callbackFullSync = {
1541 success : AjaxObject.fullSyncCleanup,
1542 failure : AjaxObject.handleFailure,
1543 timeout : 9999999999999,
1546 var callbackGeneric = {
1547 success : function() {
1550 failure : AjaxObject.handleFailure,
1551 timeout : AjaxObject.timeout,
1554 var callbackIeAccountRetrieve = {
1555 success : function(o) {
1556 // return JSON encoding
1558 SUGAR.email2.accounts.fillIeAccount(o.responseText);
1559 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
1561 failure : AjaxObject.handleFailure,
1562 timeout : AjaxObject.timeout,
1565 var callbackImportOneEmail = {
1566 success : AjaxObject.detailView.showImportForm,
1567 failure : AjaxObject.handleFailure,
1568 timeout : AjaxObject.timeout,
1571 var callbackRelateEmail = {
1572 success : AjaxObject.detailView.showRelateForm,
1573 failure : AjaxObject.handleFailure,
1574 timeout : AjaxObject.timeout,
1577 var callbackEmailDetailView = {
1578 success : AjaxObject.detailView.showEmailDetailView,
1579 failure : AjaxObject.handleFailure,
1580 timeout : AjaxObject.timeout,
1583 var callbackAssignmentDialog = {
1584 success : AjaxObject.detailView.showAssignmentDialogWithData,
1585 failure : AjaxObject.handleFailure,
1586 timeout : AjaxObject.timeout,
1589 var callbackAssignmentAction = {
1590 success : function(o) {
1591 SE.listView.refreshGrid();
1593 if(o.responseText != '') {
1594 overlay('Assignment action result', o.responseText, 'alert');
1597 failure : AjaxObject.handleFailure,
1598 timeout : AjaxObject.timeout,
1601 var callbackMoveEmails = {
1602 success : function(o) {
1603 SE.listView.refreshGrid();
1605 if(o.responseText != '') {
1606 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
1609 failure : AjaxObject.handleFailure,
1610 timeout : AjaxObject.timeout,
1613 var callbackLoadAttachments = {
1614 success : AjaxObject.loadAttachments,
1615 failure : AjaxObject.handleFailure,
1616 timeout : AjaxObject.timeout,
1619 var callbackLoadRules = {
1620 success : AjaxObject.rules.loadRulesForSettings,
1621 failure : AjaxObject.handleFailure,
1622 timeout : AjaxObject.timeout,
1625 var callbackLoadSignature = {
1626 success : AjaxObject.loadSignature,
1627 failure : AjaxObject.handleFailure,
1628 timeout : AjaxObject.timeout,
1631 var callbackDeleteSignature = {
1632 success : AjaxObject.handleDeleteSignature,
1633 failure : AjaxObject.handleFailure,
1634 timeout : AjaxObject.timeout,
1637 /*var callbackMoveEmails = {
1638 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
1639 failure : AjaxObject.handleFailure,
1640 timeout : AjaxObject.timeout,
1643 var callbackOutboundSave = {
1644 success : AjaxObject.accounts.saveOutboundCleanup,
1645 failure : AjaxObject.handleFailure,
1646 timeout : AjaxObject.timeout,
1649 var callbackDefaultOutboundSave = {
1650 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
1651 failure : AjaxObject.handleFailure,
1652 timeout : AjaxObject.timeout,
1655 var callbackQuickCreate = {
1656 success : AjaxObject.detailView.showQuickCreateForm,
1657 failure : AjaxObject.handleFailure,
1658 timeout : AjaxObject.timeout,
1661 var callbackQuickCreateSave = {
1662 success : AjaxObject.detailView.saveQuickCreateForm,
1663 failure : AjaxObject.handleFailure,
1664 timeout : AjaxObject.timeout,
1667 var callbackQuickCreateSaveAndAddToAddressBook = {
1668 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
1669 failure : AjaxObject.handleFailure,
1670 timeout : AjaxObject.timeout,
1673 var callbackQuickCreateSaveAndReply = {
1674 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
1675 failure : AjaxObject.handleFailure,
1676 timeout : AjaxObject.timeout,
1679 var callbackQuickCreateSaveAndReplyCase = {
1680 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
1681 failure : AjaxObject.handleFailure,
1682 timeout : AjaxObject.timeout,
1685 var callbackRebuildShowAccountList = {
1686 success : AjaxObject.rebuildShowFolders,
1687 failure : AjaxObject.handleFailure,
1688 timeout : AjaxObject.timeout,
1692 var callbackRefreshSugarFolders = {
1693 success : function(o) {
1694 var t = JSON.parse(o.responseText);
1695 SUGAR.email2.folders.setSugarFoldersEnd(t);
1697 failure : AjaxObject.handleFailure,
1698 timeout : AjaxObject.timeout,
1701 var callbackReplyForward = {
1702 success : AjaxObject.handleReplyForward,
1703 finish : function(a, retryCount) {
1704 if (typeof(retryCount) == 'undefined') {
1709 var idx = SUGAR.email2.composeLayout.currentInstanceId;
1710 var t = tinyMCE.getInstanceById('htmleditor' + idx);
1712 var html = t.getContent();
1714 if (a.type != 'draft') {
1715 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
1716 html += " <div><hr></div>" + a.description;
1718 html = " <div><hr></div>" + a.description + html;
1721 html = a.description;
1724 t.setContent(html);//
1727 if (retryCount < 5) {
1728 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
1732 var tabArray = SUGAR.email2.innerLayout.get("tabs");
1733 if (tabArray != null && tabArray.length > 0) {
1734 for (i = 0 ; i < tabArray.length ; i++) {
1735 var tabObject = tabArray[i];
1736 if (tabObject.get("id") == ("composeTab" + idx)) {
1737 var tabLabel = a.name;
1738 if (tabLabel != null && tabLabel.length > 25) {
1739 tabLabel = tabLabel.substring(0, 25) + "...";
1741 tabObject.get("labelEl").firstChild.data = tabLabel;
1747 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
1748 if (a.parent_name != null && a.parent_name != "") {
1749 document.getElementById('data_parent_name' + idx).value = a.parent_name;
1751 if (a.parent_type != null && a.parent_type != "") {
1752 document.getElementById('data_parent_type' + idx).value = a.parent_type;
1754 if (a.parent_id != null && a.parent_id != "") {
1755 document.getElementById('data_parent_id' + idx).value = a.parent_id;
1757 if (a.fromAccounts.status) {
1758 var addressFrom = document.getElementById('addressFrom' + idx);
1759 SUGAR.email2.util.emptySelectOptions(addressFrom);
1760 var fromAccountOpts = a.fromAccounts.data;
1761 for(i=0; i<fromAccountOpts.length; i++) {
1762 var key = fromAccountOpts[i].value;
1763 var display = fromAccountOpts[i].text;
1764 var opt = new Option(display, key);
1765 if (fromAccountOpts[i].selected) {
1766 opt.selected = true;
1768 addressFrom.options.add(opt);
1774 failure : AjaxObject.handleFailure,
1775 timeout : AjaxObject.timeout,
1777 argument : [sendType]
1779 var callbackSendEmail = {
1780 success : AjaxObject.sendEmailCleanUp,
1781 failure : AjaxObject.handleFailure,
1782 timeout : AjaxObject.timeout,
1785 var callbackSettings = {
1786 success : AjaxObject.updateUserPrefs,
1787 failure : AjaxObject.handleFailure,
1788 timeout : AjaxObject.timeout,
1791 var callbackSettingsFolderRefresh = {
1792 success : AjaxObject.settingsFolderRefresh,
1793 failure : AjaxObject.handleFailure,
1794 timeout : AjaxObject.timeout,
1797 var callbackLoadSettingFolder = {
1798 success : function(o) {
1799 AjaxObject.settingsFolderRefresh(o);
1800 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
1802 failure : AjaxObject.handleFailure,
1803 timeout : AjaxObject.timeout,
1807 var callbackUploadAttachment = {
1808 success : AjaxObject.uploadAttachmentSuccessful,
1809 upload : AjaxObject.uploadAttachmentSuccessful,
1810 failure : AjaxObject.handleFailure,
1811 timeout : AjaxObject.timeout,
1814 var callbackUserPrefs = {
1815 success : function(o) {
1816 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
1818 failure : AjaxObject.handleFailure,
1819 timeout : AjaxObject.timeout,
1823 var callbackContextmenus = {
1825 success : AjaxObject.markEmailCleanup,
1826 failure : AjaxObject.handleFailure,
1827 timeout : AjaxObject.timeout,
1832 var callbackCheckEmail2 = {
1833 success : function(o) {
1834 var ret = JSON.parse(o.responseText);
1835 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
1839 failure : AjaxObject.handleFailure,
1840 timeout : AjaxObject.timeout,
1842 }// End of File modules/Emails/javascript/ajax.js
1844 /*********************************************************************************
1845 * SugarCRM is a customer relationship management program developed by
1846 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
1848 * This program is free software; you can redistribute it and/or modify it under
1849 * the terms of the GNU Affero General Public License version 3 as published by the
1850 * Free Software Foundation with the addition of the following permission added
1851 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
1852 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
1853 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
1855 * This program is distributed in the hope that it will be useful, but WITHOUT
1856 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1857 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
1860 * You should have received a copy of the GNU Affero General Public License along with
1861 * this program; if not, see http://www.gnu.org/licenses or write to the Free
1862 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
1865 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
1866 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
1868 * The interactive user interfaces in modified source and object code versions
1869 * of this program must display Appropriate Legal Notices, as required under
1870 * Section 5 of the GNU Affero General Public License version 3.
1872 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
1873 * these Appropriate Legal Notices must retain the display of the "Powered by
1874 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
1875 * technical reasons, the Appropriate Legal Notices must display the words
1876 * "Powered by SugarCRM".
1877 ********************************************************************************/
1879 function gridInit() {
1880 if(SUGAR.email2.grid) {
1881 SUGAR.email2.grid.destroy();
1887 var Ck = YAHOO.util.Cookie;
1888 var widths = [ 10, 10, 150, 250, 175, 125 ];
1890 if (Ck.get("EmailGridWidths")) {
1891 for (var i=0; i < widths.length; i++) {
1892 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
1895 for (var i=0; i < widths.length; i++) {
1896 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
1900 // changes "F" to an icon
1901 function flaggedIcon(cell, record, column, value) {
1903 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
1906 // changes "A" to replied icon
1907 function repliedIcon(cell, record, column, value) {
1909 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
1912 function attachIcon(cell, record, column, value) {
1914 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
1921 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
1926 formatter: attachIcon,
1930 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
1935 formatter: flaggedIcon,
1939 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
1944 formatter: repliedIcon,
1948 label: app_strings.LBL_EMAIL_FROM,
1955 label: app_strings.LBL_EMAIL_SUBJECT,
1962 label: mod_strings.LBL_LIST_DATE,
1969 label: app_strings.LBL_EMAIL_TO,
2005 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2006 responseType: YAHOO.util.DataSource.TYPE_JSON,
2008 resultsList: 'Email',
2009 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
2010 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
2016 action : "EmailUIAjax",
2017 emailUIAction : "getMessageList",
2020 forceRefresh : "false"
2022 if(lazyLoadFolder != null) {
2023 params['mbox'] = lazyLoadFolder.folder;
2024 params['ieId'] = lazyLoadFolder.ieId;
2025 //Check if the folder is a Sugar Folder
2026 var test = new String(lazyLoadFolder.folder);
2027 if(test.match(/SUGAR\./)) {
2028 params['emailUIAction'] = 'getMessageListSugarFolders';
2029 params['mbox'] = test.substr(6);
2032 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
2035 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
2036 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2038 paginator: new YAHOO.widget.Paginator({
2039 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
2040 containers : ["dt-pag-nav"],
2041 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2042 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2043 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2044 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2045 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2047 initialRequest:SUGAR.util.paramsToUrl(params),
2054 //Override Paging request construction
2055 grid.set("generateRequest", function(oState, oSelf) {
2056 oState = oState || {pagination:null, sortedBy:null};
2057 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
2058 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2059 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2060 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2061 // Build the request
2063 SUGAR.util.paramsToUrl(oSelf.params) +
2066 "&start=" + startIndex +
2067 ((results !== null) ? "&limit=" + results : "");
2072 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2073 oPayload = oPayload || { };
2075 oPayload.totalRecords = oResponse.meta.total;
2076 oPayload.unreadRecords = oResponse.meta.unread;
2078 var tabObject = SE.innerLayout.get("tabs")[0];
2080 if (this.params.mbox != null) {
2081 mboxTitle = this.params.mbox;
2083 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
2084 tabObject.get("labelEl").firstChild.data = tabtext;
2087 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
2089 node.data.unseen = oResponse.meta.unread;
2090 SE.accounts.renderTree();
2096 var resize = grid.resizeGrid = function () {
2097 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
2098 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
2100 grid.convertDDRows = function() {
2101 var rowEl = this.getFirstTrEl();
2102 while (rowEl != null) {
2103 new this.DDRow(this, this.getRecord(rowEl), rowEl);
2104 rowEl = this.getNextTrEl(rowEl);
2109 grid.on("columnResizeEvent", function(o) {
2110 //Find the index of the column
2111 var colSet = SUGAR.email2.grid.getColumnSet().flat;
2112 for (var i=0; i < colSet.length; i++) {
2113 if (o.column == colSet[i]) {
2114 //Store it in the cookie
2115 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
2118 //this.resizeGrid();
2121 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
2122 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
2123 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
2125 SUGAR.email2.listViewLayout.on("render", resize);
2128 //Setup the default load parameters
2129 SUGAR.email2.grid.params = params;
2131 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
2132 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2133 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2140 function initRowDD() {
2141 var sg = SUGAR.email2.grid,
2142 Dom = YAHOO.util.Dom;
2143 sg.DDRow = function(oDataTable, oRecord, elTr) {
2144 if(oDataTable && oRecord && elTr) {
2145 this.ddtable = oDataTable;
2146 this.table = oDataTable.getTableEl();
2149 this.newIndex = null;
2151 this.initFrame(); // Needed for DDProxy
2152 this.invalidHandleTypes = {};
2156 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
2157 _resizeProxy: function() {
2158 this.constructor.superclass._resizeProxy.apply(this, arguments);
2159 var dragEl = this.getDragEl(),
2161 var xy = Dom.getXY(el);
2163 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
2164 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
2165 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
2166 Dom.setStyle(dragEl, 'display', "");
2169 startDrag: function(x, y) {
2170 //Check if we should be dragging a set of rows rather than just the one.
2171 var selectedRows = this.ddtable.getSelectedRows();
2172 var iSelected = false;
2173 for (var i in selectedRows) {
2174 if (this.rowEl.id == selectedRows[i]) {
2181 for (var i in selectedRows) {
2182 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
2185 this.rows = [this.row];
2186 this.ddtable.unselectAllRows();
2187 this.ddtable.selectRow(this.row);
2190 //Initialize the dragable proxy
2191 var dragEl = this.getDragEl();
2192 var clickEl = this.getEl();
2193 Dom.setStyle(clickEl, "opacity", "0.25");
2194 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
2195 Dom.addClass(dragEl, "yui-dt-liner");
2196 Dom.setStyle(dragEl, "opacity", "0.5");
2197 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
2198 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
2199 Dom.setStyle(dragEl, "border", "2px solid gray");
2202 clickValidator: function(e) {
2203 if (this.row.getData()[0] == " ")
2205 var target = YAHOO.util.Event.getTarget(e);
2206 return ( this.isValidHandleChild(target) &&
2207 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
2210 * This funciton checks that the target of the drag is a table row in this
2211 * DDGroup and simply moves the sourceEL to that location as a preview.
2213 onDragOver: function(ev, id) {
2214 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
2215 if (node && node != this.targetNode) {
2216 this.targetNode = node;
2217 SUGAR.email2.folders.unhighliteAll();
2222 onDragOut: function(e, id) {
2223 if (this.targetNode) {
2224 SUGAR.email2.folders.unhighliteAll();
2225 this.targetNode = false;
2228 endDrag: function() {
2229 Dom.setStyle(this.getEl(), "opacity", "");
2230 Dom.setStyle(this.getDragEl(), "display", "none");
2231 if (this.targetNode) {
2232 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
2234 SUGAR.email2.folders.unhighliteAll();
2240 function AddressSearchGridInit() {
2241 function moduleIcon(elCell, oRecord, oColumn, oData) {
2242 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
2244 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
2245 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
2247 var checkHeader = '<input type="checkbox" ';
2248 if (SUGAR.email2.util.isIe()) {
2249 checkHeader += 'style="top:-5px" ';
2251 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
2256 formatter: selectionCheckBox,
2260 label: mod_strings.LBL_LIST_TYPE,
2262 formatter: moduleIcon,
2266 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
2272 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
2278 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2279 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
2281 resultsList: 'Person',
2282 fields: ['name', 'email', 'bean_id', 'bean_module'],
2283 metaFields: {total: 'TotalCount'}
2285 //enable sorting on the server accross all data
2288 dataModel.params = {
2291 action : "EmailUIAjax",
2292 emailUIAction:"getAddressSearchResults"
2294 var rb = document.getElementById('hasRelatedBean').checked;
2296 var idx = SUGAR.email2.composeLayout.currentInstanceId;
2297 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2298 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2299 dataModel.params['related_bean_id'] = relatedBeanId;
2300 dataModel.params['related_bean_type'] = relatedBeanType;
2301 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
2303 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
2305 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
2306 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2308 paginator: new YAHOO.widget.Paginator({
2310 containers : ["dt-pag-nav-addressbook"],
2311 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2312 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
2313 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
2314 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
2315 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
2317 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
2321 //Override Paging request construction
2322 grid.set("generateRequest", function(oState, oSelf) {
2323 oState = oState || {pagination:null, sortedBy:null};
2324 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
2325 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2326 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2327 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2328 // Build the request
2330 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
2331 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
2332 ((results !== null) ? "&limit=" + results : "");
2336 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
2337 oPayload = oPayload || { };
2338 oPayload.totalRecords = oResponse.meta.total;
2342 grid.clickToggleSelect= function(args) {
2343 var isIE = (args.event.target == null);
2344 var targetElement = isIE ? args.event.srcElement : args.event.target;
2345 if(targetElement.type == null || targetElement.type != 'checkbox') {
2346 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
2350 grid.reSelectRowsOnRender = function (){
2351 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2352 for (var i = 0; i < rows.length; i++)
2354 var emailAddress = rows[i].getData("email");
2355 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
2358 rows[i].setData("selected", true);
2359 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2363 rows[i].setData("selected", false);
2364 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
2368 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
2369 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
2370 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
2371 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
2374 dataModel.subscribe("requestEvent", grid.disable, grid, true);
2375 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2377 grid.toggleSelectCheckbox = function(id,checked){
2378 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2379 row.setData("checked",checked);
2381 grid.toggleSelect = function(id, checked) {
2382 var row = SUGAR.email2.addressBook.grid.getRecord(id);
2383 checked = row.getData("selected");
2386 SUGAR.email2.addressBook.grid.selectRow(row);
2387 SE.addressBook.insertContactRowToResultTable(id,null)
2390 SUGAR.email2.addressBook.grid.unselectRow(row);
2391 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
2393 row.setData("selected", !checked);
2396 grid.toggleSelectAll = function(checked) {
2397 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2398 for (var i = 0; i < rows.length; i++) {
2399 if (typeof(rows[i]) != "undefined")
2400 rows[i].setData("checked", checked);
2402 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2403 for (var i = 0; i < checkBoxes.length; i++) {
2404 checkBoxes[i].checked = checked;
2408 //Initialize the grid result table.
2409 AddressSearchResultsGridInit();
2415 * Initalize the results table for the address book selection.
2418 function AddressSearchResultsGridInit()
2421 /* Full name sort funciton to compare by last name if available */
2422 var fullNameSort = function(a, b, desc) {
2423 // Deal with empty values
2424 if(!YAHOO.lang.isValue(a))
2425 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
2426 else if(!YAHOO.lang.isValue(b))
2429 var aNames = a.getData("name").split(' ');
2430 var bNames = b.getData("name").split(' ');
2432 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
2433 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
2435 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
2439 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
2440 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
2441 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
2443 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})},
2444 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
2446 var myDataSource = new YAHOO.util.DataSource([]);
2447 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
2448 myDataSource.responseSchema = {
2449 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
2452 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
2453 width: "350px",height: "250px", MSG_EMPTY: " "});
2455 var highlightEditableCell = function(oArgs) {
2456 var elCell = oArgs.target;
2457 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
2458 this.highlightCell(elCell);
2462 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
2463 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
2464 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
2465 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
2466 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
2468 //Setup the context menus
2469 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
2470 var task = p_aArgs[1];
2473 var elRow = this.contextEventTarget;
2474 elRow = p_myDataTable.getTrEl(elRow);
2481 var oRecord = p_myDataTable.getRecord(elRow);
2482 p_myDataTable.deleteRow(elRow);
2483 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2488 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
2489 {trigger:gridResults.getTbodyEl()});
2490 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
2491 contextMenu.render("addrSearchResultGrid");
2492 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
2494 // End of File modules/Emails/javascript/grid.js
2496 /*********************************************************************************
2497 * SugarCRM is a customer relationship management program developed by
2498 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
2500 * This program is free software; you can redistribute it and/or modify it under
2501 * the terms of the GNU Affero General Public License version 3 as published by the
2502 * Free Software Foundation with the addition of the following permission added
2503 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
2504 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
2505 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
2507 * This program is distributed in the hope that it will be useful, but WITHOUT
2508 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
2509 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
2512 * You should have received a copy of the GNU Affero General Public License along with
2513 * this program; if not, see http://www.gnu.org/licenses or write to the Free
2514 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
2517 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
2518 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
2520 * The interactive user interfaces in modified source and object code versions
2521 * of this program must display Appropriate Legal Notices, as required under
2522 * Section 5 of the GNU Affero General Public License version 3.
2524 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
2525 * these Appropriate Legal Notices must retain the display of the "Powered by
2526 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
2527 * technical reasons, the Appropriate Legal Notices must display the words
2528 * "Powered by SugarCRM".
2529 ********************************************************************************/
2532 var sw = YAHOO.SUGAR,
2533 Event = YAHOO.util.Event,
2534 Connect = YAHOO.util.Connect,
2535 Dom = YAHOO.util.Dom
2538 ///////////////////////////////////////////////////////////////////////////////
2541 _contactCache : new Array(), // cache of contacts
2542 _dd : new Array(), // filtered list, same format as _contactCache
2543 _ddLists : new Array(), // list of Lists
2544 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
2545 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
2546 clickBubble : true, // hack to get around onclick event bubbling
2548 relatedBeanType : '',
2551 itemSpacing : 'white-space:nowrap; padding:2px;',
2557 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
2559 initFixForDatatableSort: function () {
2560 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
2561 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
2562 var oColumn = this._oColumnSet.getColumn(column);
2565 // Validate TD element
2566 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
2568 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
2570 // Validate TH element
2572 elCell = this.getThEl(column);
2575 var allColumns = this._oColumnSet.flat;
2576 for(var i=0, len=allColumns.length; i<len; i++) {
2577 if(allColumns[i].getThEl().id === elCell.id) {
2578 oColumn = allColumns[i];
2589 cancelEdit : function() {
2590 if(this.editContactDialog)
2591 this.editContactDialog.hide();
2592 if(this.editMailingListDialog)
2593 this.editMailingListDialog.hide();
2597 * Clears filter form
2599 clear : function() {
2600 var t = document.getElementById('contactsFilter');
2606 * handle context-menu Compose-to call
2607 * @param string type 'contacts' or 'lists'
2609 composeTo : function(type, waited) {
2610 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
2611 if (activePanel.substring(0, 10) != "composeTab") {
2612 SE.composeLayout.c0_composeNewEmail();
2613 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
2614 SE.contextMenus.contactsContextMenu.hide();
2617 var idx = activePanel.substring(10);
2620 // determine if we have a selection to work with
2621 if(type == 'contacts') {
2622 var ids = SE.contactView.getSelectedRows();
2623 for (var i in ids) {
2624 rows[i] = SE.contactView.getRecord(ids[i]);
2626 removeHiddenNodes(rows, SE.contactView);
2630 if(rows.length > 0) {
2631 SE.composeLayout.handleDrop(
2632 (type == 'contacts') ? SE.contactView : SE.emailListsView,
2633 null, rows, 'addressTO' + idx );
2635 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
2639 editContact : function() {
2640 SE.contextMenus.contactsContextMenu.hide();
2641 var element = SE.contactView.getSelectedNodes()[0];
2643 if (element.className.indexOf('address-contact') > -1) {
2644 elementId = element.id;
2645 } else if (element.className.indexOf('address-exp-contact') > -1) {
2646 elementId = element.id.substring(2);
2652 * Filters contact entries based on user input
2654 filter : function(inputEl) {
2655 var ret = new Object();
2656 var re = new RegExp(inputEl.value, "gi");
2658 for(var i in this._contactCache) {
2659 if(this._contactCache[i].name.match(re)) {
2660 ret[i] = this._contactCache[i];
2664 this.buildContactList(ret);
2667 fullForm : function(id, module) {
2668 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
2672 * returns a formatted email address from the addressBook cache
2674 getFormattedAddress : function(id) {
2675 var o = this._contactCache[id];
2676 var primaryEmail = '';
2678 for(var i=0; i<o.email.length; i++) {
2679 var currentEmail = o.email[i].email_address;
2681 if(o.email[i].primary_address == 1) {
2682 primaryEmail = o.email[i].email_address;
2686 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
2687 var name = new String(o.name);
2688 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
2689 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
2695 * Sets up async call to query for matching contacts, users, etc.
2697 searchContacts : function() {
2698 var fn = document.getElementById('input_searchField').value;
2699 var pe = document.getElementById('input_searchPerson').value;
2701 var rb = document.getElementById('hasRelatedBean').checked;
2704 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2705 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2706 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2707 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2709 this.addressBookDataModel.params['related_bean_id'] = '';
2712 this.addressBookDataModel.params['search_field'] = fn;
2713 this.addressBookDataModel.params['person'] = pe;
2714 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
2715 this.grid._oDataSource = this.addressBookDataModel;
2716 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
2720 * Clear Search Crieteria For Addressbook
2722 clearAddressBookSearch : function() {
2723 document.getElementById('input_searchField').value = "";
2724 document.getElementById('input_searchPerson').selectedIndex = 0;
2728 * Opens modal select window to add contacts to addressbook
2730 selectContactsDialogue : function(destId) {
2731 if(!this.contactsDialogue) {
2732 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
2736 constraintoviewport: true,
2738 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
2739 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
2741 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
2743 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
2744 dlg.setBody(body.innerHTML);
2745 dlg.renderEvent.subscribe(function() {
2746 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
2747 if (iev && !SUGAR.isIE) {
2748 this.body.style.width = "950px";
2753 dlg.beforeRenderEvent.subscribe(function() {
2754 var dd = new YAHOO.util.DDProxy(dlg.element);
2755 dd.setHandleElId(dlg.header);
2756 dd.on('endDragEvent', function() {
2762 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
2764 var tabContent = SUGAR.util.getAndRemove("searchForm");
2765 tp.addTab(new YAHOO.widget.Tab({
2766 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
2768 content : tabContent.innerHTML,
2769 id : "addressSearchTab",
2773 var addListenerFields = ['input_searchPerson','input_searchField' ]
2774 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
2775 if (e.keyCode == 13) {
2776 YAHOO.util.Event.stopEvent(e);
2777 SUGAR.email2.addressBook.searchContacts();
2781 this.contactsDialogue.render();
2784 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
2785 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
2789 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
2790 var idx = activePanel.substring(10);
2792 SE.addressBook.idx = idx;
2795 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
2796 document.getElementById('relatedBeanColumn').style.display = '';
2797 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
2798 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2799 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2800 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
2801 SE.addressBook.relatedBeanType = relatedBeanType;
2803 document.getElementById('relatedBeanColumn').style.display = 'none';
2804 document.getElementById('hasRelatedBean').checked = false;
2807 if (!SE.addressBook.grid)
2809 if (hasRelatedBeanId) {
2810 document.getElementById('hasRelatedBean').checked = true;
2812 AddressSearchGridInit();
2813 SE.addressBook.relatedBeanId = relatedBeanId;
2817 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
2819 SE.addressBook.relatedBeanId = relatedBeanId;
2820 document.getElementById('hasRelatedBean').checked = true;
2822 if (document.getElementById('hasRelatedBean').checked == true)
2824 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2825 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2827 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
2828 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
2830 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
2831 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
2832 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
2835 //Remove any lingering rows in the result set table if the module was closed.
2836 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2838 SE.addressBook.populateResulstTableEmailAddresses();
2840 this.contactsDialogue.show();
2843 * Clear all email addresses from result table.
2846 clearAllEmailAddressFieldsFromResultTable: function () {
2847 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2848 //Unhighlight any rows currently selected if the emails were cleared.
2849 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
2850 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2853 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
2854 * results table. This function is called when the address book is displayed.
2856 populateResulstTableEmailAddresses: function () {
2858 var idx = SE.addressBook.idx;
2859 var emailFields = ['to','cc','bcc'];
2861 for(var k=0;k<emailFields.length;k++)
2863 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2864 var allEmails = document.getElementById(elKey).value;
2868 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
2870 for (var i=0; i<formatedEmails.length; i++)
2872 var t_name = formatedEmails[i].name;
2873 var t_emailAddr = formatedEmails[i].email_address;
2874 var displayEmail = t_name + ' <' + t_emailAddr + '>';
2876 t_name = displayEmail = t_emailAddr;
2878 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
2879 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
2880 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
2886 * Checks all entries in the result table against a particular email address, returning true
2887 * if the email address is found, false otherwise.
2889 doesEmailAdddressExistInResultTable: function(emailAddress)
2891 if(trim(emailAddress) == '')
2894 var emailAddressFound = false;
2895 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2896 for (var i=0; i < contacts.length; i++)
2898 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2899 //If we are adding to cc or bcc fields, make them visible.
2900 if(data.email_address == emailAddress)
2902 emailAddressFound = true;
2907 return emailAddressFound;
2910 * Takes all email addresses that the users wishes to add from the address book and populates the To
2911 * fields on the compose tab.
2913 populateEmailAddressFieldsFromResultTable: function()
2915 //Clear the fields first, all email addresses are stored in the address book
2916 var idx = SE.addressBook.idx;
2917 var emailFields = ['to','cc','bcc'];
2918 for(var k=0;k<emailFields.length;k++)
2920 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2921 document.getElementById(elKey).value = "";
2924 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2925 for (var i=0; i < contacts.length; i++)
2927 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2929 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
2930 //If we are adding to cc or bcc fields, make them visible.
2931 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
2932 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
2933 //Construct the target id
2934 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
2936 var target = document.getElementById(target_id);
2937 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
2940 //Delete all rows from the result set table
2941 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2944 SE.addressBook.contactsDialogue.hide()
2947 * Insert contacts into the result table.
2949 insertContactToResultTable : function(event,address_type) {
2951 var contactsDialogue = SE.addressBook.contactsDialogue;
2952 var contacts = SE.addressBook.grid.getSelectedRows();
2954 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2955 for (var i = 0; i < rows.length; i++)
2957 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
2959 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
2960 SE.addressBook.insertContactRowToResultTable(recId,address_type);
2961 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2962 rows[i].setData("selected",true);
2965 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2966 for (var i = 0; i < checkBoxes.length; i++) {
2967 checkBoxes[i].checked = false;
2973 insertContactRowToResultTable : function(rowId, addressType) {
2974 var data = SE.addressBook.grid.getRecord(rowId).getData();
2975 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
2977 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
2978 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
2979 if(addressType == null)
2980 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
2981 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});
2984 * Remove a row from the gridsResult table.
2986 removeRowFromGridResults : function(rowId,emailAddress)
2988 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2989 for (var i=0; i < contacts.length; i++)
2991 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
2992 var data = rec.getData();
2993 if(data.email_address == emailAddress)
2995 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
3000 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
3003 * Translates between the addressType To|Cc|Bcc labels/keys.
3005 translateAddresType: function(addressType,fromKey)
3007 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
3008 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
3009 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
3010 var mappingObject = {};
3013 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
3016 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
3017 mappingObject[displayCc] = 'cc';
3018 mappingObject[displayBcc] = 'bcc';
3021 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
3027 toggleSearchRowIcon : function(rowId,show)
3031 var idToShow = rowId + '_add_img';
3032 var idToHide = rowId + '_rm_img';
3036 var idToShow = rowId + '_rm_img';
3037 var idToHide = rowId + '_add_img';
3041 Dom.addClass(idToHide, "yui-hidden");
3042 Dom.removeClass(idToShow, "yui-hidden");
3045 * Determine if an entry has already been added to the grid results table to prevent duplicates.
3047 doesGridResultsEntryExist: function(emailAddrs)
3050 var contactExists = false;
3051 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
3052 for (var i=0; i < contacts.length; i++)
3054 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
3055 if(data.email_address == emailAddrs)
3057 contactExists = true;
3061 return contactExists;
3065 * adds an email address to a string, but first checks if it exists
3066 * @param string concat The string we are appending email addresses to
3067 * @param string addr Email address to add
3070 smartAddEmailAddressToComposeField : function(concat, addr) {
3071 var re = new RegExp(addr);
3073 if(!concat.match(re)) {
3075 concat += "; " + addr;
3084 //// END ADDRESS BOOK
3085 ///////////////////////////////////////////////////////////////////////////////
3089 ///////////////////////////////////////////////////////////////////////////////
3092 * Auto-complete object
3096 delimChar : [";", ","],
3100 prehighlightClassName : "yui-ac-prehighlight",
3103 instances : new Array(),
3106 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
3107 * @param object Contact from AddressBook
3110 getPrimaryAddress : function(contact) {
3111 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
3113 for(var eIndex in contact.email) {
3114 address = contact.email[eIndex].email_address;
3115 if(contact.email[eIndex].primary_address == 1) {
3116 return contact.email[eIndex].email_address;
3124 * initializes autocomplete widgets for a given compose view
3127 init : function(idx) {
3128 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
3129 "queryMatchContains" : false,
3130 "queryMatchSubset" : true
3133 this.instances[idx] = {
3140 // instantiate the autoComplete widgets
3141 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
3142 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
3143 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
3145 // enable hiding of interfering textareas
3146 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3147 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3148 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3150 // enable reshowing of hidden textareas
3151 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3152 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3153 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3155 // enable refreshes of contact lists
3156 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3157 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3158 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3161 refreshDataSource : function(sType, aArgs) {
3162 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
3164 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
3166 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
3167 idx = textBoxId.substr(9);
3169 idx = textBoxId.substr(10);
3172 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
3173 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
3174 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
3178 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
3180 returnDataSource : function(contacts) {
3181 var ret = new Array();
3182 for(var id in contacts) {
3183 if (contacts[id].name) {
3184 var primary = this.getPrimaryAddress(contacts[id]);
3186 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
3187 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
3189 for(var emailIndex in contacts[id].email) {
3190 ret[ret.length] = contacts[id].email[emailIndex].email_address;
3199 * Hides address textareas to prevent autocomplete dropdown from being obscured
3201 toggleTextareaHide : function(sType, aArgs) {
3202 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3206 if(textBoxId.indexOf("addressTO") > -1) {
3208 } else if(textBoxId.indexOf("addressCC") > -1) {
3211 idx = textBoxId.substr(9);
3213 // follow through if not BCC
3215 var cc = document.getElementById("addressCC" + idx);
3216 var bcc = document.getElementById("addressBCC" + idx);
3220 cc.style.visibility = 'hidden';
3222 bcc.style.visibility = 'hidden';
3229 * Redisplays the textareas after an address is commited
3231 toggleTextareaShow : function(sType, aArgs) {
3232 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3236 if(textBoxId.indexOf("addressTO") > -1) {
3238 } else if(textBoxId.indexOf("addressCC") > -1) {
3241 idx = textBoxId.substr(9);
3243 // follow through if not BCC
3245 document.getElementById("addressCC" + idx).style.visibility = 'visible';
3246 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
3251 //// END AUTOCOMPLETE
3252 ///////////////////////////////////////////////////////////////////////////////
3254 ///////////////////////////////////////////////////////////////////////////////
3257 * expands the options sidebar
3259 SE.composeLayout = {
3260 currentInstanceId : 0,
3263 outboundAccountErrors : null,
3264 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
3266 showAddressDetails : function(e) {
3267 var linkElement = document.getElementById("More"+e.id);
3268 var spanElement = document.getElementById("Detail"+e.id);
3269 var emailAddressList = e.value;
3270 if(e.value.length > 96)
3272 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
3273 var displayArray = [];
3274 for (var i=0; i<resultArray.length; i++)
3276 var t_name = resultArray[i].name;
3277 var t_emailAddr = resultArray[i].email_address;
3279 displayArray.push('<br/><' + t_emailAddr + '>');
3281 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
3284 var result = displayArray.join('<br/>');
3286 linkElement.style.display = "inline";
3287 linkElement.style.height="10px";
3288 linkElement.style.overflow="visible";
3289 spanElement.innerHTML = result;
3292 linkElement.style.display = "none";
3297 * Given a string of email address, return an array containing the name portion (if available)
3298 * and email portion.
3300 _getEmailArrayFromString : function (emailAddressList){
3303 while ((results = reg.exec(emailAddressList)) != null)
3305 orignial = results[0];
3306 parsedResult = results[0].replace(';', ':::::');
3307 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3311 while ((results = reg.exec(emailAddressList)) != null)
3313 orignial = results[0];
3314 parsedResult = results[0].replace(',', ':::::');
3315 emailAddressList = emailAddressList.replace (orignial, parsedResult);
3317 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
3318 var emailArr = emailAddressList.split(":::::");
3319 var resultsArray = [];
3321 for (var i=0; i<emailArr.length; i++)
3323 var rposition = emailArr[i].indexOf('<');
3324 var lposition = emailArr[i].indexOf('>');
3326 if(trim(emailArr[i]) != '')
3328 if(rposition != -1 && lposition != -1)
3330 var t_name = emailArr[i].substr(0, rposition-1);
3331 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
3332 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
3336 resultsArray.push({'name':'', 'email_address': emailArr[i]});
3340 return resultsArray;
3342 ///////////////////////////////////////////////////////////////////////////
3345 * Prepare bucket DIV and yui-ext tab panels
3347 _0_yui : function() {
3348 var idx = this.currentInstanceId;
3350 var composeTab = new YAHOO.SUGAR.ClosableTab({
3351 label: mod_strings.LNK_NEW_SEND_EMAIL,
3353 content : "<div id='htmleditordiv" + idx + "'/>",
3354 id : "composeTab" + idx,
3355 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
3358 SE.innerLayout.addTab(composeTab);
3360 // get template engine with template
3361 if (!SE.composeLayout.composeTemplate) {
3362 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
3365 // create Tab inner layout
3366 var composePanel = this.getComposeLayout();
3367 composePanel.getUnitByPosition("right").collapse();
3368 composePanel.autoSize();
3372 * Generate the quick compose layout
3373 * @method getQuickComposeLayout
3374 * @param {Pannel} parentPanel Parent pannel
3375 * @param {Object} o Options
3378 getQuickComposeLayout : function (parentPanel,o) {
3379 var idx = SE.composeLayout.currentInstanceId;
3381 //Before rendering the parent pannel we need to initalize the grid layout
3382 parentPanel.beforeRenderEvent.subscribe(function() {
3384 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3385 SE.composeLayout._createComposeLayout(idx);
3386 SE.composeLayout[idx].set('height', 350);
3387 SE.composeLayout[idx].render();
3391 //Wait until the Compose Layout has rendered, then add the
3392 //options tab and perform the tiny initialization.
3393 parentPanel.renderEvent.subscribe(function() {
3395 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3396 SE.composeLayout._initComposeOptionTabs(idx);
3397 SE.composeLayout[idx].getUnitByPosition("right").collapse();
3398 //Initialize tinyMCE
3399 if (!SUGAR.util.isTouchScreen())
3400 SE.composeLayout._1_tiny();
3401 //Init templates and address book
3402 SE.composeLayout._2_final();
3404 SE.composeLayout.quickCreateComposePackage(o);
3409 //Check if we have the div override for the shortcut bar
3410 if(typeof o.menu_id != 'undefined') {
3411 parentPanel.render(o.menu_id);
3413 parentPanel.render(document.body);
3416 return SE.composeLayout[idx];
3419 * Fill in all fields into the quick compose layout.
3420 * @method quickCreateComposePackage
3421 * @param {Object} o Options
3424 quickCreateComposePackage: function(o)
3426 //If we have a compose package fill in defaults.
3427 if (typeof(o.composePackage) != 'undefined')
3429 composePackage = o.composePackage; //Set the compose data object
3430 //Hijack this method called by composePackage as it's not need for quick creates.
3431 SE.composeLayout.c0_composeNewEmail = function(){};
3432 SE.composeLayout.composePackage(); //Fill in defaults.
3435 getComposeLayout : function() {
3436 var idx = SE.composeLayout.currentInstanceId;
3438 this._createComposeLayout(idx);
3439 SE.composeLayout[idx].render();
3440 this._initComposeOptionTabs(idx);
3442 return SE.composeLayout[idx];
3446 * Create the layout manager for the compose window.
3448 _createComposeLayout : function(idx)
3450 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
3451 parent: SE.complexLayout,
3461 SE.composeLayout.composeTemplate.exec({
3462 'app_strings':app_strings,
3463 'mod_strings':mod_strings,
3465 'linkbeans_options' : linkBeans,
3466 'idx' : SE.composeLayout.currentInstanceId
3477 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
3480 header: app_strings.LBL_EMAIL_OPTIONS
3486 * Create compose tab which will populate the 'right' container in the compose window.
3488 _initComposeOptionTabs : function(idx)
3490 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
3491 var tab = new YAHOO.widget.Tab({
3492 label: app_strings.LBL_EMAIL_ATTACHMENT,
3494 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
3495 id : "divAttachments" + idx,
3499 tab.layout = SE.composeLayout[idx];
3501 tab.on("activeChange", function(o){
3503 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
3509 tab = new YAHOO.widget.Tab({
3510 label: app_strings.LBL_EMAIL_OPTIONS,
3512 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
3513 id : "divOptions" + idx,
3517 tab.layout = SE.composeLayout[idx];
3518 tab.on("activeChange", function(o){
3520 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
3525 SE.composeLayout[idx].autoSize = function() {
3526 var pEl = this.get("element").parentNode.parentNode.parentNode;
3527 this.set("height", pEl.clientHeight-30);
3531 SE.composeLayout[idx].rightTabs = cTabs;
3533 isParentTypeValid : function(idx) {
3534 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3535 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3536 if (trim(parentTypeValue) == ""){
3537 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
3543 isParentTypeAndNameValid : function(idx) {
3544 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3545 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3546 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
3547 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
3548 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
3549 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
3555 callopenpopupForEmail2 : function(idx,options) {
3557 var formName = 'emailCompose' + idx;
3559 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
3560 formName = options.form_name;
3562 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3563 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3564 if (!SE.composeLayout.isParentTypeValid(idx)) {
3567 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
3569 call_back_function:"SE.composeLayout.popupAddEmail",
3571 field_to_name_array:{
3572 id:'data_parent_id' + idx,
3573 name:'data_parent_name' + idx,
3578 popupAddEmail : function(o)
3580 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
3581 var data = o.name_to_value_array;
3582 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
3583 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
3585 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
3586 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
3593 _1_tiny : function() {
3594 var idx = SE.composeLayout.currentInstanceId;
3595 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
3596 SE.tinyInstances[elId] = { };
3597 SE.tinyInstances[elId].ready = false;
3598 var t = tinyMCE.getInstanceById(elId);
3600 if(typeof(t) == 'undefined') {
3601 tinyMCE.execCommand('mceAddControl', false, elId);
3602 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
3603 SE.composeLayout.resizeEditor(idx);
3604 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
3609 resizeEditor : function(idx)
3611 var cof = Dom.get('composeOverFrame' + idx);
3612 var head = Dom.get('composeHeaderTable' + idx);
3613 var targetHeight = cof.clientHeight - head.clientHeight;
3614 var instance = tinyMCE.get(SE.tinyInstances.currentHtmleditor);
3616 var parentEl = Dom.get(instance.editorId + '_parent');
3617 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
3618 var contentEl = instance.contentAreaContainer;
3619 var iFrame = contentEl.firstChild;
3620 var tinMceToolbarOffset = 18;
3621 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
3625 * Initializes d&d, auto-complete, email templates
3627 _2_final : function() {
3628 var idx = SE.composeLayout.currentInstanceId;
3630 if(this.emailTemplates) {
3631 this.setComposeOptions(idx);
3633 //populate email template cache
3634 AjaxObject.target = '';
3635 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
3638 // handle drop targets for addressBook
3639 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3640 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3641 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3642 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
3644 // auto-complete setup
3645 SE.autoComplete.init(idx);
3648 document.getElementById("addressTO" + idx).focus();
3652 * hide tinyMCE tool bar if send email as plaintext is checked
3654 renderTinyMCEToolBar : function (idx, hide) {
3656 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
3658 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
3662 c1_composeEmail : function(isReplyForward, retry) {
3666 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
3667 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
3672 if(isReplyForward) {
3673 this.replyForwardEmailStage2();
3679 * takes draft info and prepopulates
3681 c0_composeDraft : function() {
3682 this.getNewInstanceId();
3684 document.getElementById('_blank').innerHTML = '';
3685 var idx = SE.composeLayout.currentInstanceId;
3686 SE.composeLayout.draftObject = new Object();
3687 SE.composeLayout.draftObject.id = idx;
3688 SE.composeLayout.draftObject.isDraft = true;
3689 SE.composeLayout.currentInstanceId = idx;
3690 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
3691 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
3692 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
3694 SE.composeLayout._0_yui();
3695 SE.composeLayout._1_tiny();
3698 SE.composeLayout._2_final();
3700 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
3701 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
3705 * Strip & Prep editor hidden fields
3707 c0_composeNewEmail : function() {
3708 this.getNewInstanceId();
3709 this.c1_composeEmail(false);
3713 * Sends async request to get the compose view.
3714 * Requests come from "reply" or "forwards"
3716 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
3717 SE.composeLayout.replyForwardObj = new Object();
3718 SE.composeLayout.replyForwardObj.ieId = ieId;
3719 SE.composeLayout.replyForwardObj.uid = uid;
3720 SE.composeLayout.replyForwardObj.mbox = mbox;
3721 SE.composeLayout.replyForwardObj.type = type;
3723 if(mbox == 'sugar::Emails') {
3724 SE.composeLayout.replyForwardObj.sugarEmail = true;
3727 SE.composeLayout.getNewInstanceId();
3728 SE.composeLayout.c1_composeEmail(true);
3730 //// END COMPOSE FLOW
3731 ///////////////////////////////////////////////////////////////////////////
3734 * Called when a contact, email, or mailinglist is dropped
3735 * into one of the compose fields.
3737 handleDrop : function (source, event, data, target) {
3740 target = event.getTarget();
3742 data.nodes = [data.nodes];
3746 target = document.getElementById(target);
3750 if (target.id.indexOf('address') > -1) {
3751 // dropped onto email to/cc/bcc field
3752 for(var i in nodes) {
3753 var node = nodes[i].getData();
3755 if (node[1].indexOf('contact') > -1) {
3756 email = SE.addressBook.getFormattedAddress(node[0]);
3757 } else if (node[1].indexOf('address-email') > -1){
3758 email = node[3].replace(/ /gi, '');
3759 email = email.replace('<', '<').replace('>', '>');
3760 var tr = source.getTrEl(nodes[i]);
3761 while (tr && !Dom.hasClass(tr, "address-contact")) {
3762 tr = source.getPreviousTrEl(tr);
3764 var CID = source.getRecord(tr).getData()[0];
3765 var o = SE.addressBook._contactCache[CID];
3766 var name = new String(o.name);
3767 var finalName = name.replace(/(<([^>]+)>)/ig, "");
3768 email = finalName + email;
3770 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
3776 /*/////////////////////////////////////////////////////////////////////////////
3777 /// EMAIL TEMPLATE CODE
3779 applyEmailTemplate : function (idx, id) {
3782 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
3783 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
3784 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
3786 // id is selected index of email template drop-down
3787 if(id == '' || id == "0") {
3788 YAHOO.SUGAR.MessageBox.show({
3793 if(btn=='no'){return;};
3794 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
3801 YAHOO.SUGAR.MessageBox.show({
3806 if(btn=='no'){return;};
3807 SUGAR.email2.composeLayout.processResult(idx, id);},
3813 processNoneResult : function(idx, id) {
3814 var tiny = SE.util.getTiny('htmleditor' + idx);
3815 var tinyHTML = tiny.getContent();
3816 var openTag = '<div><span><span>';
3817 var htmllow = tinyHTML.toLowerCase();
3818 var start = htmllow.indexOf(openTag);
3820 tinyHTML = tinyHTML.substr(start);
3821 tiny.setContent(tinyHTML);
3823 tiny.setContent('');
3827 processResult : function(idx , id){
3828 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
3830 // get attachments if any
3831 AjaxObject.target = '';
3832 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
3835 appendEmailTemplateJSON : function() {
3836 var idx = SE.composeLayout.currentInstanceId; // post increment
3838 // query based on template, contact_id0,related_to
3839 //jchi 09/10/2008 refix #7743
3840 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
3841 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
3844 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,'"');
3846 // cn: bug 14361 - text-only templates don't fill compose screen
3848 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/>");
3851 var tiny = SE.util.getTiny('htmleditor' + idx);
3852 var tinyHTML = tiny.getContent();
3853 var openTag = '<div><span><span>';
3854 var closeTag = '</span></span></div>';
3855 var htmllow = tinyHTML.toLowerCase();
3856 var start = htmllow.indexOf(openTag);
3858 var htmlPart2 = tinyHTML.substr(start);
3859 tinyHTML = text + htmlPart2;
3860 tiny.setContent(tinyHTML);
3862 tiny.setContent(text);
3867 * Writes out the signature in the email editor
3869 setSignature : function(idx) {
3872 var hide = document.getElementById('setEditor' + idx).checked;
3873 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
3874 //wait for signatures to load before trying to set them
3875 if (!SE.composeLayout.signatures) {
3876 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
3881 var sel = document.getElementById('signatures' + idx);
3883 var sel = document.getElementById('signature_id');
3884 idx = SE.tinyInstances.currentHtmleditor;
3887 //Ensure that the tinyMCE html has been rendered.
3888 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
3889 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
3896 signature = sel.options[sel.selectedIndex].value;
3901 var openTag = '<div><span><span>';
3902 var closeTag = '</span></span></div>';
3903 var t = SE.util.getTiny('htmleditor' + idx);
3905 if(typeof(t) != 'undefined')
3907 t.contentDocument = t.contentWindow.document;
3908 var html = t.getContent();
3913 var htmllow = html.toLowerCase();
3914 var start = htmllow.indexOf(openTag);
3915 var end = htmllow.indexOf(closeTag) + closeTag.length;
3917 // selected "none" - remove signature from email
3918 if(signature == '') {
3920 var htmlPart1 = html.substr(0, start);
3921 var htmlPart2 = html.substr(end, html.length);
3923 html = htmlPart1 + htmlPart2;
3926 SE.signatures.lastAttemptedLoad = '';
3930 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
3931 SE.signatures.lastAttemptedLoad = '';
3933 SE.signatures.lastAttemptedLoad = signature;
3935 if(typeof(SE.signatures[signature]) == 'undefined') {
3937 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
3938 SE.signatures.targetInstance = (idx) ? idx : "";
3939 AjaxObject.target = '';
3940 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
3942 var newSignature = this.prepareSignature(SE.signatures[signature]);
3944 // clear out old signature
3945 if(SE.signatures.lastAttemptedLoad && start > -1) {
3946 var htmlPart1 = html.substr(0, start);
3947 var htmlPart2 = html.substr(end, html.length);
3949 html = htmlPart1 + htmlPart2;
3953 start = html.indexOf('<div><hr></div>');
3954 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
3955 var htmlPart1 = html.substr(0, start);
3956 var htmlPart2 = html.substr(start, html.length);
3957 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
3958 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
3959 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
3961 var newHtml = html + openTag + newSignature + closeTag;
3963 //tinyMCE.setContent(newHtml);
3964 t.setContent(newHtml);
3968 prepareSignature : function(str) {
3969 var signature = new String(str);
3971 signature = signature.replace(/</gi, '<');
3972 signature = signature.replace(/>/gi, '>');
3978 showAttachmentPanel : function(idx) {
3979 var east = SE.composeLayout[idx].getUnitByPosition("right");
3980 var tabs = SE.composeLayout[idx].rightTabs;
3982 tabs.set("activeTab", tabs.getTab(0));
3986 * expands sidebar and displays options panel
3988 showOptionsPanel : function(idx) {
3989 var east = SE.composeLayout[idx].getUnitByPosition("right");
3990 var tabs = SE.composeLayout[idx].rightTabs;
3992 tabs.set("activeTab", tabs.getTab(1));
3996 * Selects the Contacts tab
3998 showContactsPanel : function() {
3999 SE.complexLayout.regions.west.showPanel("contactsTab");
4003 * Generates fields for Select Document
4005 addDocumentField : function(idx) {
4006 var basket = document.getElementById('addedDocuments' + idx);
4008 var index = (basket.childNodes.length / 7) - 1;
4015 var test = document.getElementById('documentId' + idx + index);
4017 while(test != null) {
4019 test = document.getElementById('documentId' + idx + index);
4022 var documentCup = document.createElement("div");
4023 documentCup.id = 'documentCup' + idx + index;
4024 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
4025 // document id field
4026 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
4027 // document name field
4028 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
4030 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
4031 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
4032 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
4034 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
4035 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
4036 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
4039 basket.appendChild(documentCup);
4040 //basket.innerHTML += out;
4045 * Makes async call to save a draft of the email
4046 * @param int Instance index
4048 saveDraft : function(tinyInstance) {
4049 this.sendEmail(tinyInstance, true);
4052 selectDocument : function(target) {
4053 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
4054 windowName = 'selectDocument';
4055 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
4057 win = window.open(URL, windowName, windowFeatures);
4059 // put the focus on the popup if the browser supports the focus() method
4065 * Modal popup for file attachment dialogue
4067 addFileField : function() {
4068 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
4069 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
4073 constraintoviewport: true,
4075 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
4076 fn:function(){SE.addFileDialog.hide();}
4079 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
4080 SE.addFileDialog.render();
4081 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
4083 Dom.removeClass("addFileDialog", "yui-hidden");
4085 SE.addFileDialog.show();
4089 * Async upload of file to temp dir
4091 uploadAttachment : function() {
4092 if(document.getElementById('email_attachment').value != "") {
4093 var formObject = document.getElementById('uploadAttachment');
4094 YAHOO.util.Connect.setForm(formObject, true, true);
4095 AjaxObject.target = '';
4096 AjaxObject.startRequest(callbackUploadAttachment, null);
4098 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
4103 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
4104 * @param string target in focus compose layout
4106 setDocument : function(idx, target, documentId, documentName, docRevId) {
4107 // fields are named/id'd [fieldName][instanceId][index]
4108 var addedDocs = document.getElementById("addedDocuments" + idx);
4109 var docId = document.getElementById('documentId' + idx + target);
4110 var docName = document.getElementById('documentName' + idx + target);
4111 var docRevisionId = document.getElementById('document' + idx + target);
4112 docId.value = documentId;
4113 docName.value = documentName;
4114 docRevisionId.value = docRevId;
4118 * Removes the bucket div containing the document input fields
4120 deleteDocumentField : function(documentCup) {
4121 var f0 = document.getElementById(documentCup);
4122 f0.parentNode.removeChild(f0);
4126 * Removes a Template Attachment field
4130 deleteTemplateAttachmentField : function(idx, index) {
4131 // create not-in-array values for removal filtering
4132 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
4138 r += document.getElementById('templateAttachmentId' + idx + index).value;
4139 document.getElementById("templateAttachmentsRemove" + idx).value = r;
4141 var target = 'templateAttachmentCup' + idx + index;
4142 d = document.getElementById(target);
4143 d.parentNode.removeChild(d);
4147 * Async removal of uploaded temp file
4148 * @param string index Should be a concatenation of idx and index
4151 deleteUploadAttachment : function(index, file) {
4152 var d = document.getElementById('email_attachment_bucket' + index);
4153 d.parentNode.removeChild(d);
4155 // make async call to delete cached file
4156 AjaxObject.target = '';
4157 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
4161 * Attaches files coming from Email Templates
4163 addTemplateAttachmentField : function(idx) {
4165 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
4167 var basket = document.getElementById('addedTemplateAttachments' + idx);
4170 var index = basket.childNodes.length;
4177 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
4179 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
4180 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
4181 idx + "\",\"" + index + "\");'/>" +
4183 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
4184 // templateAttachment field
4185 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
4187 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
4189 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
4190 "<br id='br" + index + "></br>" +
4191 "<br id='brdoc" + index + "></br>" +
4193 basket.innerHTML = basket.innerHTML + out;
4199 * Sends one email via async call
4200 * @param int idx Editor instance ID
4201 * @param bool isDraft
4203 sendEmail : function(idx, isDraft) {
4205 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
4206 var obAccountID = document.getElementById('addressFrom' + idx).value;
4208 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
4210 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
4215 var form = document.getElementById('emailCompose' + idx);
4216 var composeOptionsFormName = "composeOptionsForm" + idx;
4217 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
4218 var html = t.getContent();
4219 var subj = document.getElementById('emailSubject' + idx).value;
4220 var to = trim(document.getElementById('addressTO' + idx).value);
4221 var cc = trim(document.getElementById('addressCC' + idx).value);
4222 var bcc = trim(document.getElementById('addressBCC' + idx).value);
4223 var email_id = document.getElementById('email_id' + idx).value;
4224 var composeType = document.getElementById('composeType').value;
4225 var parent_type = document.getElementById("parent_type").value;
4226 var parent_id = document.getElementById("parent_id").value;
4228 var el_uid = document.getElementById("uid");
4229 var uid = (el_uid == null) ? '' : el_uid.value;
4231 var el_ieId = document.getElementById("ieId");
4232 var ieId = (el_ieId == null) ? '' : el_ieId.value;
4234 var el_mbox = document.getElementById("mbox");
4235 var mbox = (el_mbox == null) ? '' : el_mbox.value;
4237 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
4238 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
4242 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
4245 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
4246 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
4247 parent_id = parentIdValue;
4248 parent_type = parentTypeValue;
4250 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
4251 // baseline viability check
4253 if(to == "" && cc == '' && bcc == '' && !isDraft) {
4254 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
4256 } else if(subj == '' && !isDraft) {
4257 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
4260 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
4262 } else if(html == '' && !isDraft) {
4263 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
4268 SE.util.clearHiddenFieldValues('emailCompose' + idx);
4269 document.getElementById('data_parent_id' + idx).value = parentIdValue;
4270 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
4271 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
4272 html = html.replace(/</ig, "sugarLessThan");
4273 html = html.replace(/>/ig, "sugarGreaterThan");
4275 form.sendDescription.value = html;
4276 form.sendSubject.value = subj;
4277 form.sendTo.value = to;
4278 form.sendCc.value = cc;
4279 form.sendBcc.value = bcc;
4280 form.email_id.value = email_id;
4281 form.composeType.value = composeType;
4282 form.composeLayoutId.value = 'composeLayout' + idx;
4283 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
4284 form.saveToSugar.value = 1;
4285 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
4286 form.parent_type.value = parent_type;
4287 form.parent_id.value = parent_id;
4288 form.uid.value = uid;
4289 form.ieId.value = ieId;
4290 form.mbox.value = mbox;
4292 // email attachments
4293 var addedFiles = document.getElementById('addedFiles' + idx);
4295 for(i=0; i<addedFiles.childNodes.length; i++) {
4296 var bucket = addedFiles.childNodes[i];
4298 for(j=0; j<bucket.childNodes.length; j++) {
4299 var node = bucket.childNodes[j];
4300 var nName = new String(node.name);
4302 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
4303 if(form.attachments.value != '') {
4304 form.attachments.value += "::";
4306 form.attachments.value += node.value;
4313 var addedDocs = document.getElementById('addedDocuments' + idx);
4315 for(i=0; i<addedDocs.childNodes.length; i++) {
4316 var cNode = addedDocs.childNodes[i];
4317 for(j=0; j<cNode.childNodes.length; j++) {
4318 var node = cNode.childNodes[j];
4319 var nName = new String(node.name);
4320 if(node.type == 'hidden' && nName.match(/documentId/)) {
4321 if(form.documents.value != '') {
4322 form.documents.value += "::";
4324 form.documents.value += node.value;
4330 // template attachments
4331 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
4332 if(addedTemplateAttachments) {
4333 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
4334 var cNode = addedTemplateAttachments.childNodes[i];
4335 for(j=0; j<cNode.childNodes.length; j++) {
4336 var node = cNode.childNodes[j];
4337 var nName = new String(node.name);
4338 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
4339 if(form.templateAttachments.value != "") {
4340 form.templateAttachments.value += "::";
4342 form.templateAttachments.value += node.value;
4348 // remove attachments
4349 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
4351 YAHOO.util.Connect.setForm(form);
4353 AjaxObject.target = 'frameFlex';
4355 // sending a draft email
4356 if(!isDraft && in_draft) {
4358 SE.listView.removeRowByUid(email_id);
4361 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
4362 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
4364 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
4368 * Handles clicking the email address link from a given view
4370 composePackage : function() {
4371 if(composePackage != null) {
4372 SE.composeLayout.c0_composeNewEmail();
4375 if(composePackage.to_email_addrs) {
4376 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
4378 if (composePackage.subject != null && composePackage.subject.length > 0) {
4379 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
4382 //If no parent fields are set in the composePackage, ensure they are cleared.
4383 var parentFields = ['parent_type','parent_name','parent_id'];
4384 for(var i=0;i<parentFields.length;i++)
4386 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
4387 composePackage[parentFields[i]] = "";
4390 document.getElementById("parent_type").value = composePackage.parent_type;
4391 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
4392 document.getElementById("parent_id").value = composePackage.parent_id;
4393 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
4394 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
4396 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
4397 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
4399 if (composePackage.body != null && composePackage.body.length > 0) {
4400 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4401 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
4402 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
4404 if (composePackage.attachments != null) {
4405 SE.composeLayout.loadAttachments(composePackage.attachments);
4408 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
4409 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
4410 SE.util.emptySelectOptions(addressFrom);
4411 var fromAccountOpts = composePackage.fromAccounts.data;
4412 for(i=0; i<fromAccountOpts.length; i++) {
4413 var key = fromAccountOpts[i].value;
4414 var display = fromAccountOpts[i].text;
4415 var opt = new Option(display, key);
4416 if (fromAccountOpts[i].selected) {
4417 opt.selected = true;
4419 addressFrom.options.add(opt);
4426 setContentOnThisTiny : function() {
4427 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4428 var tinyHTML = tiny.getContent();
4429 composePackage.body = decodeURI(encodeURI(composePackage.body));
4430 // cn: bug 14361 - text-only templates don't fill compose screen
4431 if(composePackage.body == '') {
4432 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4434 //Flag determines if we should clear the tiny contents or just append
4435 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
4436 SE.composeLayout.tinyHTML = '';
4438 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
4440 tiny.setContent(SE.composeLayout.tinyHTML);
4441 //Indicate that the contents has been loaded successfully.
4442 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
4445 * Confirms closure of a compose screen if "x" is clicked
4447 confirmClose : function(panel) {
4448 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
4449 SE.composeLayout.closeCompose(panel.id);
4457 * forces close of a compose screen
4459 forceCloseCompose : function(id) {
4460 SE.composeLayout.closeCompose(id);
4462 // handle flow back to originating view
4463 if(composePackage) {
4464 // check if it's a module we need to return to
4465 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
4466 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
4467 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
4468 window.location = url;
4475 * closes the editor that just sent email
4476 * @param string id ID of composeLayout tab
4478 closeCompose : function(id) {
4479 // destroy tinyMCE instance
4480 var idx = id.substr(13, id.length);
4481 var instanceId = "htmleditor" + idx;
4482 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
4484 // nullify DOM and namespace values.
4486 SE.composeLayout[idx] = null;
4487 SE.tinyInstances[instanceId] = null;
4488 var tabsArray = SE.innerLayout.get("tabs");
4489 for (i = 0 ; i < tabsArray.length ; i++) {
4490 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
4491 tabsArray[i].close();
4495 //SE.innerLayout.getTab(idx).close();
4499 * Enable the quick search for the compose relate field or search tab
4501 enableQuickSearchRelate: function(idx,overides){
4503 if(typeof overides != 'undefined')
4505 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
4506 var newModule = document.getElementById(newModuleID).value;
4507 var formName = overides['formName'];
4508 var fieldName = overides['fieldName'];
4509 var fieldId = overides['fieldId'];
4510 var fullName = formName + "_" + fieldName;
4511 var postBlurFunction = null;
4515 var newModule = document.getElementById('data_parent_type'+idx).value;
4516 var formName = 'emailCompose'+idx;
4517 var fieldName = 'data_parent_name'+idx;
4518 var fieldId = 'data_parent_id'+idx;
4519 var fullName = formName + "_" + fieldName;
4520 var postBlurFunction = "SE.composeLayout.qsAddAddress";
4523 if(typeof sqs_objects == 'undefined')
4524 window['sqs_objects'] = new Array;
4526 window['sqs_objects'][fullName] = {
4529 modules:[newModule],
4531 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
4532 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
4533 post_onblur_function: postBlurFunction,
4534 order:"name","limit":"30","no_match_text":"No Match"};
4537 if(typeof QSProcessedFieldsArray != 'undefined')
4538 QSProcessedFieldsArray[fullName] = false;
4539 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
4540 QSFieldsArray[fullName].destroy();
4541 delete QSFieldsArray[fullName];
4543 if (Dom.get(fullName + "_results")) {
4544 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
4550 qsAddAddress : function(o) {
4551 if (o.name != "" && o.email1 != "")
4553 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
4554 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
4558 * Returns a new instance ID, 0-index
4560 getNewInstanceId : function() {
4561 this.currentInstanceId = this.currentInstanceId + 1;
4562 return this.currentInstanceId;
4566 * 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.
4568 loadAttachments : function(result) {
4569 var idx = SE.composeLayout.currentInstanceId;
4571 if(typeof(result) == 'object') {
4572 //jchi #20680. Clean the former template attachments;
4573 var basket = document.getElementById('addedTemplateAttachments' + idx);
4574 if(basket.innerHTML != ''){
4575 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
4577 basket.innerHTML = '';
4582 if(typeof result[i] == 'object') {
4583 var index = SE.composeLayout.addTemplateAttachmentField(idx);
4584 var bean = result[i];
4585 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
4586 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
4593 * fills drop-down values for email templates and signatures
4595 setComposeOptions : function(idx) {
4596 // send from accounts
4597 var addressFrom = document.getElementById('addressFrom' + idx);
4599 if (addressFrom.options.length <= 0) {
4600 SE.util.emptySelectOptions(addressFrom);
4601 var fromAccountOpts = SE.composeLayout.fromAccounts;
4602 for (id = 0 ; id < fromAccountOpts.length ; id++) {
4603 var key = fromAccountOpts[id].value;
4604 var display = fromAccountOpts[id].text;
4605 var is_default = false;
4606 if(key == SUGAR.default_inbound_accnt_id)
4608 var opt = new Option(display, key);
4609 addressFrom.options.add(opt);
4610 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
4615 var et = document.getElementById('email_template' + idx);
4616 SE.util.emptySelectOptions(et);
4618 for(var key in this.emailTemplates) { // iterate through assoc array
4619 var display = this.emailTemplates[key];
4620 var opt = new Option(display, key);
4621 et.options.add(opt);
4625 var sigs = document.getElementById('signatures' + idx);
4626 SE.util.emptySelectOptions(sigs);
4628 for(var key in this.signatures) { // iterate through assoc array
4629 var display = this.signatures[key];
4630 var opt = new Option(display, key);
4632 if(key == SE.userPrefs.signatures.signature_default) {
4633 opt.selected = true;
4636 sigs.options.add(opt);
4639 // html/plain email?
4640 var htmlEmail = document.getElementById('setEditor' + idx);
4641 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
4642 htmlEmail.checked = true;
4644 htmlEmail.checked = false;
4647 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
4651 * After compose screen is rendered, async call to get email body from Sugar
4653 replyForwardEmailStage2 : function() {
4654 SE.util.clearHiddenFieldValues('emailUIForm');
4655 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
4657 var ieId = SE.composeLayout.replyForwardObj.ieId;
4658 var uid = SE.composeLayout.replyForwardObj.uid;
4659 var mbox = SE.composeLayout.replyForwardObj.mbox;
4660 var type = SE.composeLayout.replyForwardObj.type;
4661 var idx = SE.composeLayout.currentInstanceId;
4663 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
4665 document.getElementById('emailSubject' + idx).value = type;
4666 document.getElementById('emailUIAction').value = 'composeEmail';
4667 document.getElementById('composeType').value = type;
4668 document.getElementById('ieId').value = ieId;
4669 document.getElementById('uid').value = uid;
4670 document.getElementById('mbox').value = mbox;
4671 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
4672 var formObject = document.getElementById('emailUIForm');
4673 YAHOO.util.Connect.setForm(formObject);
4675 var sendType = type;
4676 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
4680 * Show the hidden cc or bcc fields
4682 showHiddenAddress: function(addrType,idx){
4684 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
4685 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
4686 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
4687 this[addrType+'Hidden'+idx] = false;
4689 //After bcc or cc is added, move options below last addr field
4690 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4692 //If both cc and bcc hidden, remove the empty row containing text.
4693 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
4694 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
4695 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
4697 SE.composeLayout.resizeEditor(idx);
4700 * Hide the cc and bcc fields if they were shown.
4702 hideHiddenAddresses: function(idx){
4704 var addrTypes = ['cc','bcc'];
4705 for(var i = 0;i<addrTypes.length;i++)
4707 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
4708 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
4709 this[addrTypes[i] + 'Hidden'+idx] = true
4712 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
4713 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
4714 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4718 //// END SE.composeLayout
4719 ///////////////////////////////////////////////////////////////////////////////
4720 ///////////////////////////////////////////////////////////////////////////////
4724 * Cleans serialized UID lists of duplicates
4728 cleanUids : function(str) {
4729 var seen = new Object();
4731 var arr = new String(str).split(",");
4733 for(var i=0; i<arr.length; i++) {
4738 clean += (clean != "") ? "," : "";
4740 seen[arr[i]] = true;
4747 * Clears hidden field values
4748 * @param string id ID of form element to clear
4750 clearHiddenFieldValues : function(id) {
4751 var form = document.getElementById(id);
4753 for(i=0; i<form.elements.length; i++) {
4754 if(form.elements[i].type == 'hidden') {
4755 var e = form.elements[i];
4756 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
4764 * Reduces a SELECT drop-down to 0 items to prepare for new ones
4766 emptySelectOptions : function(el) {
4768 for(i=el.childNodes.length - 1; i >= 0; i--) {
4769 if(el.childNodes[i]) {
4770 el.removeChild(el.childNodes[i]);
4777 * Returns the MBOX path in the manner php_imap expects:
4778 * ie: INBOX.DEBUG.test
4779 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
4781 generateMboxPath : function(str) {
4782 var ex = str.split("::");
4784 /* we have a serialized MBOX path */
4788 for(var i=0; i<ex.length; i++) {
4789 if(ex[i] == 'INBOX') {
4801 /* we have a Sugar folder GUID - do nothing */
4809 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
4810 * @param HTMLElement el
4811 * @return string GUID of found element or empty on failure
4813 getGuidFromElement : function(el) {
4819 for(var i=0; i<iterations; i++) {
4821 if(el.id.match(SE.reGUID)) {
4833 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
4836 getPanelId : function() {
4837 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
4841 * wrapper to handle weirdness with IE
4842 * @param string instanceId
4843 * @return tinyMCE Controller object
4845 getTiny : function(instanceId) {
4846 if(instanceId == '') {
4850 var t = tinyMCE.getInstanceById(instanceId);
4854 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
4860 * Simple check for MSIE browser
4864 var nav = new String(navigator.appVersion);
4865 if(nav.match(/MSIE/)) {
4872 * Recursively removes an element from the DOM
4873 * @param HTMLElement
4875 removeElementRecursive : function(el) {
4876 this.emptySelectOptions(el);
4883 sleep : function(secs) {
4884 setTimeout("void(0);", secs);
4888 * Converts a <select> element to an Ext.form.combobox
4890 convertSelect : function(select) {
4891 alert('in convertSelect');
4892 if (typeof(select) == "string") {
4893 select = document.getElementById(select);
4897 findChildNode : function (parent, property, value) {
4898 for (i in parent.children) {
4899 var child = parent.children[i];
4900 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
4902 var searchChild = SE.util.findChildNode(child, property, value);
4909 cascadeNodes : function (parent, fn, scope, args) {
4910 for (i in parent.children) {
4911 var child = parent.children[i];
4912 var s = scope ? scope : child;
4913 var a = args ? args : child;
4915 SE.util.cascadeNodes(child, fn, scope, args);
4922 ///////////////////////////////////////////////////////////////////////////////
4925 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
4927 /*********************************************************************************
4928 * SugarCRM is a customer relationship management program developed by
4929 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4931 * This program is free software; you can redistribute it and/or modify it under
4932 * the terms of the GNU Affero General Public License version 3 as published by the
4933 * Free Software Foundation with the addition of the following permission added
4934 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4935 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4936 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4938 * This program is distributed in the hope that it will be useful, but WITHOUT
4939 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4940 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4943 * You should have received a copy of the GNU Affero General Public License along with
4944 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4945 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4948 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4949 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4951 * The interactive user interfaces in modified source and object code versions
4952 * of this program must display Appropriate Legal Notices, as required under
4953 * Section 5 of the GNU Affero General Public License version 3.
4955 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4956 * these Appropriate Legal Notices must retain the display of the "Powered by
4957 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4958 * technical reasons, the Appropriate Legal Notices must display the words
4959 * "Powered by SugarCRM".
4960 ********************************************************************************/
4962 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
4963 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
4964 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
4965 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
4966 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
4967 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
4968 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
4969 ' <input type="hidden" id="type{idx}" name="type" value="">' +
4970 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
4971 ' <input type="hidden" id="composeType" name="composeType">' +
4972 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
4973 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
4974 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
4975 ' <input type="hidden" id="sendTo" name="sendTo">' +
4976 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
4977 ' <input type="hidden" id="sendCc" name="sendCc">' +
4978 ' <input type="hidden" id="setEditor" name="setEditor">' +
4979 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
4980 ' <input type="hidden" id="parent_id" name="parent_id">' +
4981 ' <input type="hidden" id="parent_type" name="parent_type">' +
4982 ' <input type="hidden" id="attachments" name="attachments">' +
4983 ' <input type="hidden" id="documents" name="documents">' +
4984 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
4985 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
4986 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
4987 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
4989 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
4990 ' <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>' +
4991 ' <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>' +
4992 ' <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>' +
4993 ' <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>' +
4994 '</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>' +
4995 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
4996 '<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>' +
4997 ' </td></tr></tbody></table></th>' +
5001 ' <div style="margin:5px;">' +
5002 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
5004 ' <td class="emailUILabel" NOWRAP >' +
5005 ' {app_strings.LBL_EMAIL_FROM}:' +
5007 ' <td class="emailUIField" NOWRAP>' +
5009 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
5014 ' <td class="emailUILabel" NOWRAP>' +
5015 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
5016 ' {app_strings.LBL_EMAIL_TO}:' +
5019 ' <td class="emailUIField" NOWRAP>' +
5020 ' <div class="ac_autocomplete">' +
5021 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5022 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
5023 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
5027 ' <tr id="add_addr_options_tr{idx}">' +
5028 ' <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>'+
5030 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
5031 ' <td class="emailUILabel" NOWRAP>' +
5032 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
5033 ' {app_strings.LBL_EMAIL_CC}:' +
5036 ' <td class="emailUIField" NOWRAP>' +
5037 ' <div class="ac_autocomplete">' +
5038 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5039 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
5040 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
5044 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
5045 ' <td class="emailUILabel" NOWRAP>' +
5046 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
5047 ' {app_strings.LBL_EMAIL_BCC}:' +
5050 ' <td class="emailUIField" NOWRAP>' +
5051 ' <div class="ac_autocomplete">' +
5052 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5053 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
5054 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
5059 ' <td class="emailUILabel" NOWRAP width="1%">' +
5060 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
5062 ' <td class="emailUIField" NOWRAP width="99%">' +
5063 ' <div class="ac_autocomplete">' +
5064 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
5073 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
5074 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
5075 ' <div style="padding:5px;">' +
5076 ' <table cellpadding="2" cellspacing="0" border="0">' +
5079 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
5086 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
5087 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
5099 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
5106 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
5107 ' <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>' +
5119 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
5126 ' <div id="addedTemplateAttachments{idx}"></div>' +
5133 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
5134 ' <div style="padding:5px;">' +
5135 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
5136 ' <table border="0" width="100%">' +
5138 ' <td NOWRAP style="padding:2px;">' +
5139 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
5143 ' <td NOWRAP style="padding:2px;">' +
5144 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
5149 ' <table border="0" width="100%">' +
5151 ' <td NOWRAP style="padding:2px;">' +
5152 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
5156 ' <td NOWRAP style="padding:2px;">' +
5157 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
5161 ' <table border="0" width="100%">' +
5163 ' <td NOWRAP style="padding:2px;">' +
5164 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
5165 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
5173 // End of File modules/Emails/javascript/composeEmailTemplate.js
5175 /*********************************************************************************
5176 * SugarCRM is a customer relationship management program developed by
5177 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5179 * This program is free software; you can redistribute it and/or modify it under
5180 * the terms of the GNU Affero General Public License version 3 as published by the
5181 * Free Software Foundation with the addition of the following permission added
5182 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
5183 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
5184 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
5186 * This program is distributed in the hope that it will be useful, but WITHOUT
5187 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
5188 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
5191 * You should have received a copy of the GNU Affero General Public License along with
5192 * this program; if not, see http://www.gnu.org/licenses or write to the Free
5193 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
5196 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
5197 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
5199 * The interactive user interfaces in modified source and object code versions
5200 * of this program must display Appropriate Legal Notices, as required under
5201 * Section 5 of the GNU Affero General Public License version 3.
5203 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
5204 * these Appropriate Legal Notices must retain the display of the "Powered by
5205 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
5206 * technical reasons, the Appropriate Legal Notices must display the words
5207 * "Powered by SugarCRM".
5208 ********************************************************************************/
5213 function complexLayoutInit() {
5214 var se = SUGAR.email2;
5215 var Dom = YAHOO.util.Dom;
5217 getInnerLayout : function(rows) {
5218 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
5219 parent: se.complexLayout,
5225 scroll:false, // grid should autoScroll itself
5227 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
5235 body: "<div id='listBottom' />"
5243 body: "<div id='listRight' />",
5244 titlebar: false //,header: "right"
5247 se.complexLayout.on("render", function(){
5248 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
5249 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5250 SUGAR.email2.listViewLayout.set("height", height);
5251 SUGAR.email2.listViewLayout.render();
5253 se.listViewLayout.render();
5255 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
5256 var rp = se.listViewLayout.resizePreview = function() {
5257 var pre = Dom.get("displayEmailFramePreview");
5259 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
5260 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
5263 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
5264 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
5265 se.e2Layout.setPreviewPanel(rows);
5266 se.previewLayout = se.listViewLayout;
5267 return se.listViewLayout;
5270 getInnerLayout2Rows : function() {
5271 return this.getInnerLayout(true);
5273 getInnerLayout2Columns : function() {
5274 return this.getInnerLayout(false);
5278 // initialize state manager, we will use cookies
5279 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
5280 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
5281 se.complexLayout = new YAHOO.widget.Layout("container", {
5284 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
5285 width: Dom.getViewportWidth() - 40,
5289 body: "<div id='emailtabs'></div>"
5294 body: "<div id='lefttabs'></div>",
5304 header: Dom.get('footerLinks').innerHTML,
5311 se.complexLayout.render();
5312 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
5313 tp.addTab(new YAHOO.widget.Tab({
5316 content : "<div id='listViewDiv'/>",
5320 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
5321 tp.appendTo(centerEl);
5323 tp.get("element").style.borderRight = "1px solid #666"
5325 var listV = this.getInnerLayout2Rows();
5326 listV.set("height", tp.get("element").clientHeight - 25);
5329 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
5330 var folderTab = new YAHOO.widget.Tab({
5331 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
5333 content : "<div id='emailtree'/>",
5337 folderTab.on("activeChange", function(o){
5339 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
5342 se.leftTabs.addTab(folderTab);
5344 var tabContent = SUGAR.util.getAndRemove("searchTab");
5345 var searchTab = new YAHOO.widget.Tab({
5346 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
5348 content : tabContent.innerHTML,
5351 searchTab.on("activeChange", function(o){
5354 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
5355 //Setup the calendars if needed
5356 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_from", singleClick : true, step : 1, weekNumbers:false});
5357 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_to", singleClick : true, step : 1, weekNumbers:false});
5359 //Initalize sqs object for assigned user name
5360 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
5362 //Attach event handler for when the relate module option is selected for the correct sqs object
5363 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
5364 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
5365 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
5366 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
5368 //If enter key is pressed, perform search
5369 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
5370 for(var i=0; i < addKeyPressFields.length;i++)
5372 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
5373 if (e.keyCode == 13) {
5374 YAHOO.util.Event.stopEvent(e);
5375 SUGAR.email2.search.searchAdvanced();
5379 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
5381 //Clear parent values if selecting another parent type.
5382 YAHOO.util.Event.addListener('data_parent_type_search','change',
5384 document.getElementById('data_parent_id_search').value ='';
5385 document.getElementById('data_parent_name_search').value ='';
5390 se.leftTabs.addTab(searchTab);
5392 var resizeTabBody = function() {
5393 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
5394 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5397 se.complexLayout.on("render", resizeTabBody);
5398 se.leftTabs.on("activeTabChange", resizeTabBody);
5399 //hack to allow left pane scroll bar to fully show
5400 var lefttabsDiv = document.getElementById('lefttabs');
5401 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
5402 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
5403 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
5406 initSQSObject: function(formName,fieldName)
5408 var fullFieldName = formName + '_' + fieldName; //SQS Convention
5409 var resultName = fullFieldName + '_' + 'results';
5411 if (QSFieldsArray[fullFieldName] != null)
5413 QSFieldsArray[fullFieldName].destroy();
5414 delete QSFieldsArray[fullFieldName];
5416 if (QSProcessedFieldsArray[fullFieldName])
5417 QSProcessedFieldsArray[fullFieldName] = false;
5419 if( Dom.get(resultName) )
5421 var obj = document.getElementById(resultName);
5422 obj.parentNode.removeChild(obj);
5425 setPreviewPanel: function(rows) {
5427 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
5428 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
5429 Dom.get("listRight").innerHTML = "";
5430 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
5432 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
5433 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
5434 Dom.get("listBottom").innerHTML = "";
5435 Dom.get("listRight").innerHTML = "<div id='_blank' />";
5442 var myBufferedListenerObject = new Object();
5443 myBufferedListenerObject.refit = function() {
5444 if(SUGAR.email2.grid) {
5445 SUGAR.email2.grid.autoSize();
5448 // End of File modules/Emails/javascript/complexLayout.js