]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/sugar_grp_quickcomp.js
Release 6.1.5
[Github/sugarcrm.git] / include / javascript / sugar_grp_quickcomp.js
1 /*********************************************************************************
2  * SugarCRM is a customer relationship management program developed by
3  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4  * 
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.
11  * 
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
15  * details.
16  * 
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
20  * 02110-1301 USA.
21  * 
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.
24  * 
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.
28  * 
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  ********************************************************************************/
35
36 var req;
37 var target;
38 var flexContentOld = "";
39 var forcePreview = false;
40 var inCompose = false;
41
42 /* globals for Callback functions */
43 var email; // AjaxObject.showEmailPreview
44 var ieId;
45 var ieName;
46 var focusFolder;
47 var meta; // AjaxObject.showEmailPreview
48 var sendType;
49 var targetDiv;
50 var urlBase = 'index.php';
51 var urlStandard = 'sugar_body_only=true&to_pdf=true&module=Emails&action=EmailUIAjax';
52
53 var lazyLoadFolder = null;// End of File modules/Emails/javascript/vars.js
54                                 
55 /*********************************************************************************
56  * SugarCRM is a customer relationship management program developed by
57  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
58  *
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.
65  *
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
69  * details.
70  *
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
74  * 02110-1301 USA.
75  *
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.
78  *
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.
82  *
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&&currentNode.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='';}}
108 arrow.value='show';}
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;}
110 break;}}
111 if(!has_primary){return false;}
112 return true;}
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);}}}
119 divCount++;}}
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=='';}
122 return false;}}
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]];}}
130 if(recursive)
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
135                                 
136 /*********************************************************************************
137  * SugarCRM is a customer relationship management program developed by
138  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
139  * 
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.
146  * 
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
150  * details.
151  * 
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
155  * 02110-1301 USA.
156  * 
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.
159  * 
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.
163  * 
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  ********************************************************************************/
170
171 SUGAR.email2 = {
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),
175     templates : {},
176     tinyInstances : {
177         currentHtmleditor : ''
178     },
179
180     /**
181      * preserves hits from email server
182      */ 
183     _setDetailCache : function(ret) {
184         if(ret.meta) {
185             var compKey = ret.meta.mbox + ret.meta.uid;
186
187             if(!SUGAR.email2.cache[compKey]) {
188                 SUGAR.email2.cache[compKey] = ret;
189             }
190         }
191     },
192
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();        
203     }
204 };
205
206 /**
207  * Shows overlay progress message
208  */
209 function overlayModal(title, body) {
210     overlay(title, body);
211 }
212 function overlay(reqtitle, body, type, additconfig) {
213     var config = { };
214     if (typeof(additconfig) == "object") {
215         var config = additconfig;
216     }
217     config.type = type;
218     config.title = reqtitle;
219     config.msg = body;
220     YAHOO.SUGAR.MessageBox.show(config);
221 };
222
223 function hideOverlay() {
224         YAHOO.SUGAR.MessageBox.hide();
225 };
226 // End of File modules/Emails/javascript/EmailUIShared.js
227                                 
228 /*********************************************************************************
229  * SugarCRM is a customer relationship management program developed by
230  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
231  * 
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.
238  * 
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
242  * details.
243  * 
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
247  * 02110-1301 USA.
248  * 
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.
251  * 
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.
255  * 
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  ********************************************************************************/
262
263
264 if (typeof console == "undefined")
265         console = { log: function(o) {alert(o)} };
266
267 var AjaxObject = {
268         ret : '',
269         currentRequestObject : null,
270         //timeout : 30000, // 30 second timeout default
271         timeout : 9999999999, // 30 second timeout default
272         forceAbort : false,
273         trail : new Array(),
274
275         /**
276          */
277         _reset : function() {
278                 this.timeout = 30000;
279                 this.forceAbort = false;
280         },
281
282         folderRenameCleanup : function() {
283                 SUGAR.email2.folders.setSugarFolders();
284         },
285
286         fullSyncCleanup : function(o) {
287                 this.folders.checkMailCleanup(o);
288                 SUGAR.email2.settings.settingsDialog.hide();
289         },
290
291         /**
292          */
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);
297
298                 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
299                 SUGAR.email2.composeLayout.signatures = ret.signatures;
300                 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
301
302                 SUGAR.email2.composeLayout.setComposeOptions(idx);
303
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;
307
308
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');
318                 }
319
320                 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
321                 if(SUGAR.isIE) {
322                         var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
323                         if(overlayPanel) {
324                           overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
325                         }
326                 }
327         },
328
329
330         handleDeleteSignature : function(o) {
331                 hideOverlay();
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);
336
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);
340                 }
341                 setSigEditButtonVisibility();
342         },
343
344         /**
345          */
346         handleDeleteReturn : function(o) {
347                 // force refresh ListView
348                 hideOverlay();
349                 if(document.getElementById('focusEmailMbox')) {
350                         YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
351                 }
352
353                 // need to display success message before calling next async call?
354                 document.getElementById(this.target).innerHTML = o.responseText;
355         },
356
357         /**
358          */
359     handleFailure : function(o) {
360                 // Failure handler
361                 overlay('Exception occurred...', o.statusText, 'alert');
362         },
363
364         handleReplyForward : function(o) {
365                 var a = JSON.parse(o.responseText);
366                 globalA = a;
367                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
368
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;
373                 if(a.cc) {
374                         document.getElementById('addressCC' + idx).value = a.cc;
375                         SE.composeLayout.showHiddenAddress('cc', idx);
376                 }
377
378                 if(a.type) {
379                         document.getElementById('type' + idx).value = a.type;
380                 }
381
382                 // apply attachment values
383                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
384
385                 setTimeout("callbackReplyForward.finish(globalA);", 500);
386         },
387
388         handleReplyForwardForDraft : function(o) {
389                 var a = JSON.parse(o.responseText);
390                 globalA = a;
391                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
392
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;
396
397                 if(a.cc) {
398                         document.getElementById('addressCC' + idx).value = a.cc;
399                         SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
400                 }
401
402                 if(a.bcc) {
403                         document.getElementById('addressBCC' + idx).value = a.bcc;
404                         SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
405                 }
406
407
408                 if(a.type) {
409                         document.getElementById('type' + idx).value = a.type;
410                 }
411
412
413                 // apply attachment values
414                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
415
416                 setTimeout("callbackReplyForward.finish(globalA);", 500);
417         },
418
419         /**
420          */
421         handleSuccess : function(o) {
422                 document.getElementById(this.target).innerHTML = o.responseText;
423                 hideOverlay();
424         },
425
426         /**
427          */
428         ieDeleteSuccess : function(o) {
429                 hideOverlay();
430
431                 var ret = JSON.parse(o.responseText);
432
433                 SUGAR.email2.accounts.refreshInboundAccountTable();
434                 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
435                 SUGAR.email2.accounts.rebuildFolderList();
436
437         },
438
439         /**
440          */
441         ieSaveSuccess : function(o) {
442                 document.getElementById('saveButton').disabled = false;
443                 var a = JSON.parse(o.responseText);
444                 if (a) {
445                         if(a.error) {
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);
448                         } else {
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();
454                         }
455                 } else {
456                      hideOverlay();
457                      overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
458                 }
459
460         },
461
462         /**
463          */
464         loadAttachments : function(o) {
465                 var result = JSON.parse(o.responseText);
466
467                 SUGAR.email2.composeLayout.loadAttachments(result);
468         },
469
470         /**
471          */
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);
476         },
477
478         /**
479          * Follow up to mark email read|unread|flagged
480          */
481         markEmailCleanup : function(o) {
482                 var ret = JSON.parse(o.responseText);
483                 if (!ret['status']) {
484                 hideOverlay();
485                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
486                 } else {
487                         SUGAR.email2.contextMenus.markEmailCleanup();
488                 } // else
489         },
490
491         /**
492          */
493         rebuildShowFolders : function(o) {
494                 var t = JSON.parse(o.responseText);
495                 var show = document.getElementById('ieAccountListShow');
496
497                 SUGAR.email2.util.emptySelectOptions(show);
498
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);
503                 }
504
505                 SUGAR.email2.accounts.renderTree();
506         },
507         /**
508          */
509         saveListViewSortOrderPart2 : function() {
510                 // create the JSON string the func expects
511                 focusFolderPath = '[ "Home", "' + ieName + '"';
512
513                 var f = new String(focusFolder);
514                 var fEx = f.split('.');
515
516                 for(i=0; i<fEx.length; i++) {
517                         focusFolderPath += ', "' + fEx[i] +'"'
518                 }
519
520                 focusFolderPath += ']';
521
522                 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
523                 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
524         },
525
526         /**
527          *
528          */
529         sendEmailCleanUp : function(o) {
530                 hideOverlay();
531                 var ret = JSON.parse(o.responseText);
532                 if (ret) {
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');
537                 }
538
539                 if (typeof(SE.grid) != 'undefined')
540                         SE.listView.refreshGrid();
541                 //Disabled while address book is disabled
542
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') {
550                                 closeEmailOverlay();
551                         }
552                 }
553
554         },
555
556         ieSendSuccess : function(o) {
557                 hideOverlay();
558                 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
559         },
560
561         /**
562          */
563         settingsFolderRefresh : function(o) {
564                 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
565                 var ret = JSON.parse(o.responseText);
566                 var user = document.getElementById('userFolders');
567
568                 SUGAR.email2.util.emptySelectOptions(user);
569
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);
577                 }
578         },
579
580         /**
581          */
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);
586                         }
587                 }
588                 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
589                 this._reset();
590         },
591
592         requestInProgress : function() {
593                 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
594         },
595
596         /**
597          */
598         updateFolderSubscriptions : function() {
599                 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
600                 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
601                 hideOverlay();
602         },
603
604         /**
605          */
606         updateFrameFolder : function() {
607                 SUGAR.email2.folders.checkEmailAccounts();
608         },
609
610         /**
611          */
612         updateUserPrefs : function(o) {
613                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
614                 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
615         },
616
617         /**
618          */
619         uploadAttachmentSuccessful : function(o) {
620                 // clear out field
621                 document.getElementById('email_attachment').value = '';
622
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;
627                 var out =
628                         "<div id='email_attachment_bucket" + idx + index + "'>" +
629                                 // remove button
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 + "\");'/>" +
633                                 // file icon
634                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
635                                         "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
636                                 // hidden id field
637                                 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
638                                 // file name
639                                 ((ret.nameForDisplay != null) ? ret.nameForDisplay + "&nbsp;" : ret.name + "&nbsp;") +
640                                 "<br/>" +
641                         "</div>";
642                 overall.innerHTML += out;
643                 if(SUGAR.email2.util.isIe()) {
644                         document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
645                 }
646
647                 // hide popup
648                 SUGAR.email2.addFileDialog.hide();
649                 // focus attachments
650                 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
651         }
652 };
653
654
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;
663                 },
664         saveDefaultOutboundCleanup: function(o){
665
666         },
667         callbackEditOutbound : {
668                 success : function(o)
669                 {
670                         var ret = JSON.parse(o.responseText);
671                         // show overlay
672                         SUGAR.email2.accounts.showAddSmtp();
673
674                         // fill values
675                         document.getElementById("mail_id").value = ret.id;
676                         document.getElementById("type").value = ret.type;
677                         document.getElementById("mail_sendtype").value = ret.mail_sendtype;
678                         document.getElementById("mail_name").value = ret.name;
679                         document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
680                         document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
681                         document.getElementById("mail_smtpport").value = ret.mail_smtpport;
682                         document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
683                         document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
684                         SUGAR.email2.accounts.smtp_authenticate_field_display();
685                         document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
686
687             if(ret.type == 'system-override') {
688                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
689                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
690             }
691             else {
692                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
693                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
694             }
695             SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
696
697                 },
698                 failure : AjaxObject.handleFailure,
699                 timeout : AjaxObject.timeout,
700                 scope   : AjaxObject
701         },
702         callbackDeleteOutbound : {
703                 success : function(o) {
704                     var ret = JSON.parse(o.responseText);
705                     if(ret.is_error)
706                     {
707                         if(confirm(ret.error_message))
708                 {
709                     overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
710                     AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
711                 }
712                 else
713                     hideOverlay();
714                     }
715                     else
716                     {
717                              hideOverlay();
718                              SUGAR.email2.accounts.refreshOuboundAccountTable();
719                     }
720                 },
721
722                 failure : AjaxObject.handleFailure,
723                 timeout : AjaxObject.timeout,
724                 scope   : AjaxObject
725         },
726
727         callbackCheckMailProgress : {
728            success : function(o) {
729                if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
730                    SUGAR.email2.accounts.totalMsgCount = -1;
731                }
732
733                //Check for server timeout / errors
734                var ret = JSON.parse(o.responseText);
735                var done = false;
736
737                if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
738                    hideOverlay();
739                    overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
740                    SUGAR.email2.accounts.totalMsgCount = -1;
741                //SUGAR.email2.folders.rebuildFolders();
742                done = true;
743                }
744
745                var currIeId = ret['ieid'];
746
747
748                var serverCount = ret.count;
749
750                if (ret['status'] == 'done') {
751                    for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
752                        if (i == SUGAR.email2.accounts.ieIds.length - 1) {
753                            //We are all done
754                            done = true;
755                            break;
756                        } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
757                            //Go to next account
758                            currIeId = SUGAR.email2.accounts.ieIds[i+1];
759                            ret.count = 0;
760                            SUGAR.email2.accounts.totalMsgCount = -1;
761                            break;
762                        }
763                    }
764                }
765                else if (ret.mbox && ret.totalcount && ret.count) {
766                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
767                    if (ret.count >= ret.totalcount) {
768                        serverCount = 0;
769                    }
770                } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
771                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
772                } else {
773                        hideOverlay();
774                overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
775                SUGAR.email2.accounts.totalMsgCount = -1;
776                done = true;
777                    }
778
779                if (done) {
780                    SUGAR.email2.accounts.totalMsgCount = -1;
781                    hideOverlay();
782                    SUGAR.email2.folders.rebuildFolders();
783                    SE.listView.refreshGrid();
784                } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
785                YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
786                AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
787                                 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=0&synch=" + ret.synch);
788            } else {
789                YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
790                    app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
791                    AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
792                    '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=" + serverCount +
793                    '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
794                }
795            },
796            failure : AjaxObject.handleFailure,
797        timeout : AjaxObject.timeout,
798        scope   : AjaxObject
799         }
800 };
801
802 ///////////////////////////////////////////////////////////////////////////////
803 ////    COMPOSE LAYOUT
804 AjaxObject.composeLayout = {
805         /**
806          * Populates the record id
807          */
808         saveDraftCleanup : function(o) {
809                 hideOverlay();
810                 var ret = JSON.parse(o.responseText);
811                 if(ret)
812                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
813                 else if (o.responseText)
814                   overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
815         }
816 };
817
818 AjaxObject.composeLayout.callback = {
819         saveDraft : {
820                 success : AjaxObject.composeLayout.saveDraftCleanup,
821                 failure : AjaxObject.handleFailure,
822                 timeout : AjaxObject.timeout,
823                 scope   : AjaxObject
824         }
825 };
826
827 AjaxObject.detailView = {
828         /**
829          * Pops-up a printable view of an email
830          */
831         displayPrintable : function(o) {
832                 var ret = JSON.parse(o.responseText);
833                 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
834                 // 2 below must be in global context
835                 meta = ret.meta;
836                 meta['panelId'] = SUGAR.email2.util.getPanelId();
837                 email = ret.meta.email;
838                 if (typeof(email.cc) == 'undefined') {
839                   email.cc = "";
840                 }
841
842                 var out = displayTemplate.exec({
843                         'app_strings'   : app_strings,
844                         'theme'                 : theme,
845                         'idx'                   : 'Preview',
846                         'meta'                  : meta,
847                         'email'                 : meta.email
848                 });
849
850                 // open popup window
851                 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
852                     'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
853
854                 popup.document.write(out);
855                 popup.document.close();
856         },
857
858         /**
859          * Takes formatted response and creates a modal pop-over containing a title and content
860          */
861         displayView : function(o) {
862                 var SED = SUGAR.email2.detailView;
863                 var ret = JSON.parse(o.responseText);
864
865                 if(!SED.viewDialog) {
866                         SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
867                                 modal:true,
868                 visible:true,
869                 fixedcenter:true,
870                 constraintoviewport: true,
871                                 shadow  : true
872                         });
873             SED.viewDialog.renderEvent.subscribe(function() {
874                 var content = this.body.firstChild;
875                 var viewH = YAHOO.util.Dom.getViewportHeight();
876                 if (content) {
877                         this.body.style.overflow = "auto";
878                         this.body.style.width = "800px";
879                         this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
880                 }
881             }, SED.viewDialog);
882                 } // end lazy load
883                 SED.viewDialog.setHeader(ret.title);
884                 SED.viewDialog.setBody(ret.html);
885                 SED.viewDialog.render();
886                 SED.viewDialog.show();
887         },
888
889         /**
890          * Generates a modal popup to populate with the contents of bean's full EditView
891          */
892         showQuickCreateForm : function(o) {
893                 var SED = SUGAR.email2.detailView;
894                 var ret = JSON.parse(o.responseText);
895
896                 if(!SED.quickCreateDialog) {
897                         SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
898                                 modal:true,
899                                 visible:true,
900                 fixedcenter:true,
901                 constraintoviewport: true,
902                                 shadow  : true
903                         });
904
905             SED.quickCreateDialog.renderEvent.subscribe(function() {
906                 var viewH = YAHOO.util.Dom.getViewportHeight();
907                 var contH = 0;
908                 for (var i in this.body.childNodes) {
909                         if (this.body.childNodes[i].clientHeight) {
910                                 contH += this.body.childNodes[i].clientHeight;
911                         } else if (this.body.childNodes[i].offsetHeight) {
912                                 contH += this.body.childNodes[i].offsetHeight;
913                         } // if
914                 }
915                         this.body.style.width = "800px";
916                         this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
917                         this.body.style.overflow = "auto";
918             }, SED.quickCreateDialog);
919
920             SED.quickCreateDialog.hideEvent.subscribe(function(){
921                                 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
922                                 /*for(var qsField in qsFields){
923                                         if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
924                                         Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
925                                 }*/
926                         });
927             SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
928                 } // end lazy load
929                 if (ret.html) {
930                         ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
931                 }
932                 SED.quickCreateDialog.setBody(ret.html ? ret.html : "&nbsp;");
933                 SED.quickCreateDialog.render();
934                 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
935
936                 SED.quickCreateDialog.ieId = ret.ieId;
937                 SED.quickCreateDialog.uid = ret.uid;
938         SED.quickCreateDialog.mbox = ret.mbox;
939         SED.quickCreateDialog.qcmodule = ret.module;
940
941         SED.quickCreateDialog.show();
942
943                 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
944                 if (editForm) {
945                   editForm.module.value = 'Emails';
946                   var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
947                   var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
948                   var instId = ret.module + count;
949                   SED.quickCreateEmailsToAdd = ret.emailAddress;
950                   SED.quickCreateEmailCallback = function(instId, tableId) {
951                           var eaw = SUGAR.EmailAddressWidget.instances[instId];
952                           if (typeof(eaw) == "undefined")
953                                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
954                                                 + instId + "','" + tableId + "');", 100);
955                           eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
956                   }
957                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
958                                         + instId + "','" + tableId + "');", 100);
959                 }
960         },
961
962         saveQuickCreateForm : function(o) {
963             hideOverlay();
964                 SUGAR.email2.detailView.quickCreateDialog.hide();
965                 validate['EditView'] = [ ];
966         },
967
968         saveQuickCreateFormAndReply : function(o) {
969             hideOverlay();
970             var ret = JSON.parse(o.responseText);
971         SUGAR.email2.detailView.quickCreateDialog.hide();
972         var qcd = SUGAR.email2.detailView.quickCreateDialog;
973         var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
974         if (ret) {
975             var emailID = ret.id;
976             SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
977         } else {
978             SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
979         }
980         //Cean the validate cache to prevent errors on the next call
981         validate['EditView'] = [ ];
982     },
983
984         saveQuickCreateFormAndAddToAddressBook : function(o) {
985            hideOverlay();
986                 SUGAR.email2.detailView.quickCreateDialog.hide();
987                 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
988                 validate['EditView'] = [ ];
989         },
990
991         handleAssignmentDialogAssignAction : function() {
992
993
994             var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
995
996             var dist = 'direct';
997             var users = false;
998             var rules = false;
999             var get = "";
1000             var found_teams = false;
1001             var warning_message = mod_strings.LBL_WARN_NO_USERS;
1002             if(!found_teams && assign_user_id == '' )
1003             {
1004                 alert(warning_message);
1005                 return;
1006             }
1007
1008             var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1009             var uids = "";
1010             for(i=0; i<emailUids.length; i++) {
1011                 if(uids != '') {
1012                     uids += app_strings.LBL_EMAIL_DELIMITER;
1013                 }
1014                 uids += emailUids[i];
1015             }
1016
1017             var row = SUGAR.email2.grid.getSelectedRows()[0];
1018             var data = SUGAR.email2.grid.getRecord(row).getData();
1019             var ieid = data.ieId;
1020             var mbox = data.mbox;
1021             AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
1022             SUGAR.email2.contextMenus.assignToDialogue.hide();
1023             overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
1024
1025         },
1026
1027         handleAssignmentDialogDeleteAction : function() {
1028                 // TO pass list of UIDS/emailIds
1029                 var uids = SUGAR.email2.listView.getUidsFromSelection();
1030                 var row = SUGAR.email2.grid.getSelections()[0];
1031                 var ieid = row.data.ieId;
1032             var mbox = row.data.mbox;
1033         AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
1034         SUGAR.email2.contextMenus.assignmentDialog.hide();
1035                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1036
1037                 // AJAX Call
1038
1039         },
1040
1041         showEmailDetailView : function(o) {
1042         hideOverlay();
1043         var SED = SUGAR.email2.detailView;
1044                 var ret = JSON.parse(o.responseText);
1045
1046                 if(!SED.quickCreateDialog) {
1047                         SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
1048                                 modal:true,
1049                                 visible:true,
1050                 //fixedcenter:true,
1051                 constraintoviewport: true,
1052                 draggable: true,
1053                                 autofillheight: "body",
1054                                 shadow  : true
1055                         });
1056                         SED.quickCreateDialog.renderEvent.subscribe(function() {
1057                 var viewHeight = YAHOO.util.Dom.getViewportHeight();
1058                 var contH = 0;
1059                 for (var i in this.body.childNodes) {
1060                         if (this.body.childNodes[i].offsetHeight)
1061                                 contH += this.body.childNodes[i].offsetHeight;
1062                 }
1063                         this.body.style.overflow = "auto";
1064                         this.body.style.width = "800px";
1065                         this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
1066                         this.center();
1067             }, SED.quickCreateDialog);
1068                 }
1069                 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
1070                 SED.quickCreateDialog.setBody(ret.html);
1071                 SED.quickCreateDialog.render();
1072         SUGAR.util.evalScript(ret.html);
1073         SED.quickCreateDialog.show();
1074         },
1075
1076         showAssignmentDialogWithData : function(o) {
1077         var SEC = SUGAR.email2.contextMenus;
1078                 hideOverlay();
1079         var ret = JSON.parse(o.responseText);
1080         if (!SEC.assignmentDialog) {
1081                 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
1082                         visible:false,
1083                 fixedcenter:true,
1084                 constraintoviewport: true,
1085                         modal   : true
1086                 });
1087                 SEC.assignmentDialog.setBody("");
1088                 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
1089                 SEC.assignmentDialog.renderEvent.subscribe(function() {
1090                 var iev = YAHOO.util.Dom.get("Distribute");
1091                 if (iev) {
1092                         this.body.style.width = "700px";
1093                 }
1094             },  SEC.assignmentDialog);
1095                 SEC.assignmentDialog.render();
1096         }
1097         SEC.assignmentDialog.setBody(ret);
1098         SEC.assignmentDialog.render();
1099         validate = [];
1100         SEC.assignmentDialog.show();
1101         SUGAR.util.evalScript(ret);
1102         },
1103
1104         showImportForm : function(o) {
1105                 var SED = SUGAR.email2.detailView;
1106                 var ret = JSON.parse(o.responseText);
1107
1108         document.getElementById('quickCreateContent').innerHTML = "";
1109         hideOverlay();
1110         if (!ret) {
1111             return false;
1112         }
1113
1114         if(!SED.importDialog) {
1115             SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
1116                 modal:true,
1117                 visible:false,
1118                 fixedcenter:true,
1119                 constraintoviewport: true,
1120                 buttons : [{
1121                         text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
1122                                 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
1123                 }]//,
1124                 //scroll : true
1125             });
1126             SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
1127             SED.importDialog.setBody("");
1128             SED.importDialog.hideEvent.subscribe(function(){
1129                 for(var i in QSFieldsArray) {
1130                         if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
1131                                 QSFieldsArray[i].destroy();
1132                                 delete QSFieldsArray[i];
1133                         }
1134                         if (QSProcessedFieldsArray[i]) {
1135                                 QSProcessedFieldsArray[i] = false;
1136                         } // if
1137                                 }
1138             });
1139             SED.importDialog.renderEvent.subscribe(function() {
1140                 var iev = YAHOO.util.Dom.get("ImportEditView");
1141                 if (iev) {
1142                         //this.body.style.height = (iev.clientHeight + 10) + "px";
1143                         this.body.style.width = "600px";
1144                 }
1145             }, SED.importDialog);
1146             SED.importDialog.render();
1147         } // end lazy load
1148         SED.importDialog.setBody(ret.html);
1149         SED.importDialog.ret = ret;
1150         SUGAR.util.evalScript(ret.html);
1151         SED.importDialog.render();
1152         validate = [];
1153         SED.importDialog.show();
1154         SED.importDialog.focusFirstButton();
1155     },
1156     getImportAction : function(ret) {
1157         if (!check_form('ImportEditView')) return false;
1158         if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
1159                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
1160                 return false;
1161         } // if
1162                 var get = "";
1163         var editView = document.getElementById('ImportEditView');
1164         if (editView.assigned_user_id != null) {
1165             get = get + "&user_id=" + editView.assigned_user_id.value
1166             //var user_id = editView.assigned_user_id.value;
1167         }
1168         var parent_id = editView.parent_id.value;
1169         var parent_type = editView.parent_type.value;
1170         var row = SUGAR.email2.grid.getSelectedRows()[0];
1171         row = SUGAR.email2.grid.getRecord(row);
1172         var data = row.getData();
1173         var ieId = data.ieId;
1174         var mbox = data.mbox;
1175         var serverDelete = editView.serverDelete.checked;
1176         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1177         var uids = "";
1178         for(i=0; i<emailUids.length; i++) {
1179             if(uids != '') {
1180                 uids += app_strings.LBL_EMAIL_DELIMITER;
1181             }
1182             uids += emailUids[i];
1183         }
1184
1185         var action = 'importEmail&uid=';
1186         if (ret.move) {
1187             action = 'moveEmails';
1188             action = action + '&sourceFolder=' + ret['srcFolder'];
1189             action = action + '&sourceIeId=' + ret['srcIeId'];
1190             action = action + '&destinationFolder=' + ret['dstFolder'];
1191             action = action + '&destinationIeId=' + ret['dstIeId'];
1192             action = action + '&emailUids=';
1193         }
1194         if (action.search(/importEmail/) != -1) {
1195             overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
1196         } else {
1197             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
1198         }
1199
1200         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
1201         get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
1202         SUGAR.email2.detailView.importDialog.hide();
1203         document.getElementById('importDialogContent').innerHTML = "";
1204
1205     },
1206     showRelateForm : function(o) {
1207         var SED = SUGAR.email2.detailView;
1208         var ret = JSON.parse(o.responseText);
1209         document.getElementById('quickCreateContent').innerHTML = "";
1210         hideOverlay();
1211         if (!ret) {
1212             return false;
1213         }
1214         dialog_loaded = true;
1215
1216         if(!SED.relateDialog) {
1217             SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
1218                                 modal:true,
1219                                 visible:true,
1220                 fixedcenter:true,
1221                 width: '800px',
1222                 constraintoviewport: true,
1223                                 buttons : [{
1224                         text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
1225                                         if (!check_form('RelateEditView')) return false;
1226                                         var get = "";
1227                         var editView = document.getElementById('RelateEditView');
1228                         var parent_id = editView.parent_id.value;
1229                         var parent_type = editView.parent_type.value;
1230                         var row = SUGAR.email2.grid.getSelectedRows()[0];
1231                         row  = SUGAR.email2.grid.getRecord(row);
1232                         var ieId = row.getData().ieId;
1233                         var mbox = row.getData().mbox;
1234                         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
1235                         var uids = "";
1236                         for(i=0; i<emailUids.length; i++) {
1237                             if(uids != '') {
1238                                 uids += app_strings.LBL_EMAIL_DELIMITER;
1239                             }
1240                             uids += emailUids[i];
1241                         }
1242                         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1243                         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
1244                             + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
1245                         SED.relateDialog.hide();
1246                         document.getElementById('relateDialogContent').innerHTML = "";
1247                         }
1248                 }]
1249                         });
1250
1251             SED.relateDialog.hideEvent.subscribe(function(){
1252                 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
1253                         QSFieldsArray['ImportEditView_parent_name'].destroy();
1254                         delete QSFieldsArray['ImportEditView_parent_name'];
1255                 } // if
1256                                 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
1257                                         QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
1258                                 } // if
1259             });
1260
1261             SED.relateDialog.renderEvent.subscribe(function() {
1262                 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
1263                 var contH = 0;
1264                 for (var i in this.body.childNodes) {
1265                         if (this.body.childNodes[i].clientHeight)
1266                                 contH += this.body.childNodes[i].clientHeight;
1267                 }
1268             }, SED.relateDialog);
1269             SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
1270                 } // end lazy load
1271
1272         SED.relateDialog.setBody(ret.html);
1273         SED.relateDialog.render();
1274         SUGAR.util.evalScript(ret.html);
1275         SED.relateDialog.show();
1276     }
1277 };
1278 /**
1279  * DetailView callbacks
1280  */
1281 AjaxObject.detailView.callback = {
1282         emailDetail : {
1283                 success : function(o) {
1284                         SUGAR.email2.o = o;
1285                         var ret = JSON.parse(o.responseText);
1286                         SUGAR.email2.detailView.consumeMetaDetail(ret);
1287                 },
1288                 argument: [targetDiv],
1289                 failure : AjaxObject.handleFailure,
1290                 timeout : 0,
1291                 scope   : AjaxObject
1292         },
1293         emailPreview : {
1294                 success : function(o) {
1295                         SUGAR.email2.o = o;
1296                         var ret = JSON.parse(o.responseText);
1297                         SUGAR.email2.detailView.consumeMetaPreview(ret);
1298                 },
1299                 failure : AjaxObject.handleFailure,
1300                 timeout : 0,
1301                 scope   : AjaxObject
1302         },
1303         viewPrint : {
1304                 success : AjaxObject.detailView.displayPrintable,
1305                 failure : AjaxObject.handleFailure,
1306                 timeout : AjaxObject.timeout,
1307                 scope   : AjaxObject
1308         },
1309         viewRaw : {
1310                 success : AjaxObject.detailView.displayView,
1311                 failure : AjaxObject.handleFailure,
1312                 timeout : AjaxObject.timeout,
1313                 scope   : AjaxObject
1314         }
1315 };
1316
1317
1318
1319
1320
1321 AjaxObject.folders = {
1322         /**
1323          * check-mail post actions
1324          */
1325         checkMailCleanup : function(o) {
1326                 hideOverlay();
1327                 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
1328
1329                 // refresh focus ListView
1330                 SE.listView.refreshGrid();
1331                 SUGAR.email2.folders.startCheckTimer(); // resets the timer
1332         },
1333
1334         /**
1335          */
1336         rebuildFolders : function(o) {
1337                 hideOverlay();
1338
1339                 var data = JSON.parse(o.responseText);
1340
1341                 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
1342                 SUGAR.email2.folders.setSugarFolders();
1343         }
1344 };
1345 AjaxObject.folders.callback = {
1346         checkMail : {
1347                 success : AjaxObject.folders.checkMailCleanup,
1348                 failure : AjaxObject.handleFailure,
1349                 timeout : 600000, // 5 mins
1350                 scope   : AjaxObject
1351         }
1352 }
1353
1354 AjaxObject.rules = {
1355         loadRulesForSettings : function(o) {
1356                 document.getElementById("rulesListCell").innerHTML = o.responseText;
1357                 // assume we have the class we need
1358                 SUGAR.routing.getStrings();
1359                 SUGAR.routing.getDependentDropdowns();
1360         }
1361 };
1362 ////    END PER MODULE CALLBACK OBJECTS
1363 ///////////////////////////////////////////////////////////////////////////
1364
1365
1366 var callback = {
1367         success : AjaxObject.handleSuccess,
1368         failure : AjaxObject.handleFailure,
1369         timeout : AjaxObject.timeout,
1370         scope   : AjaxObject
1371 };
1372 var callbackAccount = {
1373         success : AjaxObject.ieSaveSuccess,
1374         failure : AjaxObject.handleFailure,
1375         timeout : AjaxObject.timeout,
1376         scope   : AjaxObject
1377 };
1378 var callbackAccountDelete = {
1379         success : AjaxObject.ieDeleteSuccess,
1380         failure : AjaxObject.handleFailure,
1381         timeout : AjaxObject.timeout,
1382         scope   : AjaxObject
1383 };
1384 var callbackOutboundTest = {
1385         success : AjaxObject.ieSendSuccess,
1386         failure : AjaxObject.handleFailure,
1387         timeout : AjaxObject.timeout,
1388         scope   : AjaxObject
1389 };
1390
1391
1392
1393 var callbackTeamInfoForSettings = {
1394 success : function (o) {
1395         var data = JSON.parse(o.responseText);
1396         document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
1397 },
1398 failure : AjaxObject.handleFailure,
1399 timeout : AjaxObject.timeout,
1400 scope   : AjaxObject
1401
1402 };
1403
1404 var callbackStatusForImport = {
1405 success : function (o) {
1406         hideOverlay();
1407         if (o.responseText != "")  {
1408                 var statusString = "";
1409                 var data = JSON.parse(o.responseText);
1410                 for(i=0; i<data.length; i++) {
1411                         statusString = statusString + data[i] + '<br/>';
1412                 }
1413                 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
1414         }
1415         SE.listView.refreshGrid();
1416
1417 },
1418 failure : AjaxObject.handleFailure,
1419 timeout : AjaxObject.timeout,
1420 scope   : AjaxObject
1421
1422 };
1423 var callbackComposeCache = {
1424         success : AjaxObject.composeCache,
1425         failure : AjaxObject.handleFailure,
1426         timeout : AjaxObject.timeout,
1427         scope   : AjaxObject
1428 };
1429 var callbackDelete = {
1430         success : AjaxObject.handleDeleteReturn,
1431         failure : AjaxObject.handleFailure,
1432         timeout : AjaxObject.timeout,
1433         scope   : AjaxObject
1434 };
1435 var callbackEmailDetailMultiple = {
1436         success : function(o) {
1437                 hideOverlay();
1438                 var retMulti = JSON.parse(o.responseText);
1439                 var ret = new Object();
1440
1441                 for(var i=0; i<retMulti.length; i++) {
1442                         ret = retMulti[i];
1443
1444                         SUGAR.email2._setDetailCache(ret);
1445                         SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
1446                 }
1447         },
1448         failure : AjaxObject.handleFailure,
1449         timeout : 0,
1450         scope   : AjaxObject
1451 };
1452 var callbackListViewSortOrderChange = {
1453         success : AjaxObject.saveListViewSortOrderPart2,
1454         failure : AjaxObject.handleFailure,
1455         timeout : AjaxObject.timeout,
1456         scope   : AjaxObject,
1457         argument        : [ieId, ieName, focusFolder]
1458 };
1459 var callbackEmptyTrash = {
1460         success : function(o) {
1461                 hideOverlay();
1462                 AjaxObject.folderRenameCleanup;
1463         },
1464         failure : AjaxObject.handleFailure,
1465         timeout : AjaxObject.timeout,
1466         scope   : AjaxObject
1467 };
1468 var callbackClearCacheFiles = {
1469         success : function(o) {
1470                 hideOverlay();
1471         },
1472         failure : AjaxObject.handleFailure,
1473         timeout : AjaxObject.timeout,
1474         scope   : AjaxObject
1475 };
1476 var callbackFolderRename = {
1477         success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
1478         failure : AjaxObject.handleFailure,
1479         timeout : AjaxObject.timeout,
1480         scope   : AjaxObject
1481 };
1482 var callbackFolderDelete = {
1483         success : function(o) {
1484                 var ret = JSON.parse(o.responseText);
1485                 if (ret.status) {
1486                     if (ret.folder_id) {
1487                         var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
1488                         if(node)
1489                                 SUGAR.email2.tree.removeNode(node, true);
1490                     } else if (ret.ieId && ret.mbox) {
1491                         var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
1492                         if(node)
1493                                 SUGAR.email2.tree.removeNode(node, true);
1494                     }
1495                         hideOverlay();
1496                         //SUGAR.email2.folders.loadSettingFolder();
1497                 } else {
1498                         hideOverlay();
1499                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
1500                 } // else
1501         },
1502         failure : AjaxObject.handleFailure,
1503         timeout : AjaxObject.timeout,
1504         scope   : AjaxObject
1505 };
1506 var callbackFolderSave = {
1507         success : function(o) {
1508                 var ret = JSON.parse(o.responseText);
1509
1510                 switch(ret.action) {
1511                         case 'newFolderSave':
1512                                 SUGAR.email2.folders.rebuildFolders();
1513                         break;
1514                 }
1515         },
1516         failure : AjaxObject.handleFailure,
1517         timeout : AjaxObject.timeout,
1518         scope   : AjaxObject
1519 };
1520 var callbackFolderSubscriptions = {
1521         success : AjaxObject.updateFolderSubscriptions,
1522         failure : AjaxObject.handleFailure,
1523         timeout : AjaxObject.timeout,
1524         scope   : AjaxObject
1525 };
1526 var callbackFolderUpdate = {
1527         success : AjaxObject.updateFrameFolder,
1528         failure : AjaxObject.handleFailure,
1529         timeout : AjaxObject.timeout,
1530         scope   : AjaxObject
1531 };
1532 var callbackFolders = {
1533         success : AjaxObject.folders.rebuildFolders,
1534         //success : void(true),
1535         failure : AjaxObject.handleFailure,
1536         timeout : AjaxObject.timeout,
1537         scope   : AjaxObject
1538 };
1539 var callbackFullSync = {
1540         success : AjaxObject.fullSyncCleanup,
1541         failure : AjaxObject.handleFailure,
1542         timeout : 9999999999999,
1543         scope   : AjaxObject
1544 };
1545 var callbackGeneric = {
1546         success : function() {
1547                 hideOverlay();
1548         },
1549         failure : AjaxObject.handleFailure,
1550         timeout : AjaxObject.timeout,
1551         scope   : AjaxObject
1552 };
1553 var callbackIeAccountRetrieve = {
1554         success : function(o) {
1555                 // return JSON encoding
1556                 hideOverlay();
1557                 SUGAR.email2.accounts.fillIeAccount(o.responseText);
1558                 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
1559         },
1560         failure : AjaxObject.handleFailure,
1561         timeout : AjaxObject.timeout,
1562         scope   : AjaxObject
1563 };
1564 var callbackImportOneEmail = {
1565         success :  AjaxObject.detailView.showImportForm,
1566         failure : AjaxObject.handleFailure,
1567         timeout : AjaxObject.timeout,
1568         scope   : AjaxObject
1569 };
1570 var callbackRelateEmail = {
1571     success : AjaxObject.detailView.showRelateForm,
1572     failure : AjaxObject.handleFailure,
1573     timeout : AjaxObject.timeout,
1574     scope   : AjaxObject
1575 }
1576 var callbackEmailDetailView = {
1577     success : AjaxObject.detailView.showEmailDetailView,
1578     failure : AjaxObject.handleFailure,
1579     timeout : AjaxObject.timeout,
1580     scope   : AjaxObject
1581 }
1582 var callbackAssignmentDialog = {
1583         success :  AjaxObject.detailView.showAssignmentDialogWithData,
1584         failure : AjaxObject.handleFailure,
1585         timeout : AjaxObject.timeout,
1586         scope   : AjaxObject
1587 };
1588 var callbackAssignmentAction = {
1589         success :  function(o) {
1590                 SE.listView.refreshGrid();
1591                 hideOverlay();
1592                 if(o.responseText != '') {
1593                overlay('Assignment action result', o.responseText, 'alert');
1594             } // if
1595         } ,
1596         failure : AjaxObject.handleFailure,
1597         timeout : AjaxObject.timeout,
1598         scope   : AjaxObject
1599 };
1600 var callbackMoveEmails = {
1601         success :  function(o) {
1602             SE.listView.refreshGrid();
1603                 hideOverlay();
1604                 if(o.responseText != '') {
1605                overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
1606             } // if
1607         } ,
1608         failure : AjaxObject.handleFailure,
1609         timeout : AjaxObject.timeout,
1610         scope   : AjaxObject
1611 };
1612 var callbackLoadAttachments = {
1613         success : AjaxObject.loadAttachments,
1614         failure : AjaxObject.handleFailure,
1615         timeout : AjaxObject.timeout,
1616         scope   : AjaxObject
1617 };
1618 var callbackLoadRules = {
1619         success : AjaxObject.rules.loadRulesForSettings,
1620         failure : AjaxObject.handleFailure,
1621         timeout : AjaxObject.timeout,
1622         scope   : AjaxObject
1623 };
1624 var callbackLoadSignature = {
1625         success : AjaxObject.loadSignature,
1626         failure : AjaxObject.handleFailure,
1627         timeout : AjaxObject.timeout,
1628         scope   : AjaxObject
1629 };
1630 var callbackDeleteSignature = {
1631         success : AjaxObject.handleDeleteSignature,
1632         failure : AjaxObject.handleFailure,
1633         timeout : AjaxObject.timeout,
1634         scope   : AjaxObject
1635 };
1636 /*var callbackMoveEmails = {
1637     success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
1638     failure : AjaxObject.handleFailure,
1639     timeout : AjaxObject.timeout,
1640     scope   : AjaxObject
1641 }*/
1642 var callbackOutboundSave = {
1643         success : AjaxObject.accounts.saveOutboundCleanup,
1644         failure : AjaxObject.handleFailure,
1645         timeout : AjaxObject.timeout,
1646         scope   : AjaxObject
1647 };
1648 var callbackDefaultOutboundSave = {
1649         success : AjaxObject.accounts.saveDefaultOutboundCleanup,
1650         failure : AjaxObject.handleFailure,
1651         timeout : AjaxObject.timeout,
1652         scope   : AjaxObject
1653 };
1654 var callbackQuickCreate = {
1655         success : AjaxObject.detailView.showQuickCreateForm,
1656         failure : AjaxObject.handleFailure,
1657         timeout : AjaxObject.timeout,
1658         scope   : AjaxObject
1659 };
1660 var callbackQuickCreateSave = {
1661         success : AjaxObject.detailView.saveQuickCreateForm,
1662         failure : AjaxObject.handleFailure,
1663         timeout : AjaxObject.timeout,
1664         scope   : AjaxObject
1665 };
1666 var callbackQuickCreateSaveAndAddToAddressBook = {
1667         success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
1668         failure : AjaxObject.handleFailure,
1669         timeout : AjaxObject.timeout,
1670         scope   : AjaxObject
1671 };
1672 var callbackQuickCreateSaveAndReply = {
1673     success : AjaxObject.detailView.saveQuickCreateFormAndReply,
1674     failure : AjaxObject.handleFailure,
1675     timeout : AjaxObject.timeout,
1676     scope   : AjaxObject
1677 }
1678 var callbackQuickCreateSaveAndReplyCase = {
1679     success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
1680     failure : AjaxObject.handleFailure,
1681     timeout : AjaxObject.timeout,
1682     scope   : AjaxObject
1683 }
1684 var callbackRebuildShowAccountList = {
1685         success : AjaxObject.rebuildShowFolders,
1686         failure : AjaxObject.handleFailure,
1687         timeout : AjaxObject.timeout,
1688         scope   : AjaxObject
1689 };
1690
1691 var callbackRefreshSugarFolders = {
1692         success : function(o) {
1693                 var t = JSON.parse(o.responseText);
1694                 SUGAR.email2.folders.setSugarFoldersEnd(t);
1695         },
1696         failure : AjaxObject.handleFailure,
1697         timeout : AjaxObject.timeout,
1698         scope   : AjaxObject
1699 };
1700 var callbackReplyForward = {
1701         success : AjaxObject.handleReplyForward,
1702         finish : function(a, retryCount) {
1703                 if (typeof(retryCount) == 'undefined') {
1704                         retryCount = 0;
1705                 } else {
1706                         retryCount++;
1707                 }
1708                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
1709                 var t = tinyMCE.getInstanceById('htmleditor' + idx);
1710         try {
1711                         var html = t.getContent();
1712
1713             if (a.type != 'draft') {
1714                         if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
1715                                 html += "&nbsp;<div><hr></div>" + a.description;
1716                         } else {
1717                                 html =  "&nbsp;<div><hr></div>" + a.description + html;
1718                         }
1719             }else {
1720                 html = a.description;
1721             }
1722
1723                         t.setContent(html);//
1724
1725                 } catch(e) {
1726                         if (retryCount < 5) {
1727                                 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
1728                                 return;
1729                         }
1730                 }
1731                 var tabArray = SUGAR.email2.innerLayout.get("tabs");
1732                 if (tabArray != null && tabArray.length > 0) {
1733                         for (i = 0 ; i < tabArray.length ; i++) {
1734                                 var tabObject = tabArray[i];
1735                                 if (tabObject.get("id") == ("composeTab" + idx)) {
1736                                         var tabLabel = a.name;
1737                                 if (tabLabel != null && tabLabel.length > 25) {
1738                                         tabLabel = tabLabel.substring(0, 25) + "...";
1739                                 } // if
1740                                         tabObject.get("labelEl").firstChild.data = tabLabel;
1741                                         break;
1742                                 }
1743                         }
1744                 }
1745
1746                 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
1747                 if (a.parent_name != null && a.parent_name != "") {
1748                         document.getElementById('data_parent_name' + idx).value = a.parent_name;
1749                 }
1750                 if (a.parent_type != null && a.parent_type != "") {
1751                         document.getElementById('data_parent_type' + idx).value = a.parent_type;
1752                 }
1753                 if (a.parent_id != null && a.parent_id != "") {
1754                         document.getElementById('data_parent_id' + idx).value = a.parent_id;
1755                 }
1756                 if (a.fromAccounts.status) {
1757                         var addressFrom = document.getElementById('addressFrom' + idx);
1758                 SUGAR.email2.util.emptySelectOptions(addressFrom);
1759                 var fromAccountOpts = a.fromAccounts.data;
1760                 for(i=0; i<fromAccountOpts.length; i++) {
1761                       var key = fromAccountOpts[i].value;
1762                       var display = fromAccountOpts[i].text;
1763                       var opt = new Option(display, key);
1764                       if (fromAccountOpts[i].selected) {
1765                         opt.selected = true;
1766                       }
1767                       addressFrom.options.add(opt);
1768                 }
1769                 } // if
1770                 hideOverlay();
1771
1772         },
1773         failure : AjaxObject.handleFailure,
1774         timeout : AjaxObject.timeout,
1775         scope   : AjaxObject,
1776         argument        : [sendType]
1777 };
1778 var callbackSendEmail = {
1779         success : AjaxObject.sendEmailCleanUp,
1780         failure : AjaxObject.handleFailure,
1781         timeout : AjaxObject.timeout,
1782         scope   : AjaxObject
1783 };
1784 var callbackSettings = {
1785         success : AjaxObject.updateUserPrefs,
1786         failure : AjaxObject.handleFailure,
1787         timeout : AjaxObject.timeout,
1788         scope   : AjaxObject
1789 };
1790 var callbackSettingsFolderRefresh = {
1791         success : AjaxObject.settingsFolderRefresh,
1792         failure : AjaxObject.handleFailure,
1793         timeout : AjaxObject.timeout,
1794         scope   : AjaxObject
1795 };
1796 var callbackLoadSettingFolder = {
1797         success : function(o) {
1798                 AjaxObject.settingsFolderRefresh(o);
1799                 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
1800         },
1801         failure : AjaxObject.handleFailure,
1802         timeout : AjaxObject.timeout,
1803         scope   : AjaxObject
1804
1805 };
1806 var callbackUploadAttachment = {
1807         success : AjaxObject.uploadAttachmentSuccessful,
1808         upload  : AjaxObject.uploadAttachmentSuccessful,
1809         failure : AjaxObject.handleFailure,
1810         timeout : AjaxObject.timeout,
1811         scope   : AjaxObject
1812 };
1813 var callbackUserPrefs = {
1814         success : function(o) {
1815                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
1816         },
1817         failure : AjaxObject.handleFailure,
1818         timeout : AjaxObject.timeout,
1819         scope   : AjaxObject
1820 };
1821
1822 var callbackContextmenus = {
1823         markUnread : {
1824                 success : AjaxObject.markEmailCleanup,
1825                 failure : AjaxObject.handleFailure,
1826                 timeout : AjaxObject.timeout,
1827                 scope   : AjaxObject
1828         }
1829 };
1830
1831 var callbackCheckEmail2 = {
1832         success : function(o) {
1833                 var ret = JSON.parse(o.responseText);
1834                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
1835
1836
1837         },
1838         failure : AjaxObject.handleFailure,
1839         timeout : AjaxObject.timeout,
1840         scope   : AjaxObject
1841 }// End of File modules/Emails/javascript/ajax.js
1842                                 
1843 /*********************************************************************************
1844  * SugarCRM is a customer relationship management program developed by
1845  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
1846  * 
1847  * This program is free software; you can redistribute it and/or modify it under
1848  * the terms of the GNU Affero General Public License version 3 as published by the
1849  * Free Software Foundation with the addition of the following permission added
1850  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
1851  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
1852  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
1853  * 
1854  * This program is distributed in the hope that it will be useful, but WITHOUT
1855  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1856  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
1857  * details.
1858  * 
1859  * You should have received a copy of the GNU Affero General Public License along with
1860  * this program; if not, see http://www.gnu.org/licenses or write to the Free
1861  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
1862  * 02110-1301 USA.
1863  * 
1864  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
1865  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
1866  * 
1867  * The interactive user interfaces in modified source and object code versions
1868  * of this program must display Appropriate Legal Notices, as required under
1869  * Section 5 of the GNU Affero General Public License version 3.
1870  * 
1871  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
1872  * these Appropriate Legal Notices must retain the display of the "Powered by
1873  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
1874  * technical reasons, the Appropriate Legal Notices must display the words
1875  * "Powered by SugarCRM".
1876  ********************************************************************************/
1877
1878 function gridInit() {
1879         if(SUGAR.email2.grid) {
1880                 SUGAR.email2.grid.destroy();
1881         }
1882         
1883         e2Grid = {
1884                 init : function() {
1885                 
1886                         var Ck = YAHOO.util.Cookie;
1887                         var widths = [ 10, 10, 150, 250, 175, 125 ];
1888
1889                         if (Ck.get("EmailGridWidths")) {
1890                                 for (var i=0; i < widths.length; i++) {
1891                                         widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
1892                                 }
1893                         } else {
1894                                 for (var i=0; i < widths.length; i++) {
1895                                         Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
1896                                 }
1897                         }
1898                         
1899                         // changes "F" to an icon
1900                         function flaggedIcon(cell, record, column, value) {
1901                                 if(value != "") {
1902                                         cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
1903                                 }
1904                         }
1905                         // changes "A" to replied icon
1906                         function repliedIcon(cell, record, column, value) {
1907                                 if(value != "") {
1908                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
1909                                 }
1910                         }
1911                 function attachIcon(cell, record, column, value) {
1912                                 if(value == "1") {
1913                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
1914                                 }
1915                         }
1916
1917                         var colModel = 
1918                                 [
1919                                         {
1920                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>", 
1921                                                 width: 10, 
1922                                                 sortable: false, 
1923                                                 fixed: true,
1924                                                 resizeable: true,
1925                                                 formatter: attachIcon,
1926                                                 key: 'hasAttach'
1927                                         }, 
1928                                     {
1929                                                 label: "<span style='color: #f00; font-weight:bold;'>!</span>", 
1930                                                 width: widths[0], 
1931                                                 sortable: true, 
1932                                                 fixed: true,
1933                                                 resizeable: true,
1934                                                 formatter: flaggedIcon,
1935                                                 key: 'flagged'
1936                                         }, 
1937                                         {
1938                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>", 
1939                                                 width: widths[1], 
1940                                                 sortable: true, 
1941                                                 fixed: true,
1942                                                 resizeable: true,
1943                                                 formatter: repliedIcon,
1944                                                 key: 'status'
1945                                         },
1946                                         {
1947                                                 label: app_strings.LBL_EMAIL_FROM, 
1948                                                 width: widths[2],
1949                                                 sortable: true,
1950                                                 resizeable: true,
1951                                                 key: 'from'
1952                                         }, 
1953                                         {
1954                                                 label: app_strings.LBL_EMAIL_SUBJECT,
1955                                                 width: widths[3], 
1956                                                 sortable: true,
1957                                                 resizeable: true,
1958                                                 key: 'subject'
1959                                         }, 
1960                                         {
1961                                                 label: mod_strings.LBL_LIST_DATE,
1962                                                 width: widths[4], 
1963                                                 sortable: true,
1964                                                 resizeable: true,
1965                         key: 'date'
1966                                         }, 
1967                                         {
1968                                                 label: app_strings.LBL_EMAIL_TO,
1969                                                 width: widths[5], 
1970                                                 sortable: false,
1971                                                 resizeable: true,
1972                         key: 'to_addrs'
1973                                         }, 
1974                                         {
1975                                                 label: 'uid',
1976                                                 hidden: true,
1977                         key: 'uid'
1978                                         }, 
1979                                         {
1980                                                 label: 'mbox',
1981                                                 hidden: true,
1982                         key: 'mbox'
1983                                         }, 
1984                                         {
1985                                                 label: 'ieId',
1986                                                 hidden: true,
1987                         key: 'ieId'
1988                                         }, 
1989                                         {       
1990                                                 label: 'site_url',
1991                                                 hidden: true,
1992                         key: 'site_url'
1993                                         },
1994                                         {       label: 'seen',
1995                                                 hidden: true,
1996                         key: 'seen'
1997                                         },
1998                                         {       label: 'type',
1999                                                 hidden: true,
2000                         key: 'type'
2001                                         }
2002                                 ];
2003                         
2004                         var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2005                                 responseType: YAHOO.util.DataSource.TYPE_JSON,
2006                                 responseSchema: {
2007                                     resultsList: 'Email',
2008                             fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
2009                             metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
2010                                 }
2011                     });
2012                         var params = {
2013                                         to_pdf : "true",
2014                                         module : "Emails",
2015                                         action : "EmailUIAjax",
2016                                         emailUIAction : "getMessageList",
2017                                         mbox : "INBOX",
2018                                         ieId : "",
2019                                         forceRefresh : "false"
2020                         };
2021                         if(lazyLoadFolder != null) {
2022                                 params['mbox'] = lazyLoadFolder.folder;
2023                                 params['ieId'] = lazyLoadFolder.ieId;
2024                                 //Check if the folder is a Sugar Folder
2025                                 var test = new String(lazyLoadFolder.folder);
2026                                 if(test.match(/SUGAR\./)) {
2027                                         params['emailUIAction'] = 'getMessageListSugarFolders';
2028                                         params['mbox'] = test.substr(6);
2029                                 }
2030                         }
2031                         //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
2032         
2033                         // create the Grid
2034                         var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
2035                                 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2036                                 dynamicData: true,
2037                                 paginator: new YAHOO.widget.Paginator({ 
2038                                         rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),  
2039                                         containers : ["dt-pag-nav"],
2040                                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2041                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
2042                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
2043                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
2044                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
2045                                 }),
2046                                 initialRequest:SUGAR.util.paramsToUrl(params),
2047                                 width:  "800px",
2048                                 height: "400px"
2049                         });
2050
2051                         initRowDD();
2052
2053                         //Override Paging request construction
2054                         grid.set("generateRequest", function(oState, oSelf) {
2055                     oState = oState || {pagination:null, sortedBy:null};
2056                     var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
2057                     var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2058                     var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2059                     var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2060                     // Build the request 
2061                     var ret = 
2062                             SUGAR.util.paramsToUrl(oSelf.params) + 
2063                             "&sort=" + sort +
2064                         "&dir=" + dir +
2065                         "&start=" + startIndex +
2066                         ((results !== null) ? "&limit=" + results : "");
2067                     return  ret;
2068                 });
2069                         
2070                         
2071                         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
2072                                 oPayload = oPayload || { };
2073                                 
2074                                 oPayload.totalRecords = oResponse.meta.total;
2075                                 oPayload.unreadRecords = oResponse.meta.unread;
2076                                 
2077                         var tabObject = SE.innerLayout.get("tabs")[0];
2078                         var mboxTitle = "";
2079                         if (this.params.mbox != null) {
2080                                 mboxTitle = this.params.mbox;
2081                         }
2082                         var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
2083                         tabObject.get("labelEl").firstChild.data = tabtext;
2084                         
2085                         if (SE.tree) {
2086                                 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
2087                                 if (node) {
2088                                         node.data.unseen = oResponse.meta.unread;
2089                                         SE.accounts.renderTree();
2090                                 }
2091                         }
2092                                 return oPayload; 
2093                         }
2094                         
2095                         var resize = grid.resizeGrid = function () {
2096                                 SUGAR.email2.grid.set("width",  SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
2097                                 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
2098                         }
2099                         grid.convertDDRows = function() {
2100                                 var rowEl = this.getFirstTrEl();
2101                                 while (rowEl != null) {
2102                                         new this.DDRow(this, this.getRecord(rowEl), rowEl);
2103                                         rowEl = this.getNextTrEl(rowEl);
2104                                 }
2105                         }
2106                         
2107                         
2108                         grid.on("columnResizeEvent", function(o) {
2109                                 //Find the index of the column
2110                                 var colSet = SUGAR.email2.grid.getColumnSet().flat;
2111                                 for (var i=0; i < colSet.length; i++) {
2112                                         if (o.column == colSet[i]) {
2113                                                 //Store it in the cookie
2114                                                 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
2115                                         }
2116                                 }
2117                                 //this.resizeGrid();
2118                         }, null, grid); 
2119                         
2120                         grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
2121                         grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);  
2122                         grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);  
2123                         grid.render();
2124                         SUGAR.email2.listViewLayout.on("render", resize);
2125                         resize();
2126                         
2127                         //Setup the default load parameters
2128                         SUGAR.email2.grid.params = params;
2129                         
2130                         grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
2131                         dataModel.subscribe("requestEvent", grid.disable, grid, true);
2132                         dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2133                 }
2134         };
2135         e2Grid.init();
2136 };
2137
2138
2139 function initRowDD() {
2140         var sg = SUGAR.email2.grid,
2141         Dom = YAHOO.util.Dom;
2142         sg.DDRow = function(oDataTable, oRecord, elTr) {
2143                 if(oDataTable && oRecord && elTr) {
2144                         this.ddtable = oDataTable;
2145                 this.table = oDataTable.getTableEl();
2146                 this.row = oRecord;
2147                 this.rowEl = elTr;
2148                 this.newIndex = null;
2149                 this.init(elTr);
2150                 this.initFrame(); // Needed for DDProxy
2151                 this.invalidHandleTypes = {};
2152             }   
2153         };
2154         
2155         YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
2156             _resizeProxy: function() {
2157                 this.constructor.superclass._resizeProxy.apply(this, arguments);
2158                 var dragEl = this.getDragEl(),
2159                     el = this.getEl();
2160                 var xy = Dom.getXY(el);
2161                 
2162                 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
2163                 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
2164                 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
2165                 Dom.setStyle(dragEl, 'display', "");
2166             },
2167             
2168             startDrag: function(x, y) { 
2169                 //Check if we should be dragging a set of rows rather than just the one.
2170                 var selectedRows = this.ddtable.getSelectedRows();
2171                 var iSelected = false;
2172                 for (var i in selectedRows) {
2173                         if (this.rowEl.id == selectedRows[i]) {
2174                                 iSelected = true;
2175                                 break
2176                         }
2177                 }
2178                 if (iSelected) {
2179                         this.rows = [];
2180                         for (var i in selectedRows) {
2181                                 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
2182                         }
2183                 } else {
2184                         this.rows = [this.row];
2185                         this.ddtable.unselectAllRows();
2186                         this.ddtable.selectRow(this.row);
2187                 }
2188                 
2189                 //Initialize the dragable proxy
2190                 var dragEl = this.getDragEl(); 
2191                 var clickEl = this.getEl(); 
2192                 Dom.setStyle(clickEl, "opacity", "0.25"); 
2193                 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>"; 
2194                 Dom.addClass(dragEl, "yui-dt-liner");
2195                 Dom.setStyle(dragEl, "opacity", "0.5"); 
2196                 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
2197                 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); 
2198                     Dom.setStyle(dragEl, "border", "2px solid gray"); 
2199             },
2200             
2201             clickValidator: function(e) {
2202                 if (this.row.getData()[0] == " ")
2203                         return false;
2204                 var target = YAHOO.util.Event.getTarget(e);
2205                 return ( this.isValidHandleChild(target) && 
2206                                 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
2207             },
2208             /**
2209              * This funciton checks that the target of the drag is a table row in this
2210              * DDGroup and simply moves the sourceEL to that location as a preview.
2211              */
2212             onDragOver: function(ev, id) {
2213                 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
2214                 if (node && node != this.targetNode) {
2215                         this.targetNode = node;
2216                         SUGAR.email2.folders.unhighliteAll();
2217                         node.highlight();
2218                 }
2219             },
2220             
2221             onDragOut: function(e, id) {
2222                 if (this.targetNode) {
2223                         SUGAR.email2.folders.unhighliteAll();
2224                         this.targetNode = false;
2225                 }
2226             },
2227             endDrag: function() {
2228                 Dom.setStyle(this.getEl(), "opacity", "");
2229                 Dom.setStyle(this.getDragEl(), "display", "none"); 
2230                 if (this.targetNode) {
2231                         SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
2232                 }
2233                 SUGAR.email2.folders.unhighliteAll();
2234                 this.rows = null;
2235             }
2236         });
2237 }
2238
2239 function AddressSearchGridInit() {
2240     function moduleIcon(elCell, oRecord, oColumn, oData) {
2241         elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
2242     };
2243     function selectionCheckBox(elCell, oRecord, oColumn, oData) {
2244         elCell.innerHTML =  '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
2245     };
2246     var checkHeader = '<input type="checkbox" ';
2247     if (SUGAR.email2.util.isIe()) {
2248         checkHeader += 'style="top:-5px" ';
2249     }
2250     checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
2251     var colModel = 
2252             [{
2253                 label: checkHeader,
2254             width: 30,
2255             formatter: selectionCheckBox,
2256             key: 'bean_id'
2257         },
2258             {
2259                 label: mod_strings.LBL_LIST_TYPE,
2260                 width: 25,
2261                 formatter: moduleIcon,
2262                 key: 'bean_module'
2263         },
2264             {
2265                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME, 
2266                 width: 180,
2267                 sortable: true,
2268                 key: 'name'
2269             }, 
2270             {
2271                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
2272                 width: 300, 
2273                 sortable: true,
2274                 key: 'email'
2275             }];
2276     
2277     var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
2278                 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
2279         responseSchema: {
2280             resultsList: 'Person',
2281             fields: ['name', 'email', 'bean_id', 'bean_module'],
2282                     metaFields: {total: 'TotalCount'}
2283         },
2284         //enable sorting on the server accross all data
2285         remoteSort: true
2286     });
2287     dataModel.params = {
2288                 to_pdf          : true,
2289                 module          : "Emails",
2290                 action          : "EmailUIAjax",
2291                 emailUIAction:"getAddressSearchResults"
2292     }
2293     var rb = document.getElementById('hasRelatedBean').checked;
2294         if (rb) {
2295                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
2296                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2297                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2298                 dataModel.params['related_bean_id'] = relatedBeanId;
2299                 dataModel.params['related_bean_type'] = relatedBeanType;
2300                 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
2301         }
2302     SUGAR.email2.addressBook.addressBookDataModel = dataModel;
2303     
2304     var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
2305         MSG_EMPTY: "&nbsp;", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
2306                 dynamicData: true,
2307                 paginator: new YAHOO.widget.Paginator({ 
2308                         rowsPerPage: 25,  
2309                         containers : ["dt-pag-nav-addressbook"],
2310                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
2311                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
2312                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
2313                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
2314                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
2315                 }),
2316                 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
2317                 width:  "560px",
2318                 height: "250px"
2319     });
2320         //Override Paging request construction
2321         grid.set("generateRequest", function(oState, oSelf) {
2322         oState = oState || {pagination:null, sortedBy:null};
2323         var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
2324         var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
2325         var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
2326         var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
2327         // Build the request 
2328         var ret = 
2329             SUGAR.util.paramsToUrl(oSelf.getDataSource().params) + 
2330             "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
2331             ((results !== null) ? "&limit=" + results : "");
2332         return  ret;
2333     });
2334     
2335         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
2336                 oPayload = oPayload || { };
2337                 oPayload.totalRecords = oResponse.meta.total;
2338                 return oPayload; 
2339         }
2340         
2341         grid.clickToggleSelect= function(args) {
2342                 var isIE = (args.event.target == null);
2343                 var targetElement = isIE ? args.event.srcElement : args.event.target;
2344                 if(targetElement.type == null || targetElement.type != 'checkbox') {
2345                         SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
2346                 }
2347         }
2348         
2349         grid.reSelectRowsOnRender = function (){
2350             var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2351         for (var i = 0; i < rows.length; i++) 
2352         {
2353                 var emailAddress = rows[i].getData("email");
2354             var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
2355             if(alreadyAdded)
2356             {
2357                 rows[i].setData("selected",  true);
2358                         SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2359             }
2360             else
2361             {
2362                 rows[i].setData("selected",  false);
2363                 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
2364             }
2365         }
2366         }
2367         grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow); 
2368         grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow); 
2369         grid.subscribe("rowClickEvent", grid.clickToggleSelect);
2370     grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
2371     
2372     grid.render();
2373     dataModel.subscribe("requestEvent", grid.disable, grid, true);
2374     dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
2375     
2376     grid.toggleSelectCheckbox = function(id,checked){
2377         var row = SUGAR.email2.addressBook.grid.getRecord(id);
2378         row.setData("checked",checked);
2379     };
2380     grid.toggleSelect = function(id, checked) {
2381         var row = SUGAR.email2.addressBook.grid.getRecord(id);
2382         checked = row.getData("selected");
2383         if (!checked)
2384         {
2385             SUGAR.email2.addressBook.grid.selectRow(row);
2386             SE.addressBook.insertContactRowToResultTable(id,null)
2387         } else 
2388         {
2389             SUGAR.email2.addressBook.grid.unselectRow(row);
2390             SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
2391         }
2392         row.setData("selected", !checked);
2393     };
2394     
2395     grid.toggleSelectAll = function(checked) {
2396         rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2397         for (var i = 0; i < rows.length; i++) {
2398                         if (typeof(rows[i]) != "undefined")
2399                                 rows[i].setData("checked",  checked);
2400         }
2401         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2402         for (var i = 0; i < checkBoxes.length; i++) {
2403             checkBoxes[i].checked = checked;
2404         }
2405     };
2406     
2407     //Initialize the grid result table.
2408     AddressSearchResultsGridInit();
2409 }
2410
2411
2412
2413 /**
2414 *  Initalize the results table for the address book selection.
2415 *
2416 */
2417 function AddressSearchResultsGridInit()
2418 {
2419     
2420     /* Full name sort funciton to compare by last name if available */
2421     var fullNameSort = function(a, b, desc) {
2422         // Deal with empty values
2423         if(!YAHOO.lang.isValue(a))
2424             return (!YAHOO.lang.isValue(b)) ? 0 : 1;
2425         else if(!YAHOO.lang.isValue(b))
2426             return -1;
2427
2428         var aNames = a.getData("name").split(' ');
2429         var bNames = b.getData("name").split(' ');
2430
2431         var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
2432         var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
2433
2434         return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
2435
2436     };
2437     
2438     var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
2439                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
2440                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')]; 
2441               
2442     var ColumnDefs = [{key:'type',label:app_strings.LBL_EMAIL_ADDRESS_BOOK_ADRRESS_TYPE, width: 60, sortable: true, editor: new YAHOO.widget.RadioCellEditor({radioOptions:typeDdOptions,disableBtns:true})},
2443                      {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
2444      
2445      var myDataSource = new YAHOO.util.DataSource([]); 
2446          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
2447          myDataSource.responseSchema = { 
2448                     fields: ["name","type","email_address","display_email_address","bean_id","idx"] 
2449                 };                                                                 
2450     
2451          var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
2452                         width:  "350px",height: "250px", MSG_EMPTY: "&nbsp;"});
2453     
2454      var highlightEditableCell = function(oArgs) {
2455             var elCell = oArgs.target;
2456             if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
2457                 this.highlightCell(elCell);
2458             }
2459         };
2460       
2461      gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
2462      gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
2463      gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
2464      gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow); 
2465          gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow); 
2466      
2467      //Setup the context menus
2468      var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) { 
2469              var task = p_aArgs[1]; 
2470              if(task) 
2471              { 
2472                  var elRow = this.contextEventTarget; 
2473                  elRow = p_myDataTable.getTrEl(elRow); 
2474          
2475                  if(elRow) 
2476                  { 
2477                      switch(task.index) 
2478                      { 
2479                          case 0:     
2480                              var oRecord = p_myDataTable.getRecord(elRow); 
2481                              p_myDataTable.deleteRow(elRow);  
2482                              SUGAR.email2.addressBook.grid.reSelectRowsOnRender();    
2483                      } 
2484                  } 
2485              } 
2486          };
2487      var contextMenu = new YAHOO.widget.ContextMenu("contextmenu", 
2488                         {trigger:gridResults.getTbodyEl()}); 
2489          contextMenu.addItem(app_strings.LBL_EMAIL_DELETE); 
2490          contextMenu.render("addrSearchResultGrid"); 
2491          contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults); 
2492 }
2493 // End of File modules/Emails/javascript/grid.js
2494                                 
2495 /*********************************************************************************
2496  * SugarCRM is a customer relationship management program developed by
2497  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
2498  * 
2499  * This program is free software; you can redistribute it and/or modify it under
2500  * the terms of the GNU Affero General Public License version 3 as published by the
2501  * Free Software Foundation with the addition of the following permission added
2502  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
2503  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
2504  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
2505  * 
2506  * This program is distributed in the hope that it will be useful, but WITHOUT
2507  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
2508  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
2509  * details.
2510  * 
2511  * You should have received a copy of the GNU Affero General Public License along with
2512  * this program; if not, see http://www.gnu.org/licenses or write to the Free
2513  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
2514  * 02110-1301 USA.
2515  * 
2516  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
2517  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
2518  * 
2519  * The interactive user interfaces in modified source and object code versions
2520  * of this program must display Appropriate Legal Notices, as required under
2521  * Section 5 of the GNU Affero General Public License version 3.
2522  * 
2523  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
2524  * these Appropriate Legal Notices must retain the display of the "Powered by
2525  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
2526  * technical reasons, the Appropriate Legal Notices must display the words
2527  * "Powered by SugarCRM".
2528  ********************************************************************************/
2529
2530  (function() {
2531         var sw = YAHOO.SUGAR,
2532                 Event = YAHOO.util.Event,
2533                 Connect = YAHOO.util.Connect,
2534             Dom = YAHOO.util.Dom
2535             SE = SUGAR.email2;
2536
2537 ///////////////////////////////////////////////////////////////////////////////
2538 ////    ADDRESS BOOK
2539 SE.addressBook = {
2540     _contactCache : new Array(), // cache of contacts
2541     _dd : new Array(), // filtered list, same format as _contactCache
2542     _ddLists : new Array(), // list of Lists
2543     _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
2544     _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
2545     clickBubble : true, // hack to get around onclick event bubbling
2546         relatedBeanId : '',
2547         relatedBeanType : '',
2548         idx : 0,
2549
2550     itemSpacing : 'white-space:nowrap; padding:2px;',
2551     reGUID : SE.reGUID,
2552
2553
2554
2555     /**
2556     *  YUI bug fix 2527707.  Causes nested datatable's in <tables> to cause 404 errors whens earching.
2557     */
2558     initFixForDatatableSort: function () {
2559         //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
2560         YAHOO.widget.DataTable.prototype.getColumn = function(column) {
2561             var oColumn = this._oColumnSet.getColumn(column);
2562
2563             if(!oColumn) {
2564                 // Validate TD element
2565                 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
2566                 if(elCell) {
2567                     oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
2568                 }
2569                 // Validate TH element
2570                 else {
2571                     elCell = this.getThEl(column);
2572                     if(elCell) {
2573                         // Find by TH el ID
2574                         var allColumns = this._oColumnSet.flat;
2575                         for(var i=0, len=allColumns.length; i<len; i++) {
2576                             if(allColumns[i].getThEl().id === elCell.id) {
2577                                 oColumn = allColumns[i];
2578                             }
2579                         }
2580                     }
2581                 }
2582             }
2583
2584             return oColumn;
2585         };
2586     },
2587
2588     cancelEdit : function() {
2589         if(this.editContactDialog)
2590             this.editContactDialog.hide();
2591         if(this.editMailingListDialog)
2592             this.editMailingListDialog.hide();
2593     },
2594
2595     /**
2596      * Clears filter form
2597      */
2598     clear : function() {
2599         var t = document.getElementById('contactsFilter');
2600         t.value = '';
2601         this.filter(t);
2602     },
2603
2604     /**
2605      * handle context-menu Compose-to call
2606      * @param string type 'contacts' or 'lists'
2607      */
2608     composeTo : function(type, waited) {
2609         var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
2610         if (activePanel.substring(0, 10) != "composeTab") {
2611             SE.composeLayout.c0_composeNewEmail();
2612             setTimeout("SE.addressBook.composeTo('" + type + "', true);");
2613                 SE.contextMenus.contactsContextMenu.hide();
2614             return;
2615         }
2616         var idx = activePanel.substring(10);
2617         var rows = [ ];
2618         var id = '';
2619         // determine if we have a selection to work with
2620         if(type == 'contacts') {
2621             var ids = SE.contactView.getSelectedRows();
2622             for (var i in ids) {
2623                 rows[i] = SE.contactView.getRecord(ids[i]);
2624             }
2625             removeHiddenNodes(rows, SE.contactView);
2626         }
2627                 else { return; }
2628
2629         if(rows.length > 0) {
2630             SE.composeLayout.handleDrop(
2631                 (type == 'contacts') ? SE.contactView : SE.emailListsView,
2632                 null, rows, 'addressTO' + idx );
2633         } else {
2634             alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
2635         }
2636     },
2637
2638     editContact : function() {
2639         SE.contextMenus.contactsContextMenu.hide();
2640         var element = SE.contactView.getSelectedNodes()[0];
2641         var elementId = "";
2642         if (element.className.indexOf('address-contact') > -1) {
2643             elementId = element.id;
2644         } else if (element.className.indexOf('address-exp-contact') > -1) {
2645             elementId = element.id.substring(2);
2646         }
2647     },
2648
2649
2650     /**
2651      * Filters contact entries based on user input
2652      */
2653     filter : function(inputEl) {
2654         var ret = new Object();
2655         var re = new RegExp(inputEl.value, "gi");
2656
2657         for(var i in this._contactCache) {
2658             if(this._contactCache[i].name.match(re)) {
2659                 ret[i] = this._contactCache[i];
2660             }
2661         }
2662
2663         this.buildContactList(ret);
2664     },
2665
2666     fullForm : function(id, module) {
2667         document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
2668     },
2669
2670     /**
2671      * returns a formatted email address from the addressBook cache
2672      */
2673     getFormattedAddress : function(id) {
2674         var o = this._contactCache[id];
2675         var primaryEmail = '';
2676
2677         for(var i=0; i<o.email.length; i++) {
2678             var currentEmail = o.email[i].email_address;
2679
2680             if(o.email[i].primary_address == 1) {
2681                 primaryEmail = o.email[i].email_address;
2682             }
2683         }
2684
2685         var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
2686         var name = new String(o.name);
2687         var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/&#039;/gi,'\'');
2688         var ret = finalName + " <" + finalEmail.replace(/&#039;/gi,'\'') + ">";
2689
2690         return ret;
2691     },
2692
2693     /**
2694      * Sets up async call to query for matching contacts, users, etc.
2695      */
2696     searchContacts : function() {
2697         var fn = document.getElementById('input_searchField').value;
2698         var pe = document.getElementById('input_searchPerson').value;
2699
2700         var rb = document.getElementById('hasRelatedBean').checked;
2701         if (rb) {
2702                         var idx = this.idx;
2703                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2704                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2705                 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2706                 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2707         } else {
2708                 this.addressBookDataModel.params['related_bean_id'] = '';
2709         }
2710
2711         this.addressBookDataModel.params['search_field'] = fn;
2712         this.addressBookDataModel.params['person'] = pe;
2713         this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
2714         this.grid._oDataSource = this.addressBookDataModel;
2715         this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params),  this.grid.onDataReturnInitializeTable, this.grid);
2716     },
2717
2718     /**
2719      * Clear Search Crieteria For Addressbook
2720      */
2721     clearAddressBookSearch : function() {
2722         document.getElementById('input_searchField').value = "";
2723         document.getElementById('input_searchPerson').selectedIndex = 0;
2724     },
2725
2726     /**
2727      * Opens modal select window to add contacts to addressbook
2728      */
2729     selectContactsDialogue : function(destId) {
2730         if(!this.contactsDialogue) {
2731                 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
2732                 modal:true,
2733                 visible:false,
2734                 draggable: false,
2735                 constraintoviewport: true,
2736                 width   : 980,
2737                 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
2738                            {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
2739             });
2740                 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
2741
2742                 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
2743                 dlg.setBody(body.innerHTML);
2744                 dlg.renderEvent.subscribe(function() {
2745                 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
2746                 if (iev && !SUGAR.isIE) {
2747                         this.body.style.width = "950px";
2748                 }
2749             }, dlg);
2750
2751
2752                 dlg.beforeRenderEvent.subscribe(function() {
2753                         var dd = new YAHOO.util.DDProxy(dlg.element);
2754                         dd.setHandleElId(dlg.header);
2755                         dd.on('endDragEvent', function() {
2756                                 dlg.show();
2757                         });
2758                 }, dlg, true);
2759                 dlg.render();
2760
2761                 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
2762
2763                 var tabContent = SUGAR.util.getAndRemove("searchForm");
2764                 tp.addTab(new YAHOO.widget.Tab({
2765                                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
2766                                 scroll : true,
2767                                 content : tabContent.innerHTML,
2768                                 id : "addressSearchTab",
2769                                 active : true
2770                         }));
2771
2772                 var addListenerFields = ['input_searchPerson','input_searchField' ]
2773                 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
2774                         if (e.keyCode == 13) {
2775                                 YAHOO.util.Event.stopEvent(e);
2776                                 SUGAR.email2.addressBook.searchContacts();
2777                         }
2778                 });
2779
2780                 this.contactsDialogue.render();
2781                 dlg.center();
2782         }
2783         //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
2784         if (typeof(SUGAR.email2.innerLayout) == 'undefined')
2785             var idx = 0;
2786         else
2787         {
2788             var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
2789             var idx = activePanel.substring(10);
2790         }
2791         SE.addressBook.idx = idx;
2792
2793                 var relatedBeanId;
2794         if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
2795                 document.getElementById('relatedBeanColumn').style.display = '';
2796                 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
2797                         var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
2798                         relatedBeanId = document.getElementById('data_parent_id' + idx).value;
2799                         document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
2800                         SE.addressBook.relatedBeanType = relatedBeanType;
2801             } else {
2802                 document.getElementById('relatedBeanColumn').style.display = 'none';
2803                 document.getElementById('hasRelatedBean').checked = false;
2804             }
2805
2806             if (!SE.addressBook.grid)
2807             {
2808                 if (hasRelatedBeanId) {
2809                         document.getElementById('hasRelatedBean').checked = true;
2810                 }
2811                 AddressSearchGridInit();
2812                         SE.addressBook.relatedBeanId = relatedBeanId;
2813             }
2814             else
2815             {
2816                 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
2817                 {
2818                         SE.addressBook.relatedBeanId = relatedBeanId;
2819                         document.getElementById('hasRelatedBean').checked = true;
2820                 }
2821                 if (document.getElementById('hasRelatedBean').checked == true)
2822                 {
2823                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
2824                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
2825                 } else {
2826                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
2827                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
2828                 }
2829                 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
2830                         SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
2831                 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params),  SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
2832             }
2833
2834             //Remove any lingering rows in the result set table if the module was closed.
2835             SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2836             //Repopulate
2837             SE.addressBook.populateResulstTableEmailAddresses();
2838
2839         this.contactsDialogue.show();
2840     },
2841     /**
2842     *  Clear all email addresses from result table.
2843     *
2844     */
2845     clearAllEmailAddressFieldsFromResultTable: function () {
2846         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2847         //Unhighlight any rows currently selected if the emails were cleared.
2848         SUGAR.email2.addressBook.grid.toggleSelectAll(false);
2849         SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
2850     },
2851     /**
2852     *  Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
2853     *  results table.  This function is called when the address book is displayed.
2854     */
2855     populateResulstTableEmailAddresses: function () {
2856
2857         var idx = SE.addressBook.idx;
2858         var emailFields = ['to','cc','bcc'];
2859
2860         for(var k=0;k<emailFields.length;k++)
2861         {
2862             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2863             var allEmails = document.getElementById(elKey).value;
2864             if(allEmails == '')
2865                 continue;
2866
2867             var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
2868
2869                 for (var i=0; i<formatedEmails.length; i++)
2870                 {
2871                     var t_name = formatedEmails[i].name;
2872                     var t_emailAddr = formatedEmails[i].email_address;
2873                     var displayEmail = t_name + ' <' + t_emailAddr + '>';
2874                     if(t_name == '')
2875                         t_name = displayEmail = t_emailAddr;
2876
2877                     var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
2878                 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
2879                     'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
2880                 }
2881         }
2882     },
2883
2884     /**
2885     * Checks all entries in the result table against a particular email address, returning true
2886     * if the email address is found, false otherwise.
2887     */
2888     doesEmailAdddressExistInResultTable: function(emailAddress)
2889     {
2890         if(trim(emailAddress) == '')
2891             return false;
2892
2893         var emailAddressFound = false;
2894         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2895         for (var i=0; i < contacts.length; i++)
2896         {
2897             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2898             //If we are adding to cc or bcc fields, make them visible.
2899             if(data.email_address == emailAddress)
2900             {
2901                 emailAddressFound = true;
2902                 break;
2903             }
2904         }
2905
2906         return emailAddressFound;
2907     },
2908     /**
2909     *  Takes all email addresses that the users wishes to add from the address book and populates the To
2910     *  fields on the compose tab.
2911     */
2912     populateEmailAddressFieldsFromResultTable: function()
2913     {
2914         //Clear the fields first, all email addresses are stored in the address book
2915         var idx = SE.addressBook.idx;
2916         var emailFields = ['to','cc','bcc'];
2917         for(var k=0;k<emailFields.length;k++)
2918         {
2919             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
2920             document.getElementById(elKey).value = "";
2921         }
2922
2923         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2924         for (var i=0; i < contacts.length; i++)
2925         {
2926             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
2927
2928             var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
2929             //If we are adding to cc or bcc fields, make them visible.
2930             if(addressTypeKey =='cc' || addressTypeKey =='bcc')
2931                 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
2932             //Construct the target id
2933             var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
2934
2935             var target = document.getElementById(target_id);
2936             target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
2937         }
2938
2939         //Delete all rows from the result set table
2940         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
2941
2942         //Hide the dialogue
2943         SE.addressBook.contactsDialogue.hide()
2944     },
2945     /**
2946     *  Insert contacts into the result table.
2947     */
2948     insertContactToResultTable : function(event,address_type) {
2949
2950         var contactsDialogue = SE.addressBook.contactsDialogue;
2951         var contacts = SE.addressBook.grid.getSelectedRows();
2952
2953         var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
2954         for (var i = 0; i < rows.length; i++)
2955         {
2956                         if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
2957                         {
2958                             var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
2959                 SE.addressBook.insertContactRowToResultTable(recId,address_type);
2960                 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
2961                 rows[i].setData("selected",true);
2962                         }
2963         }
2964         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
2965         for (var i = 0; i < checkBoxes.length; i++) {
2966             checkBoxes[i].checked = false;
2967         }
2968     },
2969     /**
2970     *
2971     */
2972     insertContactRowToResultTable : function(rowId, addressType) {
2973         var data = SE.addressBook.grid.getRecord(rowId).getData();
2974         if(SE.addressBook.doesGridResultsEntryExist(data.email) )
2975                 return;
2976         var name = data.name.replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
2977         var ea = name + ' <' + data.email.replace(/&#039;/gi,'\'') + '>';
2978         if(addressType == null)
2979             addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
2980         SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':name,'email_address': data.email,'display_email_address': ea,'bean_id': data.bean_id,'idx' : SE.addressBook.idx});
2981     },
2982     /**
2983     * Remove a row from the gridsResult table.
2984     */
2985     removeRowFromGridResults : function(rowId,emailAddress)
2986     {
2987         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
2988         for (var i=0; i < contacts.length; i++)
2989         {
2990             var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
2991             var data = rec.getData();
2992             if(data.email_address == emailAddress)
2993             {
2994                 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
2995                 break;
2996             }
2997         }
2998
2999        SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
3000     },
3001     /**
3002     * Translates between the addressType To|Cc|Bcc labels/keys.
3003     */
3004     translateAddresType: function(addressType,fromKey)
3005     {
3006         var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
3007         var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
3008         var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
3009         var mappingObject = {};
3010
3011         if(fromKey)
3012             mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
3013         else
3014         {
3015             mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
3016             mappingObject[displayCc] = 'cc';
3017             mappingObject[displayBcc] = 'bcc';
3018         }
3019
3020         return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
3021
3022     },
3023     /**
3024     *
3025     */
3026     toggleSearchRowIcon : function(rowId,show)
3027     {
3028         if(show)
3029         {
3030             var idToShow = rowId + '_add_img';
3031             var idToHide = rowId + '_rm_img';
3032         }
3033         else
3034         {
3035             var idToShow = rowId + '_rm_img';
3036             var idToHide = rowId + '_add_img';
3037         }
3038
3039
3040         Dom.addClass(idToHide, "yui-hidden");
3041         Dom.removeClass(idToShow, "yui-hidden");
3042     },
3043     /**
3044     * Determine if an entry has already been added to the grid results table to prevent duplicates.
3045     */
3046     doesGridResultsEntryExist: function(emailAddrs)
3047     {
3048
3049         var contactExists = false;
3050         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
3051         for (var i=0; i < contacts.length; i++)
3052         {
3053             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
3054             if(data.email_address == emailAddrs)
3055             {
3056                 contactExists = true;
3057                 break;
3058             }
3059         }
3060         return contactExists;
3061     },
3062
3063     /**
3064      * adds an email address to a string, but first checks if it exists
3065      * @param string concat The string we are appending email addresses to
3066      * @param string addr Email address to add
3067      * @return string
3068      */
3069     smartAddEmailAddressToComposeField : function(concat, addr) {
3070         var re = new RegExp(addr);
3071
3072         if(!concat.match(re)) {
3073             if(concat != "") {
3074                 concat += "; " + addr;
3075             } else {
3076                 concat = addr;
3077             }
3078         }
3079
3080         return concat;
3081     }
3082 };
3083 ////    END ADDRESS BOOK
3084 ///////////////////////////////////////////////////////////////////////////////
3085
3086
3087
3088 ///////////////////////////////////////////////////////////////////////////////
3089 ////    AUTOCOMPLETE
3090 /**
3091  * Auto-complete object
3092  */
3093 SE.autoComplete = {
3094     config : {
3095         delimChar : [";", ","],
3096         useShadow :    false,
3097         useIFrame : false,
3098         typeAhead : true,
3099         prehighlightClassName : "yui-ac-prehighlight",
3100         queryDelay : 0
3101     },
3102     instances : new Array(),
3103
3104     /**
3105      * Parses an addressBook entry looking for primary address.  If not found, it will return the last found address.
3106      * @param object Contact from AddressBook
3107      * @return string
3108      */
3109     getPrimaryAddress : function(contact) {
3110         var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
3111
3112         for(var eIndex in contact.email) {
3113             address = contact.email[eIndex].email_address;
3114             if(contact.email[eIndex].primary_address == 1) {
3115                 return contact.email[eIndex].email_address;
3116             }
3117         }
3118         return address;
3119     },
3120
3121
3122     /**
3123      * initializes autocomplete widgets for a given compose view
3124      * @param int idx
3125      */
3126     init : function(idx) {
3127         var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
3128             "queryMatchContains" : false,
3129             "queryMatchSubset" : true
3130         });
3131
3132         this.instances[idx] = {
3133             to : null,
3134             cc : null,
3135             bcc : null
3136         };
3137
3138
3139         // instantiate the autoComplete widgets
3140         this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
3141         this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
3142         this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
3143
3144         // enable hiding of interfering textareas
3145         this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3146         this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3147         this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
3148
3149         // enable reshowing of hidden textareas
3150         this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3151         this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3152         this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
3153
3154         // enable refreshes of contact lists
3155         this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3156         this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3157         this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
3158     },
3159
3160     refreshDataSource : function(sType, aArgs) {
3161         var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
3162         var idx;
3163         var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
3164
3165         if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
3166             idx = textBoxId.substr(9);
3167         } else {
3168             idx = textBoxId.substr(10);
3169         }
3170
3171         SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
3172         SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
3173         SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
3174     },
3175
3176     /**
3177      * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
3178      */
3179     returnDataSource : function(contacts) {
3180         var ret = new Array();
3181         for(var id in contacts) {
3182             if (contacts[id].name) {
3183                     var primary = this.getPrimaryAddress(contacts[id]);
3184
3185                     ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
3186                     //ret[ret.length] = contacts[id].name + " <" + primary + ">";
3187
3188                     for(var emailIndex in contacts[id].email) {
3189                         ret[ret.length] = contacts[id].email[emailIndex].email_address;
3190                     }
3191             }
3192         }
3193
3194         return ret;
3195     },
3196
3197     /**
3198      * Hides address textareas to prevent autocomplete dropdown from being obscured
3199      */
3200     toggleTextareaHide : function(sType, aArgs) {
3201         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3202         var type = "";
3203         var idx = -1;
3204
3205         if(textBoxId.indexOf("addressTO") > -1) {
3206             type = "to";
3207         } else if(textBoxId.indexOf("addressCC") > -1) {
3208             type = "cc";
3209         }
3210         idx = textBoxId.substr(9);
3211
3212         // follow through if not BCC
3213         if(type != "") {
3214             var cc = document.getElementById("addressCC" + idx);
3215             var bcc = document.getElementById("addressBCC" + idx);
3216
3217             switch(type) {
3218                 case "to":
3219                     cc.style.visibility = 'hidden';
3220                 case "cc":
3221                     bcc.style.visibility = 'hidden';
3222                 break;
3223             }
3224         }
3225     },
3226
3227     /**
3228      * Redisplays the textareas after an address is commited
3229      */
3230     toggleTextareaShow : function(sType, aArgs) {
3231         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
3232         var type = "";
3233         var idx = -1;
3234
3235         if(textBoxId.indexOf("addressTO") > -1) {
3236             type = "to";
3237         } else if(textBoxId.indexOf("addressCC") > -1) {
3238             type = "cc";
3239         }
3240         idx = textBoxId.substr(9);
3241
3242         // follow through if not BCC
3243         if(type != "") {
3244             document.getElementById("addressCC" + idx).style.visibility = 'visible';
3245             document.getElementById("addressBCC" + idx).style.visibility = 'visible';
3246         }
3247     }
3248 };
3249
3250 ////    END AUTOCOMPLETE
3251 ///////////////////////////////////////////////////////////////////////////////
3252
3253 ///////////////////////////////////////////////////////////////////////////////
3254 ////    COMPOSE & SEND
3255 /**
3256  * expands the options sidebar
3257  */
3258 SE.composeLayout = {
3259     currentInstanceId : 0,
3260     ccHidden : true,
3261     bccHidden : true,
3262     outboundAccountErrors : null,
3263     loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
3264
3265     showAddressDetails : function(e) {
3266         var linkElement = document.getElementById("More"+e.id);
3267         var spanElement = document.getElementById("Detail"+e.id);
3268         var emailAddressList = e.value;
3269         if(e.value.length > 96)
3270         {
3271                 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
3272             var displayArray = [];
3273                 for (var i=0; i<resultArray.length; i++)
3274                 {
3275                     var t_name = resultArray[i].name;
3276                     var t_emailAddr = resultArray[i].email_address;
3277                     if(t_name == '')
3278                        displayArray.push('<br/>&lt;' + t_emailAddr + '&gt;');
3279                     else
3280                        displayArray.push(t_name + '<br/>&lt;' + t_emailAddr + '&gt;');
3281                 }
3282
3283             var result = displayArray.join('<br/>');
3284                 // Display
3285             linkElement.style.display = "inline";
3286             linkElement.style.height="10px";
3287             linkElement.style.overflow="visible";
3288             spanElement.innerHTML = result;
3289         }
3290         else
3291                 linkElement.style.display = "none";
3292
3293         },
3294
3295    /**
3296     *  Given a string of email address, return an array containing the name portion (if available)
3297     *  and email portion.
3298     */
3299     _getEmailArrayFromString : function (emailAddressList){
3300
3301         var reg = /@.*?;/g;
3302         while ((results = reg.exec(emailAddressList)) != null)
3303         {
3304             orignial = results[0];
3305             parsedResult = results[0].replace(';', ':::::');
3306             emailAddressList = emailAddressList.replace (orignial, parsedResult);
3307         }
3308
3309         reg = /@.*?,/g;
3310         while ((results = reg.exec(emailAddressList)) != null)
3311         {
3312             orignial = results[0];
3313             parsedResult = results[0].replace(',', ':::::');
3314             emailAddressList = emailAddressList.replace (orignial, parsedResult);
3315         }
3316         //Administrator <johndoe@som.com>  ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
3317         var emailArr = emailAddressList.split(":::::");
3318         var resultsArray = [];
3319         var newArr = [];
3320         for (var i=0; i<emailArr.length; i++)
3321         {
3322             var rposition = emailArr[i].indexOf('<');
3323             var lposition = emailArr[i].indexOf('>');
3324
3325             if(trim(emailArr[i]) != '')
3326             {
3327                 if(rposition != -1 && lposition != -1)
3328                 {
3329                     var t_name = emailArr[i].substr(0, rposition-1);
3330                     var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
3331                     resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
3332                 }
3333                 else
3334                 {
3335                     resultsArray.push({'name':'', 'email_address': emailArr[i]});
3336                 }
3337             }
3338         }
3339         return resultsArray;
3340     },
3341     ///////////////////////////////////////////////////////////////////////////
3342     ////    COMPOSE FLOW
3343     /**
3344      * Prepare bucket DIV and yui-ext tab panels
3345      */
3346     _0_yui : function() {
3347         var idx = this.currentInstanceId;
3348
3349         var composeTab = new YAHOO.SUGAR.ClosableTab({
3350                         label: mod_strings.LNK_NEW_SEND_EMAIL,
3351                                 scroll : true,
3352                                 content : "<div id='htmleditordiv" + idx + "'/>",
3353                                 id : "composeTab" + idx,
3354                                 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
3355                                 active : true
3356         }, SE.innerLayout);
3357         SE.innerLayout.addTab(composeTab);
3358
3359         // get template engine with template
3360         if (!SE.composeLayout.composeTemplate) {
3361                 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
3362         }
3363
3364         // create Tab inner layout
3365         var composePanel =  this.getComposeLayout();
3366         composePanel.getUnitByPosition("right").collapse();
3367         composePanel.autoSize();
3368
3369     },
3370         /**
3371      * Generate the quick compose layout
3372          * @method getQuickComposeLayout
3373          * @param {Pannel} parentPanel Parent pannel
3374          * @param {Object} o Options
3375          * @return {} none
3376          **/
3377     getQuickComposeLayout : function (parentPanel,o) {
3378          var idx = SE.composeLayout.currentInstanceId;
3379
3380          //Before rendering the parent pannel we need to initalize the grid layout
3381          parentPanel.beforeRenderEvent.subscribe(function() {
3382
3383                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3384                         SE.composeLayout._createComposeLayout(idx);
3385                         SE.composeLayout[idx].set('height', 350);
3386                         SE.composeLayout[idx].render();
3387            });
3388         });
3389
3390          //Wait until the Compose Layout has rendered, then add the
3391          //options tab and perform the tiny initialization.
3392          parentPanel.renderEvent.subscribe(function() {
3393
3394                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
3395                 SE.composeLayout._initComposeOptionTabs(idx);
3396                 SE.composeLayout[idx].getUnitByPosition("right").collapse();
3397                 //Initialize tinyMCE
3398                 if (!SUGAR.util.isTouchScreen())
3399                     SE.composeLayout._1_tiny();
3400                 //Init templates and address book
3401                 SE.composeLayout._2_final();
3402
3403             SE.composeLayout.quickCreateComposePackage(o);
3404
3405                 });
3406          });
3407
3408             //Check if we have the div override for the shortcut bar
3409         if(typeof o.menu_id != 'undefined') {
3410                    parentPanel.render(o.menu_id);
3411             } else {
3412                    parentPanel.render(document.body);
3413             }
3414
3415         return SE.composeLayout[idx];
3416     },
3417     /**
3418      * Fill in all fields into the quick compose layout.
3419          * @method quickCreateComposePackage
3420          * @param {Object} o Options
3421          * @return {} none
3422          **/
3423     quickCreateComposePackage: function(o)
3424     {
3425         //If we have a compose package fill in defaults.
3426         if (typeof(o.composePackage) != 'undefined')
3427         {
3428             composePackage = o.composePackage; //Set the compose data object
3429             //Hijack this method called by composePackage as it's not need for quick creates.
3430             SE.composeLayout.c0_composeNewEmail = function(){};
3431             SE.composeLayout.composePackage(); //Fill in defaults.
3432         }
3433     },
3434     getComposeLayout : function() {
3435         var idx = SE.composeLayout.currentInstanceId;
3436
3437         this._createComposeLayout(idx);
3438         SE.composeLayout[idx].render();
3439         this._initComposeOptionTabs(idx);
3440
3441         return SE.composeLayout[idx];
3442         },
3443
3444         /**
3445         *       Create the layout manager for the compose window.
3446         */
3447         _createComposeLayout : function(idx)
3448         {
3449                 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
3450                 parent: SE.complexLayout,
3451                 border:true,
3452             hideOnLayout: true,
3453             height: 400,
3454                         units: [{
3455                                         position: "center",
3456                         animate: false,
3457                         scroll: false,
3458                         split:true,
3459                         body:
3460                                 SE.composeLayout.composeTemplate.exec({
3461                                 'app_strings':app_strings,
3462                                 'mod_strings':mod_strings,
3463                                 'theme': theme,
3464                                 'linkbeans_options' : linkBeans,
3465                                 'idx' : SE.composeLayout.currentInstanceId
3466                                 })
3467                     },{
3468                         position: "right",
3469                                     scroll:true,
3470                                     collapse: true,
3471                                     collapsed: true,
3472                                     resize: true,
3473                                     border:true,
3474                                     animate: false,
3475                                     width:'230',
3476                                     body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
3477                                     titlebar: true,
3478                                     split: true,
3479                                     header: app_strings.LBL_EMAIL_OPTIONS
3480                     }]
3481                 });
3482         },
3483
3484         /**
3485         *  Create compose tab which will populate the 'right' container in the compose window.
3486         */
3487         _initComposeOptionTabs : function(idx)
3488         {
3489                 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
3490                 var tab = new YAHOO.widget.Tab({
3491                                 label: app_strings.LBL_EMAIL_ATTACHMENT,
3492                                 scroll : true,
3493                                 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
3494                                 id : "divAttachments" + idx,
3495                                 active : true
3496                         });
3497
3498                 tab.layout = SE.composeLayout[idx];
3499
3500            tab.on("activeChange", function(o){
3501                         if (o.newValue) {
3502                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
3503                         }
3504                 });
3505
3506                 cTabs.addTab(tab);
3507
3508                 tab = new YAHOO.widget.Tab({
3509                                 label: app_strings.LBL_EMAIL_OPTIONS,
3510                                 scroll : true,
3511                                 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
3512                                 id : "divOptions" + idx,
3513                                 active : false
3514                         });
3515
3516                 tab.layout = SE.composeLayout[idx];
3517                 tab.on("activeChange", function(o){
3518                         if (o.newValue) {
3519                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
3520                         }
3521                 });
3522                 cTabs.addTab(tab);
3523
3524                 SE.composeLayout[idx].autoSize = function() {
3525                         var pEl = this.get("element").parentNode.parentNode.parentNode;
3526                         this.set("height", pEl.clientHeight-30);
3527                         this.render();
3528                 }
3529
3530                 SE.composeLayout[idx].rightTabs = cTabs;
3531     },
3532     isParentTypeValid : function(idx) {
3533                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3534                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3535                 if (trim(parentTypeValue) == ""){
3536                         alert(mod_strings.LBL_ERROR_SELECT_MODULE);
3537                         return false;
3538                 } // if
3539                 return true;
3540     },
3541
3542     isParentTypeAndNameValid : function(idx) {
3543                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3544                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3545                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
3546                 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
3547                         (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
3548                                 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
3549                         return false;
3550                 } // if
3551                 return true;
3552     },
3553
3554     callopenpopupForEmail2 : function(idx,options) {
3555
3556         var formName = 'emailCompose' + idx;
3557
3558         if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
3559             formName = options.form_name;
3560
3561                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
3562                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
3563                 if (!SE.composeLayout.isParentTypeValid(idx)) {
3564                         return;
3565                 } // if
3566                 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
3567                 {
3568                         call_back_function:"SE.composeLayout.popupAddEmail",
3569                         form_name:formName,
3570                         field_to_name_array:{
3571                                 id:'data_parent_id' + idx,
3572                                 name:'data_parent_name' + idx,
3573                                 email1:'email1'}
3574                 });
3575         },
3576
3577         popupAddEmail : function(o)
3578         {
3579                 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
3580                 var data = o.name_to_value_array;
3581                 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
3582                         && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
3583         {
3584                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
3585                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
3586         }
3587                 set_return(o);
3588         },
3589     /**
3590      * Prepare TinyMCE
3591      */
3592     _1_tiny : function() {
3593         var idx = SE.composeLayout.currentInstanceId;
3594         var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
3595         SE.tinyInstances[elId] = { };
3596         SE.tinyInstances[elId].ready = false;
3597         var t = tinyMCE.getInstanceById(elId);
3598
3599         if(typeof(t) == 'undefined')  {
3600             tinyMCE.execCommand('mceAddControl', false, elId);
3601             YAHOO.util.Event.onAvailable(elId + "_parent", function() {
3602                 SE.composeLayout.resizeEditor(idx);
3603                 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
3604             }, this);
3605         }
3606     },
3607
3608     resizeEditor : function(idx)
3609     {
3610         var cof = Dom.get('composeOverFrame' + idx);
3611         var head = Dom.get('composeHeaderTable' + idx);
3612         var targetHeight = cof.clientHeight - head.clientHeight;
3613         var instance =  tinyMCE.get(SE.tinyInstances.currentHtmleditor);
3614
3615         var parentEl = Dom.get(instance.editorId + '_parent');
3616         var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
3617         var contentEl  = instance.contentAreaContainer;
3618         var iFrame = contentEl.firstChild;
3619         var tinMceToolbarOffset = 18;
3620         iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset)  + "px";
3621     },
3622
3623     /**
3624      * Initializes d&d, auto-complete, email templates
3625      */
3626     _2_final : function() {
3627         var idx = SE.composeLayout.currentInstanceId;
3628
3629         if(this.emailTemplates) {
3630             this.setComposeOptions(idx);
3631         } else {
3632             //populate email template cache
3633             AjaxObject.target = '';
3634             AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
3635         }
3636
3637         // handle drop targets for addressBook
3638        var to =  new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3639        var cc =  new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3640        var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
3641        to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
3642
3643         // auto-complete setup
3644         SE.autoComplete.init(idx);
3645
3646         // set focus on to:
3647         document.getElementById("addressTO" + idx).focus();
3648     },
3649
3650         /**
3651      * hide tinyMCE tool bar if send email as plaintext is checked
3652      */
3653     renderTinyMCEToolBar : function (idx, hide) {
3654         if (hide) {
3655                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
3656         } else {
3657                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
3658         }
3659     },
3660
3661     c1_composeEmail : function(isReplyForward, retry) {
3662         if (!retry) {
3663             this._0_yui();
3664         }
3665         if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
3666             setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
3667         } else {
3668                 this._1_tiny();
3669                 this._2_final();
3670
3671                 if(isReplyForward) {
3672                     this.replyForwardEmailStage2();
3673                 }
3674         }
3675     },
3676
3677     /**
3678      * takes draft info and prepopulates
3679      */
3680     c0_composeDraft : function() {
3681         this.getNewInstanceId();
3682         inCompose = true;
3683         document.getElementById('_blank').innerHTML = '';
3684         var idx = SE.composeLayout.currentInstanceId;
3685                 SE.composeLayout.draftObject = new Object();
3686                 SE.composeLayout.draftObject.id = idx;
3687                 SE.composeLayout.draftObject.isDraft = true;
3688         SE.composeLayout.currentInstanceId = idx;
3689         SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
3690         SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
3691         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
3692
3693         SE.composeLayout._0_yui();
3694         SE.composeLayout._1_tiny();
3695
3696         // final touches
3697         SE.composeLayout._2_final();
3698
3699         /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
3700         setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
3701     },
3702
3703     /**
3704      * Strip & Prep editor hidden fields
3705      */
3706     c0_composeNewEmail : function() {
3707         this.getNewInstanceId();
3708         this.c1_composeEmail(false);
3709     },
3710
3711     /**
3712      * Sends async request to get the compose view.
3713      * Requests come from "reply" or "forwards"
3714      */
3715     c0_replyForwardEmail : function(ieId, uid, mbox, type) {
3716         SE.composeLayout.replyForwardObj = new Object();
3717         SE.composeLayout.replyForwardObj.ieId = ieId;
3718         SE.composeLayout.replyForwardObj.uid = uid;
3719         SE.composeLayout.replyForwardObj.mbox = mbox;
3720         SE.composeLayout.replyForwardObj.type = type;
3721
3722         if(mbox == 'sugar::Emails') {
3723             SE.composeLayout.replyForwardObj.sugarEmail = true;
3724         }
3725
3726         SE.composeLayout.getNewInstanceId();
3727         SE.composeLayout.c1_composeEmail(true);
3728     },
3729     ////    END COMPOSE FLOW
3730     ///////////////////////////////////////////////////////////////////////////
3731
3732     /**
3733      * Called when a contact, email, or mailinglist is dropped
3734      * into one of the compose fields.
3735      */
3736     handleDrop : function (source, event, data, target) {
3737         var nodes;
3738         if (!target) {
3739             target = event.getTarget();
3740             if (data.single) {
3741                 data.nodes = [data.nodes];
3742             }
3743             nodes = data.nodes;
3744         } else {
3745             target = document.getElementById(target);
3746             nodes = data;
3747         }
3748
3749         if (target.id.indexOf('address') > -1) {
3750             // dropped onto email to/cc/bcc field
3751             for(var i in nodes) {
3752                 var node = nodes[i].getData();
3753                 var email = "";
3754                 if (node[1].indexOf('contact') > -1) {
3755                     email = SE.addressBook.getFormattedAddress(node[0]);
3756                 } else if (node[1].indexOf('address-email') > -1){
3757                     email = node[3].replace(/&nbsp;/gi, '');
3758                     email = email.replace('&lt;', '<').replace('&gt;', '>');
3759                     var tr = source.getTrEl(nodes[i]);
3760                     while (tr && !Dom.hasClass(tr, "address-contact")) {
3761                         tr = source.getPreviousTrEl(tr);
3762                     }
3763                     var CID = source.getRecord(tr).getData()[0];
3764                     var o = SE.addressBook._contactCache[CID];
3765                     var name = new String(o.name);
3766                     var finalName = name.replace(/(<([^>]+)>)/ig, "");
3767                     email = finalName + email;
3768                 }
3769                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
3770             }
3771         }
3772     },
3773
3774
3775     /*/////////////////////////////////////////////////////////////////////////////
3776     ///    EMAIL TEMPLATE CODE
3777      */
3778     applyEmailTemplate : function (idx, id) {
3779
3780         //bug #20680
3781         var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
3782                 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
3783                 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
3784
3785                 // id is selected index of email template drop-down
3786                 if(id == '' || id == "0") {
3787                         YAHOO.SUGAR.MessageBox.show({
3788                    title:box_title,
3789                    msg: box_none_msg,
3790                    type: 'confirm',
3791                    fn: function(btn){
3792                                 if(btn=='no'){return;};
3793                                 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
3794                    modal:true,
3795                    scope:this
3796                });
3797                return;
3798                 }
3799
3800                 YAHOO.SUGAR.MessageBox.show({
3801            title:box_title,
3802            msg: box_msg,
3803            type: 'confirm',
3804            fn: function(btn){
3805                         if(btn=='no'){return;};
3806                         SUGAR.email2.composeLayout.processResult(idx, id);},
3807            modal:true,
3808            scope:this
3809        });
3810     },
3811
3812     processNoneResult : function(idx, id) {
3813         var tiny = SE.util.getTiny('htmleditor' + idx);
3814         var tinyHTML = tiny.getContent();
3815         var openTag = '<div><span><span>';
3816         var htmllow = tinyHTML.toLowerCase();
3817         var start = htmllow.indexOf(openTag);
3818                 if (start > -1) {
3819                 tinyHTML = tinyHTML.substr(start);
3820                 tiny.setContent(tinyHTML);
3821                 } else {
3822                 tiny.setContent('');
3823                 }
3824     },
3825
3826         processResult : function(idx , id){
3827         call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
3828
3829         // get attachments if any
3830         AjaxObject.target = '';
3831         AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
3832     },
3833
3834     appendEmailTemplateJSON : function() {
3835         var idx = SE.composeLayout.currentInstanceId; // post increment
3836
3837         // query based on template, contact_id0,related_to
3838         //jchi 09/10/2008 refix #7743
3839         if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
3840             document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
3841         }
3842
3843         var text = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body_html'])).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
3844
3845         // cn: bug 14361 - text-only templates don't fill compose screen
3846         if(text == '') {
3847             text = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body'])).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"').replace(/\r\n/gi,"<br/>");
3848         }
3849
3850         var tiny = SE.util.getTiny('htmleditor' + idx);
3851         var tinyHTML = tiny.getContent();
3852         var openTag = '<div><span><span>';
3853         var closeTag = '</span></span></div>';
3854         var htmllow = tinyHTML.toLowerCase();
3855         var start = htmllow.indexOf(openTag);
3856                 if (start > -1) {
3857                 var htmlPart2 = tinyHTML.substr(start);
3858                 tinyHTML = text + htmlPart2;
3859                 tiny.setContent(tinyHTML);
3860                 } else {
3861                 tiny.setContent(text);
3862                 }
3863     },
3864
3865     /**
3866      * Writes out the signature in the email editor
3867      */
3868     setSignature : function(idx) {
3869         if (!tinyMCE)
3870             return false;
3871         var hide = document.getElementById('setEditor' + idx).checked;
3872         SE.composeLayout.renderTinyMCEToolBar(idx,hide);
3873         //wait for signatures to load before trying to set them
3874         if (!SE.composeLayout.signatures) {
3875             setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
3876                         return;
3877         }
3878
3879         if(idx) {
3880             var sel = document.getElementById('signatures' + idx);
3881         } else {
3882             var sel = document.getElementById('signature_id');
3883             idx = SE.tinyInstances.currentHtmleditor;
3884         }
3885
3886         //Ensure that the tinyMCE html has been rendered.
3887         if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
3888             setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
3889                     return;
3890                 }
3891
3892         var signature = '';
3893
3894         try {
3895             signature = sel.options[sel.selectedIndex].value;
3896         } catch(e) {
3897
3898         }
3899
3900         var openTag = '<div><span><span>';
3901         var closeTag = '</span></span></div>';
3902         var t = SE.util.getTiny('htmleditor' + idx);
3903         //IE 6 Hack
3904         if(typeof(t) != 'undefined')
3905         {
3906             t.contentDocument = t.contentWindow.document;
3907             var html = t.getContent();
3908         }
3909         else
3910             var html = '';
3911
3912         var htmllow = html.toLowerCase();
3913         var start = htmllow.indexOf(openTag);
3914         var end = htmllow.indexOf(closeTag) + closeTag.length;
3915
3916         // selected "none" - remove signature from email
3917         if(signature == '') {
3918             if (start > -1) {
3919                 var htmlPart1 = html.substr(0, start);
3920                 var htmlPart2 = html.substr(end, html.length);
3921
3922                 html = htmlPart1 + htmlPart2;
3923                 t.setContent(html);
3924             }
3925             SE.signatures.lastAttemptedLoad = '';
3926             return false;
3927         }
3928
3929         if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
3930             SE.signatures.lastAttemptedLoad = '';
3931
3932         SE.signatures.lastAttemptedLoad = signature;
3933
3934         if(typeof(SE.signatures[signature]) == 'undefined') {
3935             //lazy load
3936             SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
3937             SE.signatures.targetInstance = (idx) ? idx : "";
3938             AjaxObject.target = '';
3939             AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
3940         } else {
3941             var newSignature = this.prepareSignature(SE.signatures[signature]);
3942
3943             // clear out old signature
3944             if(SE.signatures.lastAttemptedLoad && start > -1) {
3945                 var htmlPart1 = html.substr(0, start);
3946                 var htmlPart2 = html.substr(end, html.length);
3947
3948                 html = htmlPart1 + htmlPart2;
3949             }
3950
3951             // [pre|ap]pend
3952                         start = html.indexOf('<div><hr></div>');
3953             if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
3954                                 var htmlPart1 = html.substr(0, start);
3955                                 var htmlPart2 = html.substr(start, html.length);
3956                 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
3957             } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
3958                 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
3959             } else {
3960                 var newHtml = html + openTag + newSignature + closeTag;
3961             }
3962             //tinyMCE.setContent(newHtml);
3963             t.setContent(newHtml);
3964         }
3965     },
3966
3967     prepareSignature : function(str) {
3968         var signature = new String(str);
3969
3970         signature = signature.replace(/&lt;/gi, '<');
3971         signature = signature.replace(/&gt;/gi, '>');
3972
3973         return signature;
3974     },
3975
3976
3977     showAttachmentPanel : function(idx) {
3978         var east = SE.composeLayout[idx].getUnitByPosition("right");
3979         var tabs = SE.composeLayout[idx].rightTabs;
3980         east.expand();
3981         tabs.set("activeTab", tabs.getTab(0));
3982     },
3983
3984     /**
3985      * expands sidebar and displays options panel
3986      */
3987     showOptionsPanel : function(idx) {
3988         var east = SE.composeLayout[idx].getUnitByPosition("right");
3989         var tabs = SE.composeLayout[idx].rightTabs;
3990         east.expand();
3991         tabs.set("activeTab", tabs.getTab(1));
3992     },
3993
3994     /**
3995      * Selects the Contacts tab
3996      */
3997     showContactsPanel : function() {
3998         SE.complexLayout.regions.west.showPanel("contactsTab");
3999     },
4000
4001     /**
4002      * Generates fields for Select Document
4003      */
4004     addDocumentField : function(idx) {
4005         var basket = document.getElementById('addedDocuments' + idx);
4006         if(basket) {
4007             var index = (basket.childNodes.length / 7) - 1;
4008             if(index < 0)
4009                 index = 0;
4010         } else {
4011             index = 0;
4012         }
4013
4014         var test = document.getElementById('documentId' + idx + index);
4015
4016         while(test != null) {
4017             index++;
4018             test = document.getElementById('documentId' + idx + index);
4019         }
4020
4021         var documentCup = document.createElement("div");
4022         documentCup.id = 'documentCup' + idx + index;
4023         documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
4024                 // document id field
4025                 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
4026                 // document name field
4027                 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
4028                 // select button
4029                 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
4030                     "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
4031                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
4032                 // remove button
4033                 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
4034                     "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
4035                  "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
4036                 "<br/>";
4037
4038         basket.appendChild(documentCup);
4039         //basket.innerHTML += out;
4040         return index;
4041     },
4042
4043     /**
4044      * Makes async call to save a draft of the email
4045      * @param int Instance index
4046      */
4047     saveDraft : function(tinyInstance) {
4048         this.sendEmail(tinyInstance, true);
4049     },
4050
4051     selectDocument : function(target) {
4052         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
4053         windowName = 'selectDocument';
4054         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
4055
4056         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4057         if(window.focus) {
4058             // put the focus on the popup if the browser supports the focus() method
4059             win.focus();
4060         }
4061     },
4062
4063     /**
4064      * Modal popup for file attachment dialogue
4065      */
4066     addFileField : function() {
4067         if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
4068             SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
4069                 modal:true,
4070                 visible:false,
4071                 fixedcenter:true,
4072                 constraintoviewport: true,
4073                 scroll: true,
4074                 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
4075                         fn:function(){SE.addFileDialog.hide();}
4076                 })
4077             });
4078             SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
4079             SE.addFileDialog.render();
4080            // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
4081         }
4082         Dom.removeClass("addFileDialog", "yui-hidden");
4083
4084         SE.addFileDialog.show();
4085     },
4086
4087     /**
4088      * Async upload of file to temp dir
4089      */
4090     uploadAttachment : function() {
4091         if(document.getElementById('email_attachment').value != "") {
4092             var formObject = document.getElementById('uploadAttachment');
4093             YAHOO.util.Connect.setForm(formObject, true, true);
4094             AjaxObject.target = '';
4095             AjaxObject.startRequest(callbackUploadAttachment, null);
4096         } else {
4097             alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
4098         }
4099     },
4100
4101     /**
4102      * Adds a SugarDocument to an outbound email.  Action occurs in a popup window displaying a ListView from the Documents module
4103      * @param string target in focus compose layout
4104      */
4105     setDocument : function(idx, target, documentId, documentName, docRevId) {
4106         // fields are named/id'd [fieldName][instanceId][index]
4107         var addedDocs = document.getElementById("addedDocuments" + idx);
4108         var docId = document.getElementById('documentId' + idx + target);
4109         var docName = document.getElementById('documentName' + idx + target);
4110         var docRevisionId = document.getElementById('document' + idx + target);
4111         docId.value = documentId;
4112         docName.value = documentName;
4113         docRevisionId.value = docRevId;
4114     },
4115
4116     /**
4117      * Removes the bucket div containing the document input fields
4118      */
4119     deleteDocumentField : function(documentCup) {
4120         var f0 = document.getElementById(documentCup);
4121         f0.parentNode.removeChild(f0);
4122     },
4123
4124     /**
4125      * Removes a Template Attachment field
4126      * @param int
4127      * @param int
4128      */
4129     deleteTemplateAttachmentField : function(idx, index) {
4130         // create not-in-array values for removal filtering
4131         var r = document.getElementById("templateAttachmentsRemove" + idx).value;
4132
4133         if(r != "") {
4134             r += "::";
4135         }
4136
4137         r += document.getElementById('templateAttachmentId' + idx + index).value;
4138         document.getElementById("templateAttachmentsRemove" + idx).value = r;
4139
4140         var target = 'templateAttachmentCup' + idx + index;
4141         d =  document.getElementById(target);
4142         d.parentNode.removeChild(d);
4143     },
4144
4145     /**
4146      * Async removal of uploaded temp file
4147      * @param string index Should be a concatenation of idx and index
4148      * @param string
4149      */
4150     deleteUploadAttachment : function(index, file) {
4151         var d = document.getElementById('email_attachment_bucket' + index);
4152         d.parentNode.removeChild(d);
4153
4154         // make async call to delete cached file
4155         AjaxObject.target = '';
4156         AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
4157     },
4158
4159     /**
4160      * Attaches files coming from Email Templates
4161      */
4162     addTemplateAttachmentField : function(idx) {
4163         // expose title
4164         document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
4165
4166         var basket = document.getElementById('addedTemplateAttachments' + idx);
4167
4168         if(basket) {
4169             var index = basket.childNodes.length;
4170             if(index < 0)
4171                 index = 0;
4172         } else {
4173             index = 0;
4174         }
4175
4176         var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
4177                                 // remove button
4178                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
4179                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
4180                                         idx + "\",\"" + index + "\");'/>" +
4181                                 // file icon
4182                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
4183                                 // templateAttachment field
4184                                 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
4185                                 // docId field
4186                                 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
4187                                 // file name
4188                                 "<span id='templateAttachmentName"  + idx + index + "'" + ">&nbsp;</span>" +
4189                                 "<br id='br" + index + "></br>" +
4190                                 "<br id='brdoc" + index + "></br>" +
4191                         "</div>";
4192                 basket.innerHTML = basket.innerHTML + out;
4193
4194         return index;
4195     },
4196
4197     /**
4198      * Sends one email via async call
4199      * @param int idx Editor instance ID
4200      * @param bool isDraft
4201      */
4202     sendEmail : function(idx, isDraft) {
4203
4204         //If the outbound account has an error message associate with it, alert the user and refuse to continue.
4205         var obAccountID = document.getElementById('addressFrom' + idx).value;
4206
4207         if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
4208         {
4209             overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
4210             return false;
4211         }
4212
4213
4214         var form = document.getElementById('emailCompose' + idx);
4215         var composeOptionsFormName = "composeOptionsForm" + idx;
4216         var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
4217         var html = t.getContent();
4218         var subj = document.getElementById('emailSubject' + idx).value;
4219         var to = trim(document.getElementById('addressTO' + idx).value);
4220         var cc = trim(document.getElementById('addressCC' + idx).value);
4221         var bcc = trim(document.getElementById('addressBCC' + idx).value);
4222         var email_id = document.getElementById('email_id' + idx).value;
4223         var composeType = document.getElementById('composeType').value;
4224         var parent_type = document.getElementById("parent_type").value;
4225         var parent_id = document.getElementById("parent_id").value;
4226
4227         var el_uid = document.getElementById("uid");
4228         var uid = (el_uid == null) ? '' : el_uid.value;
4229
4230         var el_ieId = document.getElementById("ieId");
4231         var ieId = (el_ieId == null) ? '' : el_ieId.value;
4232
4233         var el_mbox = document.getElementById("mbox");
4234         var mbox = (el_mbox == null) ? '' : el_mbox.value;
4235
4236         if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
4237                         alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
4238                 return false;
4239         }
4240
4241         if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
4242                 return;
4243         } // if
4244                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
4245                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
4246         parent_id = parentIdValue;
4247         parent_type = parentTypeValue;
4248
4249         var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
4250         // baseline viability check
4251
4252         if(to == "" && cc == '' && bcc == '' && !isDraft) {
4253             alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
4254             return false;
4255         } else if(subj == '' && !isDraft) {
4256             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
4257                 return false;
4258             } else {
4259                 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
4260             }
4261         } else if(html == '' && !isDraft) {
4262             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
4263                 return false;
4264             }
4265         }
4266
4267         SE.util.clearHiddenFieldValues('emailCompose' + idx);
4268                 document.getElementById('data_parent_id' + idx).value = parentIdValue;
4269                 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
4270         overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
4271         html = html.replace(/&lt;/ig, "sugarLessThan");
4272         html = html.replace(/&gt;/ig, "sugarGreaterThan");
4273
4274         form.sendDescription.value = html;
4275         form.sendSubject.value = subj;
4276         form.sendTo.value = to;
4277         form.sendCc.value = cc;
4278         form.sendBcc.value = bcc;
4279         form.email_id.value = email_id;
4280         form.composeType.value = composeType;
4281         form.composeLayoutId.value = 'composeLayout' + idx;
4282         form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
4283         form.saveToSugar.value = 1;
4284         form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
4285         form.parent_type.value = parent_type;
4286         form.parent_id.value = parent_id;
4287         form.uid.value = uid;
4288         form.ieId.value = ieId;
4289         form.mbox.value = mbox;
4290
4291         // email attachments
4292         var addedFiles = document.getElementById('addedFiles' + idx);
4293         if(addedFiles) {
4294             for(i=0; i<addedFiles.childNodes.length; i++) {
4295                 var bucket = addedFiles.childNodes[i];
4296
4297                 for(j=0; j<bucket.childNodes.length; j++) {
4298                     var node = bucket.childNodes[j];
4299                     var nName = new String(node.name);
4300
4301                     if(node.type == 'hidden' && nName.match(/email_attachment/)) {
4302                         if(form.attachments.value != '') {
4303                             form.attachments.value += "::";
4304                         }
4305                         form.attachments.value += node.value;
4306                     }
4307                 }
4308             }
4309         }
4310
4311         // sugar documents
4312         var addedDocs = document.getElementById('addedDocuments' + idx);
4313         if(addedDocs) {
4314             for(i=0; i<addedDocs.childNodes.length; i++) {
4315                 var cNode = addedDocs.childNodes[i];
4316                 for(j=0; j<cNode.childNodes.length; j++) {
4317                     var node = cNode.childNodes[j];
4318                     var nName = new String(node.name);
4319                     if(node.type == 'hidden' && nName.match(/documentId/)) {
4320                         if(form.documents.value != '') {
4321                             form.documents.value += "::";
4322                         }
4323                         form.documents.value += node.value;
4324                     }
4325                 }
4326             }
4327         }
4328
4329         // template attachments
4330         var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
4331         if(addedTemplateAttachments) {
4332             for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
4333                 var cNode = addedTemplateAttachments.childNodes[i];
4334                 for(j=0; j<cNode.childNodes.length; j++) {
4335                     var node = cNode.childNodes[j];
4336                     var nName = new String(node.name);
4337                     if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
4338                         if(form.templateAttachments.value != "") {
4339                             form.templateAttachments.value += "::";
4340                         }
4341                         form.templateAttachments.value += node.value;
4342                     }
4343                 }
4344             }
4345         }
4346
4347         // remove attachments
4348         form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
4349
4350         YAHOO.util.Connect.setForm(form);
4351
4352         AjaxObject.target = 'frameFlex';
4353
4354         // sending a draft email
4355         if(!isDraft && in_draft) {
4356             // remove row
4357             SE.listView.removeRowByUid(email_id);
4358         }
4359
4360         var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
4361         var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
4362
4363         AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
4364     },
4365
4366     /**
4367      * Handles clicking the email address link from a given view
4368      */
4369     composePackage : function() {
4370         if(composePackage != null) {
4371             SE.composeLayout.c0_composeNewEmail();
4372
4373
4374             if(composePackage.to_email_addrs) {
4375                 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
4376             } // if
4377             if (composePackage.subject != null && composePackage.subject.length > 0) {
4378                 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
4379             }
4380
4381             //If no parent fields are set in the composePackage, ensure they are cleared.
4382             var parentFields = ['parent_type','parent_name','parent_id'];
4383             for(var i=0;i<parentFields.length;i++)
4384             {
4385                 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
4386                     composePackage[parentFields[i]] = "";
4387             }
4388
4389             document.getElementById("parent_type").value = composePackage.parent_type;
4390             document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
4391             document.getElementById("parent_id").value = composePackage.parent_id;
4392             document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
4393             document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
4394
4395             if(composePackage.email_id != null && composePackage.email_id.length > 0) {
4396                 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
4397             } // if
4398             if (composePackage.body != null && composePackage.body.length > 0) {
4399                         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4400                         SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
4401                         setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
4402             } // if
4403             if (composePackage.attachments != null) {
4404                                 SE.composeLayout.loadAttachments(composePackage.attachments);
4405             } // if
4406
4407             if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
4408                                 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
4409                         SE.util.emptySelectOptions(addressFrom);
4410                         var fromAccountOpts = composePackage.fromAccounts.data;
4411                         for(i=0; i<fromAccountOpts.length; i++) {
4412                               var key = fromAccountOpts[i].value;
4413                               var display = fromAccountOpts[i].text;
4414                               var opt = new Option(display, key);
4415                               if (fromAccountOpts[i].selected) {
4416                                 opt.selected = true;
4417                               }
4418                               addressFrom.options.add(opt);
4419                         }
4420
4421             } // if
4422         } // if
4423     },
4424
4425     setContentOnThisTiny : function() {
4426         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
4427         var tinyHTML = tiny.getContent();
4428         composePackage.body = decodeURI(encodeURI(composePackage.body));
4429         // cn: bug 14361 - text-only templates don't fill compose screen
4430         if(composePackage.body == '') {
4431             composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
4432         } // if
4433         //Flag determines if we should clear the tiny contents or just append
4434         if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
4435             SE.composeLayout.tinyHTML = '';
4436         else
4437             SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
4438
4439          tiny.setContent(SE.composeLayout.tinyHTML);
4440          //Indicate that the contents has been loaded successfully.
4441          SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
4442     },
4443     /**
4444      * Confirms closure of a compose screen if "x" is clicked
4445      */
4446     confirmClose : function(panel) {
4447         if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
4448             SE.composeLayout.closeCompose(panel.id);
4449             return true;
4450         } else {
4451             return false;
4452         }
4453     },
4454
4455     /**
4456      * forces close of a compose screen
4457      */
4458     forceCloseCompose : function(id) {
4459         SE.composeLayout.closeCompose(id);
4460
4461         // handle flow back to originating view
4462         if(composePackage) {
4463             // check if it's a module we need to return to
4464             if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
4465                 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
4466                     var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
4467                     window.location = url;
4468                 }
4469             }
4470         }
4471     },
4472
4473     /**
4474      * closes the editor that just sent email
4475      * @param string id ID of composeLayout tab
4476      */
4477     closeCompose : function(id) {
4478         // destroy tinyMCE instance
4479         var idx = id.substr(13, id.length);
4480         var instanceId = "htmleditor" + idx;
4481         tinyMCE.execCommand('mceRemoveControl', false, instanceId);
4482
4483         // nullify DOM and namespace values.
4484         inCompose = false;
4485         SE.composeLayout[idx] = null;
4486         SE.tinyInstances[instanceId] = null;
4487         var tabsArray = SE.innerLayout.get("tabs");
4488         for (i = 0 ; i < tabsArray.length ; i++) {
4489                 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
4490                         tabsArray[i].close();
4491                         break;
4492                 }
4493         }
4494         //SE.innerLayout.getTab(idx).close();
4495     },
4496
4497     /**
4498     *  Enable the quick search for the compose relate field or search tab
4499     */
4500     enableQuickSearchRelate: function(idx,overides){
4501
4502         if(typeof overides != 'undefined')
4503         {
4504             var newModuleID = overides['moduleSelectField']; //data_parent_type_search
4505             var newModule = document.getElementById(newModuleID).value;
4506             var formName = overides['formName'];
4507             var fieldName = overides['fieldName'];
4508             var fieldId = overides['fieldId'];
4509             var fullName = formName + "_" + fieldName;
4510             var postBlurFunction = null;
4511         }
4512         else
4513         {
4514             var newModule = document.getElementById('data_parent_type'+idx).value;
4515             var formName = 'emailCompose'+idx;
4516             var fieldName = 'data_parent_name'+idx;
4517             var fieldId = 'data_parent_id'+idx;
4518             var fullName = formName + "_" + fieldName;
4519             var postBlurFunction = "SE.composeLayout.qsAddAddress";
4520         }
4521
4522         if(typeof sqs_objects == 'undefined')
4523             window['sqs_objects'] = new Array;
4524
4525         window['sqs_objects'][fullName] = {
4526             form:formName,
4527                         method:"query",
4528                         modules:[newModule],
4529                         group:"or",
4530             field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
4531             conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
4532                         post_onblur_function: postBlurFunction,
4533             order:"name","limit":"30","no_match_text":"No Match"};
4534
4535
4536         if(typeof QSProcessedFieldsArray != 'undefined')
4537                 QSProcessedFieldsArray[fullName] = false;
4538         if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
4539                 QSFieldsArray[fullName].destroy();
4540                 delete QSFieldsArray[fullName];
4541         }
4542         if (Dom.get(fullName + "_results")) {
4543                 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
4544         }
4545
4546         enableQS(false);
4547     },
4548
4549         qsAddAddress : function(o) {
4550         if (o.name != "" && o.email1 != "")
4551         {
4552                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
4553                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
4554         }
4555     },
4556     /**
4557      * Returns a new instance ID, 0-index
4558      */
4559     getNewInstanceId : function() {
4560         this.currentInstanceId = this.currentInstanceId + 1;
4561         return this.currentInstanceId;
4562     },
4563
4564     /**
4565      * Takes an array of objects that contain the filename and GUID of a Note (attachment or Sugar Document) and applies the values to the compose screen.  Valid use-cases are applying an EmailTemplate or resuming a Draft Email.
4566      */
4567     loadAttachments : function(result) {
4568         var idx = SE.composeLayout.currentInstanceId;
4569
4570         if(typeof(result) == 'object') {
4571                 //jchi #20680. Clean the former template attachments;
4572                 var basket = document.getElementById('addedTemplateAttachments' + idx);
4573                         if(basket.innerHTML != ''){
4574                                 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
4575                                         if (btn != 'yes'){
4576                                                 basket.innerHTML = '';
4577                                         }
4578                                 });
4579                         }
4580             for(i in result) {
4581                 if(typeof result[i] == 'object') {
4582                     var index = SE.composeLayout.addTemplateAttachmentField(idx);
4583                     var bean = result[i];
4584                     document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
4585                     document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
4586                 }
4587             }
4588         }
4589     },
4590
4591     /**
4592      * fills drop-down values for email templates and signatures
4593      */
4594     setComposeOptions : function(idx) {
4595         // send from accounts
4596         var addressFrom = document.getElementById('addressFrom' + idx);
4597
4598         if (addressFrom.options.length <= 0) {
4599                 SE.util.emptySelectOptions(addressFrom);
4600                 var fromAccountOpts = SE.composeLayout.fromAccounts;
4601                 for (id = 0 ; id < fromAccountOpts.length ; id++) {
4602                       var key = fromAccountOpts[id].value;
4603                       var display = fromAccountOpts[id].text;
4604                       var is_default = false;
4605                       if(key == SUGAR.default_inbound_accnt_id)
4606                         is_default = true;
4607                       var opt = new Option(display, key);
4608                       addressFrom.options.add(opt);
4609                       addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
4610                 }
4611         }
4612
4613         // email templates
4614         var et = document.getElementById('email_template' + idx);
4615         SE.util.emptySelectOptions(et);
4616
4617         for(var key in this.emailTemplates) { // iterate through assoc array
4618             var display = this.emailTemplates[key];
4619             var opt = new Option(display, key);
4620             et.options.add(opt);
4621         }
4622
4623         // signatures
4624         var sigs = document.getElementById('signatures' + idx);
4625         SE.util.emptySelectOptions(sigs);
4626
4627         for(var key in this.signatures) { // iterate through assoc array
4628             var display = this.signatures[key];
4629             var opt = new Option(display, key);
4630
4631             if(key == SE.userPrefs.signatures.signature_default) {
4632                 opt.selected = true;
4633             }
4634
4635             sigs.options.add(opt);
4636         }
4637
4638         // html/plain email?
4639         var htmlEmail = document.getElementById('setEditor' + idx);
4640         if(SE.userPrefs.emailSettings.sendPlainText == 1) {
4641             htmlEmail.checked = true;
4642         } else {
4643                 htmlEmail.checked = false;
4644         }
4645
4646         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
4647     },
4648
4649     /**
4650      * After compose screen is rendered, async call to get email body from Sugar
4651      */
4652     replyForwardEmailStage2 : function() {
4653         SE.util.clearHiddenFieldValues('emailUIForm');
4654         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
4655
4656         var ieId = SE.composeLayout.replyForwardObj.ieId;
4657         var uid = SE.composeLayout.replyForwardObj.uid;
4658         var mbox = SE.composeLayout.replyForwardObj.mbox;
4659         var type = SE.composeLayout.replyForwardObj.type;
4660         var idx = SE.composeLayout.currentInstanceId;
4661
4662         var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
4663
4664         document.getElementById('emailSubject' + idx).value = type;
4665         document.getElementById('emailUIAction').value = 'composeEmail';
4666         document.getElementById('composeType').value = type;
4667         document.getElementById('ieId').value = ieId;
4668         document.getElementById('uid').value = uid;
4669         document.getElementById('mbox').value = mbox;
4670                 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
4671         var formObject = document.getElementById('emailUIForm');
4672         YAHOO.util.Connect.setForm(formObject);
4673
4674         var sendType = type;
4675         AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
4676     },
4677
4678     /**
4679     *  Show the hidden cc or bcc fields
4680     */
4681     showHiddenAddress: function(addrType,idx){
4682
4683         Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
4684         Dom.addClass(addrType+"_span"+idx, "yui-hidden");
4685                 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
4686                 this[addrType+'Hidden'+idx] = false;
4687
4688                 //After bcc or cc is added, move options below last addr field
4689                 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4690
4691                 //If both cc and bcc hidden, remove the empty row containing text.
4692                 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
4693                            && ( this['ccHidden'+idx]  == false && this['bccHidden'+idx] == false) )
4694                         Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
4695
4696                 SE.composeLayout.resizeEditor(idx);
4697     },
4698     /**
4699     *  Hide the cc and bcc fields if they were shown.
4700     */
4701     hideHiddenAddresses: function(idx){
4702
4703         var addrTypes = ['cc','bcc'];
4704         for(var i = 0;i<addrTypes.length;i++)
4705         {
4706             Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
4707             Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
4708             this[addrTypes[i] + 'Hidden'+idx] = true
4709         }
4710
4711         Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
4712         Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
4713         Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
4714     }
4715 };
4716
4717 ////    END SE.composeLayout
4718 ///////////////////////////////////////////////////////////////////////////////
4719 ///////////////////////////////////////////////////////////////////////////////
4720 ////    SE.util
4721 SE.util = {
4722     /**
4723      * Cleans serialized UID lists of duplicates
4724      * @param string
4725      * @return string
4726      */
4727     cleanUids : function(str) {
4728         var seen = new Object();
4729         var clean = "";
4730         var arr = new String(str).split(",");
4731
4732         for(var i=0; i<arr.length; i++) {
4733             if(seen[arr[i]]) {
4734                 continue;
4735             }
4736
4737             clean += (clean != "") ? "," : "";
4738             clean += arr[i];
4739             seen[arr[i]] = true;
4740         }
4741
4742         return clean;
4743     },
4744
4745     /**
4746      * Clears hidden field values
4747      * @param string id ID of form element to clear
4748      */
4749     clearHiddenFieldValues : function(id) {
4750         var form = document.getElementById(id);
4751
4752         for(i=0; i<form.elements.length; i++) {
4753             if(form.elements[i].type == 'hidden') {
4754                 var e = form.elements[i];
4755                 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
4756                     e.value = '';
4757                 }
4758             }
4759         }
4760     },
4761
4762     /**
4763      * Reduces a SELECT drop-down to 0 items to prepare for new ones
4764      */
4765     emptySelectOptions : function(el) {
4766         if(el) {
4767             for(i=el.childNodes.length - 1; i >= 0; i--) {
4768                 if(el.childNodes[i]) {
4769                     el.removeChild(el.childNodes[i]);
4770                 }
4771             }
4772         }
4773     },
4774
4775     /**
4776      * Returns the MBOX path in the manner php_imap expects:
4777      * ie: INBOX.DEBUG.test
4778      * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
4779      */
4780     generateMboxPath : function(str) {
4781         var ex = str.split("::");
4782
4783         /* we have a serialized MBOX path */
4784         if(ex.length > 1) {
4785             var start = false;
4786             var ret = '';
4787             for(var i=0; i<ex.length; i++) {
4788                 if(ex[i] == 'INBOX') {
4789                     start = true;
4790                 }
4791
4792                 if(start == true) {
4793                     if(ret != "") {
4794                         ret += ".";
4795                     }
4796                     ret += ex[i];
4797                 }
4798             }
4799         } else {
4800             /* we have a Sugar folder GUID - do nothing */
4801             return str;
4802         }
4803
4804         return ret;
4805     },
4806
4807     /**
4808      * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
4809      * @param HTMLElement el
4810      * @return string GUID of found element or empty on failure
4811      */
4812     getGuidFromElement : function(el) {
4813         var GUID = '';
4814         var iterations = 4;
4815         var passedEl = el;
4816
4817         // upwards
4818         for(var i=0; i<iterations; i++) {
4819             if(el) {
4820                 if(el.id.match(SE.reGUID)) {
4821                     return el.id;
4822                 } else {
4823                     el = el.parentNode;
4824                 }
4825             }
4826         }
4827
4828         return GUID;
4829     },
4830
4831     /**
4832      * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
4833      * @return string
4834      */
4835     getPanelId : function() {
4836         return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
4837     },
4838
4839     /**
4840      * wrapper to handle weirdness with IE
4841      * @param string instanceId
4842      * @return tinyMCE Controller object
4843      */
4844     getTiny : function(instanceId) {
4845         if(instanceId == '') {
4846             return null;
4847         }
4848
4849         var t = tinyMCE.getInstanceById(instanceId);
4850
4851         if(this.isIe()) {
4852             this.sleep(200);
4853             YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
4854         }
4855         return t;
4856     },
4857
4858     /**
4859      * Simple check for MSIE browser
4860      * @return bool
4861      */
4862     isIe : function() {
4863         var nav = new String(navigator.appVersion);
4864         if(nav.match(/MSIE/)) {
4865             return true;
4866         }
4867         return false;
4868     },
4869
4870     /**
4871      * Recursively removes an element from the DOM
4872      * @param HTMLElement
4873      */
4874     removeElementRecursive : function(el) {
4875         this.emptySelectOptions(el);
4876     },
4877
4878     /**
4879      * Fakes a sleep
4880      * @param int
4881      */
4882     sleep : function(secs) {
4883         setTimeout("void(0);", secs);
4884     },
4885
4886     /**
4887      * Converts a <select> element to an Ext.form.combobox
4888      */
4889      convertSelect : function(select) {
4890        alert('in convertSelect');
4891        if (typeof(select) == "string") {
4892            select = document.getElementById(select);
4893        }
4894      },
4895
4896      findChildNode : function (parent, property, value) {
4897          for (i in parent.children) {
4898                  var child = parent.children[i];
4899                  if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
4900                          return child;
4901                  var searchChild = SE.util.findChildNode(child, property, value);
4902                  if (searchChild)
4903                          return searchChild;
4904          }
4905          return false;
4906      },
4907
4908      cascadeNodes : function (parent, fn, scope, args) {
4909          for (i in parent.children) {
4910                  var child = parent.children[i];
4911                  var s = scope ? scope : child;
4912                  var a = args ? args : child;
4913                  fn.call(s, a);
4914                  SE.util.cascadeNodes(child, fn, scope, args);
4915          }
4916      }
4917 };
4918
4919
4920 ////    END UTIL
4921 ///////////////////////////////////////////////////////////////////////////////
4922
4923
4924 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
4925                                 
4926 /*********************************************************************************
4927  * SugarCRM is a customer relationship management program developed by
4928  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4929  * 
4930  * This program is free software; you can redistribute it and/or modify it under
4931  * the terms of the GNU Affero General Public License version 3 as published by the
4932  * Free Software Foundation with the addition of the following permission added
4933  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4934  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4935  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4936  * 
4937  * This program is distributed in the hope that it will be useful, but WITHOUT
4938  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4939  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
4940  * details.
4941  * 
4942  * You should have received a copy of the GNU Affero General Public License along with
4943  * this program; if not, see http://www.gnu.org/licenses or write to the Free
4944  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4945  * 02110-1301 USA.
4946  * 
4947  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4948  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4949  * 
4950  * The interactive user interfaces in modified source and object code versions
4951  * of this program must display Appropriate Legal Notices, as required under
4952  * Section 5 of the GNU Affero General Public License version 3.
4953  * 
4954  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4955  * these Appropriate Legal Notices must retain the display of the "Powered by
4956  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4957  * technical reasons, the Appropriate Legal Notices must display the words
4958  * "Powered by SugarCRM".
4959  ********************************************************************************/
4960
4961 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
4962 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
4963 '       <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
4964 '               <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
4965 '               <input type="hidden" id="uid{idx}" name="uid" value="">' +
4966 '               <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
4967 '               <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
4968 '               <input type="hidden" id="type{idx}" name="type" value="">' +
4969 '               <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
4970 '               <input type="hidden" id="composeType" name="composeType">' +
4971 '               <input type="hidden" id="fromAccount" name="fromAccount">' +
4972 '               <input type="hidden" id="sendSubject" name="sendSubject">' +
4973 '               <input type="hidden" id="sendDescription" name="sendDescription">' +
4974 '               <input type="hidden" id="sendTo" name="sendTo">' +
4975 '               <input type="hidden" id="sendBcc" name="sendBcc">' +
4976 '               <input type="hidden" id="sendCc" name="sendCc">' +
4977 '               <input type="hidden" id="setEditor" name="setEditor">' +
4978 '               <input type="hidden" id="saveToSugar" name="saveToSugar">' +
4979 '               <input type="hidden" id="parent_id" name="parent_id">' +
4980 '               <input type="hidden" id="parent_type" name="parent_type">' +
4981 '               <input type="hidden" id="attachments" name="attachments">' +
4982 '               <input type="hidden" id="documents" name="documents">' +
4983 '               <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
4984 '               <input type="hidden" id="templateAttachments" name="templateAttachments">' +
4985 '               <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
4986 '               <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
4987 '                       <tr>' +
4988 '                               <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
4989 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.sendEmail({idx}, false);"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_send.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_SEND}</button>' +
4990 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.saveDraft({idx}, false);"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_save.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_SAVE_DRAFT}</button>' +
4991 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.showAttachmentPanel({idx}, false);"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_attach.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_ATTACHMENT}</button>' +
4992 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.showOptionsPanel({idx}, false);"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_options.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_OPTIONS}</button>' +
4993 '</td><td style="padding: 0px !important;margin:0px; !important">&nbsp;&nbsp;{mod_strings.LBL_EMAIL_RELATE}:&nbsp;&nbsp;<select class="select" id="data_parent_type{idx}" onchange="document.getElementById(\'data_parent_name{idx}\').value=\'\';document.getElementById(\'data_parent_id{idx}\').value=\'\'; SUGAR.email2.composeLayout.enableQuickSearchRelate(\'{idx}\');" name="data_parent_type{idx}">{linkbeans_options}</select>' + 
4994 '&nbsp;</td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
4995 '<input class="sqsEnabled" id="data_parent_name{idx}" name="data_parent_name{idx}" type="text" value="">&nbsp;<button type="button" class="button" onclick="SUGAR.email2.composeLayout.callopenpopupForEmail2({idx});"><img src="index.php?entryPoint=getImage&themeName=default&imageName=id-ff-select.png" align="absmiddle" border="0"></button>' +
4996 '                       </td></tr></tbody></table></th>'     +
4997 '                       </tr>' +
4998 '                       <tr>' +
4999 '                               <td>' +
5000 '                                       <div style="margin:5px;">' +
5001 '                                       <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
5002 '                                               <tr>' +
5003 '                                                       <td class="emailUILabel" NOWRAP >' +
5004 '                                                               {app_strings.LBL_EMAIL_FROM}:' +
5005 '                                                       </td>' +
5006 '                                                       <td class="emailUIField" NOWRAP>' +
5007 '                                                               <div>' +
5008 '                                                                       &nbsp;&nbsp;<select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
5009 '                                                               </div>' +
5010 '                                                       </td>' +
5011 '                                               </tr>' +
5012 '                                               <tr>' +
5013 '                                                       <td class="emailUILabel" NOWRAP>' +
5014 '                                                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' + 
5015 '                                   {app_strings.LBL_EMAIL_TO}:' +
5016 '                               </button>' + 
5017 '                                                       </td>' +
5018 '                                                       <td class="emailUIField" NOWRAP>' +
5019 '                                                               <div class="ac_autocomplete">' +
5020 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5021 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}">&nbsp;</span></a> </span>' +
5022 '                                                                       <div class="ac_container" id="addressToAC{idx}"></div>' +
5023 '                                                               </div>' +
5024 '                                                       </td>' +
5025 '                                               </tr>' +
5026 '                                               <tr id="add_addr_options_tr{idx}">' +
5027 '                                                       <td class="emailUILabel" NOWRAP>&nbsp;</td><td class="emailUIField" valign="top" NOWRAP>&nbsp;&nbsp;<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}">&nbsp;{mod_strings.LBL_ADD_CC_BCC_SEP}&nbsp;</span><span id="bcc_span{idx}"><a href="#" onclick="SE.composeLayout.showHiddenAddress(\'bcc\',\'{idx}\');">{mod_strings.LBL_ADD_BCC}</a></span></td>'+
5028 '                                               </tr>'+
5029 '                                               <tr class="yui-hidden" id="cc_tr{idx}">' +
5030 '                                                       <td class="emailUILabel" NOWRAP>' +
5031 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' + 
5032 '                                                               {app_strings.LBL_EMAIL_CC}:' +
5033 '                               </button>' + 
5034 '                                                       </td>' +
5035 '                                                       <td class="emailUIField" NOWRAP>' +
5036 '                                                               <div class="ac_autocomplete">' +
5037 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5038 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#"  style="display: none;">+<span id="DetailaddressCC{idx}">&nbsp;</span></a> </span>' + 
5039 '                                                                       <div class="ac_container" id="addressCcAC{idx}"></div>' +
5040 '                                                               </div>' +
5041 '                                                       </td>' +
5042 '                                               </tr>' +
5043 '                                               <tr class="yui-hidden" id="bcc_tr{idx}">' +
5044 '                                                       <td class="emailUILabel" NOWRAP>' +
5045 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' + 
5046 '                               {app_strings.LBL_EMAIL_BCC}:' +
5047 '                               </button>' + 
5048 '                                                       </td>' +
5049 '                                                       <td class="emailUIField" NOWRAP>' +
5050 '                                                               <div class="ac_autocomplete">' +
5051 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
5052 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}">&nbsp;</span></a> </span>' +
5053 '                                                                       <div class="ac_container" id="addressBccAC{idx}"></div>' +
5054 '                                                               </div>' +
5055 '                                                       </td>' +
5056 '                                               </tr>' +
5057 '                                               <tr>' +
5058 '                                                       <td class="emailUILabel" NOWRAP width="1%">' +
5059 '                                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
5060 '                                                       </td>' +
5061 '                                                       <td class="emailUIField" NOWRAP width="99%">' +
5062 '                                                               <div class="ac_autocomplete">' +
5063 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
5064 '                                                               </div>' +
5065 '                                                       </td>' +
5066 '                                               </tr>' +
5067 '                                       </table>' +
5068 '                                       </div>' +
5069 '                               </td>'   +
5070 '                       </tr>' +
5071 '               </table>' +
5072 '               <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
5073 '               <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
5074 '                       <div style="padding:5px;">' +
5075 '                               <table cellpadding="2" cellspacing="0" border="0">' +
5076 '                                       <tr>' +
5077 '                                               <th>' +
5078 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
5079 '                                                       <br />' +
5080 '                                                       &nbsp;' +
5081 '                                               </th>' +
5082 '                                       </tr>' +
5083 '                                       <tr>' +
5084 '                                               <td>' +
5085 '                                                       <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
5086 '                                                       <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
5087 '                                               </td>' +
5088 '                                       </tr>' +
5089 '                                       <tr>' +
5090 '                                               <td>' +
5091 '                                                       &nbsp;' +
5092 '                                                       <br />' +
5093 '                                                       &nbsp;' +
5094 '                                               </td>' +
5095 '                                       </tr>' +
5096 '                                       <tr>' +
5097 '                                               <th>' +
5098 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
5099 '                                                       <br />' +
5100 '                                                       &nbsp;' +
5101 '                                               </th>' +
5102 '                                       </tr>' +
5103 '                                       <tr>' +
5104 '                                               <td>' +
5105 '                                                       <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
5106 '                                                       <div id="addedDocuments{idx}"></div>' + //<input name="document{idx}0" id="document{idx}0" type="hidden" /><input name="documentId{idx}0" id="documentId{idx}0" type="hidden" /><input name="documentName{idx}0" id="documentName{idx}0" disabled size="30" type="text" /><input type="button" id="documentSelect{idx}0" onclick="SUGAR.email2.selectDocument({idx}0, this);" class="button" value="{app_strings.LBL_EMAIL_SELECT}" /><input type="button" id="documentRemove{idx}0" onclick="SUGAR.email2.deleteDocumentField({idx}0, this);" class="button" value="{app_strings.LBL_EMAIL_REMOVE}" /><br /></div>' +
5107 '                                               </td>' +
5108 '                                       </tr>' +
5109 '                                       <tr>' +
5110 '                                               <td>' +
5111 '                                                       &nbsp;' +
5112 '                                                       <br />' +
5113 '                                                       &nbsp;' +
5114 '                                               </td>' +
5115 '                                       </tr>' +
5116 '                                       <tr>' +
5117 '                                               <th>' +
5118 '                                                       <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
5119 '                                                       <br />' +
5120 '                                                       &nbsp;' +
5121 '                                               </th>' +
5122 '                                       </tr>' +
5123 '                                       <tr>' +
5124 '                                               <td>' +
5125 '                                                       <div id="addedTemplateAttachments{idx}"></div>' +
5126 '                                               </td>' +
5127 '                                       </tr>' +
5128 '                               </table>' +
5129 '                       </div>' +
5130 '               </div>' +
5131 '       </form>' +
5132 '               <div id="divOptions{idx}" class="ylayout-inactive-content"' +
5133 '             <div style="padding:5px;">' +
5134 '                       <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' + 
5135 '                               <table border="0" width="100%">' +
5136 '                                       <tr>' +
5137 '                                               <td NOWRAP style="padding:2px;">' +
5138 '                                                       <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
5139 '                                               </td>' +
5140 '                                       </tr>' +
5141 '                                       <tr>' +
5142 '                                               <td NOWRAP style="padding:2px;">' +
5143 '                                                       <select name="email_template{idx}" id="email_template{idx}"  onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
5144 '                                               </td>' +
5145 '                                       </tr>' +
5146 '                               </table>' +
5147 '                               <br />' +
5148 '                               <table border="0" width="100%">' +
5149 '                                       <tr>' +
5150 '                                               <td NOWRAP style="padding:2px;">' +
5151 '                                                       <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
5152 '                                               </td>' +
5153 '                                       </tr>' +
5154 '                                       <tr>' +
5155 '                                               <td NOWRAP style="padding:2px;">' +
5156 '                                                       <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
5157 '                                               </td>' +
5158 '                                       </tr>' +
5159 '                               </table>' +
5160 '                               <table border="0" width="100%">' +
5161 '                                       <tr>' +
5162 '                                               <td NOWRAP style="padding:2px;">' +
5163 '                                                       <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/>&nbsp;' +
5164 '                                                       <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
5165 '                                               </td>' +
5166 '                                       </tr>' +
5167 '                               </table>' +
5168 '         </form>' +
5169 '                       </div> ' +
5170 '               </div>' +
5171 '</div>';
5172 // End of File modules/Emails/javascript/composeEmailTemplate.js
5173                                 
5174 /*********************************************************************************
5175  * SugarCRM is a customer relationship management program developed by
5176  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5177  * 
5178  * This program is free software; you can redistribute it and/or modify it under
5179  * the terms of the GNU Affero General Public License version 3 as published by the
5180  * Free Software Foundation with the addition of the following permission added
5181  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
5182  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
5183  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
5184  * 
5185  * This program is distributed in the hope that it will be useful, but WITHOUT
5186  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
5187  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
5188  * details.
5189  * 
5190  * You should have received a copy of the GNU Affero General Public License along with
5191  * this program; if not, see http://www.gnu.org/licenses or write to the Free
5192  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
5193  * 02110-1301 USA.
5194  * 
5195  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
5196  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
5197  * 
5198  * The interactive user interfaces in modified source and object code versions
5199  * of this program must display Appropriate Legal Notices, as required under
5200  * Section 5 of the GNU Affero General Public License version 3.
5201  * 
5202  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
5203  * these Appropriate Legal Notices must retain the display of the "Powered by
5204  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
5205  * technical reasons, the Appropriate Legal Notices must display the words
5206  * "Powered by SugarCRM".
5207  ********************************************************************************/
5208
5209 /**
5210   Complex layout init
5211  */
5212 function complexLayoutInit() {
5213         var se = SUGAR.email2;
5214         var Dom = YAHOO.util.Dom;
5215         se.e2Layout = {
5216         getInnerLayout : function(rows) {
5217                 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
5218                 parent: se.complexLayout,  
5219                         border:true,
5220                     hideOnLayout: true,
5221                     height: 400,
5222                                 units: [{
5223                                         position: "center",
5224                                     scroll:false, // grid should autoScroll itself
5225                                     split:true,
5226                                     body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
5227                                 },{
5228                                         position: "bottom",
5229                                     scroll:true,
5230                                     collapse: false,
5231                                     resize: true,
5232                                     useShim:true,
5233                                     height:'250',
5234                                     body: "<div id='listBottom' />"
5235                                 },{
5236                                     position: "right",
5237                                     scroll:true,
5238                                     collapse: false,
5239                                     resize: true,
5240                                     useShim:true,
5241                                     width:'250',
5242                                     body: "<div id='listRight' />",
5243                                     titlebar: false //,header: "right"
5244                                 }]
5245             });
5246                 se.complexLayout.on("render", function(){
5247                         var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
5248                                 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5249                                 SUGAR.email2.listViewLayout.set("height", height);
5250                                 SUGAR.email2.listViewLayout.render();
5251                 });
5252             se.listViewLayout.render();
5253             //CSS hack for now
5254             se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
5255             var rp = se.listViewLayout.resizePreview = function() {
5256                 var pre = Dom.get("displayEmailFramePreview");
5257                 if (pre) {
5258                         var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
5259                         pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
5260                 }
5261             };
5262             se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
5263             se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
5264             se.e2Layout.setPreviewPanel(rows);
5265             se.previewLayout = se.listViewLayout;
5266             return se.listViewLayout;
5267         },
5268         
5269         getInnerLayout2Rows : function() {
5270             return this.getInnerLayout(true);
5271         },
5272         getInnerLayout2Columns : function() {
5273             return this.getInnerLayout(false);
5274         },
5275         
5276         init : function(){
5277             // initialize state manager, we will use cookies
5278 //                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
5279                 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
5280                 se.complexLayout = new YAHOO.widget.Layout("container", {
5281                         border:true,
5282                 hideOnLayout: true,
5283                 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
5284                 width: Dom.getViewportWidth() - 40,
5285                 units: [{
5286                         position: "center",
5287                     scroll:false,
5288                     body: "<div id='emailtabs'></div>"
5289                 },
5290                 {
5291                         position: "left",
5292                         scroll: true,
5293                         body: "<div id='lefttabs'></div>",
5294                     collapse: true,
5295                     width: 210,
5296                     minWidth: 100,
5297                     resize:true,
5298                     useShim:true,
5299                     titlebar: true,
5300                     header: "&nbsp;"
5301                 },
5302                 {
5303                     header: Dom.get('footerLinks').innerHTML,
5304                                         position: 'bottom',
5305                                         id: 'mbfooter',
5306                                         height: 22,
5307                                         border: false
5308                 }]
5309             });
5310                 se.complexLayout.render();
5311                 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
5312                         tp.addTab(new YAHOO.widget.Tab({ 
5313                                 label: "Inbox",
5314                                 scroll : true,
5315                                 content : "<div id='listViewDiv'/>",
5316                                 id : "center",
5317                                 active : true
5318                         }));
5319                 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
5320                         tp.appendTo(centerEl);
5321                         //CSS hack for now
5322                         tp.get("element").style.borderRight = "1px solid #666"
5323                         
5324                         var listV =  this.getInnerLayout2Rows();
5325                         listV.set("height", tp.get("element").clientHeight - 25);
5326                         listV.render();
5327                 
5328             se.leftTabs = new YAHOO.widget.TabView("lefttabs");
5329             var folderTab = new YAHOO.widget.Tab({ 
5330                                 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
5331                                 scroll : true,
5332                                 content : "<div id='emailtree'/>",
5333                                 id : "tree",
5334                                 active : true
5335                         });
5336             folderTab.on("activeChange", function(o){ 
5337                 if (o.newValue) {
5338                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
5339                 }
5340             });
5341             se.leftTabs.addTab(folderTab);
5342             
5343             var tabContent = SUGAR.util.getAndRemove("searchTab");
5344             var searchTab = new YAHOO.widget.Tab({ 
5345                                 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
5346                                 scroll : true,
5347                                 content : tabContent.innerHTML,
5348                                 id : tabContent.id
5349                         });
5350             searchTab.on("activeChange", function(o){ 
5351                 if (o.newValue) 
5352                 {
5353                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
5354                    //Setup the calendars if needed
5355                        Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_from", singleClick : true, step : 1, weekNumbers:false});
5356                        Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_to", singleClick : true, step : 1, weekNumbers:false});
5357                    
5358                        //Initalize sqs object for assigned user name 
5359                        se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');  
5360                        
5361                        //Attach event handler for when the relate module option is selected for the correct sqs object
5362                        var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
5363                                                 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
5364                        YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){ 
5365                            SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
5366                        
5367                        //If enter key is pressed, perform search
5368                        var  addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
5369                        for(var i=0; i < addKeyPressFields.length;i++)
5370                        {
5371                        YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
5372                                 if (e.keyCode == 13) {
5373                                         YAHOO.util.Event.stopEvent(e);
5374                                         SUGAR.email2.search.searchAdvanced();
5375                                 }
5376                        });
5377                        }
5378                                    //Initiate quick search for the search tab.  Do this only when the tab is selected rather than onDomLoad for perf. gains.
5379                        enableQS(true);
5380                        //Clear parent values if selecting another parent type.
5381                        YAHOO.util.Event.addListener('data_parent_type_search','change', 
5382                            function(){ 
5383                                document.getElementById('data_parent_id_search').value =''; 
5384                                document.getElementById('data_parent_name_search').value =''; 
5385                            });
5386                 
5387                 }
5388             });
5389             se.leftTabs.addTab(searchTab);
5390             
5391             var resizeTabBody = function() {
5392                 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
5393                                 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
5394             }
5395             resizeTabBody();
5396             se.complexLayout.on("render", resizeTabBody);
5397             se.leftTabs.on("activeTabChange", resizeTabBody);
5398                         //hack to allow left pane scroll bar to fully show
5399                 var lefttabsDiv = document.getElementById('lefttabs');
5400                         var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
5401                         var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
5402                         lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
5403           
5404         },
5405         initSQSObject: function(formName,fieldName)
5406         {
5407             var fullFieldName = formName + '_' + fieldName; //SQS Convention
5408             var resultName = fullFieldName + '_' + 'results';
5409             
5410             if (QSFieldsArray[fullFieldName] != null) 
5411             {
5412                 QSFieldsArray[fullFieldName].destroy();
5413                 delete QSFieldsArray[fullFieldName];
5414             }
5415             if (QSProcessedFieldsArray[fullFieldName])
5416             QSProcessedFieldsArray[fullFieldName] = false;
5417
5418             if( Dom.get(resultName) )
5419             {
5420                 var obj = document.getElementById(resultName);
5421                 obj.parentNode.removeChild(obj);
5422             }
5423         },
5424         setPreviewPanel: function(rows) {
5425                 if (rows) {
5426                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
5427                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
5428                 Dom.get("listRight").innerHTML = "";
5429                 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
5430             } else {
5431                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
5432                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
5433                 Dom.get("listBottom").innerHTML = "";
5434                 Dom.get("listRight").innerHTML = "<div id='_blank' />";
5435             }
5436         }
5437     };
5438         se.e2Layout.init();
5439 }
5440
5441 var myBufferedListenerObject = new Object();
5442 myBufferedListenerObject.refit = function() {
5443     if(SUGAR.email2.grid) {
5444         SUGAR.email2.grid.autoSize();
5445     }
5446 }
5447 // End of File modules/Emails/javascript/complexLayout.js
5448