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