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