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