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