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