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