]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/sugar_grp_emails.js
Release 6.1.4
[Github/sugarcrm.git] / include / javascript / sugar_grp_emails.js
1
2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
3
4 /**
5  * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6  * dragged element is inserted before the dragged-over element.
7  *
8  * @extends YAHOO.util.DDProxy
9  * @constructor
10  * @param {String} id the id of the linked element
11  * @param {String} sGroup the group of related DragDrop objects
12  */
13 function ygDDList(id, sGroup) {
14
15         if (id) {
16                 this.init(id, sGroup);
17                 this.initFrame();
18                 //this.logger = new ygLogger("ygDDList");
19         }
20
21         var s = this.getDragEl().style;
22         s.borderColor = "transparent";
23         s.backgroundColor = "#f6f5e5";
24         s.opacity = 0.76;
25         s.filter = "alpha(opacity=76)";
26 }
27
28 ygDDList.prototype = new YAHOO.util.DDProxy();
29
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
32
33 ygDDList.prototype.startDrag = function(x, y) {
34         //this.logger.debug(this.id + " startDrag");
35
36         var dragEl = this.getDragEl();
37         var clickEl = this.getEl();
38
39         dragEl.innerHTML = clickEl.innerHTML;
40         dragElObjects = dragEl.getElementsByTagName('object');
41
42         
43         dragEl.className = clickEl.className;
44         dragEl.style.color = clickEl.style.color;
45         dragEl.style.border = "1px solid #aaa";
46
47         // save the style of the object 
48         clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
49         
50         this.borderDiv = document.createElement('div'); // create a div to display border
51         this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52         this.borderDiv.style.border = '2px dashed #cccccc';
53         
54         for(i in clickEl.childNodes) { // hide contents of the target elements contents
55                 if(typeof clickEl.childNodes[i].style != 'undefined') {
56                         this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57                         clickEl.childNodes[i].style.display = 'none';
58                 }
59
60         }
61         clickEl.appendChild(this.borderDiv);
62 };
63
64 ygDDList.prototype.endDrag = function(e) {
65         // disable moving the linked element
66         var clickEl = this.getEl();
67
68         clickEl.removeChild(this.borderDiv); // remove border div
69         
70         for(i in clickEl.childNodes) { // show target elements contents
71                 if(typeof clickEl.childNodes[i].style != 'undefined') {
72                         clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
73                 }
74         }
75         
76         if(this.clickHeight) 
77             clickEl.style.height = this.clickHeight;
78         else 
79                 clickEl.style.height = '';
80         
81         if(this.clickBorder) 
82             clickEl.style.border = this.clickBorder;
83         else 
84                 clickEl.style.border = '';
85                 
86         dragEl = this.getDragEl();
87         dragEl.innerHTML = '';
88
89         this.afterEndDrag(e);
90 };
91
92 ygDDList.prototype.afterEndDrag = function(e) {
93
94 }
95
96 ygDDList.prototype.onDrag = function(e, id) {
97     
98 };
99
100 ygDDList.prototype.onDragOver = function(e, id) {
101         // this.logger.debug(this.id.toString() + " onDragOver " + id);
102         var el;
103         
104     if ("string" == typeof id) {
105         el = YAHOO.util.DDM.getElement(id);
106     } else { 
107         el = YAHOO.util.DDM.getBestMatch(id).getEl();
108     }
109     
110         dragEl = this.getDragEl();
111         elRegion = YAHOO.util.Dom.getRegion(el);
112             
113 //    this.logger.debug('id: ' + el.id);
114 //    this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 //    this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116         var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 //    this.logger.debug('mid: ' + mid);
118         
119 //    this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " <  " + mid);
120 //    this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
121         
122         if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123                 var el2 = this.getEl();
124                 var p = el.parentNode;
125                 p.insertBefore(el2, el);
126         }
127         if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128                 var el2 = this.getEl();
129                 var p = el.parentNode;
130                 p.insertBefore(el2, el.nextSibling);
131         }
132 };
133
134 ygDDList.prototype.onDragEnter = function(e, id) {
135         // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136         // this.getDragEl().style.border = "1px solid #449629";
137 };
138
139 ygDDList.prototype.onDragOut = function(e, id) {
140     // I need to know when we are over nothing
141         // this.getDragEl().style.border = "1px solid #964428";
142 }
143
144 /////////////////////////////////////////////////////////////////////////////
145
146 function ygDDListBoundary(id, sGroup) {
147         if (id) {
148                 this.init(id, sGroup);
149                 //this.logger = new ygLogger("ygDDListBoundary");
150                 this.isBoundary = true;
151         }
152 }
153
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
156                                 
157 /*********************************************************************************
158  * SugarCRM is a customer relationship management program developed by
159  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
160  *
161  * This program is free software; you can redistribute it and/or modify it under
162  * the terms of the GNU Affero General Public License version 3 as published by the
163  * Free Software Foundation with the addition of the following permission added
164  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
167  *
168  * This program is distributed in the hope that it will be useful, but WITHOUT
169  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
171  * details.
172  *
173  * You should have received a copy of the GNU Affero General Public License along with
174  * this program; if not, see http://www.gnu.org/licenses or write to the Free
175  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
176  * 02110-1301 USA.
177  *
178  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
180  *
181  * The interactive user interfaces in modified source and object code versions
182  * of this program must display Appropriate Legal Notices, as required under
183  * Section 5 of the GNU Affero General Public License version 3.
184  *
185  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186  * these Appropriate Legal Notices must retain the display of the "Powered by
187  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188  * technical reasons, the Appropriate Legal Notices must display the words
189  * "Powered by SugarCRM".
190  ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span>&nbsp;</span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace('&#039;',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML='&nbsp;';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};addToValidate(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,'email',this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
216 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
217 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
218 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
219 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
220 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
221 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
222 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
223 if(SUGAR.isIE){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
224 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
225 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();// End of File include/SugarEmailAddress/SugarEmailAddress.js
226                                 
227 /*********************************************************************************
228  * SugarCRM is a customer relationship management program developed by
229  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
230  *
231  * This program is free software; you can redistribute it and/or modify it under
232  * the terms of the GNU Affero General Public License version 3 as published by the
233  * Free Software Foundation with the addition of the following permission added
234  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
235  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
236  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
237  *
238  * This program is distributed in the hope that it will be useful, but WITHOUT
239  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
240  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
241  * details.
242  *
243  * You should have received a copy of the GNU Affero General Public License along with
244  * this program; if not, see http://www.gnu.org/licenses or write to the Free
245  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
246  * 02110-1301 USA.
247  *
248  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
249  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
250  *
251  * The interactive user interfaces in modified source and object code versions
252  * of this program must display Appropriate Legal Notices, as required under
253  * Section 5 of the GNU Affero General Public License version 3.
254  *
255  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
256  * these Appropriate Legal Notices must retain the display of the "Powered by
257  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
258  * technical reasons, the Appropriate Legal Notices must display the words
259  * "Powered by SugarCRM".
260  ********************************************************************************/
261 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)
262 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_","_")]);}
263 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
264 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;}
265 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();}
266 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';}
267 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='';}
268 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
269 this.js_more();this.js_more();}
270 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
271 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
272 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
273 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
274 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';}
275 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
276 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);}}}
277 currentNode.name=new_name;currentNode.id=new_name;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_name;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
278 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
279 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='';}}
280 arrow.value='show';}
281 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
282 break;}}
283 if(!has_primary){return false;}
284 return true;}
285 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
286 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;}}}}
287 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;}
288 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
289 if(noAdd){enableQS(false);}
290 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_collection_"+i);var id_field=document.getElementById("id_"+this.field+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].id==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
291 divCount++;}}
292 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
293 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=='';}
294 return false;}}
295 SUGAR.collection.safe_clone=function(e,recursive)
296 {if(e.nodeName=="#text")
297 {return document.createTextNode(e.data);}
298 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];for(var i in properties)
299 {if(e[properties[i]])
300 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
301 newNode[properties[i]]=e[properties[i]];}}
302 if(recursive)
303 {for(var i in e.childNodes)
304 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
305 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
306 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
307                                 
308 /*********************************************************************************
309  * SugarCRM is a customer relationship management program developed by
310  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
311  *
312  * This program is free software; you can redistribute it and/or modify it under
313  * the terms of the GNU Affero General Public License version 3 as published by the
314  * Free Software Foundation with the addition of the following permission added
315  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
316  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
317  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
318  *
319  * This program is distributed in the hope that it will be useful, but WITHOUT
320  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
321  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
322  * details.
323  *
324  * You should have received a copy of the GNU Affero General Public License along with
325  * this program; if not, see http://www.gnu.org/licenses or write to the Free
326  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
327  * 02110-1301 USA.
328  *
329  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
330  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
331  *
332  * The interactive user interfaces in modified source and object code versions
333  * of this program must display Appropriate Legal Notices, as required under
334  * Section 5 of the GNU Affero General Public License version 3.
335  *
336  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
337  * these Appropriate Legal Notices must retain the display of the "Powered by
338  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
339  * technical reasons, the Appropriate Legal Notices must display the words
340  * "Powered by SugarCRM".
341  ********************************************************************************/
342 SUGAR.inboundEmail={};Rot13={map:null,convert:function(a){Rot13.init();var s="";for(i=0;i<a.length;i++){var b=a.charAt(i);s+=((b>='A'&&b<='Z')||(b>='a'&&b<='z')?Rot13.map[b]:b);}
343 return s;},init:function(){if(Rot13.map!=null)
344 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
345 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
346 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
347 function getEncryptedPassword(login,password,mailbox){var words=new Array(login,password,mailbox);for(i=0;i<3;i++){word=words[i];if(word.indexOf('&')>0){fragment1=word.substr(0,word.indexOf('&'));fragment2=word.substr(word.indexOf('&')+1,word.length);newWord=fragment1+'::amp::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
348 if(word.indexOf('+')>0){fragment1=word.substr(0,word.indexOf('+'));fragment2=word.substr(word.indexOf('+')+1,word.length);newWord=fragment1+'::plus::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
349 if(word.indexOf('%')>0){fragment1=word.substr(0,word.indexOf('%'));fragment2=word.substr(word.indexOf('%')+1,word.length);newWord=fragment1+'::percent::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}}
350 return words;}
351 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName)
352 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
353 URL='index.php?'
354 +'module='+module_name
355 +'&to_pdf=1'
356 +'&action='+action
357 +'&target='+pageTarget
358 +'&target1='+pageTarget
359 +'&server_url='+mail_server
360 +'&email_user='+words[0]
361 +'&protocol='+protocol
362 +'&port='+port
363 +'&email_password='+words[1]
364 +'&mailbox='+words[2]
365 +'&ssl='+ssl
366 +'&personal='+isPersonal;var SI=SUGAR.inboundEmail;if(!SI.testDlg){SI.testDlg=new YAHOO.widget.SimpleDialog("testSettingsDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.testDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);if(this.evalJS)
367 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
368 this.body.style.width=w}}
369 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
370 title=SUGAR.language.get('InboundEmail','LBL_TEST_SETTINGS');SI.testDlg.setHeader(title);SI.testDlg.setBody(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.testDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.testDlg._updateContent,failure:SI.testDlg.hide,scope:SI.testDlg});SI.testDlg.show();}
371 function isDataValid(formName,validateMonitoredFolder){var formObject=document.getElementById(formName);var errors=new Array();var out=new String();if(trim(formObject.server_url.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_SERVER'));}
372 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
373 if(trim(formObject.email_password.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PASSWORD'));}
374 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
375 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
376 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
377 if(errors.length>0){out=SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_DESC');for(i=0;i<errors.length;i++){if(out!=""){out+="\n";}
378 out+=errors[i];}
379 alert(out);return false;}else{return true;}}
380 function getFoldersListForInboundAccount(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,searchFieldValue,formName){if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';URL='index.php?'
381 +'module='+module_name
382 +'&to_pdf=1'
383 +'&action='+action
384 +'&target='+pageTarget
385 +'&target1='+pageTarget
386 +'&server_url='+mail_server
387 +'&email_user='+words[0]
388 +'&protocol='+protocol
389 +'&port='+port
390 +'&email_password='+words[1]
391 +'&mailbox='+words[2]
392 +'&ssl='+ssl
393 +'&personal='+isPersonal
394 +'&searchField='+searchFieldValue;var SI=SUGAR.inboundEmail;if(!SI.listDlg){SI.listDlg=new YAHOO.widget.SimpleDialog("selectFoldersDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.listDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
395 this.body.style.width=w}}
396 SI.listDlg.setHeader(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.listDlg.setBody('');SI.listDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.listDlg._updateContent,failure:SI.listDlg.hide,scope:SI.listDlg});SI.listDlg.show();}
397 function setPortDefault(){var prot=document.getElementById('protocol');var ssl=document.getElementById('ssl');var port=document.getElementById('port');var stdPorts=new Array("110","143","993","995");var stdBool=new Boolean(false);if(port.value==''){stdBool.value=true;}else{for(i=0;i<stdPorts.length;i++){if(stdPorts[i]==port.value){stdBool.value=true;}}}
398 if(stdBool.value==true){if(prot.value=='imap'&&ssl.checked==false){port.value="143";}else if(prot.value=='imap'&&ssl.checked==true){port.value='993';}else if(prot.value=='pop3'&&ssl.checked==false){port.value='110';}else if(prot.value=='pop3'&&ssl.checked==true){port.value='995';}}}
399 function toggle_monitored_folder(field){var field1=document.getElementById('protocol');var mailbox=document.getElementById('mailbox');var label_inbox=document.getElementById('label_inbox');var subscribeFolderButton=document.getElementById('subscribeFolderButton');var trashFolderRow=document.getElementById('trashFolderRow');var trashFolderRow1=document.getElementById('trashFolderRow1');var sentFolderRow=document.getElementById('sentFolderRow');if(field1.value=='imap'){mailbox.disabled=false;try{mailbox.style.display='';trashFolderRow.style.display='';sentFolderRow.style.display='';trashFolderRow1.style.display='';subscribeFolderButton.style.display='';}catch(e){};label_inbox.style.display='';}
400 else{mailbox.value="INBOX";mailbox.disabled=false;try{mailbox.style.display="none";trashFolderRow.style.display="none";sentFolderRow.style.display="none";trashFolderRow1.style.display="none";subscribeFolderButton.style.display="none";}catch(e){};label_inbox.style.display="none";}}// End of File modules/InboundEmail/InboundEmail.js
401                                 
402 /*********************************************************************************
403  * SugarCRM is a customer relationship management program developed by
404  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
405  * 
406  * This program is free software; you can redistribute it and/or modify it under
407  * the terms of the GNU Affero General Public License version 3 as published by the
408  * Free Software Foundation with the addition of the following permission added
409  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
410  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
411  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
412  * 
413  * This program is distributed in the hope that it will be useful, but WITHOUT
414  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
415  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
416  * details.
417  * 
418  * You should have received a copy of the GNU Affero General Public License along with
419  * this program; if not, see http://www.gnu.org/licenses or write to the Free
420  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
421  * 02110-1301 USA.
422  * 
423  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
424  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
425  * 
426  * The interactive user interfaces in modified source and object code versions
427  * of this program must display Appropriate Legal Notices, as required under
428  * Section 5 of the GNU Affero General Public License version 3.
429  * 
430  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
431  * these Appropriate Legal Notices must retain the display of the "Powered by
432  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
433  * technical reasons, the Appropriate Legal Notices must display the words
434  * "Powered by SugarCRM".
435  ********************************************************************************/
436
437 SUGAR.email2 = {
438     cache : new Object(),
439     o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
440     reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
441     templates : {},
442     tinyInstances : {
443         currentHtmleditor : ''
444     },
445
446     /**
447      * preserves hits from email server
448      */ 
449     _setDetailCache : function(ret) {
450         if(ret.meta) {
451             var compKey = ret.meta.mbox + ret.meta.uid;
452
453             if(!SUGAR.email2.cache[compKey]) {
454                 SUGAR.email2.cache[compKey] = ret;
455             }
456         }
457     },
458
459     autoSetLayout : function() {
460         var c = document.getElementById('container');
461         var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
462         //Ensure a minimum height.
463         tHeight = Math.max(tHeight, 550);
464         c.style.height = tHeight + "px";
465         SUGAR.email2.complexLayout.set('height', tHeight);
466         SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
467         SUGAR.email2.complexLayout.render();
468         SUGAR.email2.listViewLayout.resizePreview();        
469     }
470 };
471
472 /**
473  * Shows overlay progress message
474  */
475 function overlayModal(title, body) {
476     overlay(title, body);
477 }
478 function overlay(reqtitle, body, type, additconfig) {
479     var config = { };
480     if (typeof(additconfig) == "object") {
481         var config = additconfig;
482     }
483     config.type = type;
484     config.title = reqtitle;
485     config.msg = body;
486     YAHOO.SUGAR.MessageBox.show(config);
487 };
488
489 function hideOverlay() {
490         YAHOO.SUGAR.MessageBox.hide();
491 };
492 // End of File modules/Emails/javascript/EmailUIShared.js
493                                 
494 /*********************************************************************************
495  * SugarCRM is a customer relationship management program developed by
496  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
497  * 
498  * This program is free software; you can redistribute it and/or modify it under
499  * the terms of the GNU Affero General Public License version 3 as published by the
500  * Free Software Foundation with the addition of the following permission added
501  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
502  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
503  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
504  * 
505  * This program is distributed in the hope that it will be useful, but WITHOUT
506  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
507  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
508  * details.
509  * 
510  * You should have received a copy of the GNU Affero General Public License along with
511  * this program; if not, see http://www.gnu.org/licenses or write to the Free
512  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
513  * 02110-1301 USA.
514  * 
515  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
516  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
517  * 
518  * The interactive user interfaces in modified source and object code versions
519  * of this program must display Appropriate Legal Notices, as required under
520  * Section 5 of the GNU Affero General Public License version 3.
521  * 
522  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
523  * these Appropriate Legal Notices must retain the display of the "Powered by
524  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
525  * technical reasons, the Appropriate Legal Notices must display the words
526  * "Powered by SugarCRM".
527  ********************************************************************************/
528
529
530 (function() {
531         var sw = YAHOO.SUGAR,
532                 Event = YAHOO.util.Event,
533                 Connect = YAHOO.util.Connect,
534             Dom = YAHOO.util.Dom
535             SE = SUGAR.email2;
536
537 ///////////////////////////////////////////////////////////////////////////////
538 ////    EMAIL ACCOUNTS
539 SE.accounts = {
540     outboundDialog : null,
541     inboundAccountEditDialog : null,
542     inboundAccountsSettingsTable : null,
543     outboundAccountsSettingsTable : null,
544     testOutboundDialog : null,
545     errorStyle : 'input-error',
546     normalStyle : '',
547     newAddedOutboundId : '',
548
549     /**
550      * makes async call to retrieve an outbound instance for editting
551      */
552      //EXT111
553     editOutbound : function(obi) {
554
555             AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
556         
557     },
558     deleteOutbound : function(obi) {
559
560         if(obi.match(/^(add|line|sendmail)+/)) {
561             alert('Invalid Operation');
562         } else {
563                 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
564             AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
565         }
566     },
567     //EXT111
568     getReplyAddress : function() {
569         var primary = '';
570
571         for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
572             var addy = SE.userPrefs.current_user.emailAddresses[i];
573
574             if(addy.primary_address == "1") {
575                 primary = addy.email_address;
576             }
577
578             if(addy.reply_to == "1") {
579                 return addy.email_address;
580             }
581         }
582
583         return primary;
584     },
585
586     /**
587      * Called on "Accounts" tab activation event
588      */
589     lazyLoad : function() {
590                 
591         this._setupInboundAccountTable();
592         this._setupOutboundAccountTable();      
593
594     },
595     
596     _setupInboundAccountTable: function()
597     {
598         //Setup the inbound mail settings
599         if(!this.inboundAccountsSettingsTable)
600         {
601                   this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) { 
602                                         var clckEvent = oColumn.key;
603                                         var imgSrc = "";
604                                         var is_group = oRecord.getData("is_group");
605                                         if(!is_group)
606                                         {
607                                         if(oColumn.key == 'edit')
608                                         {
609                                                 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
610                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
611                                         }
612                                         else if(oColumn.key == 'delete')
613                                         {
614                                                 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
615                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
616                                         }
617                                 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
618                                         }
619                    }; 
620                    
621                    this.showBoolean = function(el, oRecord, oColumn, oData)
622                    {
623                        var is_group = oRecord.getData("is_group");
624                        var bChecked = oData;
625                        bChecked = (bChecked) ? " checked" : "";
626                        if(!is_group)
627                        {
628                        el.innerHTML = "<input type=\"radio\"" + bChecked +
629                            " name=\"col" + oColumn.getId() + "-radio\"" +
630                            " class=\"yui-dt-radio\">";
631                        }
632                    };
633
634
635                 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;                
636                 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
637                 
638                 var typeHoverHelp = '&nbsp;<div id="rollover"><a href="#" class="rollover">'+
639                                     '<img border="0" src="themes/default/images/helpInline.gif">' +
640                                     '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
641                 
642                 
643                 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
644                                       {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'}, 
645                                       {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},     
646                                       {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
647                                       {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
648                                       {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
649                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
650                 this.ieDataSource = new YAHOO.util.DataSource(query);
651                         this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON; 
652                         this.ieDataSource.responseSchema = {
653                                 resultsList: "account_list",
654                                 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
655                         };
656                 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
657                         this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){ 
658                         
659                     var elCheckbox = oArgs.target; 
660                     var oColumn = this.getColumn(elCheckbox);
661                         if(oColumn.key == 'is_active')
662                         {
663                                 var oRecord = this.getRecord(elCheckbox); 
664                                 oRecord.setData("is_active",elCheckbox.checked);
665                                 var t_id = oRecord.getData('id');
666                         var isGroupFolder = oRecord.getData('has_groupfolder');
667                         
668                         if(isGroupFolder)
669                             SUGAR.email2.folders.updateSubscriptions();
670                         else
671                         SUGAR.email2.folders.setFolderSelection();
672                         
673                         }
674                 });
675                         var lastDefaultSelectedId = "";
676                 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){ 
677                     
678                     var elRadio = oArgs.target; 
679                     var oColumn = this.getColumn(elRadio);
680                         if(oColumn.key == 'is_default')
681                         {
682                                 var oRecord = this.getRecord(elRadio);
683                                 var t_id = oRecord.getData('id');
684                                 var t_isGroup = oRecord.getData('is_group');
685                                 if(t_id != lastDefaultSelectedId && !t_isGroup)
686                                 {
687                                                 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose                                      
688                                         lastDefaultSelectedId = t_id;
689                                         AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);                                     
690                                 }
691                                 else if(t_isGroup)
692                                    YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
693                  
694                         }
695                 });
696                 
697                         this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow); 
698                         this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow); 
699         }
700     },
701      _setupOutboundAccountTable: function()
702     {
703         if(!this.outboundAccountsSettingsTable)
704         {            
705                 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) { 
706                                         var clckEvent = oColumn.key;
707                                         var imgSrc = "";
708                                         var isEditable = oRecord.getData("is_editable");
709                                         var type = oRecord.getData("type");
710                                         if(isEditable)
711                                         {
712                                         if(oColumn.key == 'edit')
713                                         {
714                                                 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
715                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
716                                         }
717                                         else if(oColumn.key == 'delete' && type == 'user')
718                                         {
719                                                 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
720                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
721                                         }
722                                         if(imgSrc != '')
723                                     elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
724                                         }
725                 }; 
726                 
727                 //Custom formatter to display any error messages.
728                         this.messageDisplay = function(elLiner, oRecord, oColumn, oData) { 
729                             
730                     if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
731                                             SUGAR.email2.composeLayout.outboundAccountErrors = {};
732                                             
733                         var id = oRecord.getData('id');
734                                         var message = oRecord.getData("errors");
735                                         if(message != '')
736                                         {
737                                     elLiner.innerHTML = '<span class="required">' + message + '</span>';
738                                         //Add the id and message for all outbound accounts.
739                                         SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
740                                         }
741                                         else
742                                         {
743                                             if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
744                                             delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
745                                         }
746                 }; 
747                 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
748                 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
749                 
750                 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
751                                                                    {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
752                                                                    {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},  
753                                                                    {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
754                                                                    
755                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
756                 this.obDataSource = new YAHOO.util.DataSource(query);
757                         this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON; 
758                         this.obDataSource.responseSchema = {
759                                 
760                                 resultsList: "outbound_account_list",
761                                 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
762                         };
763                         
764                 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
765                         
766                 
767                         this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow); 
768                         this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow); 
769                 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
770         }
771     },
772     /**
773      * Displays a modal diaglogue to edit outbound account settings
774      */
775     showEditInboundAccountDialogue : function(clear) {
776  
777         if(!this.inboundAccountEditDialog) {
778                 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
779                 modal:true,
780                                 visible:true,
781                 fixedcenter:true,
782                 constraintoviewport: true,
783                 width   : "600px",
784                 shadow  : true
785             });
786                         EAD.showEvent.subscribe(function() {
787                 var el = this.element;
788                 var viewH = YAHOO.util.Dom.getViewportHeight();
789                 if (this.header && el && viewH - 50 < el.clientHeight) {
790                     var body = this.header.nextElementSibling;
791                                         body.style.overflow = "auto";
792                     body.style.height = (viewH - 50) + "px";
793                 }
794             }, EAD);
795             EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
796                         Dom.removeClass("editAccountDialogue", "yui-hidden");
797
798         } // end lazy load
799
800         if(clear == undefined || clear == true) 
801         {
802                 SE.accounts.clearInboundAccountEditScreen();
803                 //Set default protocol to IMAP when creating new records
804                 document.forms['ieAccount'].elements['protocol'].value = "imap";
805                 SE.accounts.setPortDefault();           
806         }
807         
808         //Check if we should display username/password fields for outbound account if errors were detected.
809         this.checkOutBoundSelection();
810             
811         this.inboundAccountEditDialog.render();
812         this.inboundAccountEditDialog.show();
813     },
814     
815     /**
816     *  Set all fields on the outbound edit form to either enabled/disabled
817     *  except for the username/password.
818     *
819     */
820     toggleOutboundAccountDisabledFields: function(disable)
821     {
822         var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
823         for(var i=0;i<fields.length;i++)
824         {
825             document.getElementById(fields[i]).disabled = disable;
826         }
827         if(disable)
828             Dom.addClass("mail_smtpssl_row", "yui-hidden");
829         else
830             Dom.removeClass('mail_smtpssl_row', "yui-hidden");
831                 
832     },
833     /**
834     * Refresh the inbound accounts table.
835     */
836     refreshInboundAccountTable : function()
837     {   
838             this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
839                 { 
840                         success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
841                                 scope: this.inboundAccountsSettingsTable }
842                         );
843     },
844     /**
845     * Refresh the outbound accounts table.
846     */
847     refreshOuboundAccountTable : function()
848     {   
849             this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
850                 { 
851                         success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
852                                 scope: this.outboundAccountsSettingsTable }
853                         );
854     },
855     /**
856      * Displays a modal diaglogue to add a SMTP server
857      */
858     showAddSmtp : function() {
859         // lazy load dialogue
860         if(!this.outboundDialog) {
861                 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
862                 modal:true,
863                                 visible:true,
864                 fixedcenter:true,
865                 constraintoviewport: true,
866                 width   : "750px",
867                 shadow  : true
868             });
869             this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
870             this.outboundDialog.hideEvent.subscribe(function(){
871                 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
872                 var out = Dom.get("outbound_email");
873                 if (out && out.value == "SYSTEM_ADD")
874                 {
875                         out.value = out.options[0].value;
876                 }
877                 //Check if we should display username/password for system account.
878                 SE.accounts.checkOutBoundSelection();
879                 return true;
880             });
881             
882             Dom.removeClass("outboundDialog", "yui-hidden");
883         } // end lazy load
884         
885         // clear out form
886         var form = document.getElementById('outboundEmailForm');
887         for(i=0; i<form.elements.length; i++) {
888             if(form.elements[i].name == 'mail_smtpport') {
889                 form.elements[i].value = 25;
890             } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
891                 form.elements[i].value = '';
892             } else if(form.elements[i].type == 'checkbox') {
893                 form.elements[i].checked = false;
894             }
895         }
896         //Render the SMTP buttons
897         if ( !SUGAR.smtpButtonGroup ) {
898             SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
899             SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
900             {
901                 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
902                 document.getElementById('smtp_settings').style.display = '';
903                 form.mail_smtptype.value = e.newValue.get('value');
904             });
905             YAHOO.widget.Button.addHiddenFieldsToForm(form);
906         }
907         //Hide Username/Password
908         SUGAR.email2.accounts.smtp_authenticate_field_display();
909         //Unset readonly fields
910         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
911         SUGAR.email2.accounts.changeEmailScreenDisplay('other');
912                 this.outboundDialog.render();
913         this.outboundDialog.show();
914     },
915
916     /**
917      * Accounts' Advanced Settings view toggle
918      */
919     toggleAdv : function() {
920         var adv = document.getElementById("ie_adv");
921         if(adv.style.display == 'none') {
922             adv.style.display = "";
923         } else {
924             adv.style.display = 'none';
925         }
926     },
927     
928         smtp_authenticate_field_display : function() {
929                 var smtpauth_req = document.getElementById("mail_smtpauth_req");
930                 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
931                 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
932         },
933
934     /**
935      * Changes the display used in the outbound email SMTP dialog to match the 
936      */
937     changeEmailScreenDisplay : function(smtptype, isSystemAccount)
938     {
939         document.getElementById("smtpButtonGroupTD").style.display = '';
940         document.getElementById("chooseEmailProviderTD").style.display = '';
941         document.getElementById("mailsettings1").style.display = '';
942         document.getElementById("mailsettings2").style.display = '';
943         document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
944         document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
945         document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
946         document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
947         
948         switch (smtptype) {
949         case "yahoomail":
950             document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
951             document.getElementById("mail_smtpport").value = '465';
952             document.getElementById("mail_smtpauth_req").checked = true;
953             var ssl = document.getElementById("mail_smtpssl");
954             for(var j=0;j<ssl.options.length;j++) {
955                 if(ssl.options[j].text == 'SSL') {
956                     ssl.options[j].selected = true;
957                     break;
958                 }
959             }
960             document.getElementById("mailsettings1").style.display = 'none';
961             document.getElementById("mailsettings2").style.display = 'none';
962             document.getElementById("mail_smtppass_label").innerHTML = 
963             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
964             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
965             break;
966         case "gmail":
967             document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
968             document.getElementById("mail_smtpport").value = '587';
969             document.getElementById("mail_smtpauth_req").checked = true;
970             var ssl = document.getElementById("mail_smtpssl");
971             for(var j=0;j<ssl.options.length;j++) {
972                 if(ssl.options[j].text == 'TLS') {
973                     ssl.options[j].selected = true;
974                     break;
975                 }
976             }
977             document.getElementById("mailsettings1").style.display = 'none';
978             document.getElementById("mailsettings2").style.display = 'none';
979             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
980             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
981             break;
982         case "exchange":
983             if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com' 
984                     || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
985                 document.getElementById("mail_smtpserver").value = '';
986             }
987             document.getElementById("mail_smtpport").value = '25';
988             document.getElementById("mail_smtpauth_req").checked = true;
989             document.getElementById("mailsettings1").style.display = '';
990             document.getElementById("mailsettings2").style.display = '';
991             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
992             document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
993             document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
994             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
995             break;
996         }
997         if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
998         {
999             document.getElementById("smtpButtonGroupTD").style.display = 'none';
1000             document.getElementById("chooseEmailProviderTD").style.display = 'none';
1001             document.getElementById("mailsettings2").style.display = 'none';
1002         }
1003         
1004         SUGAR.email2.accounts.smtp_authenticate_field_display();
1005     },
1006
1007     /**
1008     * Fill the gmail default values for inbound accounts.
1009     */
1010     fillInboundGmailDefaults: function () {
1011         
1012         document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1013         document.forms['ieAccount'].elements['ssl'].checked = true;
1014         document.forms['ieAccount'].elements['protocol'].value = "imap";
1015         SUGAR.email2.accounts.setPortDefault();
1016     },
1017     /**
1018      * Sets Port field to selected protocol and SSL settings defaults
1019      */
1020     setPortDefault : function() {
1021         var prot = document.getElementById('protocol');
1022         var ssl  = document.getElementById('ssl');
1023         var port = document.getElementById('port');
1024         var stdPorts= new Array("110", "143", "993", "995");
1025         var stdBool    = new Boolean(false);
1026         var mailboxdiv = document.getElementById("mailboxdiv");
1027         var trashFolderdiv = document.getElementById("trashFolderdiv");
1028         var sentFolderdiv = document.getElementById("sentFolderdiv");
1029                 var monitoredFolder = document.getElementById("subscribeFolderButton");
1030         if(port.value == '') {
1031             stdBool.value = true;
1032         } else {
1033             for(i=0; i<stdPorts.length; i++) {
1034                 if(stdPorts[i] == port.value) {
1035                     stdBool.value = true;
1036                 }
1037             }
1038         }
1039
1040         if(stdBool.value == true) {
1041             if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1042                 port.value = "143";
1043             } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1044                 port.value = '993';
1045             } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1046                 port.value = '110';
1047             } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1048                 port.value = '995';
1049             }
1050         }
1051         
1052         if (prot.value == 'imap') {
1053                 mailboxdiv.style.display = "";
1054                 trashFolderdiv.style.display = "";
1055                 sentFolderdiv.style.display = "";
1056                 monitoredFolder.style.display = "";
1057                 if (document.getElementById('mailbox').value == "") {
1058                         document.getElementById('mailbox').value = "INBOX";
1059                 }
1060         } else {
1061                 mailboxdiv.style.display = "none";
1062                 trashFolderdiv.style.display = "none";
1063                 sentFolderdiv.style.display = "none";
1064                         monitoredFolder.style.display = "none";
1065                 document.getElementById('mailbox').value = "";
1066         } // else
1067     },
1068
1069     /**
1070      * Draws/removes red boxes around required fields.
1071      */
1072     ieAccountError : function(style) {
1073         document.getElementById('server_url').className = style;
1074         document.getElementById('email_user').className = style;
1075         document.getElementById('email_password').className = style;
1076         document.getElementById('protocol').className = style;
1077         document.getElementById('port').className = style;
1078     },
1079     
1080     checkOutBoundSelection: function() {
1081         var select = Dom.get('outbound_email');
1082         if (!select || select.selectedIndex == -1) { return; }
1083         
1084         var v = select.options[select.selectedIndex].value;
1085         
1086         if(v == '')
1087         {
1088                 select.options[select.selectedIndex].selected = false;
1089                 v = select.options[0].value;
1090         }
1091         else if (v == 'SYSTEM_ADD')
1092                 SUGAR.email2.accounts.showAddSmtp();
1093                 
1094         var foundError = false;
1095         var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1096                 for(i in errorAccounts)
1097                 {
1098                     if(v == i)
1099                     {
1100                         foundError = true;
1101                         break;
1102                     }
1103                 }
1104                 
1105                 //Should username/password fields for outbound account.
1106                 if(foundError)
1107                     this.toggleInboundOutboundFields(true);
1108                 else
1109                     this.toggleInboundOutboundFields(false);
1110                     
1111         
1112         
1113     },
1114     toggleInboundOutboundFields : function (display)
1115     {
1116         if(display)
1117         {
1118             Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1119                     Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1120         }
1121         else
1122         {
1123             Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1124                     Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1125         }  
1126     },
1127     /**
1128      * rebuilds the select options for mailer options
1129      */
1130     rebuildMailerOptions : function() {
1131         var select = document.forms['ieAccount'].elements['outbound_email'];
1132         SE.util.emptySelectOptions(select);
1133                 
1134         //Get the available sugar mailers 
1135         var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1136  
1137         for(i=0;i<a_outbound.length;i++)
1138         {
1139                 var t_record = a_outbound[i];
1140                 var key = t_record.getData('id');
1141                 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1142                 
1143                 var opt = new Option(display, key);
1144                 select.options.add(opt);
1145                 if (key == SE.accounts.newAddedOutboundId) {
1146                         select.options.selectedIndex = i;
1147                 }
1148         }
1149
1150         select.options.add(new Option('',''));
1151         select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1152         //Hide/Show username password fields if necessary.
1153         SE.accounts.checkOutBoundSelection();
1154     },
1155     /**
1156      * Empties all the fields in the accounts edit view
1157      */
1158     clearInboundAccountEditScreen:function() {
1159         
1160         document.getElementById('ie_id').value = '';
1161         document.getElementById('ie_name').value = '';
1162         document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1163         document.getElementById('ie_from_addr').value = this.getReplyAddress();
1164         document.getElementById('reply_to_addr').value = '';
1165         document.getElementById('server_url').value = '';
1166         document.getElementById('email_user').value = '';
1167         document.getElementById('email_password').value = '';
1168         document.getElementById('port').value = '';
1169         document.getElementById('inbound_mail_smtpuser').value = '';
1170         document.getElementById('inbound_mail_smtppass').value = '';
1171         document.ieAccount.protocol.options[0].selected = true;
1172         // handle SSL
1173         document.getElementById('ssl').checked = false;
1174         
1175     },
1176
1177     /**
1178      * Populates an account's fields in Settings->Accounts
1179      */
1180     fillIeAccount:function(jsonstr) {
1181         var o = JSON.parse(jsonstr);
1182
1183         document.getElementById('ie_id').value = o.id;
1184         document.getElementById('ie_name').value = o.name;
1185         if (o.stored_options != null) {
1186                 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;    
1187                 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;    
1188                 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;   
1189                 if (o.stored_options.trashFolder != null) {
1190                         document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1191                 }
1192                 if (o.stored_options.sentFolder != null) {
1193                         document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1194                 }
1195         }
1196         document.getElementById('server_url').value = o.server_url;
1197         document.getElementById('email_user').value = o.email_user;
1198         document.getElementById('email_password').value = o.email_password;
1199         document.getElementById('port').value = o.port;
1200         document.getElementById('group_id').value = o.group_id;
1201         document.getElementById('mailbox').value = o.mailbox;
1202
1203
1204         var i = 0;
1205
1206         // handle SSL
1207         if(typeof(o.service[2]) != 'undefined') {
1208             document.getElementById('ssl').checked = true;
1209         }
1210
1211         // handle protocol
1212         if(document.getElementById('protocol').value != o.protocol) {
1213             var prot = document.getElementById('protocol');
1214             for(i=0; i<prot.options.length; i++) {
1215                 if(prot.options[i].value == o.service[3]) {
1216                     prot.options[i].selected = true;
1217                     this.setPortDefault();
1218                 }
1219             }
1220         }
1221  // handle SMTP selection
1222         if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1223             var opts = document.getElementById('outbound_email').options;
1224             for(i=0; i<opts.length; i++) {
1225                 if(opts[i].value == o.stored_options.outbound_email) {
1226                     opts[i].selected = true;
1227                 }
1228             }
1229         }
1230     },
1231
1232     deleteIeAccount : function(IeAccountID,IeGroupID) {
1233         if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM)) 
1234         {
1235             overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1236
1237             AjaxObject.target = 'frameFlex';
1238             AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1239             SUGAR.email2.accounts.refreshInboundAccountTable();
1240          }                
1241      },
1242         
1243        // Null check for Outbound Settings.
1244     checkOutboundSettings: function() {
1245         var errorMessage = '';
1246         var isError = false;
1247         if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1248             var mailName = document.getElementById('mail_name').value;
1249             var smtpServer = document.getElementById('mail_smtpserver').value;
1250             var smtpPort = document.getElementById('mail_smtpport').value;
1251             
1252             var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1253             if(trim(mailName) == '') {
1254                 isError = true;
1255                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1256             }            
1257             if(trim(smtpServer) == '') {
1258                 isError = true;
1259                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1260             }
1261             if(trim(smtpPort) == '') {
1262                 isError = true;
1263                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1264             }
1265             if(mailsmtpauthreq.checked) {
1266                 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1267                     isError = true;
1268                     errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1269                 }
1270                 if(trim(document.getElementById('mail_smtppass').value) == '') {
1271                     isError = true;
1272                     errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS + "<br/>";
1273                 }                
1274             }
1275         } 
1276         if(isError) {
1277             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1278             return false;    
1279         } else {
1280             return true;
1281         }
1282     },    
1283     
1284     testOutboundSettings: function() {
1285         var errorMessage = '';
1286         var isError = false;
1287         var fromAddress = document.getElementById("outboundtest_from_address").value;
1288         if (trim(fromAddress) == "") {
1289             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1290             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1291             return false;    
1292
1293         }
1294         else if (!isValidEmail(fromAddress)) {
1295             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1296             overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1297             return false;    
1298         }
1299         
1300         //Hide the dialogue and show an in progress indicator.
1301         SE.accounts.testOutboundDialog.hide();
1302         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1303         
1304         //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1305         //nothing is sent in the request.
1306         var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1307         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1308             
1309         YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1310         if(outboundType == 'system-override')
1311             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1312             
1313         var data = "&emailUIAction=testOutbound&outboundtest_from_address=" +  fromAddress;
1314         AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1315         
1316     },
1317     
1318     testOutboundSettingsDialog: function() {
1319         //Ensure that all settings are correct before proceeding to send test email.
1320         if(!SE.accounts.checkOutboundSettings())
1321             return;    
1322     
1323         // lazy load dialogue
1324         if(!SE.accounts.testOutboundDialog) {
1325                 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1326                 modal:true,
1327                                 visible:true,
1328                 fixedcenter:true,
1329                 constraintoviewport: true,
1330                 width   : 600,
1331                 shadow  : true
1332             });
1333             SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1334             Dom.removeClass("testOutboundDialog", "yui-hidden");
1335         } // end lazy load
1336         SE.accounts.testOutboundDialog.render();
1337         SE.accounts.testOutboundDialog.show();
1338     },
1339     
1340     /**
1341      * Saves Outbound email settings
1342      */
1343     saveOutboundSettings : function() {
1344         if(SE.accounts.checkOutboundSettings()) {
1345             //Enable the form fields for the post.
1346             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1347             YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1348             AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1349         } else {
1350             return false;
1351         }
1352     },
1353
1354     saveIeAccount : function() {
1355         
1356         //Before saving check if there are any error messages associated with the outbound account.
1357         var outboundID = document.getElementById('outbound_email').value;
1358
1359         if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1360             'validateSMTPCreds':true}) ) 
1361         {
1362             document.getElementById('saveButton').disabled = true;
1363
1364             overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1365
1366             var formObject = document.getElementById('ieAccount');
1367             YAHOO.util.Connect.setForm(formObject);
1368
1369             AjaxObject._reset();
1370             AjaxObject.target = 'frameFlex';
1371             AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1372         }
1373     },
1374
1375     testSettings : function() {
1376         form = document.getElementById('ieAccount');
1377
1378         if(SE.accounts.checkIeCreds()) {
1379             ie_test_open_popup_with_submit("InboundEmail", "Popup", "Popup", 400, 300, trim(form.server_url.value), form.protocol.value, trim(form.port.value), trim(form.email_user.value), Rot13.write(form.email_password.value), trim(form.mailbox.value), form.ssl.checked, true, "ieAccount");
1380         }
1381     },
1382
1383     getFoldersListForInboundAccountForEmail2 : function() {
1384         form = document.getElementById('ieAccount');
1385         if(SE.accounts.checkIeCreds()) {
1386                 var mailBoxValue = form.mailbox.value;
1387                 if (form.searchField.value.length > 0) {
1388                         mailBoxValue = "";
1389                 } // if
1390             getFoldersListForInboundAccount("InboundEmail", "ShowInboundFoldersList", "Popup", 400, 300, form.server_url.value, form.protocol.value, form.port.value, form.email_user.value, Rot13.write(form.email_password.value), mailBoxValue, form.ssl.checked, true, form.searchField.value );
1391         } // if
1392         
1393     },
1394     
1395     checkIeCreds : function(validateRules) {
1396         if(typeof(validateRules) == 'undefined')    
1397             validateRules = {};
1398             
1399         var errors = new Array();
1400         var out = new String();
1401
1402         var ie_name = Dom.get('ie_name').value;
1403         var fromAddress = Dom.get('ie_from_addr').value;
1404         var server_url = Dom.get('server_url').value;
1405         var email_user = Dom.get('email_user').value;
1406         var email_password = Dom.get('email_password').value;
1407         var protocol = Dom.get('protocol').value;
1408         var port = Dom.get('port').value;
1409         var oe = Dom.get('outbound_email');
1410         var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1411         
1412         var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1413         var outboundPass = Dom.get('inbound_mail_smtppass').value;
1414         
1415         //If the username and password were provided then ignore the error messge
1416         
1417         var outboundCredentialsFound = false;
1418         
1419         if(outboundUserName != "" && outboundPass != "")
1420             outboundCredentialsFound = true;
1421         
1422         var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1423                 
1424         if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null 
1425              && validateSMTPCreds)
1426         {
1427             if(trim(outboundUserName) == "") {
1428                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1429             }
1430             if(trim(outboundPass) == "") {
1431                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1432             }
1433         }
1434
1435         if(trim(ie_name) == "") {
1436             errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1437         }
1438         
1439         if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1440         {            
1441             if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1442                 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1443             }
1444         }
1445         
1446         
1447         if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1448              || trim(oe_value) == "SYSTEM_ADD") ) {
1449             errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1450         }
1451         if(trim(server_url) == "") {
1452             errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1453         }
1454         if(trim(email_user) == "") {
1455             errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1456         }
1457         if(trim(email_password) == "") {
1458             errors.push(app_strings.LBL_EMAIL_ERROR_PASSWORD);
1459         }
1460         if(protocol == "") {
1461             errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1462         }
1463         if (protocol == 'imap') {
1464                 var mailbox = document.getElementById('mailbox').value;
1465                 if (trim(mailbox) == "") {
1466                         errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1467                 } // if
1468                 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1469                         var trashFolder = document.getElementById('trashFolder').value;
1470                         if (trim(trashFolder) == "") {
1471                                 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1472                         } // if
1473                         } // if
1474         }
1475         if(port == "") {
1476             errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1477         }
1478
1479         if(errors.length > 0) {
1480             out = app_strings.LBL_EMAIL_ERROR_DESC;
1481             for(i=0; i<errors.length; i++) {
1482                 if(out != "") {
1483                     out += "\n";
1484                 }
1485                 out += errors[i];
1486             }
1487
1488             alert(out);
1489             return false;
1490         } else {
1491
1492             return true;
1493         }
1494     },
1495
1496     getIeAccount : function(ieId) {
1497         if(ieId == '')
1498             return;
1499
1500         overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1501                 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1502
1503         AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1504     },
1505
1506     /**
1507      * Iterates through TreeView nodes to apply styles dependent nature of node
1508      */
1509     renderTree:function() {
1510         SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1511         SE.tree.render();
1512     },
1513     
1514     //Sets the style for any nodes that need it.
1515     setNodeStyle : function(node) {
1516         if (!node.data.origText) {
1517             node.data.origText = node.data.text;
1518         }
1519         //Set unread
1520         if (typeof(node.data.unseen) != 'undefined') {
1521                 if (node.data.unseen > 0) {
1522                                 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1523                         }
1524                         else {
1525                                 node.setUpLabel(node.data.origText);
1526                         }
1527         } else {
1528                 node.setUpLabel('<span>' + node.data.origText + '</span>');
1529         }
1530         SE.accounts.setupDDTarget(node);
1531     },
1532     
1533     setupDDTarget : function(node) {
1534         if (node.ddTarget) {
1535                 node.ddTarget.removeFromGroup();
1536                 delete node.ddTarget;
1537         }
1538         var id = node.getElId();
1539         var num = id.substring(4);
1540         if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1541                         node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&  
1542                         node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1543                 
1544                 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1545         }
1546         else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1547                 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1548         }
1549     },
1550
1551     /**
1552      * Async call to rebuild the folder list.  After a folder delete or account delete
1553      */
1554     rebuildFolderList : function() {
1555         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1556         AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1557     },
1558     
1559     /**
1560      * Returns the number of remote accounts the user has active.
1561      */
1562     getAccountCount : function() {
1563         var tree = SE.tree;
1564         var count = 0;
1565         for(i=0; i<tree._nodes.length; i++) {
1566             var node = tree._nodes[i];
1567
1568             if(typeof(node) != 'undefined' && node.data.ieId) {
1569                 count++;
1570             }
1571         }
1572         return count;
1573     }
1574 };
1575 ////    END ACCOUNTS
1576 ///////////////////////////////////////////////////////////////////////////////
1577
1578
1579
1580
1581 ///////////////////////////////////////////////////////////////////////////////
1582 ////    CONTEXT MENU CALLS
1583 SE.contextMenus = {
1584     
1585     assignToDialogue : null,
1586     /**
1587      * Archives from context menu
1588      * @param Array uids
1589      * @param string ieId
1590      * @param string folder
1591      */
1592     _archiveToSugar : function(uids, ieId, folder) {
1593         var ser = '';
1594
1595         for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1596             if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1597             ser += uids[i];
1598         }
1599         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1600     },
1601
1602     /**
1603      * Archives from context menu
1604      */
1605     archiveToSugar : function(menuItem) {
1606         SE.contextMenus.emailListContextMenu.hide();
1607         
1608         var rows = SE.grid.getSelectedRows();
1609         var uids = [];
1610         /* iterate through available rows JIC a row is deleted - use first available */
1611         for(var i=0; i<rows.length; i++) {
1612             uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1613         }
1614         var data = SE.grid.getRecord(rows[0]).getData();
1615         SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1616     },
1617     
1618     /**
1619      * Popup the printable version and start system's print function.
1620      */
1621     viewPrintable : function(menuItem) {
1622         var rows = SE.grid.getSelectedRows();
1623         var data = SE.grid.getRecord(rows[0]).getData();
1624         SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1625     },
1626
1627     /**
1628      * Marks email flagged on mail server
1629      */
1630     markRead : function(type, contextMenuId) {
1631         SE.contextMenus.markEmail('read');
1632     },
1633
1634     /**
1635      * Assign this emails to people based on assignment rules
1636      */
1637     assignEmailsTo : function(type, contextMenuId) {
1638         if(!SE.contextMenus.assignToDialogue)
1639         {
1640                 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1641                 modal:true,
1642                                 visible:false,
1643                 fixedcenter:true,
1644                 constraintoviewport: true,
1645                 width   : "600px",
1646                 shadow  : true
1647             });
1648             SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1649             enableQS(true);
1650         }
1651        
1652         Dom.removeClass("assignToDiv", "yui-hidden");
1653         SE.contextMenus.assignToDialogue.render();
1654         SE.contextMenus.assignToDialogue.show();
1655     },
1656     
1657     /**
1658      * Marks email flagged on mail server
1659      */
1660     markFlagged : function(contextMenuId) {
1661         SE.contextMenus.markEmail('flagged');
1662     },
1663
1664     /**
1665      * Marks email unflagged on mail server
1666      */
1667     markUnflagged : function(contextMenuId) {
1668         SE.contextMenus.markEmail('unflagged');
1669     },
1670
1671     /**
1672      * Marks email unread on mail server
1673      */
1674     markUnread : function() {
1675         SE.contextMenus.markEmail('unread');
1676     },
1677
1678     /**
1679      * Deletes an email from context menu
1680      */
1681     markDeleted : function() {
1682         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1683                 document.getElementById('_blank').innerHTML = "";
1684                 SE.contextMenus.markEmail('deleted');
1685         }
1686     },
1687
1688     /**
1689      * generic call API to apply a flag to emails on the server and on sugar
1690      * @param string type "read" | "unread" | "flagged" | "deleted"
1691      */
1692     markEmail : function(type) {
1693         SE.contextMenus.emailListContextMenu.hide();
1694         
1695         //var dm = SE.grid.getStore();
1696         //var uids = SE.grid.getSelectedRowIds();
1697         //var indexes = SE.grid.getSelectedRowIndexes();
1698         var rows = SE.grid.getSelectedRows();
1699         if (rows.length == 0)
1700                 rows = [SE.contextMenus.currentRow];
1701         var ser = [ ];
1702         
1703         for(var i=0; i<rows.length; i++) {
1704             ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1705         }
1706
1707         ser = YAHOO.lang.JSON.stringify(ser);
1708             
1709         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1710         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1711
1712
1713         var count = 0;
1714         
1715         
1716         if(type == 'read' || type == 'deleted') {
1717             // mark read
1718             for(var j=0; j<rows.length; j++) {
1719                 if(SE.grid.getRecord(rows[j]).getData().seen == '0') { 
1720                     count = count + 1;
1721                     SE.grid.getRecord(rows[j]).setData("seen", "1");
1722                 }
1723             }
1724            //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1725             if(ieId){
1726             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1727             var unseenCount = node.data.unseen;
1728             if (isNaN(unseenCount)) {
1729                 unseenCount = 0;
1730             }
1731             var finalCount = parseInt(unseenCount) - count;
1732             node.data.unseen = finalCount;
1733
1734             SE.accounts.renderTree();
1735             }
1736         } else if(type == 'unread') {
1737             // mark unread
1738             for(var j=0; j<rows.length; j++) {
1739                 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1740                     count = count + 1;
1741                 }
1742             }
1743
1744             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1745             var unseenCount = node.data.unseen;
1746             if (isNaN(unseenCount)) {
1747                 unseenCount = 0;
1748             }
1749             var finalCount = parseInt(unseenCount) + count;
1750             node.data.unseen = finalCount;
1751             SE.accounts.renderTree();
1752         }
1753
1754         if (type == 'unread') {
1755                 for(var i=0; i<rows.length; i++) {
1756                     SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1757                 } // for
1758         }
1759                 
1760                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1761         AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1762     },
1763
1764     /**
1765      * refreshes the ListView to show changes to cache
1766      */
1767     markEmailCleanup : function() {
1768         SE.accounts.renderTree();
1769         hideOverlay();
1770         SE.listView.refreshGrid();
1771     },
1772
1773         showAssignmentDialog : function() {
1774                 if (SE.contextMenus.assignmentDialog == null) {
1775                         AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1776                 } else {
1777                         SE.contextMenus.assignmentDialog.show();
1778                 } // else
1779         },
1780         
1781         /**
1782      * shows the import dialog with only relate visible.
1783      */
1784     relateTo : function() {
1785         SE.contextMenus.emailListContextMenu.hide();
1786         
1787         var rows = SE.grid.getSelectedRows();
1788         var data = SE.grid.getRecord(rows[0]).getData();
1789         var ieId = data.ieId;
1790         var folder = data.mbox;
1791         var uids = [];
1792         /* iterate through available rows JIC a row is deleted - use first available */
1793         for(var i=0; i<rows.length; i++) {
1794             uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1795         }
1796         var ser = JSON.stringifyNoSecurity(uids);
1797         
1798         AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1799     },
1800
1801         /**
1802      * shows the import dialog with only relate visible.
1803      */
1804     showDetailView : function() {
1805         SE.contextMenus.emailListContextMenu.hide();
1806         var rows = SE.grid.getSelectedRows();
1807         if (rows.length > 1) {
1808                 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1809                 return;
1810         }
1811         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1812         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1813         /* iterate through available rows JIC a row is deleted - use first available */
1814         var uid = SE.grid.getRecord(rows[0]).getData().uid;
1815         SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1816     },
1817     
1818     /**
1819      *
1820      */
1821     showEmailDetailViewInPopup : function(ieId,uid, folder) {
1822         overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1823         AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1824     },
1825     
1826     /**
1827      * Opens multiple messages from ListView context click
1828      */
1829     openMultiple : function() {
1830         SE.contextMenus.emailListContextMenu.hide();
1831
1832         var rows = SE.grid.getSelectedRows();
1833         var uids = SE.listView.getUidsFromSelection();
1834
1835         if(uids.length > 0) {
1836             var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1837             var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1838             SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1839         }
1840     },
1841
1842     /**
1843      * Replies/forwards email
1844      */
1845     replyForwardEmailContext : function() {
1846         SE.contextMenus.emailListContextMenu.hide();
1847
1848         var indexes = SE.grid.getSelectedRows();
1849         //var dm = SE.grid.getDataModel();
1850         var type = this.id;
1851
1852         for(var i=0; i<indexes.length; i++) {
1853             var row = SE.grid.getRecord(indexes[i]).getData();
1854             SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1855         }
1856     },
1857     
1858     //show menu functions
1859     showEmailsListMenu : function(grid, row) {
1860
1861        var data = row.getData();
1862        var draft = (data.type == "draft");
1863        var menu = SE.contextMenus.emailListContextMenu;
1864        var folderNode;
1865
1866        if (SE.tree) 
1867        {       
1868                if (data.mbox == 'sugar::Emails') 
1869                    folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1870                else 
1871                    folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1872                    
1873                if (  folderNode != null && typeof(folderNode) != "undefined"  && typeof(folderNode.data) != "undefined" 
1874                    && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true')) 
1875                   ||  (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1876                        menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1877                else 
1878                    menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item 
1879        } 
1880        else 
1881            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1882       
1883        menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1884        menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1885        menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1886        menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1887        menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1888
1889                                   
1890        if (data.mbox == "sugar::Emails") 
1891        {
1892            //Allow users to reassign imported emails
1893            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1894            menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1895            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1896            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1897        } 
1898        else 
1899        {
1900            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1901            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1902        }
1903     },
1904     
1905     showFolderMenu : function(grid, rowIndex, event) {
1906        event.stopEvent();
1907        var coords = event.getXY();
1908        SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1909     }
1910 };
1911
1912 SE.contextMenus.dv = {
1913     archiveToSugar : function(contextMenuId) {
1914
1915         SE.contextMenus._archiveToSugar(uids, ieId, folder);
1916     },
1917
1918     replyForwardEmailContext : function(all) {
1919         SE.contextMenus.detailViewContextMenu.hide();
1920     }
1921
1922 };
1923
1924
1925
1926
1927
1928 ////    END SE.contextMenus
1929 ///////////////////////////////////////////////////////////////////////////////
1930
1931
1932
1933 ///////////////////////////////////////////////////////////////////////////////
1934 ////    DETAIL VIEW
1935 SE.detailView = {
1936     consumeMetaDetail : function(ret) {
1937         // handling if the Email drafts
1938         if(ret.type == 'draft') {
1939             SE.composeLayout.c0_composeDraft(); 
1940             return;
1941         }
1942         
1943
1944         // cache contents browser-side
1945         SE._setDetailCache(ret);
1946
1947         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1948         // 2 below must be in global context
1949         meta = ret.meta;
1950         meta['panelId'] = SE.util.getPanelId();
1951
1952         email = ret.meta.email;
1953         var out = displayTemplate.exec({
1954             'app_strings' : app_strings,
1955             'theme' : theme,
1956             'idx' : targetDiv.id,
1957             'meta' : meta,
1958             'email' : meta.email,
1959             'linkBeans' : linkBeans
1960         });
1961         var tabLabel = meta.email.name;
1962         if (tabLabel != null && tabLabel.length > 25) {
1963                 tabLabel = tabLabel.substring(0, 25) + "...";
1964         } // if
1965         targetDiv.set("label", tabLabel);
1966         targetDiv.set("content", out);
1967         
1968         var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1969         if (SUGAR.email2.util.isIe()) {
1970                 displayEmailFrameDiv.style.height = "390px";
1971         } else {
1972                 displayEmailFrameDiv.style.height = "410px";
1973         }
1974
1975         var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1976         displayFrame.contentWindow.document.write(email.description);
1977         displayFrame.contentWindow.document.close();
1978         
1979         // hide archive links
1980         if(ret.meta.is_sugarEmail) {
1981                         document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";                  
1982             document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1983         } else {
1984             if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1985                 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1986         } // else
1987         
1988     },
1989
1990     consumeMetaPreview : function(ret) {
1991         // cache contents browser-side
1992         SE._setDetailCache(ret);
1993         
1994         
1995         
1996         var currrow = SE.grid.getLastSelectedRecord();
1997         currrow = SE.grid.getRecord(currrow);
1998         if (!currrow) {
1999             document.getElementById('_blank').innerHTML = '';
2000             return;
2001         }
2002         // handling if the Email drafts
2003         if(ret.type == 'draft'){
2004             if (currrow.getData().uid == ret.uid) {
2005                 SE.composeLayout.c0_composeDraft();
2006             }
2007             return;
2008         }
2009         
2010         if (currrow.getData().uid != ret.meta.uid) {
2011            return;
2012         }
2013         
2014         // remove loading sprite
2015         document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2016         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2017         meta = ret.meta;
2018         meta['panelId'] = SE.util.getPanelId();
2019         email = ret.meta.email;
2020
2021         document.getElementById('_blank').innerHTML = displayTemplate.exec({
2022             'app_strings' : app_strings,
2023             'theme' : theme,
2024             'idx' : 'Preview',
2025             'meta' : meta,
2026             'email' :meta.email,
2027             'linkBeans' : linkBeans
2028         });
2029        // document.getElementById('_blank').innerHTML = meta.email;
2030        /* displayTemplate.append('_blank', {
2031             'app_strings' : app_strings,
2032             'theme' : theme,
2033             'idx' : 'Preview',
2034             'meta' : meta,
2035             'email' :meta.email,
2036             'linkBeans' : linkBeans
2037         });*/
2038         
2039         var displayFrame = document.getElementById('displayEmailFramePreview');
2040         displayFrame.contentWindow.document.write(email.description);
2041         displayFrame.contentWindow.document.close();
2042         
2043         SE.listViewLayout.resizePreview();
2044
2045         // hide archive links
2046         if(ret.meta.is_sugarEmail) {
2047             document.getElementById("archiveEmailPreview").innerHTML = "&nbsp;";
2048             document.getElementById("btnEmailViewPreview").style.display = "none";
2049             document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2050         } else {
2051           //hide view relationship link
2052                  document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2053         }
2054     },
2055
2056     /**
2057      * wraps emailDelete() for single messages, comes from preview or tab
2058      */
2059     emailDeleteSingle : function(ieId, uid, mbox) {
2060         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2061             // find active panel and close if the user double clicked the email to view.
2062             var activeTabId = SE.util.getPanelId();
2063             if(activeTabId != 'Preview')
2064                 SE.innerLayout.get("activeTab").close();
2065             
2066             document.getElementById('_blank').innerHTML = "";
2067                 var ser = [ ];
2068                         ser.push(uid);
2069                 uid = JSON.stringifyNoSecurity(ser);
2070             this.emailDelete(ieId, uid, mbox);
2071         }
2072     },
2073
2074     /**
2075      * Sends async call to delete a given message
2076      * @param
2077      */
2078     emailDelete : function(ieId, uid, mbox) {
2079        overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2080        AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' + 
2081            uid + "&ieId=" + ieId + "&folder=" + mbox);
2082     },
2083
2084     /**
2085      * retrieves one email to display in the preview pane.
2086      */
2087     getEmailPreview : function() {
2088         var row = SUGAR.email2.listView.currentRow;
2089         var data = row.getData();
2090             if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2091                var setRead = (data['seen'] == 0) ? true : false;
2092                    SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2093                    SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2094             }
2095     },
2096
2097     /**
2098      * Imports one email into Sugar
2099      */
2100     importEmail : function(ieId, uid, mbox) {
2101         SE.util.clearHiddenFieldValues('emailUIForm');
2102
2103         overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2104
2105         var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2106         AjaxObject.target = '';
2107         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2108     },
2109
2110     /**
2111      * Populates the frameFlex div with the contents of an email
2112      */
2113     populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2114         SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2115
2116         var mboxStr = new String(mbox);
2117         var compKey = mbox + uid;
2118
2119         if(setRead == true) {
2120                 SE.listView.boldUnreadRows()
2121                 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2122         }
2123
2124         if(destination == SE.innerLayout) {
2125                 /*
2126              * loading email into a tab, peer with ListView
2127              * targetDiv must remain in the global namespace as it is used by AjaxObject
2128              */
2129                 //Check if we already have a tab of the email open
2130                 var tabs = SE.innerLayout.get("tabs");
2131                 for (var t in tabs) {
2132                         if (tabs[t].id && tabs[t].id == uid) {
2133                                 SE.innerLayout.set("activeTab", tabs[t]);
2134                                 return;
2135                         }
2136                 }
2137                 
2138                 targetDiv = new YAHOO.SUGAR.ClosableTab({
2139                                 label: loadingSprite,
2140                                         scroll : true,
2141                                         content : "",
2142                                         active : true
2143                 }, SE.innerLayout);
2144                 targetDiv.id = uid;
2145                 SE.innerLayout.addTab(targetDiv);
2146             
2147             // use cache if available
2148             if(SE.cache[compKey]) {
2149                 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2150             } else {
2151                 // open email as peer-tab to listView
2152                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2153                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null); 
2154             }
2155         } else {
2156             // loading email into preview pane
2157             document.getElementById('_blank').innerHTML = loadingSprite;
2158
2159             // use cache if available
2160             if(SE.cache[compKey]) {
2161                 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2162             } else {
2163                 AjaxObject.forceAbort = true;
2164                 // open in preview window
2165                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2166                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null); 
2167             }
2168         }
2169     },
2170     
2171     requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2172     {
2173         if(mboxStr.substring(0,7) == 'sugar::') {
2174             // display an email from Sugar
2175             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2176         } else {
2177             // display an email from an email server
2178             document.getElementById('emailUIAction').value = 'getSingleMessage';
2179         }
2180         document.getElementById('mbox').value = mbox;
2181         document.getElementById('ieId').value = ieId;
2182         document.getElementById('uid').value = uid;
2183
2184         YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2185
2186         AjaxObject.forceAbort = true;
2187         AjaxObject.target = '_blank';
2188         AjaxObject.startRequest(callback, null); 
2189     },
2190
2191     /**
2192      * Retrieves multiple emails for DetailView
2193      */
2194     populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2195         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2196         SE.util.clearHiddenFieldValues('emailUIForm');
2197
2198         var mboxStr = new String(mbox);
2199
2200         uids = SE.util.cleanUids(uids);
2201
2202         if(mboxStr.substring(0,7) == 'sugar::') {
2203             // display an email from Sugar
2204             document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2205             document.getElementById('uid').value = uids;
2206         } else {
2207             // display an email from an email server
2208             document.getElementById('emailUIAction').value = 'getMultipleMessages';
2209             document.getElementById('mbox').value = mbox;
2210             document.getElementById('ieId').value = ieId;
2211             document.getElementById('uid').value = uids;
2212         }
2213
2214         var formObject = document.getElementById('emailUIForm');
2215         YAHOO.util.Connect.setForm(formObject);
2216
2217         AjaxObject.target = 'frameFlex';
2218         AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2219
2220         if(setRead == true) {
2221             var c = uids.split(",");
2222             SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2223         }
2224     },
2225
2226     /**
2227      * Makes async call to get QuickCreate form
2228      * Renders a modal edit view for a given module
2229      */
2230     quickCreate : function(module, ieId, uid, mailbox) {
2231         var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2232
2233         if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2234             get += "&sugarEmail=true";
2235         }
2236         
2237         AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2238     },
2239
2240     /**
2241      * Makes async call to save a quick create
2242      * @param bool
2243      */
2244     saveQuickCreate : function(action) {
2245         var qcd = SE.detailView.quickCreateDialog;
2246         if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2247                 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2248                 var theCallback = callbackQuickCreateSave;
2249                 var accountType = '&sugarEmail=true';
2250                 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2251                    accountType = '&ieId=' + qcd.ieId;
2252                 }
2253                 
2254             if (action == 'reply') {
2255                    theCallback = callbackQuickCreateSaveAndReply;
2256                 } else if (action == true) {
2257                     theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2258                 }
2259                 formObject.action.value = 'EmailUIAjax';
2260                 YAHOO.util.Connect.setForm(formObject);
2261                 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2262                 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2263                                        accountType + '&mbox=' + qcd.mbox);
2264         }
2265     },
2266
2267     /**
2268      * Code to show/hide long list of email address in DetailView
2269      */
2270     showCroppedEmailList : function(el) {
2271         el.style.display = 'none';
2272         el.previousSibling.style.display = 'inline'
2273     },
2274     showFullEmailList : function(el) {
2275         el.style.display = 'none';
2276         el.nextSibling.style.display = 'inline';
2277     },
2278
2279     /**
2280      * Shows the QuickCreate overlay
2281      * @param string ieId
2282      * @param string uid
2283      * @param string mailbox
2284      */
2285     showQuickCreate : function(ieId, uid, mailbox) {
2286         var panelId = SE.util.getPanelId();
2287         var context = document.getElementById("quickCreateSpan" + panelId);
2288         
2289         if (!SE.detailView.cqMenus)
2290                 SE.detailView.cqMenus = {};
2291         
2292         if (SE.detailView.cqMenus[context]) 
2293                 SE.detailView.cqMenus[context].destroy();
2294         
2295             var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2296                 lazyload:true,
2297                 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2298         });
2299             
2300             for (var i=0; i < this.qcmodules.length; i++) {
2301             var module = this.qcmodules[i];
2302             menu.addItem({
2303                 text:   app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2304                 modulename: module,
2305                 value: module,
2306                 onclick: { fn: function() {
2307                                 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2308                         }
2309                 }
2310             });
2311         }
2312                 
2313                 menu.render(document.body);
2314                 menu.show();
2315     },
2316
2317     /**
2318      * Displays the "View" submenu in the detailView
2319      * @param string ieId
2320      * @param string uid
2321      * @param string mailbox
2322      */
2323     showViewMenu : function(ieId, uid, mailbox) {
2324         var panelId = SE.util.getPanelId();
2325         var context = "btnEmailView" + panelId;
2326         if (!SE.detailView.viewMenus)
2327                 SE.detailView.viewMenus = {};
2328         
2329         if (SE.detailView.viewMenus[context]) 
2330                 SE.detailView.viewMenus[context].destroy();
2331         
2332             var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2333                 lazyload:true,
2334                 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2335                 clicktohide: true
2336         });
2337                 menu.addItems(
2338                                 (ieId == 'null' || ieId == null) ? 
2339                         //No ieId - Sugar Email
2340                         [{
2341                                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2342                                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2343             }]
2344                         :
2345                         //IeID exists, on a remote server
2346                         [{
2347                 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2348                 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2349             },{
2350                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2351                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2352             }]
2353         );
2354                 menu.render(document.body);
2355                 menu.show();
2356                 
2357
2358         /*
2359         //#23108 jchi@07/17/2008
2360         menu.render('quickCreateSpan'+ panelId);*/
2361         //this.viewMenu = menu;
2362         //this.viewMenu.show(context);
2363     },
2364     /**
2365      * Makes async call to get an email's headers
2366      */
2367     viewHeaders : function(ieId, uid, mailbox) {
2368         var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2369         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2370     },
2371
2372     /**
2373      * Makes async call to get a printable version
2374      */
2375     viewPrintable : function(ieId, uid, mailbox) {
2376         if(mailbox == 'sugar::Emails') {
2377             // display an email from Sugar
2378             var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2379         } else {
2380             // display an email from an email server
2381             var emailUIAction = '&emailUIAction=getSingleMessage';
2382         }
2383
2384         var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2385         AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2386     },
2387
2388     /**
2389      * Makes async call to get an email's raw source
2390      */
2391     viewRaw : function(ieId, uid, mailbox) {
2392         var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2393         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2394     },
2395     
2396     /**
2397      * Display all email addresses in detailview.
2398      */
2399     displayAllAddrs : function(el) {
2400         el.style.display = 'none';
2401         Dom.getNextSibling(el).style.display = 'inline';
2402     }
2403 };
2404 ////    END SE.detailView
2405 ///////////////////////////////////////////////////////////////////////////////
2406
2407
2408
2409 ///////////////////////////////////////////////////////////////////////////////
2410 ////    SE.folders
2411 SE.folders = {
2412     contextMenuFocus : new Object(),
2413
2414     /**
2415      * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2416      * SugarFolder ID - folder strings
2417      */
2418     _createFolderId : function(node) {
2419         var ret = '';
2420
2421         if(!node.data.id)
2422             return ret;
2423
2424         if(node.data.ieId) {
2425             /* we have a local Sugar folder */
2426             if(node.data.ieId == 'folder') {
2427                 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2428             } else if(node.data.ieId.match(SE.reGUID)) {
2429                 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2430             }
2431         } else {
2432             ret = node.data.id;
2433         }
2434
2435         return ret;
2436     },
2437
2438     addChildNode : function(parentNode, childNode) {
2439         var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2440         var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2441         var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2442
2443         if(childNode.nodes) {
2444             if(childNode.nodes.length > 0) {
2445                 for(j=0; j<childNode.nodes.length; j++) {
2446                     var newChildNode = childNode.nodes[j];
2447                     this.addChildNode(node, newChildNode);
2448                 }
2449             }
2450         }
2451     },
2452    
2453     /**
2454      * Builds and returns a new TreeView Node
2455      * @param string name
2456      * @param string id
2457      * @param int is_group
2458      * @return object
2459      */
2460     buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2461         var node = new YAHOO.widget.TextNode(name, parentNode, true);
2462
2463         //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2464         node.expanded = expanded;
2465         node.data = new Object;
2466         node.data['id'] = id;
2467         node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2468         node.data['label'] = name;
2469         node.data['ieId'] = 'folder';
2470         node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2471         node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2472         node.data['unseen'] = unseen;
2473         return node;
2474     },
2475
2476     /**
2477      * ensures that a new folder has a valid name
2478      */
2479     checkFolderName : function(name) {
2480         if(name == "")
2481             return false;
2482
2483         this.folderAdd(name);
2484     },
2485
2486     /**
2487      * Pings email servers for new email - forces refresh of folder pane
2488      */
2489     checkEmailAccounts : function() {
2490         this.checkEmailAccountsSilent(true);
2491     },
2492
2493     checkEmailAccountsSilent : function(showOverlay) {
2494         if(typeof(SE.folders.checkingMail)) {
2495             clearTimeout(SE.folders.checkingMail);
2496         }
2497
2498         // don't stomp an on-going request
2499         if(AjaxObject.currentRequestObject.conn == null) {
2500             if(showOverlay) {
2501                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2502                       app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2503             }
2504             AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2505         } else {
2506             // wait 5 secs before trying again.
2507             SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2508         }
2509     },
2510     
2511     /**
2512      * Starts check of all email Accounts using a loading bar for large POP accounts
2513      */
2514     startEmailAccountCheck : function() {
2515         // don't do two checks at the same time
2516        if(!AjaxObject.requestInProgress()) {
2517             overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2518             SE.accounts.ieIds = SE.folders.getIeIds();
2519             if (SE.accounts.ieIds.length > 0) {
2520                 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard + 
2521                                 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "&currentCount=0");
2522             } else {
2523                hideOverlay();
2524             }
2525         } else {
2526             // wait 5 secs before trying again.
2527             SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2528         }
2529     },
2530     
2531     /**
2532      * Checks a single Account check based on passed ieId
2533      */
2534      startEmailCheckOneAccount : function(ieId, synch) {
2535             if (synch) {
2536                 synch = true;
2537             } else {
2538                 synch = false;
2539             }
2540             var mbox = "";
2541             var node = SE.clickedFolderNode;
2542             if (node && !synch) {
2543                 mbox = node.data.mbox;
2544             } // if
2545             overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2546             SE.accounts.ieIds = [ieId];
2547             AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard + 
2548                                 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "&currentCount=0&synch=" + synch);
2549       },
2550
2551
2552     /**
2553      * Empties trash for subscribed accounts
2554      */
2555     emptyTrash : function() {
2556         SE.contextMenus.frameFoldersContextMenu.hide();
2557         overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2558         AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2559     },
2560     
2561     /**
2562      * Clears Cache files of the inboundemail account
2563      */
2564     clearCacheFiles : function(ieId) {
2565         SE.contextMenus.frameFoldersContextMenu.hide();
2566         overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2567         AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2568     },
2569     
2570     
2571     /**
2572      * Returns an array of all the active accounts in the folder view
2573      */
2574     getIeIds : function() {
2575          var ieIds = [];
2576          var root = SE.tree.getRoot();
2577          for(i=0; i < root.children.length; i++) {
2578            if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2579                         (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2580                ieIds.push(root.children[i].children[0].data.ieId);
2581            }
2582          }
2583          return ieIds;
2584      },
2585
2586     /**
2587      * loads folder lists in Settings->Folders
2588      */
2589     lazyLoadSettings : function() {
2590         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2591         AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2592     },
2593
2594     /**
2595      * After the add new folder is done via folders tab on seetings, this function should get called
2596      * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2597      */
2598     loadSettingFolder : function() {
2599         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2600         AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2601     },
2602     
2603     /**
2604      * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2605      */
2606     removeSugarFolders : function() {
2607         var tree = SE.tree;
2608         var root = tree.getRoot();
2609         var folder = SE.util.findChildNode(root, "ieId", "folder");
2610         while(folder) {
2611             tree.removeNode(folder);
2612             folder = SE.util.findChildNode(root, "ieId", "folder");
2613         }
2614         if (!root.childrenRendered) {
2615                 root.childrenRendered = true;
2616         }
2617     },
2618     
2619     rebuildFolders : function(silent) {
2620       if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2621        AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2622     },
2623
2624     
2625     
2626     /**
2627      * Updates TreeView with Sugar Folders
2628      */
2629     setSugarFolders : function(delay) {
2630         this.removeSugarFolders();
2631                 //AjaxObject.forceAbort = true;
2632                 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2633     },
2634
2635     /**
2636      * Takes async data object and creates the sugar folders in TreeView
2637      */
2638     setSugarFoldersEnd : function(o) {
2639         var root = SE.tree.getRoot();
2640         addChildNodes(root, {nodes: o});
2641         SE.accounts.renderTree();
2642         //If nothing is loaded in the grid, load "My Inbox"
2643         if (SE.grid.params.ieId == "undefined") {
2644                 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2645         }
2646     },
2647
2648     startCheckTimer : function() {
2649         if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2650             var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2651
2652             if(typeof(SE.folders.checkTimer) != 'undefined') {
2653                 clearTimeout(SE.folders.checkTimer);
2654             }
2655
2656             SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2657             if (!SE.userPrefs.emailSettings.firstAutoCheck)
2658             {
2659                 SE.userPrefs.emailSettings.firstAutoCheck = true;
2660                 SE.folders.checkEmailAccountsSilent(false);
2661             }
2662         }
2663     },
2664
2665     /**
2666      * makes an async call to save user preference and refresh folder view
2667      * @param object SELECT list object
2668      */
2669     setFolderSelection : function() {
2670         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2671
2672         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2673         var a_active_accnts = "";
2674         for(i=0;i<a_rs.length;i++)
2675         {
2676                 var t_record = a_rs[i];
2677                 var is_active = t_record.getData('is_active');
2678                 if(is_active)
2679                         a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2680         }
2681         
2682         if(a_active_accnts == "")
2683                 a_active_accnts = "&ieIdShow[]=";
2684
2685         var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2686
2687         AjaxObject.startRequest(callbackFolders, urlStandard + query);
2688     },
2689
2690     /**
2691      * makes async call to save user preference for a given node's open state
2692      * @param object node YUI TextNode object
2693      */
2694     setOpenState : function(node) {
2695         SE.util.clearHiddenFieldValues('emailUIForm');
2696         var nodePath = node.data.id;
2697         var nodeParent = node.parent;
2698
2699         while(nodeParent != null) {
2700             // root node has no ID param
2701             if(nodeParent.data != null) {
2702                 nodePath = nodeParent.data.id + "::" + nodePath;
2703             }
2704
2705             var nodeParent = nodeParent.parent;
2706         }
2707
2708         document.getElementById('emailUIAction').value = 'setFolderOpenState';
2709         document.getElementById('focusFolder').value = nodePath;
2710
2711         if(node.expanded == true) {
2712             document.getElementById('focusFolderOpen').value = 'open';
2713         } else {
2714             document.getElementById('focusFolderOpen').value = 'closed';
2715         }
2716
2717         var formObject = document.getElementById('emailUIForm');
2718         YAHOO.util.Connect.setForm(formObject);
2719
2720         AjaxObject.startRequest(null, null);
2721     },
2722
2723     getNodeFromMboxPath : function(path) {
2724         var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2725         var a = JSON.parse(path);
2726
2727         var node = tree.getRoot();
2728
2729         var i = 0;
2730         while(i < a.length) {
2731             node = this.getChildNodeFromLabel(node, a[i]);
2732             i++;
2733         }
2734
2735         return node;
2736     },
2737
2738     getChildNodeFromLabel : function(node, nodeLabel) {
2739         for(i=0; i<node.children.length; i++) {
2740             if(node.children[i].data.id == nodeLabel) {
2741                 return node.children[i];
2742             }
2743         }
2744     },
2745
2746     /**
2747      * returns the node that presumably under the user's right-click
2748      */
2749     getNodeFromContextMenuFocus : function() {
2750         //// get the target(parent) node
2751         var tree = YAHOO.widget.TreeView.trees.frameFolders;
2752         var index = -1;
2753         var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2754
2755         // filter local folders
2756         if(target.className == 'localFolder' || target.className == 'groupInbox') {
2757             while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2758                 if(target.id == '') {
2759                     target = target.parentNode;
2760                 } else {
2761                     break;
2762                 }
2763             }
2764         }
2765
2766         var targetNode = document.getElementById(target.id);
2767         re = new RegExp(/ygtv[a-z]*(\d+)/i);
2768
2769         try {
2770             var matches = re.exec(targetNode.id);
2771         } catch(ex) {
2772             return document.getElementById(ygtvlabelel1);
2773         }
2774
2775         if(matches) {
2776             index = matches[1];
2777         } else {
2778             // usually parent node
2779             matches = re.exec(targetNode.parentNode.id);
2780
2781             if(matches) {
2782                 index = matches[1];
2783             }
2784         }
2785
2786         var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2787         parentNode.expand();
2788
2789         return parentNode;
2790     },
2791
2792     /**
2793      * Decrements the Unread Email count in folder text
2794      * @param string ieId ID to look for
2795      * @param string mailbox name
2796      * @param count how many to decrement
2797      */
2798     decrementUnreadCount : function(ieId, mbox, count) {
2799         
2800         if(mbox == null)
2801             return;
2802             
2803         if(mbox.indexOf("sugar::") === 0) {
2804             var node = this.getNodeFromId(ieId);
2805         } else {
2806             var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2807         }
2808         if(node) {
2809             var unseen = node.data.unseen;
2810             if(unseen > 0) {
2811                 var check = unseen - count;
2812                 var finalCount = (check >= 0) ? check : 0;
2813                 node.data.unseen = finalCount;
2814             }
2815             SE.accounts.renderTree();
2816         }
2817     },
2818
2819     /**
2820      * gets the TreeView node with a given ID/ieId
2821      * @param string id ID to look for
2822      * @return object Node
2823      */
2824     getNodeFromId : function(id) {
2825         SE.folders.focusNode = null;
2826         SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2827             if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2828                 SE.folders.focusNode = this;
2829                 return false;
2830             }
2831         }, null, [id]);
2832         return SE.folders.focusNode;
2833     },
2834
2835     /**
2836      * Uses ieId and mailbox to try to find a node in the tree
2837      */
2838     getNodeFromIeIdAndMailbox : function(id, mbox) {
2839                 SE.folders.focusNode = null;
2840         if (mbox == "sugar::Emails") {        
2841                 mbox = id;
2842                 id = "folder";
2843         } // if
2844         SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2845                 if (varsarray instanceof Array) {
2846             if (this.data.ieId && this.data.ieId == varsarray[0] 
2847                     && this.data.mbox == varsarray[1]) {
2848                 SE.folders.focusNode = this;
2849                 return false;
2850             } }
2851                 else {
2852                         if (this.data.ieId && this.data.ieId == varsarray) {
2853                                 SE.folders.focusNode = this;
2854                     return false;
2855                         }
2856                 }
2857         }, null, [id, mbox]);
2858         return SE.folders.focusNode;
2859     },
2860     
2861     unhighliteAll : function() {
2862         SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2863     },
2864
2865     /**
2866      * Displays a short form
2867      */
2868     folderAdd : function() {
2869         SE.contextMenus.frameFoldersContextMenu.hide();
2870
2871         var node = SE.clickedFolderNode;
2872
2873         if(node != null && node.data) {
2874             overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE, 
2875                     app_strings.LBL_EMAIL_SETTINGS_NAME, 
2876                     'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2877         } else {
2878             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2879         }
2880     },
2881
2882     folderAddRegisterEnter : function() {
2883         this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"), 
2884                                                                                                                         {keys: YAHOO.util.KeyListener.KEY.ENTER},
2885                                                                                                                         this.buttons[1].handler);
2886         
2887                 this.enterKeyListener.enable();                                                                                                                         
2888     },
2889     
2890     folderRemoveRegisterEnter : function() {
2891         this.enterKeyListener.disable();
2892     },
2893     
2894     folderAddXmlCall : function(name) {
2895         if (trim(name) == "") {
2896                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2897                 return false;
2898         }
2899         name = escape(name);
2900         var post = '';
2901         var type = 'sugar';
2902
2903         var parentNode = SE.clickedFolderNode;
2904         
2905         this.contextMenuFocus = parentNode;
2906
2907         if(parentNode.data.ieId) {
2908             if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2909                 type = 'imap';
2910             }
2911         }
2912         if(type == 'imap') {
2913                 // make an IMAP folder
2914             post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2915             AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2916         } else if(type == 'sugar') {
2917             // make a Sugar folder
2918             if(SE.folders.isUniqueFolderName(name)) {
2919                 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2920                 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2921             } else {
2922                 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2923                 SE.folders.folderAdd();
2924                 return;
2925             }
2926         } else {
2927             alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2928         }
2929
2930         // hide add-folder diaglogue
2931         SE.e2overlay.hide();
2932     },
2933
2934     /**
2935      * Removes either an IMAP folder or a Sugar Folder
2936      */
2937     folderDelete : function() {
2938         SE.contextMenus.frameFoldersContextMenu.hide();
2939         
2940         if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2941             var post = '';
2942             var parentNode = SE.clickedFolderNode;
2943
2944             if(parentNode != null && parentNode.data) {
2945                 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2946                     overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2947                     return;
2948                 }
2949
2950                 AjaxObject.target = 'frameFlex';
2951
2952                 if(parentNode.data.ieId != 'folder') {
2953                     // delete an IMAP folder
2954                     post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2955                 } else {
2956                     // delete a sugar folder
2957                     post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2958                 }
2959                 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2960                 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2961             } else {
2962                 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2963             }
2964         }
2965     },
2966
2967     /**
2968      * Rename folder form
2969      */
2970      //EXT111
2971     folderRename : function() {
2972         SE.contextMenus.frameFoldersContextMenu.hide();
2973         var node = SE.clickedFolderNode;
2974
2975         if(node != null) {
2976             if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2977                 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2978                 return;
2979             }
2980             
2981                         overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text, 
2982                     app_strings.LBL_EMAIL_SETTINGS_NAME, 
2983                     'prompt',
2984                     {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});        
2985         } else {
2986             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2987         }
2988     },
2989
2990     /**
2991      * fills an Object with key-value pairs of available folders
2992      */
2993     getAvailableFoldersObject : function() {
2994         var ret = new Object();
2995         var tree = SE.tree.root;
2996
2997         if(tree.children) {
2998             for(var i=0; i<tree.children.length; i++) {
2999                 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3000             }
3001         } else {
3002             ret['none'] = app_strings.LBL_NONE;
3003         }
3004
3005         return ret;
3006     },
3007
3008     /**
3009      * Fills in key-value pairs for dependent dropdowns
3010      * @param object ret Associative array
3011      * @param object node TreeView node in focus
3012      * @param string currentPath Built up path thus far
3013      * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3014      */
3015     getFolderFromChild : function(ret, node, currentPath, spacer) {
3016         if(node.data != null && node.depth > 0) {
3017             /* handle visual separtors differentiating b/t mailserver and local */
3018             if(node.data.ieId && node.data.ieId == 'folder') {
3019                 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3020             }
3021
3022             if(!ret.spacer0) {
3023                 ret['spacer0'] = spacer;
3024             } else if(ret.spacer0 != spacer) {
3025                 ret['spacer1'] = spacer
3026             }
3027
3028             var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3029             var depthMarker = currentPath;
3030             var retIndex = SE.folders._createFolderId(node);
3031             ret[retIndex] = depthMarker + theLabel;
3032         }
3033
3034         if(node.children != null) {
3035             if(theLabel) {
3036                 currentPath += theLabel + "/";
3037             }
3038
3039             for(var i=0; i<node.children.length; i++) {
3040                 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3041             }
3042         }
3043
3044         return ret;
3045     },
3046
3047     /**
3048      * Wrapper to refresh folders tree
3049      */
3050     getFolders : function() {
3051         SE.accounts.rebuildFolderList();
3052     },
3053
3054     /**
3055      * handles events around folder-rename input field changes
3056      * @param object YUI event object
3057      */
3058     handleEnter : function(e) {
3059         switch(e.browserEvent.type) {
3060             case 'click':
3061                 e.preventDefault(); // click in text field
3062             break;
3063
3064             case 'blur':
3065                 SE.folders.submitFolderRename(e);
3066             break;
3067
3068             case 'keypress':
3069                 var kc = e.browserEvent.keyCode;
3070                 switch(kc) {
3071                     case 13: // enter
3072                         e.preventDefault();
3073                         SE.folders.submitFolderRename(e);
3074                     break;
3075
3076                     case 27: // esc
3077                         e.preventDefault(e);
3078                         SE.folders.cancelFolderRename(e);
3079                     break;
3080                 }
3081             break;
3082         }
3083     },
3084     /**
3085     * Called when a node is clicked on in the folder tree
3086     * @param node, The node clicked on
3087     * @param e, The click event
3088     */
3089     handleClick : function(o) {
3090         var node = o.node;
3091         //If the click was on a sugar folder
3092         if (node.data.ieId == "folder") {
3093             SE.listView.populateListFrameSugarFolder(node, node.id, false);
3094         }
3095         else {
3096             SE.listView.populateListFrame(node, node.data.ieId, false);
3097         }
3098        //eval(node.data.click);
3099        //debugger;
3100     },
3101     
3102     /**
3103     * Called when a node is right-clicked on in the folder tree
3104     */
3105     handleRightClick : function(e) {
3106         YAHOO.util.Event.preventDefault(e);
3107                 //Get the Tree Node
3108                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3109                 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3110                 
3111                 //If the click was on a sugar folder
3112         SE.clickedFolderNode = node;
3113         var inbound = (node.data.ieId && node.data.ieId != 'folder');
3114                 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3115                 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3116                 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3117                 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3118                 menu.getItem(3).cfg.setProperty("disabled", false);
3119                 menu.getItem(4).cfg.setProperty("disabled", false);
3120                 menu.getItem(5).cfg.setProperty("disabled", false);
3121                 menu.getItem(6).cfg.setProperty("disabled", true);
3122                 //Group folder
3123                 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3124                         menu.getItem(0).cfg.setProperty("disabled", true);
3125                         menu.getItem(1).cfg.setProperty("disabled", true);
3126                         menu.getItem(2).cfg.setProperty("disabled", true);
3127                         menu.getItem(3).cfg.setProperty("disabled", true);
3128                         menu.getItem(4).cfg.setProperty("disabled", true);
3129                 }
3130         if (node.data.protocol != null) {
3131                 menu.getItem(6).cfg.setProperty("disabled", false);
3132         }
3133                 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3134                                 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3135                         //Sent or Draft folders
3136                         menu.getItem(3).cfg.setProperty("disabled", true);
3137                         menu.getItem(4).cfg.setProperty("disabled", true);
3138                         menu.getItem(5).cfg.setProperty("disabled", true);
3139                 }
3140                 
3141                 //For group with auto inbound, disable everything.
3142                 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3143                 {
3144                     menu.getItem(0).cfg.setProperty("disabled", true);
3145                 menu.getItem(1).cfg.setProperty("disabled", true);
3146                 menu.getItem(2).cfg.setProperty("disabled", true);
3147                 menu.getItem(3).cfg.setProperty("disabled", true);
3148                 menu.getItem(4).cfg.setProperty("disabled", true);
3149                 menu.getItem(5).cfg.setProperty("disabled", true);
3150                 menu.getItem(6).cfg.setProperty("disabled", true);
3151                 }
3152                 
3153                 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3154                 menu.show();
3155     },
3156     
3157     /**
3158     * Called when a row is dropped on a node
3159     */
3160     handleDrop : function(rows, targetFolder) {
3161         var rowData = rows[0].getData();
3162         if (rowData.mbox != targetFolder.data.mbox) {
3163             var srcIeId = rowData.ieId;
3164             var srcFolder = rowData.mbox;
3165             var destIeId = targetFolder.data.ieId;
3166             var destFolder = targetFolder.data.mbox;
3167             var uids = [];
3168             for(var i=0; i<rows.length; i++) {
3169                 uids[i] = rows[i].getData().uid;
3170             }
3171             SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3172         }
3173     },
3174     
3175     /**
3176     * Called when something is dragged over a Folder Node
3177     */
3178     dragOver : function(dragObject) {
3179        return true;
3180     },
3181     
3182     /**
3183      * Determines if a folder name is unique to the folder tree
3184      * @param string name
3185      */
3186     isUniqueFolderName : function(name) {
3187         uniqueFolder = true;
3188         var root = SE.tree.getRoot();
3189         SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3190             if (this.attributes && this.attributes.ieId == "folder") {
3191                 if (this.attributes.text == name) {
3192                     uniqueFolder = false;
3193                     return false;
3194                 }
3195             }
3196         }, null, [name]);
3197         return uniqueFolder;
3198     },
3199
3200     /**
3201      * Makes async call to rename folder in focus
3202      * @param object e Event Object
3203      */
3204     submitFolderRename : function(newName) {
3205         if (trim(newName) == "") {
3206                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3207                 return false;
3208         }
3209                 newName = escape(newName);        
3210         var node = SE.clickedFolderNode;
3211         var origName = node.data.text
3212         //Ignore no change
3213         if (newName == origName) {
3214             return true;
3215         }
3216         if(SE.folders.isUniqueFolderName(newName)) {
3217             overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3218             if (node.data.ieId == "folder") {
3219                 //Sugar Folder
3220                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3221             }
3222             else {
3223                 //IMAP folder or POP mailbox
3224                 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3225                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId=" 
3226                     + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3227             }
3228             return true;
3229         } else {
3230             alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3231             return false;
3232         }
3233     },
3234     
3235     moveFolder : function(folderId, parentFolderId) {
3236         if (folderId != parentFolderId)
3237         {
3238                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId=" 
3239                     + folderId + "&newParentId=" + parentFolderId);
3240         }
3241     },
3242
3243     /**
3244      * makes async call to do a full synchronization of all accounts
3245      */
3246     synchronizeAccounts : function() {
3247         if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3248             overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3249             AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3250         }
3251     },
3252
3253     /**
3254      * Updates user's folder subscriptsion (Sugar only)
3255      * @param object SELECT DOM object in focus
3256      * @param string type of Folder selection
3257      */
3258     updateSubscriptions : function() {
3259         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);    
3260     
3261         var active = "";
3262
3263         select = document.getElementById('userFolders');
3264
3265         for(i=0; i<select.options.length; i++) {
3266             var opt = select.options[i];
3267              if(opt.selected && opt.value != "") {
3268                  if(active != "") {
3269                      active += "::";
3270                  }
3271                  active += opt.value;
3272              }
3273         }
3274         
3275         //Add the group folder ids.
3276         var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3277         for(i=0; i<group_folders.length; i++) 
3278         {
3279             active += ("::" + group_folders[i]);
3280         }
3281         
3282         AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3283     },
3284     /**
3285      * Updates user's group folder subscriptsion (Sugar only)
3286      * @param ieID The group folder to add to the tree view
3287      */
3288     retrieveGroupFolderSubscriptions : function() {
3289         
3290         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3291         var activeGroupFolders = "";
3292         var activeGroupIds = [];
3293         for(i=0;i<a_rs.length;i++)
3294         {
3295                 var t_record = a_rs[i];
3296                 var is_active = t_record.getData('is_active');
3297                 var isGroupFolder = t_record.getData('has_groupfolder');
3298                 var ieID = t_record.getData('id');
3299                 if( isGroupFolder )
3300                 {
3301                     if(is_active)
3302                       activeGroupIds.push(ieID);
3303                 }
3304         }         
3305        
3306         return activeGroupIds;
3307     }
3308
3309 };
3310
3311 SE.folders.checkEmail2 = function() {
3312     AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3313 }
3314 ////    END FOLDERS OBJECT
3315 ///////////////////////////////////////////////////////////////////////////////
3316
3317
3318 ///////////////////////////////////////////////////////////////////////////////
3319 ////    SE.keys
3320 /**
3321  * Keypress Event capture and processing
3322  */
3323 SE.keys = {
3324     overall : function(e) {
3325         switch(e.charCode) {
3326             case 119: // "w"
3327                 if(e.ctrlKey || e.altKey) {
3328                     var focusRegion = SE.innerLayout.regions.center;
3329                     if(focusRegion.activePanel.closable == true) {
3330                         focusRegion.remove(focusRegion.activePanel);
3331                     }
3332                 }
3333             break;
3334         }
3335     }
3336 };
3337 ////    END SE.keys
3338 ///////////////////////////////////////////////////////////////////////////////
3339
3340
3341 ///////////////////////////////////////////////////////////////////////////////
3342 ////    SE.listView
3343 /**
3344  * ListView object methods and attributes
3345  */
3346 SE.listView = {
3347     currentRowId : -1,
3348
3349     /**
3350      * Fills the ListView pane with detected messages.
3351      */
3352     populateListFrame : function(node, ieId, forceRefresh) {
3353         SE.innerLayout.selectTab(0);
3354                 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3355
3356         Dom.get('_blank').innerHTML = "";
3357         SE.grid.params['emailUIAction'] = 'getMessageList';
3358         SE.grid.params['mbox'] = node.data.mbox;
3359         SE.grid.params['ieId'] = ieId;
3360         forcePreview = true; // loads the preview pane with first item in grid
3361         SE.listView.refreshGrid();
3362     },
3363
3364     /**
3365      * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3366      */
3367     populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3368         SE.innerLayout.selectTab(0);
3369         Dom.get('_blank').innerHTML = "";
3370         SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3371         SE.grid.params['ieId'] = node.data.id;
3372         SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3373         SE.listView.refreshGrid();
3374     },
3375
3376     /**Mac
3377      * Sets sort order as user preference
3378      * @param
3379      */
3380     saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3381         ieId = ieIdPassed;
3382         ieName = ieNamePassed;
3383         focusFolder = focusFolderPassed;
3384
3385         SE.util.clearHiddenFieldValues('emailUIForm');
3386         var previousSort = document.getElementById('sortBy').value;
3387
3388         document.getElementById('sortBy').value = sortBy;
3389         document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3390         document.getElementById('focusFolder').value = focusFolder;
3391         document.getElementById('ieId').value = ieId;
3392
3393         if(sortBy == previousSort) {
3394             document.getElementById('reverse').value = '1';
3395         }
3396
3397         var formObject = document.getElementById('emailUIForm');
3398         YAHOO.util.Connect.setForm(formObject);
3399
3400         AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3401     },
3402
3403
3404     /**
3405      * Enables click/arrow select of grid items which then populate the preview pane.
3406      */
3407     selectFirstRow : function() {
3408         SE.grid.selModel.selectFirstRow();
3409     },
3410
3411     selectLastRow : function() {
3412         SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3413     },
3414
3415     setEmailListStyles : function() {
3416         SE.listView.boldUnreadRows();
3417         return;
3418         var ds = SE.grid.getStore();
3419         if (SE.grid.getSelections().length == 0) {
3420             document.getElementById('_blank').innerHTML = '';
3421         }
3422
3423         var acctMbox = '';
3424         if(typeof(ds.baseParams.mbox) != 'undefined') {
3425             acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3426             var cm = SE.grid.getColumnModel();
3427             if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3428                 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3429                 //SE.grid.render();
3430             } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3431                 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3432                 //SE.grid.render();
3433             }
3434         }
3435         var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3436         SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3437
3438
3439         // 4/20/2007 added to hide overlay after search
3440         //hideOverlay();
3441         if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3442             var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3443             var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3444             if (node) node.data.unseen = unread;
3445         }
3446         SE.accounts.renderTree();
3447
3448         
3449         // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3450         if(forcePreview && ds.totalCount > 0) {
3451             SE.detailView.getEmailPreview();
3452             forcePreview = false;
3453         }
3454     },
3455
3456     /**
3457      * Removes a row if found via its UID
3458      */
3459     removeRowByUid : function(uid) {
3460         uid = new String(uid);
3461         uids = uid.split(',');
3462         var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3463         
3464         for(j=0; j<uids.length; j++) {
3465             var theUid = uids[j];
3466             for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3467                 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3468                         SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3469                 }
3470             } // for
3471         }
3472     },
3473
3474     displaySelectedEmails : function(rows) {
3475         var dm = SE.grid.getDataModel();
3476         var uids = '';
3477
3478         for(i=0; i<rows.length; i++) {
3479             var rowIndex = rows[i].rowIndex;
3480             var metadata = dm.data[rowIndex];
3481
3482             if(uids != "") {
3483                 uids += ",";
3484             }
3485             uids += metadata[5];
3486
3487             // unbold unseen email
3488             this.unboldRow(rowIndex);
3489         }
3490
3491         SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3492     },
3493
3494     /**
3495      * exception handler for data load failures
3496      */
3497     loadException : function(dataModel, ex, response) {
3498         //debugger;
3499     },
3500
3501     /**
3502      * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3503      * @param string sourceIeId Email's source I-E id
3504      * @param string sourceFolder Email's current folder
3505      * @param destinationIeId Destination I-E id
3506      * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3507      *
3508      * @param array emailUids Array of email's UIDs
3509      */
3510     moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3511         if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3512             overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3513         } else {
3514             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3515             // remove rows from visibility
3516             for(row in selectedRows) {
3517                 //SE.grid.getStore().remove(row);
3518             }
3519
3520             var baseUrl =    '&sourceIeId=' + sourceIeId +
3521                             '&sourceFolder=' + sourceFolder +
3522                             '&destinationIeId=' + destinationIeId +
3523                             '&destinationFolder=' + destinationFolder;
3524             var uids = '';
3525
3526             for(i=0; i<emailUids.length; i++) {
3527                 if(uids != '') {
3528                     uids += app_strings.LBL_EMAIL_DELIMITER;
3529                 }
3530                 uids += emailUids[i];
3531             }
3532             if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3533                 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3534             } else {
3535                 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3536             }
3537         }
3538     },
3539     
3540     /**
3541      * Unbolds text in the grid view to denote read status
3542      */
3543     markRead : function(index, record) {
3544         // unbold unseen email
3545         var row = SE.grid.getRecord(record);
3546         row.getData().seen = 1;
3547         SE.grid.getTrEl(record).style.fontWeight = "normal";
3548     },
3549
3550     /**
3551      * grid row output, bolding unread emails
3552      */
3553     boldUnreadRows : function() {
3554         // bold unread emails
3555         var trEl = SE.grid.getFirstTrEl();
3556         while(trEl != null) {
3557                 if(SE.grid.getRecord(trEl).getData().seen == "0")
3558                         trEl.style.fontWeight = "bold";
3559                 else
3560                         trEl.style.fontWeight = "";
3561                 trEl = SE.grid.getNextTrEl(trEl);
3562         }
3563     },
3564
3565     /**
3566      * Show preview for an email if 1 and only 1 is selected
3567      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3568      */
3569     handleRowSelect : function(e) {
3570         if(e.selectedRows.length == 1) {
3571             SE.detailView.getEmailPreview();
3572         }
3573     },
3574
3575     handleDrop : function(e, dd, targetId, e2) {
3576         switch(targetId) {
3577             case 'htmleditordiv':
3578                 var rows = SE.grid.getSelectedRows();
3579                 if(rows.length > 0) {
3580                     SE.listView.displaySelectedEmails(rows);
3581                 }
3582             break;
3583
3584             default:
3585                 var targetElId = new String(targetId);
3586                 var targetIndex = targetElId.replace('ygtvlabelel',"");
3587                 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3588                 var dm = SE.grid.getDataModel();
3589                 var emailUids = new Array();
3590                 var destinationIeId = targetNode.data.ieId;
3591                 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3592
3593
3594                 var rows = SE.grid.getSelectedRows();
3595                 // iterate through dragged rows
3596                 for(i=0; i<rows.length; i++) {
3597                     //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3598                     var rowIndex = rows[i].rowIndex;
3599                     var dataModelRow = dm.data[rowIndex];
3600                     var sourceIeId = dataModelRow[7];
3601                     var sourceFolder = dataModelRow[6];
3602                     emailUids[i] = dataModelRow[5];
3603                 }
3604
3605                 // event wrapped call - need FQ
3606                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3607                 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3608             break;
3609         }
3610     },
3611
3612     /**
3613      * Hack-around to get double-click and single clicks to work on the grid
3614      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3615      */
3616     handleClick : function(o) {
3617         SUGAR.email2.grid.clearTextSelection();
3618         
3619         var el = SUGAR.email2.grid.getSelectedRows();
3620         
3621         //Load an email preview only if a single record is selected.  For multiple selections do nothing.
3622         if ( el.length == 1)
3623         {
3624            var rowId = el[0];
3625            SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3626            SUGAR.email2.listView.currentRowIndex = rowId;
3627            clearTimeout(SUGAR.email2.detailView.previewTimer);
3628            SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3629         }
3630     },
3631
3632     /**
3633      * Custom handler for double-click/enter
3634      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3635      */
3636     getEmail : function(e) {
3637         var rows = SE.grid.getSelectedRows();
3638         var row = SE.grid.getRecord(rows[0]).getData();
3639         
3640         clearTimeout(SE.detailView.previewTimer);
3641         document.getElementById("_blank").innerHTML = "";
3642
3643         if(row.type != "draft") {
3644             SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3645         } else {
3646             // circumventing yui-ext tab generation, let callback handler build new view
3647             SE.util.clearHiddenFieldValues('emailUIForm');
3648             //function(uid, mbox, ieId, setRead, destination) {
3649             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3650             document.getElementById('uid').value = row.uid; // uid;
3651             document.getElementById('mbox').value = row.mbox; // mbox;
3652             document.getElementById('ieId').value = row.ieId; // ieId;
3653
3654             YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3655             AjaxObject.target = '_blank';
3656             AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3657         }
3658     },
3659
3660     /**
3661      * Retrieves a row if found via its UID
3662      * @param string
3663      * @return int
3664      */
3665     getRowIndexByUid : function(uid) {
3666         uid = new String(uid);
3667         uids = uid.split(',');
3668
3669         for(j=0; j<uids.length; j++) {
3670             var theUid = uids[j];
3671
3672             for(i=0; i<SE.grid.getStore().data.length; i++) {
3673                 if(SE.grid.getStore().data[i].id == theUid) {
3674                     return i;
3675                 }
3676             }
3677         }
3678     },
3679     
3680     /**
3681      * Returns the UID's of the seleted rows
3682      *
3683      */
3684      getUidsFromSelection : function() {
3685          var rows = SE.grid.getSelectedRows();
3686          var uids = [];
3687          /* iterate through available rows JIC a row is deleted - use first available */
3688          for(var i=0; i<rows.length; i++) {
3689                  uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3690          }
3691          return uids;
3692      },
3693     
3694     refreshGrid : function() {
3695         SE.grid.getDataSource().sendRequest(
3696             SUGAR.util.paramsToUrl(SE.grid.params), 
3697                 SE.grid.onDataReturnInitializeTable,
3698                 SE.grid
3699         );
3700     }
3701     
3702 };
3703 ////    END SE.listView
3704 ///////////////////////////////////////////////////////////////////////////////
3705
3706 ///////////////////////////////////////////////////////////////////////////////
3707 ////    SEARCH
3708 SE.search = {
3709     /**
3710      * sends search criteria
3711      * @param reference element search field
3712      */
3713     search : function(el) {
3714         var searchCriteria = new String(el.value);
3715
3716         if(searchCriteria == '') {
3717             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3718             return false;
3719         }
3720
3721         var safeCriteria = escape(searchCriteria);
3722
3723         var accountListSearch = document.getElementById('accountListSearch');
3724         //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3725
3726         SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3727         SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3728         SE.grid.getStore().baseParams['subject'] = safeCriteria;
3729         SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3730         SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3731         
3732     },
3733
3734     /**
3735      * sends advanced search criteria
3736      */
3737     searchAdvanced : function() {
3738         var formObject = document.getElementById('advancedSearchForm');
3739         var search = false;
3740
3741         //Set assigned user id to blank if name is not present.
3742         if (formObject.elements['assigned_user_name'].value == "")
3743             formObject.elements['assigned_user_id'].value = "";
3744             
3745         for(i=0; i<formObject.elements.length; i++) {
3746             if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3747                 search = true;
3748             }
3749             if(formObject.elements[i].type == 'text') {
3750                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3751             }
3752             if(formObject.elements[i].type == 'hidden') {
3753                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3754             }
3755              if(formObject.elements[i].type == 'select-one') {
3756                 var el = formObject.elements[i];
3757                 var v = el.options[el.selectedIndex].value;
3758
3759                 if(v != "")
3760                     SE.grid.params[el.name] = v;
3761                 else
3762                 {
3763                     //Clear previous search results if necessary
3764                     if(typeof( SE.grid.params[el.name]) != 'undefined')
3765                         delete SE.grid.params[el.name]
3766                 }
3767              }
3768         }
3769
3770         if (search) 
3771         {
3772             if(! this.validateSearchFormInput() )
3773                 return;
3774                                 
3775                 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3776                 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3777                 var accountListSearch = document.getElementById('accountListSearch');
3778                 SE.listView.refreshGrid();
3779         } else {
3780             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3781         }
3782     },
3783     
3784     /**
3785     *  Validates the search form inputs to ensure all parameters are valid
3786     *  @return bool
3787     */
3788     validateSearchFormInput: function()
3789     { 
3790         addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);  
3791         addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM); 
3792         var dateCheck = check_form('advancedSearchForm');
3793        
3794         //If the parent type is selected ensure the user selected a parent_id.
3795         if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3796             return true;
3797         else
3798             return false;
3799     },
3800     /**
3801     *   Toggles the advanced options, either hidding or showing the selection.
3802     */
3803     toggleAdvancedOptions: function()
3804     {
3805         var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3806
3807         for(var i=0;i<el.length;i++)
3808         {
3809             if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))    
3810                 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3811             else
3812                 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3813         }
3814     },
3815     /**
3816      * clears adv search form fields
3817      */
3818     searchClearAdvanced : function() {
3819         var form = document.getElementById('advancedSearchForm');
3820
3821         for(i=0; i<form.elements.length; i++) {
3822             if(form.elements[i].type != 'button') {
3823                 form.elements[i].value = '';
3824             }
3825         }
3826     }
3827 };
3828 ////    END SE.search
3829 //////////////////////////////////////////////////////////////////////////////
3830
3831
3832 //////////////////////////////////////////////////////////////////////////////
3833 ////    SE.settings
3834 SE.settings = {
3835     /******************************************************************************
3836      * USER SIGNATURES calls stolen from Users module
3837      *****************************************************************************/
3838     createSignature : function(record, the_user_id) {
3839         var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3840         if(record != "") {
3841             URL += "&record="+record;
3842         }
3843         if(the_user_id != "") {
3844             URL += "&the_user_id="+the_user_id;
3845         }
3846         var windowName = 'email_signature';
3847         var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3848
3849         var win = window.open(URL, windowName, windowFeatures);
3850         if(win && win.focus) {
3851             // put the focus on the popup if the browser supports the focus() method
3852             win.focus();
3853         }
3854     },
3855
3856     deleteSignature : function() {
3857         if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3858             overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3859                 var singature_id = document.getElementById('signature_id').value;
3860                 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3861         } // if
3862     },
3863     
3864     saveOptionsGeneral :  function(displayMessage) {
3865         var formObject = document.getElementById('formEmailSettingsGeneral');
3866         if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3867                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3868                 return false;
3869         } // if
3870         YAHOO.util.Connect.setForm(formObject);
3871         SE.composeLayout.emailTemplates = null;
3872
3873         AjaxObject.target = 'frameFlex';
3874         AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3875
3876         if(displayMessage)
3877             alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3878             
3879         SE.settings.settingsDialog.hide();
3880     },
3881
3882     /**
3883      * Shows settings container screen
3884      */
3885     showSettings : function() {
3886         if(!SE.settings.settingsDialog) {
3887                 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3888                 modal:true,
3889                 visible:false,
3890                 fixedcenter:true,
3891                 draggable: false,
3892                 width:"800px",
3893                                 constraintoviewport: true
3894             });
3895                         dlg.showEvent.subscribe( function (){ 
3896                                 var el = this.element;
3897                                 var viewH = YAHOO.util.Dom.getViewportHeight();
3898                 if (this.header && el && viewH - 50 < el.clientHeight) {
3899                     var body = this.header.nextElementSibling;
3900                                         body.style.overflow = "auto";
3901                     body.style.height = (viewH - 50) + "px";
3902                 }
3903             }, dlg);
3904                 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3905                 dlg.setBody('<div id="settingsTabDiv"/>');
3906                 dlg.beforeRenderEvent.subscribe(function() { 
3907                         var dd = new YAHOO.util.DDProxy(dlg.element); 
3908                         dd.setHandleElId(dlg.header); 
3909                         dd.on('endDragEvent', function() { 
3910                                 dlg.show(); 
3911                         }); 
3912                 }, dlg, true); 
3913                 dlg.render();
3914
3915                 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3916                         var tabContent = Dom.get("tab_general");
3917                 tp.addTab(new YAHOO.widget.Tab({
3918                                 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3919                                 scroll : true,
3920                                 content :  tabContent.innerHTML,
3921                                 id : "generalSettings",
3922                                 active : true
3923                         }));
3924                 tabContent.parentNode.removeChild(tabContent);
3925                 tabContent = Dom.get("tab_accounts");
3926                 var accountTab = new YAHOO.widget.Tab({
3927                                 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3928                                 scroll : true,
3929                                 content : tabContent.innerHTML,
3930                                 id : "accountSettings"
3931                         });
3932                 tp.addTab(accountTab);
3933                 tabContent.parentNode.removeChild(tabContent);
3934
3935                         tp.appendTo(dlg.body);
3936         }
3937         
3938         SE.settings.settingsDialog.show();
3939         SE.folders.lazyLoadSettings();
3940         SE.accounts.lazyLoad();
3941     },
3942     
3943
3944     lazyLoadRules : function() {
3945         if(false/*!SE.settings.rules*/) {
3946             AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3947         }
3948
3949     }
3950
3951 };
3952 ////    END SE.settings
3953 ///////////////////////////////////////////////////////////////////////////////
3954 })();
3955
3956 /******************************************************************************
3957  * UTILITIES
3958  *****************************************************************************/
3959 function removeHiddenNodes(nodes, grid) {
3960     var el;
3961         for(var i = nodes.length - 1; i > -1; i--) {
3962         el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3963         if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3964                 nodes.splice(i,1);
3965        }
3966     }
3967 }
3968
3969 function strpad(val) {
3970     return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3971 };
3972
3973 function refreshTodos() {
3974     SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3975     AjaxObject.target = 'todo';
3976     AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3977 };
3978
3979 /******************************************************************************
3980  * MUST STAY IN GLOBAL NAMESPACE
3981  *****************************************************************************/
3982 function refresh_signature_list(signature_id, signature_name) {
3983     var field=document.getElementById('signature_id');
3984     var bfound=0;
3985     for (var i=0; i < field.options.length; i++) {
3986             if (field.options[i].value == signature_id) {
3987                 if (field.options[i].selected==false) {
3988                     field.options[i].selected=true;
3989                 }
3990                 bfound=1;
3991             }
3992     }
3993     //add item to selection list.
3994     if (bfound == 0) {
3995         var newElement=document.createElement('option');
3996         newElement.text=signature_name;
3997         newElement.value=signature_id;
3998         field.options.add(newElement);
3999         newElement.selected=true;
4000     }
4001
4002     //enable the edit button.
4003     var field1=document.getElementById('edit_sig');
4004     field1.style.visibility="inherit";
4005     var deleteButt = document.getElementById('delete_sig');
4006     deleteButt.style.visibility="inherit";
4007 };
4008
4009 function setDefaultSigId(id) {
4010     var checkbox = document.getElementById("signature_default");
4011     var default_sig = document.getElementById("signatureDefault");
4012
4013     if(checkbox.checked) {
4014         default_sig.value = id;
4015     } else {
4016         default_sig.value = "";
4017     }
4018 };
4019
4020 function setSigEditButtonVisibility() {
4021     var field = document.getElementById('signature_id');
4022     var editButt = document.getElementById('edit_sig');
4023     var deleteButt = document.getElementById('delete_sig');
4024     if(field.value != '') {
4025         editButt.style.visibility = "inherit";
4026         deleteButt.style.visibility = "inherit";
4027     } else {
4028         editButt.style.visibility = "hidden";
4029         deleteButt.style.visibility = "hidden";
4030     }
4031 }// End of File modules/Emails/javascript/EmailUI.js
4032                                 
4033 /*********************************************************************************
4034  * SugarCRM is a customer relationship management program developed by
4035  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4036  * 
4037  * This program is free software; you can redistribute it and/or modify it under
4038  * the terms of the GNU Affero General Public License version 3 as published by the
4039  * Free Software Foundation with the addition of the following permission added
4040  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4041  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4042  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4043  * 
4044  * This program is distributed in the hope that it will be useful, but WITHOUT
4045  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4046  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
4047  * details.
4048  * 
4049  * You should have received a copy of the GNU Affero General Public License along with
4050  * this program; if not, see http://www.gnu.org/licenses or write to the Free
4051  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4052  * 02110-1301 USA.
4053  * 
4054  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4055  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4056  * 
4057  * The interactive user interfaces in modified source and object code versions
4058  * of this program must display Appropriate Legal Notices, as required under
4059  * Section 5 of the GNU Affero General Public License version 3.
4060  * 
4061  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4062  * these Appropriate Legal Notices must retain the display of the "Powered by
4063  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4064  * technical reasons, the Appropriate Legal Notices must display the words
4065  * "Powered by SugarCRM".
4066  ********************************************************************************/
4067
4068  (function() {
4069         var sw = YAHOO.SUGAR,
4070                 Event = YAHOO.util.Event,
4071                 Connect = YAHOO.util.Connect,
4072             Dom = YAHOO.util.Dom
4073             SE = SUGAR.email2;
4074
4075 ///////////////////////////////////////////////////////////////////////////////
4076 ////    ADDRESS BOOK
4077 SE.addressBook = {
4078     _contactCache : new Array(), // cache of contacts
4079     _dd : new Array(), // filtered list, same format as _contactCache
4080     _ddLists : new Array(), // list of Lists
4081     _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4082     _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4083     clickBubble : true, // hack to get around onclick event bubbling
4084         relatedBeanId : '',
4085         relatedBeanType : '',
4086         idx : 0,
4087
4088     itemSpacing : 'white-space:nowrap; padding:2px;',
4089     reGUID : SE.reGUID,
4090
4091
4092
4093     /**
4094     *  YUI bug fix 2527707.  Causes nested datatable's in <tables> to cause 404 errors whens earching.
4095     */
4096     initFixForDatatableSort: function () {
4097         //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4098         YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4099             var oColumn = this._oColumnSet.getColumn(column);
4100
4101             if(!oColumn) {
4102                 // Validate TD element
4103                 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4104                 if(elCell) {
4105                     oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4106                 }
4107                 // Validate TH element
4108                 else {
4109                     elCell = this.getThEl(column);
4110                     if(elCell) {
4111                         // Find by TH el ID
4112                         var allColumns = this._oColumnSet.flat;
4113                         for(var i=0, len=allColumns.length; i<len; i++) {
4114                             if(allColumns[i].getThEl().id === elCell.id) {
4115                                 oColumn = allColumns[i];
4116                             }
4117                         }
4118                     }
4119                 }
4120             }
4121
4122             return oColumn;
4123         };
4124     },
4125
4126     cancelEdit : function() {
4127         if(this.editContactDialog)
4128             this.editContactDialog.hide();
4129         if(this.editMailingListDialog)
4130             this.editMailingListDialog.hide();
4131     },
4132
4133     /**
4134      * Clears filter form
4135      */
4136     clear : function() {
4137         var t = document.getElementById('contactsFilter');
4138         t.value = '';
4139         this.filter(t);
4140     },
4141
4142     /**
4143      * handle context-menu Compose-to call
4144      * @param string type 'contacts' or 'lists'
4145      */
4146     composeTo : function(type, waited) {
4147         var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4148         if (activePanel.substring(0, 10) != "composeTab") {
4149             SE.composeLayout.c0_composeNewEmail();
4150             setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4151                 SE.contextMenus.contactsContextMenu.hide();
4152             return;
4153         }
4154         var idx = activePanel.substring(10);
4155         var rows = [ ];
4156         var id = '';
4157         // determine if we have a selection to work with
4158         if(type == 'contacts') {
4159             var ids = SE.contactView.getSelectedRows();
4160             for (var i in ids) {
4161                 rows[i] = SE.contactView.getRecord(ids[i]);
4162             }
4163             removeHiddenNodes(rows, SE.contactView);
4164         } 
4165                 else { return; }
4166
4167         if(rows.length > 0) {
4168             SE.composeLayout.handleDrop(
4169                 (type == 'contacts') ? SE.contactView : SE.emailListsView, 
4170                 null, rows, 'addressTO' + idx );
4171         } else {
4172             alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4173         }
4174     },
4175
4176     editContact : function() {
4177         SE.contextMenus.contactsContextMenu.hide();
4178         var element = SE.contactView.getSelectedNodes()[0];
4179         var elementId = "";
4180         if (element.className.indexOf('address-contact') > -1) {
4181             elementId = element.id;
4182         } else if (element.className.indexOf('address-exp-contact') > -1) {
4183             elementId = element.id.substring(2);
4184         }
4185     },
4186     
4187
4188     /**
4189      * Filters contact entries based on user input
4190      */
4191     filter : function(inputEl) {
4192         var ret = new Object();
4193         var re = new RegExp(inputEl.value, "gi");
4194
4195         for(var i in this._contactCache) {
4196             if(this._contactCache[i].name.match(re)) {
4197                 ret[i] = this._contactCache[i];
4198             }
4199         }
4200
4201         this.buildContactList(ret);
4202     },
4203
4204     fullForm : function(id, module) {
4205         document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4206     },
4207
4208     /**
4209      * returns a formatted email address from the addressBook cache
4210      */
4211     getFormattedAddress : function(id) {
4212         var o = this._contactCache[id];
4213         var primaryEmail = '';
4214
4215         for(var i=0; i<o.email.length; i++) {
4216             var currentEmail = o.email[i].email_address;
4217
4218             if(o.email[i].primary_address == 1) {
4219                 primaryEmail = o.email[i].email_address;
4220             }
4221         }
4222
4223         var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4224         var name = new String(o.name);
4225         var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/&#039;/gi,'\'');
4226         var ret = finalName + " <" + finalEmail.replace(/&#039;/gi,'\'') + ">";
4227
4228         return ret;
4229     },
4230     
4231     /**
4232      * Sets up async call to query for matching contacts, users, etc.
4233      */
4234     searchContacts : function() {
4235         var fn = document.getElementById('input_searchField').value;
4236         var pe = document.getElementById('input_searchPerson').value;
4237         
4238         var rb = document.getElementById('hasRelatedBean').checked;
4239         if (rb) {
4240                         var idx = this.idx;
4241                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4242                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4243                 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4244                 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4245         } else {
4246                 this.addressBookDataModel.params['related_bean_id'] = '';
4247         }
4248         
4249         this.addressBookDataModel.params['search_field'] = fn;
4250         this.addressBookDataModel.params['person'] = pe;
4251         this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4252         this.grid._oDataSource = this.addressBookDataModel;
4253         this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params),  this.grid.onDataReturnInitializeTable, this.grid);
4254     },
4255     
4256     /**
4257      * Clear Search Crieteria For Addressbook
4258      */
4259     clearAddressBookSearch : function() {
4260         document.getElementById('input_searchField').value = "";
4261         document.getElementById('input_searchPerson').selectedIndex = 0;
4262     },
4263     
4264     /**
4265      * Opens modal select window to add contacts to addressbook
4266      */
4267     selectContactsDialogue : function(destId) {
4268         if(!this.contactsDialogue) {
4269                 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4270                 modal:true,
4271                 visible:false,
4272                 draggable: false,
4273                 constraintoviewport: true,
4274                 width   : 980,
4275                 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4276                            {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4277             });
4278                 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4279                 
4280                 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4281                 dlg.setBody(body.innerHTML);
4282                 dlg.renderEvent.subscribe(function() {
4283                 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4284                 if (iev && !SUGAR.isIE) {
4285                         this.body.style.width = "950px";
4286                 }
4287             }, dlg);
4288                      
4289             
4290                 dlg.beforeRenderEvent.subscribe(function() { 
4291                         var dd = new YAHOO.util.DDProxy(dlg.element); 
4292                         dd.setHandleElId(dlg.header); 
4293                         dd.on('endDragEvent', function() { 
4294                                 dlg.show(); 
4295                         }); 
4296                 }, dlg, true); 
4297                 dlg.render();
4298                 
4299                 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4300                         
4301                 var tabContent = SUGAR.util.getAndRemove("searchForm");
4302                 tp.addTab(new YAHOO.widget.Tab({
4303                                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4304                                 scroll : true,
4305                                 content : tabContent.innerHTML,
4306                                 id : "addressSearchTab",
4307                                 active : true
4308                         }));
4309                         
4310                 var addListenerFields = ['input_searchPerson','input_searchField' ]
4311                 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4312                         if (e.keyCode == 13) {
4313                                 YAHOO.util.Event.stopEvent(e);
4314                                 SUGAR.email2.addressBook.searchContacts();
4315                         }
4316                 });
4317
4318                 this.contactsDialogue.render();
4319                 dlg.center();
4320         }
4321         //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4322         if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4323             var idx = 0;
4324         else
4325         {
4326             var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4327             var idx = activePanel.substring(10);
4328         }
4329         SE.addressBook.idx = idx;
4330         
4331                 var relatedBeanId;
4332         if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4333                 document.getElementById('relatedBeanColumn').style.display = '';
4334                 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4335                         var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4336                         relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4337                         document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4338                         SE.addressBook.relatedBeanType = relatedBeanType;
4339             } else {
4340                 document.getElementById('relatedBeanColumn').style.display = 'none';
4341                 document.getElementById('hasRelatedBean').checked = false;
4342             }
4343             
4344             if (!SE.addressBook.grid) 
4345             {
4346                 if (hasRelatedBeanId) {
4347                         document.getElementById('hasRelatedBean').checked = true;
4348                 }
4349                 AddressSearchGridInit();
4350                         SE.addressBook.relatedBeanId = relatedBeanId;
4351             } 
4352             else
4353             {
4354                 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4355                 {
4356                         SE.addressBook.relatedBeanId = relatedBeanId;
4357                         document.getElementById('hasRelatedBean').checked = true;
4358                 }
4359                 if (document.getElementById('hasRelatedBean').checked == true)
4360                 {
4361                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4362                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4363                 } else {
4364                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4365                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4366                 }
4367                 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4368                         SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4369                 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params),  SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4370             }
4371             
4372             //Remove any lingering rows in the result set table if the module was closed.
4373             SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4374             //Repopulate
4375             SE.addressBook.populateResulstTableEmailAddresses();
4376             
4377         this.contactsDialogue.show();
4378     },
4379     /**
4380     *  Clear all email addresses from result table.
4381     *
4382     */
4383     clearAllEmailAddressFieldsFromResultTable: function () {
4384         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4385         //Unhighlight any rows currently selected if the emails were cleared.
4386         SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4387         SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4388     },
4389     /**
4390     *  Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the 
4391     *  results table.  This function is called when the address book is displayed.
4392     */
4393     populateResulstTableEmailAddresses: function () {
4394       
4395         var idx = SE.addressBook.idx;
4396         var emailFields = ['to','cc','bcc'];
4397         
4398         for(var k=0;k<emailFields.length;k++)
4399         {
4400             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4401             var allEmails = document.getElementById(elKey).value;
4402             if(allEmails == '')
4403                 continue;
4404             
4405             var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4406             
4407                 for (var i=0; i<formatedEmails.length; i++)
4408                 {
4409                     var t_name = formatedEmails[i].name;
4410                     var t_emailAddr = formatedEmails[i].email_address;
4411                     var displayEmail = t_name + ' <' + t_emailAddr + '>';
4412                     if(t_name == '')
4413                         t_name = displayEmail = t_emailAddr;
4414                 
4415                     var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4416                 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4417                     'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4418                 }
4419         }  
4420     },
4421  
4422     /**
4423     * Checks all entries in the result table against a particular email address, returning true
4424     * if the email address is found, false otherwise.
4425     */
4426     doesEmailAdddressExistInResultTable: function(emailAddress)
4427     {
4428         if(trim(emailAddress) == '')
4429             return false;   
4430             
4431         var emailAddressFound = false;
4432         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4433         for (var i=0; i < contacts.length; i++) 
4434         {
4435             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4436             //If we are adding to cc or bcc fields, make them visible.
4437             if(data.email_address == emailAddress)    
4438             {
4439                 emailAddressFound = true;
4440                 break;
4441             }
4442         }
4443         
4444         return emailAddressFound;
4445     },
4446     /**
4447     *  Takes all email addresses that the users wishes to add from the address book and populates the To 
4448     *  fields on the compose tab. 
4449     */
4450     populateEmailAddressFieldsFromResultTable: function()
4451     {
4452         //Clear the fields first, all email addresses are stored in the address book
4453         var idx = SE.addressBook.idx;
4454         var emailFields = ['to','cc','bcc'];    
4455         for(var k=0;k<emailFields.length;k++)
4456         {
4457             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4458             document.getElementById(elKey).value = "";
4459         }
4460         
4461         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4462         for (var i=0; i < contacts.length; i++) 
4463         {
4464             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4465             
4466             var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4467             //If we are adding to cc or bcc fields, make them visible.
4468             if(addressTypeKey =='cc' || addressTypeKey =='bcc')    
4469                 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4470             //Construct the target id
4471             var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4472            
4473             var target = document.getElementById(target_id);
4474             target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4475         }
4476         
4477         //Delete all rows from the result set table
4478         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4479         
4480         //Hide the dialogue
4481         SE.addressBook.contactsDialogue.hide()
4482     },
4483     /**
4484     *  Insert contacts into the result table.
4485     */
4486     insertContactToResultTable : function(event,address_type) {
4487     
4488         var contactsDialogue = SE.addressBook.contactsDialogue;
4489         var contacts = SE.addressBook.grid.getSelectedRows();
4490         
4491         var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4492         for (var i = 0; i < rows.length; i++) 
4493         {
4494                         if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4495                         {
4496                             var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4497                 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4498                 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4499                 rows[i].setData("selected",true);
4500                         }
4501         }
4502         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4503         for (var i = 0; i < checkBoxes.length; i++) {
4504             checkBoxes[i].checked = false;
4505         }
4506     },
4507     /**
4508     *
4509     */
4510     insertContactRowToResultTable : function(rowId, addressType) {
4511         var data = SE.addressBook.grid.getRecord(rowId).getData();
4512         if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4513                 return;
4514         var name = data.name.replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
4515         var ea = name + ' <' + data.email.replace(/&#039;/gi,'\'') + '>';
4516         if(addressType == null)
4517             addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4518         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});
4519     },
4520     /**
4521     * Remove a row from the gridsResult table.
4522     */
4523     removeRowFromGridResults : function(rowId,emailAddress)
4524     {
4525         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4526         for (var i=0; i < contacts.length; i++) 
4527         {
4528             var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4529             var data = rec.getData();
4530             if(data.email_address == emailAddress)
4531             {
4532                 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4533                 break;
4534             }
4535         }
4536         
4537        SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4538     },
4539     /**
4540     * Translates between the addressType To|Cc|Bcc labels/keys.  
4541     */
4542     translateAddresType: function(addressType,fromKey)
4543     {
4544         var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4545         var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4546         var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,''); 
4547         var mappingObject = {};
4548         
4549         if(fromKey)
4550             mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4551         else
4552         {
4553             mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4554             mappingObject[displayCc] = 'cc';
4555             mappingObject[displayBcc] = 'bcc';
4556         }
4557             
4558         return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4559           
4560     },
4561     /**
4562     *
4563     */
4564     toggleSearchRowIcon : function(rowId,show) 
4565     {
4566         if(show)
4567         {
4568             var idToShow = rowId + '_add_img';
4569             var idToHide = rowId + '_rm_img';
4570         }
4571         else
4572         {
4573             var idToShow = rowId + '_rm_img';
4574             var idToHide = rowId + '_add_img';
4575         }
4576
4577
4578         Dom.addClass(idToHide, "yui-hidden");
4579         Dom.removeClass(idToShow, "yui-hidden");
4580     },
4581     /**
4582     * Determine if an entry has already been added to the grid results table to prevent duplicates.
4583     */
4584     doesGridResultsEntryExist: function(emailAddrs)
4585     {
4586         
4587         var contactExists = false;
4588         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4589         for (var i=0; i < contacts.length; i++) 
4590         {
4591             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4592             if(data.email_address == emailAddrs)
4593             {
4594                 contactExists = true;
4595                 break;
4596             }
4597         }
4598         return contactExists;
4599     },
4600     
4601     /**
4602      * adds an email address to a string, but first checks if it exists
4603      * @param string concat The string we are appending email addresses to
4604      * @param string addr Email address to add
4605      * @return string
4606      */
4607     smartAddEmailAddressToComposeField : function(concat, addr) {
4608         var re = new RegExp(addr);
4609
4610         if(!concat.match(re)) {
4611             if(concat != "") {
4612                 concat += "; " + addr;
4613             } else {
4614                 concat = addr;
4615             }
4616         }
4617
4618         return concat;
4619     }
4620 };
4621 ////    END ADDRESS BOOK
4622 ///////////////////////////////////////////////////////////////////////////////
4623
4624
4625
4626 ///////////////////////////////////////////////////////////////////////////////
4627 ////    AUTOCOMPLETE
4628 /**
4629  * Auto-complete object
4630  */
4631 SE.autoComplete = {
4632     config : {
4633         delimChar : [";", ","],
4634         useShadow :    false,
4635         useIFrame : false,
4636         typeAhead : true,
4637         prehighlightClassName : "yui-ac-prehighlight",
4638         queryDelay : 0
4639     },
4640     instances : new Array(),
4641
4642     /**
4643      * Parses an addressBook entry looking for primary address.  If not found, it will return the last found address.
4644      * @param object Contact from AddressBook
4645      * @return string
4646      */
4647     getPrimaryAddress : function(contact) {
4648         var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4649
4650         for(var eIndex in contact.email) {
4651             address = contact.email[eIndex].email_address;
4652             if(contact.email[eIndex].primary_address == 1) {
4653                 return contact.email[eIndex].email_address;
4654             }
4655         }
4656         return address;
4657     },
4658     
4659
4660     /**
4661      * initializes autocomplete widgets for a given compose view
4662      * @param int idx
4663      */
4664     init : function(idx) {
4665         var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4666             "queryMatchContains" : false,
4667             "queryMatchSubset" : true
4668         });
4669
4670         this.instances[idx] = {
4671             to : null,
4672             cc : null,
4673             bcc : null
4674         };
4675
4676    
4677         // instantiate the autoComplete widgets
4678         this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4679         this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4680         this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4681
4682         // enable hiding of interfering textareas
4683         this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4684         this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4685         this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4686
4687         // enable reshowing of hidden textareas
4688         this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4689         this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4690         this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4691
4692         // enable refreshes of contact lists
4693         this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4694         this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4695         this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4696     },
4697
4698     refreshDataSource : function(sType, aArgs) {
4699         var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4700         var idx;
4701         var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4702
4703         if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4704             idx = textBoxId.substr(9);
4705         } else {
4706             idx = textBoxId.substr(10);
4707         }
4708
4709         SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4710         SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4711         SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4712     },
4713
4714     /**
4715      * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4716      */
4717     returnDataSource : function(contacts) {
4718         var ret = new Array();
4719         for(var id in contacts) {
4720             if (contacts[id].name) {
4721                     var primary = this.getPrimaryAddress(contacts[id]);
4722         
4723                     ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4724                     //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4725         
4726                     for(var emailIndex in contacts[id].email) {
4727                         ret[ret.length] = contacts[id].email[emailIndex].email_address;
4728                     }
4729             }
4730         }
4731
4732         return ret;
4733     },
4734
4735     /**
4736      * Hides address textareas to prevent autocomplete dropdown from being obscured
4737      */
4738     toggleTextareaHide : function(sType, aArgs) {
4739         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4740         var type = "";
4741         var idx = -1;
4742
4743         if(textBoxId.indexOf("addressTO") > -1) {
4744             type = "to";
4745         } else if(textBoxId.indexOf("addressCC") > -1) {
4746             type = "cc";
4747         }
4748         idx = textBoxId.substr(9);
4749
4750         // follow through if not BCC
4751         if(type != "") {
4752             var cc = document.getElementById("addressCC" + idx);
4753             var bcc = document.getElementById("addressBCC" + idx);
4754
4755             switch(type) {
4756                 case "to":
4757                     cc.style.visibility = 'hidden';
4758                 case "cc":
4759                     bcc.style.visibility = 'hidden';
4760                 break;
4761             }
4762         }
4763     },
4764
4765     /**
4766      * Redisplays the textareas after an address is commited
4767      */
4768     toggleTextareaShow : function(sType, aArgs) {
4769         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4770         var type = "";
4771         var idx = -1;
4772
4773         if(textBoxId.indexOf("addressTO") > -1) {
4774             type = "to";
4775         } else if(textBoxId.indexOf("addressCC") > -1) {
4776             type = "cc";
4777         }
4778         idx = textBoxId.substr(9);
4779
4780         // follow through if not BCC
4781         if(type != "") {
4782             document.getElementById("addressCC" + idx).style.visibility = 'visible';
4783             document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4784         }
4785     }
4786 };
4787
4788 ////    END AUTOCOMPLETE
4789 ///////////////////////////////////////////////////////////////////////////////
4790
4791 ///////////////////////////////////////////////////////////////////////////////
4792 ////    COMPOSE & SEND
4793 /**
4794  * expands the options sidebar
4795  */
4796 SE.composeLayout = {
4797     currentInstanceId : 0,
4798     ccHidden : true,
4799     bccHidden : true,
4800     outboundAccountErrors : null,
4801     loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4802
4803     showAddressDetails : function(e) {
4804         var linkElement = document.getElementById("More"+e.id);
4805         var spanElement = document.getElementById("Detail"+e.id);
4806         var emailAddressList = e.value;
4807         if(e.value.length > 96) 
4808         {
4809                 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4810             var displayArray = [];
4811                 for (var i=0; i<resultArray.length; i++)
4812                 {
4813                     var t_name = resultArray[i].name;
4814                     var t_emailAddr = resultArray[i].email_address;
4815                     if(t_name == '')
4816                        displayArray.push('<br/>&lt;' + t_emailAddr + '&gt;');
4817                     else
4818                        displayArray.push(t_name + '<br/>&lt;' + t_emailAddr + '&gt;');     
4819                 }
4820                         
4821             var result = displayArray.join('<br/>');
4822                 // Display
4823             linkElement.style.display = "inline";
4824             linkElement.style.height="10px";
4825             linkElement.style.overflow="visible";
4826             spanElement.innerHTML = result;
4827         } 
4828         else 
4829                 linkElement.style.display = "none";
4830         
4831         },
4832
4833    /**
4834     *  Given a string of email address, return an array containing the name portion (if available)
4835     *  and email portion.
4836     */
4837     _getEmailArrayFromString : function (emailAddressList){
4838       
4839         var reg = /@.*?;/g;
4840         while ((results = reg.exec(emailAddressList)) != null) 
4841         {
4842             orignial = results[0];
4843             parsedResult = results[0].replace(';', ':::::');
4844             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4845         }
4846
4847         reg = /@.*?,/g;
4848         while ((results = reg.exec(emailAddressList)) != null) 
4849         {
4850             orignial = results[0];
4851             parsedResult = results[0].replace(',', ':::::');
4852             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4853         }
4854         //Administrator <johndoe@som.com>  ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4855         var emailArr = emailAddressList.split(":::::");
4856         var resultsArray = [];
4857         var newArr = [];
4858         for (var i=0; i<emailArr.length; i++) 
4859         {
4860             var rposition = emailArr[i].indexOf('<');
4861             var lposition = emailArr[i].indexOf('>');
4862
4863             if(trim(emailArr[i]) != '')
4864             {
4865                 if(rposition != -1 && lposition != -1)
4866                 {
4867                     var t_name = emailArr[i].substr(0, rposition-1);
4868                     var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4869                     resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4870                 }
4871                 else
4872                 {
4873                     resultsArray.push({'name':'', 'email_address': emailArr[i]});
4874                 }
4875             }
4876         }
4877         return resultsArray;  
4878     },
4879     ///////////////////////////////////////////////////////////////////////////
4880     ////    COMPOSE FLOW
4881     /**
4882      * Prepare bucket DIV and yui-ext tab panels
4883      */
4884     _0_yui : function() {
4885         var idx = this.currentInstanceId;
4886
4887         var composeTab = new YAHOO.SUGAR.ClosableTab({
4888                         label: mod_strings.LNK_NEW_SEND_EMAIL,
4889                                 scroll : true,
4890                                 content : "<div id='htmleditordiv" + idx + "'/>",
4891                                 id : "composeTab" + idx,
4892                                 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4893                                 active : true
4894         }, SE.innerLayout);
4895         SE.innerLayout.addTab(composeTab);
4896         
4897         // get template engine with template
4898         if (!SE.composeLayout.composeTemplate) {
4899                 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4900         }
4901         
4902         // create Tab inner layout
4903         var composePanel =  this.getComposeLayout();
4904         composePanel.getUnitByPosition("right").collapse();
4905         composePanel.autoSize();
4906        
4907     },
4908         /**
4909      * Generate the quick compose layout
4910          * @method getQuickComposeLayout
4911          * @param {Pannel} parentPanel Parent pannel
4912          * @param {Object} o Options
4913          * @return {} none
4914          **/
4915     getQuickComposeLayout : function (parentPanel,o) {
4916          var idx = SE.composeLayout.currentInstanceId;
4917
4918          //Before rendering the parent pannel we need to initalize the grid layout
4919          parentPanel.beforeRenderEvent.subscribe(function() {
4920                 
4921                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4922                         SE.composeLayout._createComposeLayout(idx);
4923                         SE.composeLayout[idx].set('height', 350);
4924                         SE.composeLayout[idx].render();
4925            });
4926         });
4927
4928          //Wait until the Compose Layout has rendered, then add the 
4929          //options tab and perform the tiny initialization.
4930          parentPanel.renderEvent.subscribe(function() {
4931                 
4932                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4933                 SE.composeLayout._initComposeOptionTabs(idx);
4934                 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4935                 //Initialize tinyMCE
4936                 if (!SUGAR.util.isTouchScreen())
4937                     SE.composeLayout._1_tiny();
4938                 //Init templates and address book
4939                 SE.composeLayout._2_final();
4940
4941             SE.composeLayout.quickCreateComposePackage(o);      
4942
4943                 });
4944          });
4945                 
4946             //Check if we have the div override for the shortcut bar
4947         if(typeof o.menu_id != 'undefined') {
4948                    parentPanel.render(o.menu_id);    
4949             } else {
4950                    parentPanel.render(document.body); 
4951             }
4952         
4953         return SE.composeLayout[idx];
4954     },
4955     /**
4956      * Fill in all fields into the quick compose layout.
4957          * @method quickCreateComposePackage
4958          * @param {Object} o Options
4959          * @return {} none
4960          **/
4961     quickCreateComposePackage: function(o)
4962     {
4963         //If we have a compose package fill in defaults.
4964         if (typeof(o.composePackage) != 'undefined')
4965         {
4966             composePackage = o.composePackage; //Set the compose data object
4967             //Hijack this method called by composePackage as it's not need for quick creates.
4968             SE.composeLayout.c0_composeNewEmail = function(){};
4969             SE.composeLayout.composePackage(); //Fill in defaults.
4970         }
4971     },
4972     getComposeLayout : function() {
4973         var idx = SE.composeLayout.currentInstanceId;
4974       
4975         this._createComposeLayout(idx); 
4976         SE.composeLayout[idx].render();
4977         this._initComposeOptionTabs(idx);
4978         
4979         return SE.composeLayout[idx];
4980         },
4981         
4982         /**
4983         *       Create the layout manager for the compose window.
4984         */
4985         _createComposeLayout : function(idx)
4986         {
4987                 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
4988                 parent: SE.complexLayout,
4989                 border:true,
4990             hideOnLayout: true,
4991             height: 400,
4992                         units: [{
4993                                         position: "center",
4994                         animate: false,
4995                         scroll: false,
4996                         split:true,
4997                         body:   
4998                                 SE.composeLayout.composeTemplate.exec({
4999                                 'app_strings':app_strings,
5000                                 'mod_strings':mod_strings,
5001                                 'theme': theme,
5002                                 'linkbeans_options' : linkBeans,
5003                                 'idx' : SE.composeLayout.currentInstanceId
5004                                 })
5005                     },{
5006                         position: "right",
5007                                     scroll:true,
5008                                     collapse: true,
5009                                     collapsed: true,
5010                                     resize: true,
5011                                     border:true,
5012                                     animate: false,
5013                                     width:'230',
5014                                     body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5015                                     titlebar: true,
5016                                     split: true,
5017                                     header: app_strings.LBL_EMAIL_OPTIONS
5018                     }]
5019                 });
5020         },
5021         
5022         /**
5023         *  Create compose tab which will populate the 'right' container in the compose window.
5024         */
5025         _initComposeOptionTabs : function(idx) 
5026         {
5027                 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5028                 var tab = new YAHOO.widget.Tab({ 
5029                                 label: app_strings.LBL_EMAIL_ATTACHMENT,
5030                                 scroll : true,
5031                                 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5032                                 id : "divAttachments" + idx,
5033                                 active : true
5034                         });
5035         
5036                 tab.layout = SE.composeLayout[idx];
5037
5038            tab.on("activeChange", function(o){ 
5039                         if (o.newValue) {
5040                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5041                         }
5042                 });
5043
5044                 cTabs.addTab(tab);
5045
5046                 tab = new YAHOO.widget.Tab({ 
5047                                 label: app_strings.LBL_EMAIL_OPTIONS,
5048                                 scroll : true,
5049                                 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5050                                 id : "divOptions" + idx,
5051                                 active : false
5052                         });
5053                 
5054                 tab.layout = SE.composeLayout[idx];
5055                 tab.on("activeChange", function(o){ 
5056                         if (o.newValue) {
5057                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5058                         }
5059                 });
5060                 cTabs.addTab(tab);
5061         
5062                 SE.composeLayout[idx].autoSize = function() {
5063                         var pEl = this.get("element").parentNode.parentNode.parentNode;
5064                         this.set("height", pEl.clientHeight-30);
5065                         this.render();
5066                 }
5067         
5068                 SE.composeLayout[idx].rightTabs = cTabs;
5069     },
5070     isParentTypeValid : function(idx) {
5071                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5072                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5073                 if (trim(parentTypeValue) == ""){
5074                         alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5075                         return false;
5076                 } // if
5077                 return true;
5078     },
5079     
5080     isParentTypeAndNameValid : function(idx) {
5081                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5082                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5083                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5084                 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") || 
5085                         (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5086                                 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5087                         return false;
5088                 } // if
5089                 return true;
5090     },
5091
5092     callopenpopupForEmail2 : function(idx,options) {
5093         
5094         var formName = 'emailCompose' + idx;
5095         
5096         if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5097             formName = options.form_name;   
5098             
5099                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5100                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5101                 if (!SE.composeLayout.isParentTypeValid(idx)) {
5102                         return;
5103                 } // if
5104                 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5105                 {
5106                         call_back_function:"SE.composeLayout.popupAddEmail",
5107                         form_name:formName,
5108                         field_to_name_array:{
5109                                 id:'data_parent_id' + idx,
5110                                 name:'data_parent_name' + idx,
5111                                 email1:'email1'}
5112                 });     
5113         },    
5114         
5115         popupAddEmail : function(o)
5116         {
5117                 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5118                 var data = o.name_to_value_array;
5119                 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != "" 
5120                         && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5121         {
5122                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5123                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5124         }
5125                 set_return(o);
5126         },
5127     /**
5128      * Prepare TinyMCE
5129      */
5130     _1_tiny : function() {
5131         var idx = SE.composeLayout.currentInstanceId;
5132         var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5133         SE.tinyInstances[elId] = { };
5134         SE.tinyInstances[elId].ready = false;
5135         var t = tinyMCE.getInstanceById(elId);
5136
5137         if(typeof(t) == 'undefined')  {
5138             tinyMCE.execCommand('mceAddControl', false, elId);
5139             YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5140                 SE.composeLayout.resizeEditor(idx);
5141                 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
5142             }, this);
5143         }
5144     },
5145     
5146     resizeEditor : function(idx)
5147     {
5148         var cof = Dom.get('composeOverFrame' + idx);
5149         var head = Dom.get('composeHeaderTable' + idx);
5150         var targetHeight = cof.clientHeight - head.clientHeight;
5151         var instance =  tinyMCE.get(SE.tinyInstances.currentHtmleditor);                
5152         
5153         var parentEl = Dom.get(instance.editorId + '_parent');
5154         var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5155         var contentEl  = instance.contentAreaContainer;
5156         var iFrame = contentEl.firstChild;
5157         var tinMceToolbarOffset = 18;
5158         iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset)  + "px";
5159     },
5160
5161     /**
5162      * Initializes d&d, auto-complete, email templates
5163      */
5164     _2_final : function() {
5165         var idx = SE.composeLayout.currentInstanceId;
5166
5167         if(this.emailTemplates) {
5168             this.setComposeOptions(idx);
5169         } else {
5170             //populate email template cache
5171             AjaxObject.target = '';
5172             AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5173         }
5174
5175         // handle drop targets for addressBook
5176        var to =  new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5177        var cc =  new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5178        var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5179        to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5180
5181         // auto-complete setup
5182         SE.autoComplete.init(idx);
5183
5184         // set focus on to:
5185         document.getElementById("addressTO" + idx).focus();
5186     },
5187
5188         /**
5189      * hide tinyMCE tool bar if send email as plaintext is checked
5190      */
5191     renderTinyMCEToolBar : function (idx, hide) {
5192         if (hide) {
5193                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5194         } else {
5195                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5196         }
5197     },
5198
5199     c1_composeEmail : function(isReplyForward, retry) {
5200         if (!retry) {
5201             this._0_yui();
5202         }
5203         if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5204             setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5205         } else {
5206                 this._1_tiny();
5207                 this._2_final();
5208         
5209                 if(isReplyForward) {
5210                     this.replyForwardEmailStage2();
5211                 }
5212         }
5213     },
5214
5215     /**
5216      * takes draft info and prepopulates
5217      */
5218     c0_composeDraft : function() {
5219         this.getNewInstanceId();
5220         inCompose = true;
5221         document.getElementById('_blank').innerHTML = '';
5222         var idx = SE.composeLayout.currentInstanceId;
5223                 SE.composeLayout.draftObject = new Object();
5224                 SE.composeLayout.draftObject.id = idx;
5225                 SE.composeLayout.draftObject.isDraft = true;
5226         SE.composeLayout.currentInstanceId = idx;
5227         SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5228         SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5229         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5230
5231         SE.composeLayout._0_yui();
5232         SE.composeLayout._1_tiny();
5233
5234         // final touches
5235         SE.composeLayout._2_final();
5236
5237         /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5238         setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5239     },
5240
5241     /**
5242      * Strip & Prep editor hidden fields
5243      */
5244     c0_composeNewEmail : function() {
5245         this.getNewInstanceId();
5246         this.c1_composeEmail(false);
5247     },
5248
5249     /**
5250      * Sends async request to get the compose view.
5251      * Requests come from "reply" or "forwards"
5252      */
5253     c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5254         SE.composeLayout.replyForwardObj = new Object();
5255         SE.composeLayout.replyForwardObj.ieId = ieId;
5256         SE.composeLayout.replyForwardObj.uid = uid;
5257         SE.composeLayout.replyForwardObj.mbox = mbox;
5258         SE.composeLayout.replyForwardObj.type = type;
5259
5260         if(mbox == 'sugar::Emails') {
5261             SE.composeLayout.replyForwardObj.sugarEmail = true;
5262         }
5263
5264         SE.composeLayout.getNewInstanceId();
5265         SE.composeLayout.c1_composeEmail(true);
5266     },
5267     ////    END COMPOSE FLOW
5268     ///////////////////////////////////////////////////////////////////////////
5269
5270     /**
5271      * Called when a contact, email, or mailinglist is dropped
5272      * into one of the compose fields.
5273      */
5274     handleDrop : function (source, event, data, target) {
5275         var nodes;
5276         if (!target) {
5277             target = event.getTarget();
5278             if (data.single) {
5279                 data.nodes = [data.nodes];
5280             }
5281             nodes = data.nodes;
5282         } else {
5283             target = document.getElementById(target);
5284             nodes = data;
5285         }
5286         
5287         if (target.id.indexOf('address') > -1) {
5288             // dropped onto email to/cc/bcc field
5289             for(var i in nodes) {
5290                 var node = nodes[i].getData();
5291                 var email = "";
5292                 if (node[1].indexOf('contact') > -1) {
5293                     email = SE.addressBook.getFormattedAddress(node[0]);
5294                 } else if (node[1].indexOf('address-email') > -1){
5295                     email = node[3].replace(/&nbsp;/gi, '');
5296                     email = email.replace('&lt;', '<').replace('&gt;', '>');
5297                     var tr = source.getTrEl(nodes[i]);
5298                     while (tr && !Dom.hasClass(tr, "address-contact")) {
5299                         tr = source.getPreviousTrEl(tr);
5300                     }
5301                     var CID = source.getRecord(tr).getData()[0];
5302                     var o = SE.addressBook._contactCache[CID];
5303                     var name = new String(o.name);
5304                     var finalName = name.replace(/(<([^>]+)>)/ig, "");
5305                     email = finalName + email;
5306                 }
5307                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);              
5308             }
5309         }
5310     },
5311
5312
5313     /*/////////////////////////////////////////////////////////////////////////////
5314     ///    EMAIL TEMPLATE CODE
5315      */
5316     applyEmailTemplate : function (idx, id) {
5317                 
5318         //bug #20680
5319         var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5320                 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5321                 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5322                 
5323                 // id is selected index of email template drop-down
5324                 if(id == '' || id == "0") {
5325                         YAHOO.SUGAR.MessageBox.show({
5326                    title:box_title,
5327                    msg: box_none_msg,
5328                    type: 'confirm',
5329                    fn: function(btn){
5330                                 if(btn=='no'){return;};                         
5331                                 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5332                    modal:true,
5333                    scope:this
5334                });
5335                return;
5336                 } 
5337         
5338                 YAHOO.SUGAR.MessageBox.show({
5339            title:box_title,
5340            msg: box_msg,
5341            type: 'confirm',
5342            fn: function(btn){
5343                         if(btn=='no'){return;};
5344                         SUGAR.email2.composeLayout.processResult(idx, id);},
5345            modal:true,
5346            scope:this
5347        });
5348     },
5349     
5350     processNoneResult : function(idx, id) {
5351         var tiny = SE.util.getTiny('htmleditor' + idx);
5352         var tinyHTML = tiny.getContent();
5353         var openTag = '<div><span><span>';
5354         var htmllow = tinyHTML.toLowerCase();
5355         var start = htmllow.indexOf(openTag);
5356                 if (start > -1) {
5357                 tinyHTML = tinyHTML.substr(start);
5358                 tiny.setContent(tinyHTML);
5359                 } else {
5360                 tiny.setContent('');
5361                 }       
5362     },
5363         
5364         processResult : function(idx , id){
5365         call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5366
5367         // get attachments if any
5368         AjaxObject.target = '';
5369         AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5370     },
5371
5372     appendEmailTemplateJSON : function() {
5373         var idx = SE.composeLayout.currentInstanceId; // post increment
5374
5375         // query based on template, contact_id0,related_to
5376         //jchi 09/10/2008 refix #7743
5377         if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5378             document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5379         }
5380
5381         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,'"');
5382
5383         // cn: bug 14361 - text-only templates don't fill compose screen
5384         if(text == '') {
5385             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/>");
5386         }
5387
5388         var tiny = SE.util.getTiny('htmleditor' + idx);
5389         var tinyHTML = tiny.getContent();
5390         var openTag = '<div><span><span>';
5391         var closeTag = '</span></span></div>';
5392         var htmllow = tinyHTML.toLowerCase();
5393         var start = htmllow.indexOf(openTag);
5394                 if (start > -1) {
5395                 var htmlPart2 = tinyHTML.substr(start);
5396                 tinyHTML = text + htmlPart2;
5397                 tiny.setContent(tinyHTML);
5398                 } else {
5399                 tiny.setContent(text);
5400                 }
5401     },
5402
5403     /**
5404      * Writes out the signature in the email editor
5405      */
5406     setSignature : function(idx) {
5407         if (!tinyMCE)
5408             return false;
5409         var hide = document.getElementById('setEditor' + idx).checked;
5410         SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5411         //wait for signatures to load before trying to set them
5412         if (!SE.composeLayout.signatures) {
5413             setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5414                         return;
5415         }
5416             
5417         if(idx) {
5418             var sel = document.getElementById('signatures' + idx);
5419         } else {
5420             var sel = document.getElementById('signature_id');
5421             idx = SE.tinyInstances.currentHtmleditor;
5422         }
5423         
5424         //Ensure that the tinyMCE html has been rendered.
5425         if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5426             setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5427                     return;
5428                 }
5429             
5430         var signature = '';
5431
5432         try {
5433             signature = sel.options[sel.selectedIndex].value;
5434         } catch(e) {
5435
5436         }
5437
5438         var openTag = '<div><span><span>';
5439         var closeTag = '</span></span></div>';
5440         var t = SE.util.getTiny('htmleditor' + idx);
5441         //IE 6 Hack
5442         if(typeof(t) != 'undefined')
5443         {
5444             t.contentDocument = t.contentWindow.document;
5445             var html = t.getContent();
5446         }
5447         else
5448             var html = '';
5449             
5450         var htmllow = html.toLowerCase();
5451         var start = htmllow.indexOf(openTag);
5452         var end = htmllow.indexOf(closeTag) + closeTag.length;
5453
5454         // selected "none" - remove signature from email
5455         if(signature == '') {
5456             if (start > -1) {
5457                 var htmlPart1 = html.substr(0, start);
5458                 var htmlPart2 = html.substr(end, html.length);
5459     
5460                 html = htmlPart1 + htmlPart2;
5461                 t.setContent(html);
5462             }
5463             SE.signatures.lastAttemptedLoad = '';
5464             return false;
5465         }
5466
5467         if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5468             SE.signatures.lastAttemptedLoad = '';
5469
5470         SE.signatures.lastAttemptedLoad = signature;
5471
5472         if(typeof(SE.signatures[signature]) == 'undefined') {
5473             //lazy load
5474             SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5475             SE.signatures.targetInstance = (idx) ? idx : "";
5476             AjaxObject.target = '';
5477             AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5478         } else {
5479             var newSignature = this.prepareSignature(SE.signatures[signature]);
5480
5481             // clear out old signature
5482             if(SE.signatures.lastAttemptedLoad && start > -1) {
5483                 var htmlPart1 = html.substr(0, start);
5484                 var htmlPart2 = html.substr(end, html.length);
5485
5486                 html = htmlPart1 + htmlPart2;
5487             }
5488             
5489             // [pre|ap]pend
5490                         start = html.indexOf('<div><hr></div>');
5491             if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5492                                 var htmlPart1 = html.substr(0, start);
5493                                 var htmlPart2 = html.substr(start, html.length);
5494                 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5495             } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5496                 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5497             } else {
5498                 var newHtml = html + openTag + newSignature + closeTag;
5499             }
5500             //tinyMCE.setContent(newHtml);
5501             t.setContent(newHtml);
5502         }
5503     },
5504
5505     prepareSignature : function(str) {
5506         var signature = new String(str);
5507
5508         signature = signature.replace(/&lt;/gi, '<');
5509         signature = signature.replace(/&gt;/gi, '>');
5510
5511         return signature;
5512     },
5513
5514
5515     showAttachmentPanel : function(idx) {
5516         var east = SE.composeLayout[idx].getUnitByPosition("right");
5517         var tabs = SE.composeLayout[idx].rightTabs;
5518         east.expand();
5519         tabs.set("activeTab", tabs.getTab(0));
5520     },
5521
5522     /**
5523      * expands sidebar and displays options panel
5524      */
5525     showOptionsPanel : function(idx) {
5526         var east = SE.composeLayout[idx].getUnitByPosition("right");
5527         var tabs = SE.composeLayout[idx].rightTabs;
5528         east.expand();
5529         tabs.set("activeTab", tabs.getTab(1));
5530     },
5531
5532     /**
5533      * Selects the Contacts tab
5534      */
5535     showContactsPanel : function() {
5536         SE.complexLayout.regions.west.showPanel("contactsTab");
5537     },
5538
5539     /**
5540      * Generates fields for Select Document
5541      */
5542     addDocumentField : function(idx) {
5543         var basket = document.getElementById('addedDocuments' + idx);
5544         if(basket) {
5545             var index = (basket.childNodes.length / 7) - 1;
5546             if(index < 0)
5547                 index = 0;
5548         } else {
5549             index = 0;
5550         }
5551
5552         var test = document.getElementById('documentId' + idx + index);
5553
5554         while(test != null) {
5555             index++;
5556             test = document.getElementById('documentId' + idx + index);
5557         }
5558         
5559         var documentCup = document.createElement("div");
5560         documentCup.id = 'documentCup' + idx + index;
5561         documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5562                 // document id field
5563                 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5564                 // document name field
5565                 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5566                 // select button
5567                 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" + 
5568                     "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5569                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5570                 // remove button
5571                 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" + 
5572                     "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" + 
5573                  "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +   
5574                 "<br/>";
5575         
5576         basket.appendChild(documentCup);
5577         //basket.innerHTML += out;
5578         return index;
5579     },
5580
5581     /**
5582      * Makes async call to save a draft of the email
5583      * @param int Instance index
5584      */
5585     saveDraft : function(tinyInstance) {
5586         this.sendEmail(tinyInstance, true);
5587     },
5588
5589     selectDocument : function(target) {
5590         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5591         windowName = 'selectDocument';
5592         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5593
5594         win = window.open(URL, windowName, windowFeatures);
5595         if(window.focus) {
5596             // put the focus on the popup if the browser supports the focus() method
5597             win.focus();
5598         }
5599     },
5600
5601     /**
5602      * Modal popup for file attachment dialogue
5603      */
5604     addFileField : function() {
5605         if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5606             SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5607                 modal:true,
5608                 visible:false,
5609                 fixedcenter:true,
5610                 constraintoviewport: true,
5611                 scroll: true,
5612                 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, { 
5613                         fn:function(){SE.addFileDialog.hide();}
5614                 })
5615             });
5616             SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5617             SE.addFileDialog.render();
5618            // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5619         }
5620         Dom.removeClass("addFileDialog", "yui-hidden");
5621         
5622         SE.addFileDialog.show();
5623     },
5624
5625     /**
5626      * Async upload of file to temp dir
5627      */
5628     uploadAttachment : function() {
5629         if(document.getElementById('email_attachment').value != "") {
5630             var formObject = document.getElementById('uploadAttachment');
5631             YAHOO.util.Connect.setForm(formObject, true, true);
5632             AjaxObject.target = '';
5633             AjaxObject.startRequest(callbackUploadAttachment, null);
5634         } else {
5635             alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5636         }
5637     },
5638
5639     /**
5640      * Adds a SugarDocument to an outbound email.  Action occurs in a popup window displaying a ListView from the Documents module
5641      * @param string target in focus compose layout
5642      */
5643     setDocument : function(idx, target, documentId, documentName, docRevId) {
5644         // fields are named/id'd [fieldName][instanceId][index]
5645         var addedDocs = document.getElementById("addedDocuments" + idx);
5646         var docId = document.getElementById('documentId' + idx + target);
5647         var docName = document.getElementById('documentName' + idx + target);
5648         var docRevisionId = document.getElementById('document' + idx + target);
5649         docId.value = documentId;
5650         docName.value = documentName;
5651         docRevisionId.value = docRevId;
5652     },
5653
5654     /**
5655      * Removes the bucket div containing the document input fields
5656      */
5657     deleteDocumentField : function(documentCup) {
5658         var f0 = document.getElementById(documentCup);
5659         f0.parentNode.removeChild(f0);
5660     },
5661
5662     /**
5663      * Removes a Template Attachment field
5664      * @param int
5665      * @param int
5666      */
5667     deleteTemplateAttachmentField : function(idx, index) {
5668         // create not-in-array values for removal filtering
5669         var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5670
5671         if(r != "") {
5672             r += "::";
5673         }
5674
5675         r += document.getElementById('templateAttachmentId' + idx + index).value;
5676         document.getElementById("templateAttachmentsRemove" + idx).value = r;
5677
5678         var target = 'templateAttachmentCup' + idx + index;
5679         d =  document.getElementById(target);
5680         d.parentNode.removeChild(d);
5681     },
5682
5683     /**
5684      * Async removal of uploaded temp file
5685      * @param string index Should be a concatenation of idx and index
5686      * @param string
5687      */
5688     deleteUploadAttachment : function(index, file) {
5689         var d = document.getElementById('email_attachment_bucket' + index);
5690         d.parentNode.removeChild(d);
5691
5692         // make async call to delete cached file
5693         AjaxObject.target = '';
5694         AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5695     },
5696
5697     /**
5698      * Attaches files coming from Email Templates
5699      */
5700     addTemplateAttachmentField : function(idx) {
5701         // expose title
5702         document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5703
5704         var basket = document.getElementById('addedTemplateAttachments' + idx);
5705
5706         if(basket) {
5707             var index = basket.childNodes.length;
5708             if(index < 0)
5709                 index = 0;
5710         } else {
5711             index = 0;
5712         }
5713
5714         var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5715                                 // remove button        
5716                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5717                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" + 
5718                                         idx + "\",\"" + index + "\");'/>" +
5719                                 // file icon
5720                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5721                                 // templateAttachment field
5722                                 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5723                                 // docId field
5724                                 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5725                                 // file name
5726                                 "<span id='templateAttachmentName"  + idx + index + "'" + ">&nbsp;</span>" + 
5727                                 "<br id='br" + index + "></br>" + 
5728                                 "<br id='brdoc" + index + "></br>" + 
5729                         "</div>";
5730                 basket.innerHTML = basket.innerHTML + out;
5731      
5732         return index;
5733     },
5734
5735     /**
5736      * Sends one email via async call
5737      * @param int idx Editor instance ID
5738      * @param bool isDraft
5739      */
5740     sendEmail : function(idx, isDraft) {
5741         
5742         //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5743         var obAccountID = document.getElementById('addressFrom' + idx).value;
5744         
5745         if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5746         {
5747             overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5748             return false;
5749         }
5750         
5751         
5752         var form = document.getElementById('emailCompose' + idx);
5753         var composeOptionsFormName = "composeOptionsForm" + idx;
5754         var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5755         var html = t.getContent();
5756         var subj = document.getElementById('emailSubject' + idx).value;
5757         var to = trim(document.getElementById('addressTO' + idx).value);
5758         var cc = trim(document.getElementById('addressCC' + idx).value);
5759         var bcc = trim(document.getElementById('addressBCC' + idx).value);
5760         var email_id = document.getElementById('email_id' + idx).value;
5761         var composeType = document.getElementById('composeType').value;
5762         var parent_type = document.getElementById("parent_type").value;
5763         var parent_id = document.getElementById("parent_id").value;
5764         
5765         var el_uid = document.getElementById("uid");
5766         var uid = (el_uid == null) ? '' : el_uid.value;
5767         
5768         var el_ieId = document.getElementById("ieId");
5769         var ieId = (el_ieId == null) ? '' : el_ieId.value;
5770         
5771         var el_mbox = document.getElementById("mbox");
5772         var mbox = (el_mbox == null) ? '' : el_mbox.value;
5773         
5774         if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5775                         alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5776                 return false;
5777         }
5778
5779         if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5780                 return;
5781         } // if
5782                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5783                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5784         parent_id = parentIdValue;
5785         parent_type = parentTypeValue;
5786
5787         var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5788         // baseline viability check
5789
5790         if(to == "" && cc == '' && bcc == '' && !isDraft) {
5791             alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5792             return false;
5793         } else if(subj == '' && !isDraft) {
5794             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5795                 return false;
5796             } else {
5797                 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5798             }
5799         } else if(html == '' && !isDraft) {
5800             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5801                 return false; 
5802             }
5803         }
5804
5805         SE.util.clearHiddenFieldValues('emailCompose' + idx);
5806                 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5807                 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5808         overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5809         html = html.replace(/&lt;/ig, "sugarLessThan");       
5810         html = html.replace(/&gt;/ig, "sugarGreaterThan");
5811         
5812         form.sendDescription.value = html;
5813         form.sendSubject.value = subj;
5814         form.sendTo.value = to;
5815         form.sendCc.value = cc;
5816         form.sendBcc.value = bcc;
5817         form.email_id.value = email_id;
5818         form.composeType.value = composeType;
5819         form.composeLayoutId.value = 'composeLayout' + idx;
5820         form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5821         form.saveToSugar.value = 1;
5822         form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5823         form.parent_type.value = parent_type;
5824         form.parent_id.value = parent_id;
5825         form.uid.value = uid;
5826         form.ieId.value = ieId;
5827         form.mbox.value = mbox;
5828
5829         // email attachments
5830         var addedFiles = document.getElementById('addedFiles' + idx);
5831         if(addedFiles) {
5832             for(i=0; i<addedFiles.childNodes.length; i++) {
5833                 var bucket = addedFiles.childNodes[i];
5834
5835                 for(j=0; j<bucket.childNodes.length; j++) {
5836                     var node = bucket.childNodes[j];
5837                     var nName = new String(node.name);
5838
5839                     if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5840                         if(form.attachments.value != '') {
5841                             form.attachments.value += "::";
5842                         }
5843                         form.attachments.value += node.value;
5844                     }
5845                 }
5846             }
5847         }
5848
5849         // sugar documents
5850         var addedDocs = document.getElementById('addedDocuments' + idx);
5851         if(addedDocs) {
5852             for(i=0; i<addedDocs.childNodes.length; i++) {
5853                 var cNode = addedDocs.childNodes[i];
5854                 for(j=0; j<cNode.childNodes.length; j++) {
5855                     var node = cNode.childNodes[j];
5856                     var nName = new String(node.name);
5857                     if(node.type == 'hidden' && nName.match(/documentId/)) {
5858                         if(form.documents.value != '') {
5859                             form.documents.value += "::";
5860                         }
5861                         form.documents.value += node.value;
5862                     }
5863                 }
5864             }
5865         }
5866
5867         // template attachments
5868         var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5869         if(addedTemplateAttachments) {
5870             for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5871                 var cNode = addedTemplateAttachments.childNodes[i];
5872                 for(j=0; j<cNode.childNodes.length; j++) {
5873                     var node = cNode.childNodes[j];
5874                     var nName = new String(node.name);
5875                     if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5876                         if(form.templateAttachments.value != "") {
5877                             form.templateAttachments.value += "::";
5878                         }
5879                         form.templateAttachments.value += node.value;
5880                     }
5881                 }
5882             }
5883         }
5884
5885         // remove attachments
5886         form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5887
5888         YAHOO.util.Connect.setForm(form);
5889
5890         AjaxObject.target = 'frameFlex';
5891
5892         // sending a draft email
5893         if(!isDraft && in_draft) {
5894             // remove row
5895             SE.listView.removeRowByUid(email_id);
5896         }
5897
5898         var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5899         var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5900
5901         AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5902     },
5903
5904     /**
5905      * Handles clicking the email address link from a given view
5906      */
5907     composePackage : function() {
5908         if(composePackage != null) {
5909             SE.composeLayout.c0_composeNewEmail();
5910             
5911             
5912             if(composePackage.to_email_addrs) {
5913                 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5914             } // if
5915             if (composePackage.subject != null && composePackage.subject.length > 0) {
5916                 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5917             }
5918             
5919             //If no parent fields are set in the composePackage, ensure they are cleared.
5920             var parentFields = ['parent_type','parent_name','parent_id'];
5921             for(var i=0;i<parentFields.length;i++)
5922             {
5923                 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5924                     composePackage[parentFields[i]] = "";
5925             }
5926                  
5927             document.getElementById("parent_type").value = composePackage.parent_type;
5928             document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5929             document.getElementById("parent_id").value = composePackage.parent_id;
5930             document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5931             document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;  
5932                 
5933             if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5934                 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5935             } // if
5936             if (composePackage.body != null && composePackage.body.length > 0) {
5937                         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5938                         SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5939                         setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5940             } // if
5941             if (composePackage.attachments != null) {
5942                                 SE.composeLayout.loadAttachments(composePackage.attachments);                   
5943             } // if
5944             
5945             if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5946                                 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5947                         SE.util.emptySelectOptions(addressFrom);
5948                         var fromAccountOpts = composePackage.fromAccounts.data;
5949                         for(i=0; i<fromAccountOpts.length; i++) {
5950                               var key = fromAccountOpts[i].value;
5951                               var display = fromAccountOpts[i].text;
5952                               var opt = new Option(display, key);
5953                               if (fromAccountOpts[i].selected) {
5954                                 opt.selected = true;
5955                               }
5956                               addressFrom.options.add(opt);
5957                         }                       
5958                 
5959             } // if
5960         } // if
5961     },
5962
5963     setContentOnThisTiny : function() {
5964         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5965         var tinyHTML = tiny.getContent();
5966         composePackage.body = decodeURI(encodeURI(composePackage.body));
5967         // cn: bug 14361 - text-only templates don't fill compose screen
5968         if(composePackage.body == '') {
5969             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,'"');
5970         } // if
5971         //Flag determines if we should clear the tiny contents or just append
5972         if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5973             SE.composeLayout.tinyHTML = '';
5974         else
5975             SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;                 
5976         
5977          tiny.setContent(SE.composeLayout.tinyHTML);
5978          //Indicate that the contents has been loaded successfully.
5979          SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5980     },
5981     /**
5982      * Confirms closure of a compose screen if "x" is clicked
5983      */
5984     confirmClose : function(panel) {
5985         if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
5986             SE.composeLayout.closeCompose(panel.id);
5987             return true;
5988         } else {
5989             return false;
5990         }
5991     },
5992
5993     /**
5994      * forces close of a compose screen
5995      */
5996     forceCloseCompose : function(id) {
5997         SE.composeLayout.closeCompose(id);
5998         
5999         // handle flow back to originating view
6000         if(composePackage) {
6001             // check if it's a module we need to return to
6002             if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6003                 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6004                     var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6005                     window.location = url;
6006                 }
6007             }
6008         }
6009     },
6010
6011     /**
6012      * closes the editor that just sent email
6013      * @param string id ID of composeLayout tab
6014      */
6015     closeCompose : function(id) {
6016         // destroy tinyMCE instance
6017         var idx = id.substr(13, id.length);
6018         var instanceId = "htmleditor" + idx;
6019         tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6020
6021         // nullify DOM and namespace values.
6022         inCompose = false;
6023         SE.composeLayout[idx] = null;
6024         SE.tinyInstances[instanceId] = null;
6025         var tabsArray = SE.innerLayout.get("tabs");
6026         for (i = 0 ; i < tabsArray.length ; i++) {
6027                 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6028                         tabsArray[i].close();
6029                         break;
6030                 }
6031         }
6032         //SE.innerLayout.getTab(idx).close();
6033     },
6034
6035     /**
6036     *  Enable the quick search for the compose relate field or search tab
6037     */
6038     enableQuickSearchRelate: function(idx,overides){
6039         
6040         if(typeof overides != 'undefined')
6041         {
6042             var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6043             var newModule = document.getElementById(newModuleID).value; 
6044             var formName = overides['formName'];
6045             var fieldName = overides['fieldName'];
6046             var fieldId = overides['fieldId'];
6047             var fullName = formName + "_" + fieldName;
6048             var postBlurFunction = null;
6049         }
6050         else
6051         {
6052             var newModule = document.getElementById('data_parent_type'+idx).value;
6053             var formName = 'emailCompose'+idx;
6054             var fieldName = 'data_parent_name'+idx;
6055             var fieldId = 'data_parent_id'+idx;
6056             var fullName = formName + "_" + fieldName;
6057             var postBlurFunction = "SE.composeLayout.qsAddAddress";
6058         }
6059         
6060         if(typeof sqs_objects == 'undefined')
6061             window['sqs_objects'] = new Array;
6062             
6063         window['sqs_objects'][fullName] = {
6064             form:formName,
6065                         method:"query",
6066                         modules:[newModule],
6067                         group:"or",
6068             field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6069             conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6070                         post_onblur_function: postBlurFunction,
6071             order:"name","limit":"30","no_match_text":"No Match"};
6072                                 
6073         
6074         if(typeof QSProcessedFieldsArray != 'undefined')
6075                 QSProcessedFieldsArray[fullName] = false;
6076         if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6077                 QSFieldsArray[fullName].destroy();
6078                 delete QSFieldsArray[fullName];
6079         }
6080         if (Dom.get(fullName + "_results")) {
6081                 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6082         }
6083             
6084         enableQS(false);
6085     },
6086     
6087         qsAddAddress : function(o) {
6088         if (o.name != "" && o.email1 != "")
6089         {
6090                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6091                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6092         }
6093     },
6094     /**
6095      * Returns a new instance ID, 0-index
6096      */
6097     getNewInstanceId : function() {
6098         this.currentInstanceId = this.currentInstanceId + 1;
6099         return this.currentInstanceId;
6100     },
6101
6102     /**
6103      * 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.
6104      */
6105     loadAttachments : function(result) {
6106         var idx = SE.composeLayout.currentInstanceId;
6107
6108         if(typeof(result) == 'object') {
6109                 //jchi #20680. Clean the former template attachments;
6110                 var basket = document.getElementById('addedTemplateAttachments' + idx);
6111                         if(basket.innerHTML != ''){
6112                                 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6113                                         if (btn != 'yes'){
6114                                                 basket.innerHTML = '';
6115                                         }
6116                                 });
6117                         }
6118             for(i in result) {
6119                 if(typeof result[i] == 'object') {
6120                     var index = SE.composeLayout.addTemplateAttachmentField(idx);
6121                     var bean = result[i];
6122                     document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6123                     document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6124                 }
6125             }
6126         }
6127     },
6128
6129     /**
6130      * fills drop-down values for email templates and signatures
6131      */
6132     setComposeOptions : function(idx) {
6133         // send from accounts
6134         var addressFrom = document.getElementById('addressFrom' + idx);
6135         
6136         if (addressFrom.options.length <= 0) {
6137                 SE.util.emptySelectOptions(addressFrom);
6138                 var fromAccountOpts = SE.composeLayout.fromAccounts;
6139                 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6140                       var key = fromAccountOpts[id].value;
6141                       var display = fromAccountOpts[id].text;
6142                       var is_default = false;
6143                       if(key == SUGAR.default_inbound_accnt_id)
6144                         is_default = true;
6145                       var opt = new Option(display, key);
6146                       addressFrom.options.add(opt);
6147                       addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6148                 }
6149         }
6150
6151         // email templates
6152         var et = document.getElementById('email_template' + idx);
6153         SE.util.emptySelectOptions(et);
6154
6155         for(var key in this.emailTemplates) { // iterate through assoc array
6156             var display = this.emailTemplates[key];
6157             var opt = new Option(display, key);
6158             et.options.add(opt);
6159         }
6160
6161         // signatures
6162         var sigs = document.getElementById('signatures' + idx);
6163         SE.util.emptySelectOptions(sigs);
6164
6165         for(var key in this.signatures) { // iterate through assoc array
6166             var display = this.signatures[key];
6167             var opt = new Option(display, key);
6168
6169             if(key == SE.userPrefs.signatures.signature_default) {
6170                 opt.selected = true;
6171             }
6172
6173             sigs.options.add(opt);
6174         }
6175
6176         // html/plain email?
6177         var htmlEmail = document.getElementById('setEditor' + idx);
6178         if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6179             htmlEmail.checked = true;
6180         } else {
6181                 htmlEmail.checked = false;
6182         }
6183
6184         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6185     },
6186
6187     /**
6188      * After compose screen is rendered, async call to get email body from Sugar
6189      */
6190     replyForwardEmailStage2 : function() {
6191         SE.util.clearHiddenFieldValues('emailUIForm');
6192         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6193
6194         var ieId = SE.composeLayout.replyForwardObj.ieId;
6195         var uid = SE.composeLayout.replyForwardObj.uid;
6196         var mbox = SE.composeLayout.replyForwardObj.mbox;
6197         var type = SE.composeLayout.replyForwardObj.type;
6198         var idx = SE.composeLayout.currentInstanceId;
6199
6200         var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6201
6202         document.getElementById('emailSubject' + idx).value = type;
6203         document.getElementById('emailUIAction').value = 'composeEmail';
6204         document.getElementById('composeType').value = type;
6205         document.getElementById('ieId').value = ieId;
6206         document.getElementById('uid').value = uid;
6207         document.getElementById('mbox').value = mbox;
6208                 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6209         var formObject = document.getElementById('emailUIForm');
6210         YAHOO.util.Connect.setForm(formObject);
6211
6212         var sendType = type;
6213         AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6214     },
6215     
6216     /**
6217     *  Show the hidden cc or bcc fields
6218     */
6219     showHiddenAddress: function(addrType,idx){
6220
6221         Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6222         Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6223                 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6224                 this[addrType+'Hidden'+idx] = false;
6225                 
6226                 //After bcc or cc is added, move options below last addr field
6227                 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6228                 
6229                 //If both cc and bcc hidden, remove the empty row containing text.
6230                 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6231                            && ( this['ccHidden'+idx]  == false && this['bccHidden'+idx] == false) )
6232                         Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");  
6233                 
6234                 SE.composeLayout.resizeEditor(idx);
6235     },
6236     /**
6237     *  Hide the cc and bcc fields if they were shown.
6238     */
6239     hideHiddenAddresses: function(idx){
6240         
6241         var addrTypes = ['cc','bcc'];
6242         for(var i = 0;i<addrTypes.length;i++)
6243         {
6244             Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6245             Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6246             this[addrTypes[i] + 'Hidden'+idx] = true
6247         }
6248         
6249         Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6250         Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6251         Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6252     }
6253 };
6254
6255 ////    END SE.composeLayout
6256 ///////////////////////////////////////////////////////////////////////////////
6257 ///////////////////////////////////////////////////////////////////////////////
6258 ////    SE.util
6259 SE.util = {
6260     /**
6261      * Cleans serialized UID lists of duplicates
6262      * @param string
6263      * @return string
6264      */
6265     cleanUids : function(str) {
6266         var seen = new Object();
6267         var clean = "";
6268         var arr = new String(str).split(",");
6269
6270         for(var i=0; i<arr.length; i++) {
6271             if(seen[arr[i]]) {
6272                 continue;
6273             }
6274
6275             clean += (clean != "") ? "," : "";
6276             clean += arr[i];
6277             seen[arr[i]] = true;
6278         }
6279
6280         return clean;
6281     },
6282
6283     /**
6284      * Clears hidden field values
6285      * @param string id ID of form element to clear
6286      */
6287     clearHiddenFieldValues : function(id) {
6288         var form = document.getElementById(id);
6289
6290         for(i=0; i<form.elements.length; i++) {
6291             if(form.elements[i].type == 'hidden') {
6292                 var e = form.elements[i];
6293                 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6294                     e.value = '';
6295                 }
6296             }
6297         }
6298     },
6299
6300     /**
6301      * Reduces a SELECT drop-down to 0 items to prepare for new ones
6302      */
6303     emptySelectOptions : function(el) {
6304         if(el) {
6305             for(i=el.childNodes.length - 1; i >= 0; i--) {
6306                 if(el.childNodes[i]) {
6307                     el.removeChild(el.childNodes[i]);
6308                 }
6309             }
6310         }
6311     },
6312
6313     /**
6314      * Returns the MBOX path in the manner php_imap expects:
6315      * ie: INBOX.DEBUG.test
6316      * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6317      */
6318     generateMboxPath : function(str) {
6319         var ex = str.split("::");
6320
6321         /* we have a serialized MBOX path */
6322         if(ex.length > 1) {
6323             var start = false;
6324             var ret = '';
6325             for(var i=0; i<ex.length; i++) {
6326                 if(ex[i] == 'INBOX') {
6327                     start = true;
6328                 }
6329
6330                 if(start == true) {
6331                     if(ret != "") {
6332                         ret += ".";
6333                     }
6334                     ret += ex[i];
6335                 }
6336             }
6337         } else {
6338             /* we have a Sugar folder GUID - do nothing */
6339             return str;
6340         }
6341
6342         return ret;
6343     },
6344
6345     /**
6346      * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6347      * @param HTMLElement el
6348      * @return string GUID of found element or empty on failure
6349      */
6350     getGuidFromElement : function(el) {
6351         var GUID = '';
6352         var iterations = 4;
6353         var passedEl = el;
6354
6355         // upwards
6356         for(var i=0; i<iterations; i++) {
6357             if(el) {
6358                 if(el.id.match(SE.reGUID)) {
6359                     return el.id;
6360                 } else {
6361                     el = el.parentNode;
6362                 }
6363             }
6364         }
6365
6366         return GUID;
6367     },
6368
6369     /**
6370      * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6371      * @return string
6372      */
6373     getPanelId : function() {
6374         return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6375     },
6376     
6377     /**
6378      * wrapper to handle weirdness with IE
6379      * @param string instanceId
6380      * @return tinyMCE Controller object
6381      */
6382     getTiny : function(instanceId) {
6383         if(instanceId == '') {
6384             return null;
6385         }
6386
6387         var t = tinyMCE.getInstanceById(instanceId);
6388
6389         if(this.isIe()) {
6390             this.sleep(200);
6391             YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6392         }
6393         return t;
6394     },
6395
6396     /**
6397      * Simple check for MSIE browser
6398      * @return bool
6399      */
6400     isIe : function() {
6401         var nav = new String(navigator.appVersion);
6402         if(nav.match(/MSIE/)) {
6403             return true;
6404         }
6405         return false;
6406     },
6407
6408     /**
6409      * Recursively removes an element from the DOM
6410      * @param HTMLElement
6411      */
6412     removeElementRecursive : function(el) {
6413         this.emptySelectOptions(el);
6414     },
6415     
6416     /**
6417      * Fakes a sleep
6418      * @param int
6419      */
6420     sleep : function(secs) {
6421         setTimeout("void(0);", secs);
6422     },
6423     
6424     /**
6425      * Converts a <select> element to an Ext.form.combobox
6426      */
6427      convertSelect : function(select) {
6428        alert('in convertSelect');
6429        if (typeof(select) == "string") {
6430            select = document.getElementById(select);
6431        }
6432      },
6433      
6434      findChildNode : function (parent, property, value) {
6435          for (i in parent.children) {
6436                  var child = parent.children[i];
6437                  if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6438                          return child;
6439                  var searchChild = SE.util.findChildNode(child, property, value);
6440                  if (searchChild) 
6441                          return searchChild;
6442          }
6443          return false;
6444      },
6445      
6446      cascadeNodes : function (parent, fn, scope, args) {
6447          for (i in parent.children) {
6448                  var child = parent.children[i];
6449                  var s = scope ? scope : child;
6450                  var a = args ? args : child;
6451                  fn.call(s, a);
6452                  SE.util.cascadeNodes(child, fn, scope, args);
6453          }
6454      }
6455 };
6456
6457
6458 ////    END UTIL
6459 ///////////////////////////////////////////////////////////////////////////////
6460
6461
6462 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6463                                 
6464 /*********************************************************************************
6465  * SugarCRM is a customer relationship management program developed by
6466  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6467  * 
6468  * This program is free software; you can redistribute it and/or modify it under
6469  * the terms of the GNU Affero General Public License version 3 as published by the
6470  * Free Software Foundation with the addition of the following permission added
6471  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6472  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6473  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6474  * 
6475  * This program is distributed in the hope that it will be useful, but WITHOUT
6476  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6477  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
6478  * details.
6479  * 
6480  * You should have received a copy of the GNU Affero General Public License along with
6481  * this program; if not, see http://www.gnu.org/licenses or write to the Free
6482  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6483  * 02110-1301 USA.
6484  * 
6485  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6486  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6487  * 
6488  * The interactive user interfaces in modified source and object code versions
6489  * of this program must display Appropriate Legal Notices, as required under
6490  * Section 5 of the GNU Affero General Public License version 3.
6491  * 
6492  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6493  * these Appropriate Legal Notices must retain the display of the "Powered by
6494  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6495  * technical reasons, the Appropriate Legal Notices must display the words
6496  * "Powered by SugarCRM".
6497  ********************************************************************************/
6498
6499
6500 if (typeof console == "undefined") 
6501         console = { log: function(o) {alert(o)} };
6502
6503 var AjaxObject = {
6504         ret : '',
6505         currentRequestObject : null,
6506         //timeout : 30000, // 30 second timeout default
6507         timeout : 9999999999, // 30 second timeout default
6508         forceAbort : false,
6509         trail : new Array(),
6510
6511         /**
6512          */
6513         _reset : function() {
6514                 this.timeout = 30000;
6515                 this.forceAbort = false;
6516         },
6517
6518         folderRenameCleanup : function() {
6519                 SUGAR.email2.folders.setSugarFolders();
6520         },
6521
6522         fullSyncCleanup : function(o) {
6523                 this.folders.checkMailCleanup(o);
6524                 SUGAR.email2.settings.settingsDialog.hide();
6525         },
6526
6527         /**
6528          */
6529         composeCache : function(o) {
6530                 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6531                 // get email templates and user signatures
6532                 var ret = JSON.parse(o.responseText);
6533
6534                 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6535                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6536                 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6537
6538                 SUGAR.email2.composeLayout.setComposeOptions(idx);
6539                 
6540                 //Set the error array so we can notify the user when they try to hit send if any errors 
6541                 //are present.  We will also notify them now (after hitting compose button).
6542                 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6543
6544
6545                 //if error element is returning an array, then check the length to make sure we have error messages
6546                 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6547                         //add error messages for display
6548                         for(i in ret.errorArray)
6549                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6550                 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6551                         //if error element is returning an object, and the object value is not empty or null, then display error message
6552                         for(i in ret.errorArray)
6553                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6554                 }
6555                 
6556                 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6557                 if(SUGAR.isIE) {
6558                         var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6559                         if(overlayPanel) {
6560                           overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6561                         }
6562                 }
6563         },
6564
6565
6566         handleDeleteSignature : function(o) {
6567                 hideOverlay();
6568                 var ret = JSON.parse(o.responseText);
6569                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6570         var field = document.getElementById('signature_id');
6571                 SUGAR.email2.util.emptySelectOptions(field);
6572
6573                 for(var i in ret.signatures) { // iterate through assoc array
6574                         var opt = new Option(ret.signatures[i], i);
6575                         field.options.add(opt);
6576                 }
6577                 setSigEditButtonVisibility();
6578         },
6579         
6580         /**
6581          */
6582         handleDeleteReturn : function(o) {
6583                 // force refresh ListView
6584                 hideOverlay();
6585                 if(document.getElementById('focusEmailMbox')) {
6586                         YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6587                 }
6588
6589                 // need to display success message before calling next async call?
6590                 document.getElementById(this.target).innerHTML = o.responseText;
6591         },
6592
6593         /**
6594          */
6595     handleFailure : function(o) {
6596                 // Failure handler
6597                 overlay('Exception occurred...', o.statusText, 'alert');
6598         },
6599
6600         handleReplyForward : function(o) {
6601                 var a = JSON.parse(o.responseText);
6602                 globalA = a;
6603                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6604
6605                 document.getElementById('email_id' + idx).value = a.uid;
6606                 document.getElementById('emailSubject' + idx).value = a.name;
6607                 document.getElementById('addressTO' + idx).value = a.from;
6608                 document.getElementById('uid' + idx).value = a.uid;
6609                 if(a.cc) {
6610                         document.getElementById('addressCC' + idx).value = a.cc;
6611                         SE.composeLayout.showHiddenAddress('cc', idx);
6612                 }
6613
6614                 if(a.type) {
6615                         document.getElementById('type' + idx).value = a.type;
6616                 }
6617
6618                 // apply attachment values
6619                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6620
6621                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6622         },
6623
6624         handleReplyForwardForDraft : function(o) {
6625                 var a = JSON.parse(o.responseText);
6626                 globalA = a;
6627                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6628
6629                 document.getElementById('email_id' + idx).value = a.uid;
6630                 document.getElementById('emailSubject' + idx).value = a.name;
6631                 document.getElementById('addressTO' + idx).value = a.to;
6632
6633                 if(a.cc) {
6634                         document.getElementById('addressCC' + idx).value = a.cc;
6635                         SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6636                 }
6637
6638                 if(a.bcc) {
6639                         document.getElementById('addressBCC' + idx).value = a.bcc;
6640                         SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6641                 }
6642
6643                 
6644                 if(a.type) {
6645                         document.getElementById('type' + idx).value = a.type;
6646                 }
6647
6648                 
6649                 // apply attachment values
6650                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6651
6652                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6653         },
6654                 
6655         /**
6656          */
6657         handleSuccess : function(o) {
6658                 document.getElementById(this.target).innerHTML = o.responseText;
6659                 hideOverlay();
6660         },
6661
6662         /**
6663          */
6664         ieDeleteSuccess : function(o) {
6665                 hideOverlay();
6666
6667                 var ret = JSON.parse(o.responseText);
6668
6669                 SUGAR.email2.accounts.refreshInboundAccountTable();
6670                 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6671                 SUGAR.email2.accounts.rebuildFolderList();
6672                 
6673         },
6674
6675         /**
6676          */
6677         ieSaveSuccess : function(o) {
6678                 document.getElementById('saveButton').disabled = false;
6679                 var a = JSON.parse(o.responseText);
6680                 if (a) {
6681                         if(a.error) {
6682                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6683                                 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6684                         } else {
6685                                 resp = JSON.parse(o.responseText);
6686                                 SUGAR.email2.accounts.refreshInboundAccountTable();
6687                                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6688                                 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6689                                 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6690                         }
6691                 } else {
6692                      hideOverlay();
6693                      overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert'); 
6694                 }
6695                 
6696         },
6697
6698         /**
6699          */
6700         loadAttachments : function(o) {
6701                 var result = JSON.parse(o.responseText);
6702
6703                 SUGAR.email2.composeLayout.loadAttachments(result);
6704         },
6705
6706         /**
6707          */
6708         loadSignature : function(o) {
6709                 var ret = JSON.parse(o.responseText);
6710                 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6711                 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6712         },
6713
6714         /**
6715          * Follow up to mark email read|unread|flagged
6716          */
6717         markEmailCleanup : function(o) {
6718                 var ret = JSON.parse(o.responseText);
6719                 if (!ret['status']) {
6720                 hideOverlay();
6721                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');                     
6722                 } else {
6723                         SUGAR.email2.contextMenus.markEmailCleanup();
6724                 } // else
6725         },
6726
6727         /**
6728          */
6729         rebuildShowFolders : function(o) {
6730                 var t = JSON.parse(o.responseText);
6731                 var show = document.getElementById('ieAccountListShow');
6732
6733                 SUGAR.email2.util.emptySelectOptions(show);
6734
6735                 for(i=0; i<t.length; i++) { // iterate through assoc array
6736                         var opt = new Option(t[i].text, t[i].value, t[i].selected);
6737                         opt.selected = t[i].selected;
6738                         show.options.add(opt);
6739                 }
6740
6741                 SUGAR.email2.accounts.renderTree();
6742         },
6743         /**
6744          */
6745         saveListViewSortOrderPart2 : function() {
6746                 // create the JSON string the func expects
6747                 focusFolderPath = '[ "Home", "' + ieName + '"';
6748
6749                 var f = new String(focusFolder);
6750                 var fEx = f.split('.');
6751
6752                 for(i=0; i<fEx.length; i++) {
6753                         focusFolderPath += ', "' + fEx[i] +'"'
6754                 }
6755
6756                 focusFolderPath += ']';
6757
6758                 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6759                 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6760         },
6761
6762         /**
6763          *
6764          */
6765         sendEmailCleanUp : function(o) {
6766                 hideOverlay();
6767                 var ret = JSON.parse(o.responseText);
6768                 if (ret) {
6769                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6770                   //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6771                 } else if (o.responseText) {
6772                   overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6773                 }
6774                 
6775                 if (typeof(SE.grid) != 'undefined')
6776                         SE.listView.refreshGrid();
6777                 //Disabled while address book is disabled
6778                 
6779                 //If this call back was initiated by quick compose from a Detail View page, refresh the
6780                 //history subpanel.  If it was initiated by quickcreate from shortcut bar, then
6781                 //close the shortcut bar menu
6782                 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6783                         if(action_sugar_grp1 == 'DetailView') {
6784                                 showSubPanel('history',null,true);  
6785                         } else if(action_sugar_grp1 == 'quickcreate') {
6786                                 closeEmailOverlay();
6787                         }
6788                 }
6789                 
6790         },
6791
6792         ieSendSuccess : function(o) {
6793                 hideOverlay();
6794                 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6795         },
6796         
6797         /**
6798          */
6799         settingsFolderRefresh : function(o) {
6800                 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6801                 var ret = JSON.parse(o.responseText);
6802                 var user = document.getElementById('userFolders');
6803
6804                 SUGAR.email2.util.emptySelectOptions(user);
6805
6806                 for(i=0; i<ret.userFolders.length; i++) {
6807                         var display = ret.userFolders[i].name;
6808                         var value = ret.userFolders[i].id;
6809                         var selected = (ret.userFolders[i].selected != "") ? true : false;
6810                         var opt = new Option(display, value, selected);
6811                         opt.selected = selected;
6812                         user.options.add(opt);
6813                 }
6814         },
6815
6816         /**
6817          */
6818         startRequest : function(callback, args, forceAbort) {
6819                 if(this.currentRequestObject != null) {
6820                         if(this.forceAbort == true) {
6821                                 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6822                         }
6823                 }
6824                 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6825                 this._reset();
6826         },
6827         
6828         requestInProgress : function() {
6829                 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6830         },
6831
6832         /**
6833          */
6834         updateFolderSubscriptions : function() {
6835                 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6836                 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6837                 hideOverlay();
6838         },
6839
6840         /**
6841          */
6842         updateFrameFolder : function() {
6843                 SUGAR.email2.folders.checkEmailAccounts();
6844         },
6845
6846         /**
6847          */
6848         updateUserPrefs : function(o) {
6849                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6850                 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6851         },
6852
6853         /**
6854          */
6855         uploadAttachmentSuccessful : function(o) {
6856                 // clear out field
6857                 document.getElementById('email_attachment').value = '';
6858
6859                 var ret = JSON.parse(o.responseText);
6860                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6861                 var overall = document.getElementById('addedFiles' + idx);
6862                 var index = overall.childNodes.length;
6863                 var out = 
6864                         "<div id='email_attachment_bucket" + idx + index + "'>" +
6865                                 // remove button        
6866                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6867                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" + 
6868                                         idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6869                                 // file icon
6870                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6871                                         "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6872                                 // hidden id field
6873                                 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6874                                 // file name
6875                                 ((ret.nameForDisplay != null) ? ret.nameForDisplay + "&nbsp;" : ret.name + "&nbsp;") + 
6876                                 "<br/>" +
6877                         "</div>";
6878                 overall.innerHTML += out;
6879                 if(SUGAR.email2.util.isIe()) {
6880                         document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6881                 }
6882
6883                 // hide popup
6884                 SUGAR.email2.addFileDialog.hide();
6885                 // focus attachments
6886                 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6887         }
6888 };
6889
6890
6891 ///////////////////////////////////////////////////////////////////////////
6892 ////    PER MODULE CALLBACK OBJECTS
6893 AjaxObject.accounts = {
6894         saveOutboundCleanup : function(o) {
6895                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6896                 SUGAR.email2.accounts.outboundDialog.hide();
6897                 var id = o.responseText;
6898                 SUGAR.email2.accounts.newAddedOutboundId = id;
6899                 },
6900         saveDefaultOutboundCleanup: function(o){
6901                 
6902         },
6903         callbackEditOutbound : {
6904                 success : function(o) 
6905                 {
6906                         var ret = JSON.parse(o.responseText);
6907                         // show overlay
6908                         SUGAR.email2.accounts.showAddSmtp();
6909
6910                         // fill values
6911                         document.getElementById("mail_id").value = ret.id;
6912                         document.getElementById("type").value = ret.type;
6913                         document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6914                         document.getElementById("mail_name").value = ret.name;
6915                         document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6916                         document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6917                         document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6918                         document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6919                         document.getElementById("mail_smtppass").value = ret.mail_smtppass;
6920                         document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6921                         SUGAR.email2.accounts.smtp_authenticate_field_display();
6922                         document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6923                         
6924             if(ret.type == 'system-override') {
6925                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6926                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6927             }
6928             else {
6929                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6930                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6931             }
6932             
6933                         
6934                 },
6935                 failure : AjaxObject.handleFailure,
6936                 timeout : AjaxObject.timeout,
6937                 scope   : AjaxObject
6938         },
6939         callbackDeleteOutbound : {
6940                 success : function(o) {
6941                     var ret = JSON.parse(o.responseText);
6942                     if(ret.is_error)
6943                     {
6944                         if(confirm(ret.error_message)) 
6945                 {
6946                     overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6947                     AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6948                 }
6949                 else
6950                     hideOverlay();  
6951                     }
6952                     else
6953                     {
6954                              hideOverlay();
6955                              SUGAR.email2.accounts.refreshOuboundAccountTable();
6956                     }
6957                 },
6958                 
6959                 failure : AjaxObject.handleFailure,
6960                 timeout : AjaxObject.timeout,
6961                 scope   : AjaxObject
6962         },
6963                 
6964         callbackCheckMailProgress : {
6965            success : function(o) {
6966                if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6967                    SUGAR.email2.accounts.totalMsgCount = -1;
6968                }
6969                
6970                //Check for server timeout / errors
6971                var ret = JSON.parse(o.responseText);
6972                var done = false;
6973                    
6974                if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6975                    hideOverlay();
6976                    overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6977                    SUGAR.email2.accounts.totalMsgCount = -1;
6978                //SUGAR.email2.folders.rebuildFolders();
6979                done = true;
6980                } 
6981                
6982                var currIeId = ret['ieid'];
6983                
6984               
6985                var serverCount = ret.count;
6986                
6987                if (ret['status'] == 'done') {
6988                    for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
6989                        if (i == SUGAR.email2.accounts.ieIds.length - 1) {
6990                            //We are all done
6991                            done = true;
6992                            break;
6993                        } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
6994                            //Go to next account
6995                            currIeId = SUGAR.email2.accounts.ieIds[i+1];
6996                            ret.count = 0;
6997                            SUGAR.email2.accounts.totalMsgCount = -1;
6998                            break;
6999                        }
7000                    }
7001                } 
7002                else if (ret.mbox && ret.totalcount && ret.count) {
7003                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7004                    if (ret.count >= ret.totalcount) {
7005                        serverCount = 0;
7006                    }
7007                } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7008                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7009                } else {
7010                        hideOverlay();
7011                overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7012                SUGAR.email2.accounts.totalMsgCount = -1;
7013                done = true;
7014                    }
7015                
7016                if (done) {
7017                    SUGAR.email2.accounts.totalMsgCount = -1;
7018                    hideOverlay();
7019                    SUGAR.email2.folders.rebuildFolders();
7020                    SE.listView.refreshGrid();
7021                } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7022                YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7023                AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard + 
7024                                 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=0&synch=" + ret.synch);
7025            } else {
7026                YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7027                    app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7028                    AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard + 
7029                    '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=" + serverCount + 
7030                    '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7031                }
7032            },
7033            failure : AjaxObject.handleFailure,
7034        timeout : AjaxObject.timeout,
7035        scope   : AjaxObject
7036         }
7037 };
7038
7039 ///////////////////////////////////////////////////////////////////////////////
7040 ////    COMPOSE LAYOUT
7041 AjaxObject.composeLayout = {
7042         /**
7043          * Populates the record id
7044          */
7045         saveDraftCleanup : function(o) {
7046                 hideOverlay();
7047                 var ret = JSON.parse(o.responseText);
7048                 if(ret)
7049                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7050                 else if (o.responseText) 
7051                   overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7052         }
7053 };
7054
7055 AjaxObject.composeLayout.callback = {
7056         saveDraft : {
7057                 success : AjaxObject.composeLayout.saveDraftCleanup,
7058                 failure : AjaxObject.handleFailure,
7059                 timeout : AjaxObject.timeout,
7060                 scope   : AjaxObject
7061         }
7062 };
7063
7064 AjaxObject.detailView = {
7065         /**
7066          * Pops-up a printable view of an email
7067          */
7068         displayPrintable : function(o) {
7069                 var ret = JSON.parse(o.responseText);
7070                 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7071                 // 2 below must be in global context
7072                 meta = ret.meta;
7073                 meta['panelId'] = SUGAR.email2.util.getPanelId();
7074                 email = ret.meta.email;
7075                 if (typeof(email.cc) == 'undefined') {
7076                   email.cc = "";
7077                 }
7078                 
7079                 var out = displayTemplate.exec({
7080                         'app_strings'   : app_strings,
7081                         'theme'                 : theme,
7082                         'idx'                   : 'Preview',
7083                         'meta'                  : meta,
7084                         'email'                 : meta.email
7085                 });
7086
7087                 // open popup window
7088                 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' , 
7089                     'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7090
7091                 popup.document.write(out);
7092                 popup.document.close();
7093         },
7094
7095         /**
7096          * Takes formatted response and creates a modal pop-over containing a title and content
7097          */
7098         displayView : function(o) {
7099                 var SED = SUGAR.email2.detailView;
7100                 var ret = JSON.parse(o.responseText);
7101
7102                 if(!SED.viewDialog) {
7103                         SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7104                                 modal:true,
7105                 visible:true,
7106                 fixedcenter:true,
7107                 constraintoviewport: true,
7108                                 shadow  : true
7109                         });
7110             SED.viewDialog.renderEvent.subscribe(function() {
7111                 var content = this.body.firstChild;
7112                 var viewH = YAHOO.util.Dom.getViewportHeight();
7113                 if (content) {
7114                         this.body.style.overflow = "auto";
7115                         this.body.style.width = "800px";
7116                         this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7117                 }
7118             }, SED.viewDialog);
7119                 } // end lazy load
7120                 SED.viewDialog.setHeader(ret.title);
7121                 SED.viewDialog.setBody(ret.html);
7122                 SED.viewDialog.render();
7123                 SED.viewDialog.show();  
7124         },
7125
7126         /**
7127          * Generates a modal popup to populate with the contents of bean's full EditView
7128          */
7129         showQuickCreateForm : function(o) {
7130                 var SED = SUGAR.email2.detailView;
7131                 var ret = JSON.parse(o.responseText);
7132
7133                 if(!SED.quickCreateDialog) {
7134                         SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7135                                 modal:true,
7136                                 visible:true,
7137                 fixedcenter:true,
7138                 constraintoviewport: true,
7139                                 shadow  : true
7140                         });
7141                         
7142             SED.quickCreateDialog.renderEvent.subscribe(function() {
7143                 var viewH = YAHOO.util.Dom.getViewportHeight();
7144                 var contH = 0;
7145                 for (var i in this.body.childNodes) {
7146                         if (this.body.childNodes[i].clientHeight) {
7147                                 contH += this.body.childNodes[i].clientHeight;
7148                         } else if (this.body.childNodes[i].offsetHeight) {
7149                                 contH += this.body.childNodes[i].offsetHeight;
7150                         } // if
7151                 }
7152                         this.body.style.width = "800px";
7153                         this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7154                         this.body.style.overflow = "auto";
7155             }, SED.quickCreateDialog);
7156             
7157             SED.quickCreateDialog.hideEvent.subscribe(function(){
7158                                 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7159                                 /*for(var qsField in qsFields){
7160                                         if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7161                                         Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7162                                 }*/
7163                         });
7164             SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7165                 } // end lazy load
7166                 if (ret.html) {
7167                         ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7168                 }
7169                 SED.quickCreateDialog.setBody(ret.html ? ret.html : "&nbsp;");
7170                 SED.quickCreateDialog.render();
7171                 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7172                 
7173                 SED.quickCreateDialog.ieId = ret.ieId;
7174                 SED.quickCreateDialog.uid = ret.uid;
7175         SED.quickCreateDialog.mbox = ret.mbox;
7176         SED.quickCreateDialog.qcmodule = ret.module;
7177         
7178         SED.quickCreateDialog.show();
7179
7180                 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7181                 if (editForm) {
7182                   editForm.module.value = 'Emails';
7183                   var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0; 
7184                   var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7185                   var instId = ret.module + count;
7186                   SED.quickCreateEmailsToAdd = ret.emailAddress;
7187                   SED.quickCreateEmailCallback = function(instId, tableId) {
7188                           var eaw = SUGAR.EmailAddressWidget.instances[instId];
7189                           if (typeof(eaw) == "undefined")
7190                                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('" 
7191                                                 + instId + "','" + tableId + "');", 100);
7192                           eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7193                   }
7194                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('" 
7195                                         + instId + "','" + tableId + "');", 100);
7196                 }
7197         },
7198
7199         saveQuickCreateForm : function(o) {
7200             hideOverlay();
7201                 SUGAR.email2.detailView.quickCreateDialog.hide();
7202                 validate['EditView'] = [ ];
7203         },
7204
7205         saveQuickCreateFormAndReply : function(o) {
7206             hideOverlay();
7207             var ret = JSON.parse(o.responseText);
7208         SUGAR.email2.detailView.quickCreateDialog.hide();
7209         var qcd = SUGAR.email2.detailView.quickCreateDialog;
7210         var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7211         if (ret) {
7212             var emailID = ret.id;
7213             SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7214         } else {
7215             SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7216         }
7217         //Cean the validate cache to prevent errors on the next call
7218         validate['EditView'] = [ ];
7219     },
7220
7221         saveQuickCreateFormAndAddToAddressBook : function(o) {
7222            hideOverlay();
7223                 SUGAR.email2.detailView.quickCreateDialog.hide();
7224                 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7225                 validate['EditView'] = [ ];
7226         },
7227         
7228         handleAssignmentDialogAssignAction : function() {
7229
7230
7231             var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7232
7233             var dist = 'direct';
7234             var users = false;
7235             var rules = false;
7236             var get = "";
7237             var found_teams = false;
7238             var warning_message = mod_strings.LBL_WARN_NO_USERS;
7239             if(!found_teams && assign_user_id == '' )
7240             {
7241                 alert(warning_message);
7242                 return;
7243             }
7244             
7245             var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7246             var uids = "";
7247             for(i=0; i<emailUids.length; i++) {
7248                 if(uids != '') {
7249                     uids += app_strings.LBL_EMAIL_DELIMITER;
7250                 }
7251                 uids += emailUids[i];
7252             }
7253
7254             var row = SUGAR.email2.grid.getSelectedRows()[0];
7255             var data = SUGAR.email2.grid.getRecord(row).getData();
7256             var ieid = data.ieId;
7257             var mbox = data.mbox;
7258             AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7259             SUGAR.email2.contextMenus.assignToDialogue.hide();
7260             overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7261                 
7262         },
7263         
7264         handleAssignmentDialogDeleteAction : function() {
7265                 // TO pass list of UIDS/emailIds
7266                 var uids = SUGAR.email2.listView.getUidsFromSelection();
7267                 var row = SUGAR.email2.grid.getSelections()[0];
7268                 var ieid = row.data.ieId;
7269             var mbox = row.data.mbox;
7270         AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7271         SUGAR.email2.contextMenus.assignmentDialog.hide();
7272                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7273
7274                 // AJAX Call
7275                 
7276         },
7277         
7278         showEmailDetailView : function(o) {
7279         hideOverlay();
7280         var SED = SUGAR.email2.detailView;
7281                 var ret = JSON.parse(o.responseText);
7282
7283                 if(!SED.quickCreateDialog) {
7284                         SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7285                                 modal:true,
7286                                 visible:true,
7287                 //fixedcenter:true,
7288                 constraintoviewport: true,
7289                 draggable: true,
7290                                 autofillheight: "body",
7291                                 shadow  : true
7292                         });
7293                         SED.quickCreateDialog.renderEvent.subscribe(function() {
7294                 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7295                 var contH = 0;
7296                 for (var i in this.body.childNodes) {
7297                         if (this.body.childNodes[i].offsetHeight)
7298                                 contH += this.body.childNodes[i].offsetHeight;
7299                 }
7300                         this.body.style.overflow = "auto";
7301                         this.body.style.width = "800px";
7302                         this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7303                         this.center();
7304             }, SED.quickCreateDialog);
7305                 }
7306                 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7307                 SED.quickCreateDialog.setBody(ret.html);
7308                 SED.quickCreateDialog.render();
7309         SUGAR.util.evalScript(ret.html);      
7310         SED.quickCreateDialog.show();           
7311         },
7312         
7313         showAssignmentDialogWithData : function(o) {
7314         var SEC = SUGAR.email2.contextMenus;
7315                 hideOverlay();
7316         var ret = JSON.parse(o.responseText);
7317         if (!SEC.assignmentDialog) {
7318                 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7319                         visible:false,
7320                 fixedcenter:true,
7321                 constraintoviewport: true,
7322                         modal   : true
7323                 });
7324                 SEC.assignmentDialog.setBody("");
7325                 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7326                 SEC.assignmentDialog.renderEvent.subscribe(function() {
7327                 var iev = YAHOO.util.Dom.get("Distribute");
7328                 if (iev) {
7329                         this.body.style.width = "700px";
7330                 }
7331             },  SEC.assignmentDialog);
7332                 SEC.assignmentDialog.render();
7333         }
7334         SEC.assignmentDialog.setBody(ret);
7335         SEC.assignmentDialog.render();
7336         validate = [];
7337         SEC.assignmentDialog.show();
7338         SUGAR.util.evalScript(ret);
7339         },
7340         
7341         showImportForm : function(o) {
7342                 var SED = SUGAR.email2.detailView;
7343                 var ret = JSON.parse(o.responseText);
7344         
7345         document.getElementById('quickCreateContent').innerHTML = "";
7346         hideOverlay();
7347         if (!ret) {
7348             return false;
7349         }
7350
7351         if(!SED.importDialog) {
7352             SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7353                 modal:true,
7354                 visible:false,
7355                 fixedcenter:true,
7356                 constraintoviewport: true,
7357                 buttons : [{
7358                         text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7359                                 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7360                 }]//,
7361                 //scroll : true
7362             });
7363             SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7364             SED.importDialog.setBody("");
7365             SED.importDialog.hideEvent.subscribe(function(){
7366                 for(var i in QSFieldsArray) {
7367                         if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7368                                 QSFieldsArray[i].destroy();
7369                                 delete QSFieldsArray[i];
7370                         }
7371                         if (QSProcessedFieldsArray[i]) {
7372                                 QSProcessedFieldsArray[i] = false;
7373                         } // if
7374                                 }
7375             }); 
7376             SED.importDialog.renderEvent.subscribe(function() {
7377                 var iev = YAHOO.util.Dom.get("ImportEditView");
7378                 if (iev) {
7379                         //this.body.style.height = (iev.clientHeight + 10) + "px";
7380                         this.body.style.width = "600px";
7381                 }
7382             }, SED.importDialog);
7383             SED.importDialog.render();
7384         } // end lazy load
7385         SED.importDialog.setBody(ret.html);
7386         SED.importDialog.ret = ret;
7387         SUGAR.util.evalScript(ret.html);
7388         SED.importDialog.render();
7389         validate = [];
7390         SED.importDialog.show();
7391         SED.importDialog.focusFirstButton();
7392     },
7393     getImportAction : function(ret) {
7394         if (!check_form('ImportEditView')) return false;
7395         if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7396                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7397                 return false;
7398         } // if
7399                 var get = "";
7400         var editView = document.getElementById('ImportEditView');
7401         if (editView.assigned_user_id != null) {
7402             get = get + "&user_id=" + editView.assigned_user_id.value
7403             //var user_id = editView.assigned_user_id.value;
7404         }
7405         var parent_id = editView.parent_id.value;
7406         var parent_type = editView.parent_type.value;
7407         var row = SUGAR.email2.grid.getSelectedRows()[0];
7408         row = SUGAR.email2.grid.getRecord(row);
7409         var data = row.getData();
7410         var ieId = data.ieId; 
7411         var mbox = data.mbox; 
7412         var serverDelete = editView.serverDelete.checked;
7413         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7414         var uids = "";
7415         for(i=0; i<emailUids.length; i++) {
7416             if(uids != '') {
7417                 uids += app_strings.LBL_EMAIL_DELIMITER;
7418             }
7419             uids += emailUids[i];
7420         }
7421         
7422         var action = 'importEmail&uid=';
7423         if (ret.move) {
7424             action = 'moveEmails';
7425             action = action + '&sourceFolder=' + ret['srcFolder'];
7426             action = action + '&sourceIeId=' + ret['srcIeId'];
7427             action = action + '&destinationFolder=' + ret['dstFolder'];
7428             action = action + '&destinationIeId=' + ret['dstIeId'];
7429             action = action + '&emailUids=';
7430         } 
7431         if (action.search(/importEmail/) != -1) {
7432             overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7433         } else {
7434             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7435         }
7436         
7437         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox + 
7438         get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7439         SUGAR.email2.detailView.importDialog.hide();
7440         document.getElementById('importDialogContent').innerHTML = "";
7441         
7442     },
7443     showRelateForm : function(o) {
7444         var SED = SUGAR.email2.detailView;
7445         var ret = JSON.parse(o.responseText);
7446         document.getElementById('quickCreateContent').innerHTML = "";
7447         hideOverlay();
7448         if (!ret) {
7449             return false;
7450         }
7451         dialog_loaded = true;
7452
7453         if(!SED.relateDialog) {
7454             SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7455                                 modal:true,
7456                                 visible:true,
7457                 fixedcenter:true,
7458                 width: '800px',
7459                 constraintoviewport: true,
7460                                 buttons : [{
7461                         text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7462                                         if (!check_form('RelateEditView')) return false;
7463                                         var get = "";
7464                         var editView = document.getElementById('RelateEditView');
7465                         var parent_id = editView.parent_id.value;
7466                         var parent_type = editView.parent_type.value;
7467                         var row = SUGAR.email2.grid.getSelectedRows()[0];
7468                         row  = SUGAR.email2.grid.getRecord(row);
7469                         var ieId = row.getData().ieId; 
7470                         var mbox = row.getData().mbox; 
7471                         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7472                         var uids = "";
7473                         for(i=0; i<emailUids.length; i++) {
7474                             if(uids != '') {
7475                                 uids += app_strings.LBL_EMAIL_DELIMITER;
7476                             }
7477                             uids += emailUids[i];
7478                         }
7479                         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7480                         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids 
7481                             + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7482                         SED.relateDialog.hide();
7483                         document.getElementById('relateDialogContent').innerHTML = "";
7484                         }
7485                 }]
7486                         });
7487                         
7488             SED.relateDialog.hideEvent.subscribe(function(){
7489                 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7490                         QSFieldsArray['ImportEditView_parent_name'].destroy();
7491                         delete QSFieldsArray['ImportEditView_parent_name'];
7492                 } // if
7493                                 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7494                                         QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7495                                 } // if
7496             }); 
7497                         
7498             SED.relateDialog.renderEvent.subscribe(function() {
7499                 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7500                 var contH = 0;
7501                 for (var i in this.body.childNodes) {
7502                         if (this.body.childNodes[i].clientHeight)
7503                                 contH += this.body.childNodes[i].clientHeight;
7504                 }
7505             }, SED.relateDialog);
7506             SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7507                 } // end lazy load
7508                 
7509         SED.relateDialog.setBody(ret.html);
7510         SED.relateDialog.render();
7511         SUGAR.util.evalScript(ret.html);
7512         SED.relateDialog.show();
7513     }
7514 };
7515 /**
7516  * DetailView callbacks
7517  */
7518 AjaxObject.detailView.callback = {
7519         emailDetail : {
7520                 success : function(o) {
7521                         SUGAR.email2.o = o;
7522                         var ret = JSON.parse(o.responseText);
7523                         SUGAR.email2.detailView.consumeMetaDetail(ret);
7524                 },
7525                 argument: [targetDiv],
7526                 failure : AjaxObject.handleFailure,
7527                 timeout : 0,
7528                 scope   : AjaxObject
7529         },
7530         emailPreview : {
7531                 success : function(o) {
7532                         SUGAR.email2.o = o;
7533                         var ret = JSON.parse(o.responseText);
7534                         SUGAR.email2.detailView.consumeMetaPreview(ret);
7535                 },
7536                 failure : AjaxObject.handleFailure,
7537                 timeout : 0,
7538                 scope   : AjaxObject
7539         },
7540         viewPrint : {
7541                 success : AjaxObject.detailView.displayPrintable,
7542                 failure : AjaxObject.handleFailure,
7543                 timeout : AjaxObject.timeout,
7544                 scope   : AjaxObject
7545         },
7546         viewRaw : {
7547                 success : AjaxObject.detailView.displayView,
7548                 failure : AjaxObject.handleFailure,
7549                 timeout : AjaxObject.timeout,
7550                 scope   : AjaxObject
7551         }
7552 };
7553
7554
7555
7556
7557
7558 AjaxObject.folders = {
7559         /**
7560          * check-mail post actions
7561          */
7562         checkMailCleanup : function(o) {
7563                 hideOverlay();
7564                 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7565
7566                 // refresh focus ListView
7567                 SE.listView.refreshGrid();
7568                 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7569         },
7570
7571         /**
7572          */
7573         rebuildFolders : function(o) {
7574                 hideOverlay();
7575
7576                 var data = JSON.parse(o.responseText);
7577
7578                 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7579                 SUGAR.email2.folders.setSugarFolders();
7580         }
7581 };
7582 AjaxObject.folders.callback = {
7583         checkMail : {
7584                 success : AjaxObject.folders.checkMailCleanup,
7585                 failure : AjaxObject.handleFailure,
7586                 timeout : 600000, // 5 mins
7587                 scope   : AjaxObject
7588         }
7589 }
7590
7591 AjaxObject.rules = {
7592         loadRulesForSettings : function(o) {
7593                 document.getElementById("rulesListCell").innerHTML = o.responseText;
7594                 // assume we have the class we need
7595                 SUGAR.routing.getStrings();
7596                 SUGAR.routing.getDependentDropdowns();
7597         }
7598 };
7599 ////    END PER MODULE CALLBACK OBJECTS
7600 ///////////////////////////////////////////////////////////////////////////
7601
7602
7603 var callback = {
7604         success : AjaxObject.handleSuccess,
7605         failure : AjaxObject.handleFailure,
7606         timeout : AjaxObject.timeout,
7607         scope   : AjaxObject
7608 };
7609 var callbackAccount = {
7610         success : AjaxObject.ieSaveSuccess,
7611         failure : AjaxObject.handleFailure,
7612         timeout : AjaxObject.timeout,
7613         scope   : AjaxObject
7614 };
7615 var callbackAccountDelete = {
7616         success : AjaxObject.ieDeleteSuccess,
7617         failure : AjaxObject.handleFailure,
7618         timeout : AjaxObject.timeout,
7619         scope   : AjaxObject
7620 };
7621 var callbackOutboundTest = {
7622         success : AjaxObject.ieSendSuccess,
7623         failure : AjaxObject.handleFailure,
7624         timeout : AjaxObject.timeout,
7625         scope   : AjaxObject
7626 };
7627
7628
7629
7630 var callbackTeamInfoForSettings = {
7631 success : function (o) {
7632         var data = JSON.parse(o.responseText);
7633         document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7634 },
7635 failure : AjaxObject.handleFailure,
7636 timeout : AjaxObject.timeout,
7637 scope   : AjaxObject
7638         
7639 };
7640
7641 var callbackStatusForImport = {
7642 success : function (o) {
7643         hideOverlay();
7644         if (o.responseText != "")  {
7645                 var statusString = "";
7646                 var data = JSON.parse(o.responseText);
7647                 for(i=0; i<data.length; i++) {
7648                         statusString = statusString + data[i] + '<br/>';
7649                 }
7650                 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7651         }
7652         SE.listView.refreshGrid();
7653         
7654 },
7655 failure : AjaxObject.handleFailure,
7656 timeout : AjaxObject.timeout,
7657 scope   : AjaxObject
7658         
7659 };
7660 var callbackComposeCache = {
7661         success : AjaxObject.composeCache,
7662         failure : AjaxObject.handleFailure,
7663         timeout : AjaxObject.timeout,
7664         scope   : AjaxObject
7665 };
7666 var callbackDelete = {
7667         success : AjaxObject.handleDeleteReturn,
7668         failure : AjaxObject.handleFailure,
7669         timeout : AjaxObject.timeout,
7670         scope   : AjaxObject
7671 };
7672 var callbackEmailDetailMultiple = {
7673         success : function(o) {
7674                 hideOverlay();
7675                 var retMulti = JSON.parse(o.responseText);
7676                 var ret = new Object();
7677
7678                 for(var i=0; i<retMulti.length; i++) {
7679                         ret = retMulti[i];
7680
7681                         SUGAR.email2._setDetailCache(ret);
7682                         SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7683                 }
7684         },
7685         failure : AjaxObject.handleFailure,
7686         timeout : 0,
7687         scope   : AjaxObject
7688 };
7689 var callbackListViewSortOrderChange = {
7690         success : AjaxObject.saveListViewSortOrderPart2,
7691         failure : AjaxObject.handleFailure,
7692         timeout : AjaxObject.timeout,
7693         scope   : AjaxObject,
7694         argument        : [ieId, ieName, focusFolder]
7695 };
7696 var callbackEmptyTrash = {
7697         success : function(o) {
7698                 hideOverlay();
7699                 AjaxObject.folderRenameCleanup;
7700         },
7701         failure : AjaxObject.handleFailure,
7702         timeout : AjaxObject.timeout,
7703         scope   : AjaxObject
7704 };
7705 var callbackClearCacheFiles = {
7706         success : function(o) {
7707                 hideOverlay();
7708         },
7709         failure : AjaxObject.handleFailure,
7710         timeout : AjaxObject.timeout,
7711         scope   : AjaxObject
7712 };
7713 var callbackFolderRename = {
7714         success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7715         failure : AjaxObject.handleFailure,
7716         timeout : AjaxObject.timeout,
7717         scope   : AjaxObject
7718 };
7719 var callbackFolderDelete = {
7720         success : function(o) {
7721                 var ret = JSON.parse(o.responseText);
7722                 if (ret.status) {
7723                     if (ret.folder_id) {
7724                         var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7725                         if(node)
7726                                 SUGAR.email2.tree.removeNode(node, true);
7727                     } else if (ret.ieId && ret.mbox) {
7728                         var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7729                         if(node)
7730                                 SUGAR.email2.tree.removeNode(node, true);
7731                     }
7732                         hideOverlay();
7733                         //SUGAR.email2.folders.loadSettingFolder();
7734                 } else {
7735                         hideOverlay();
7736                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7737                 } // else
7738         },
7739         failure : AjaxObject.handleFailure,
7740         timeout : AjaxObject.timeout,
7741         scope   : AjaxObject
7742 };
7743 var callbackFolderSave = {
7744         success : function(o) {
7745                 var ret = JSON.parse(o.responseText);
7746
7747                 switch(ret.action) {
7748                         case 'newFolderSave':
7749                                 SUGAR.email2.folders.rebuildFolders();
7750                         break;
7751                 }
7752         },
7753         failure : AjaxObject.handleFailure,
7754         timeout : AjaxObject.timeout,
7755         scope   : AjaxObject
7756 };
7757 var callbackFolderSubscriptions = {
7758         success : AjaxObject.updateFolderSubscriptions,
7759         failure : AjaxObject.handleFailure,
7760         timeout : AjaxObject.timeout,
7761         scope   : AjaxObject
7762 };
7763 var callbackFolderUpdate = {
7764         success : AjaxObject.updateFrameFolder,
7765         failure : AjaxObject.handleFailure,
7766         timeout : AjaxObject.timeout,
7767         scope   : AjaxObject
7768 };
7769 var callbackFolders = {
7770         success : AjaxObject.folders.rebuildFolders,
7771         //success : void(true),
7772         failure : AjaxObject.handleFailure,
7773         timeout : AjaxObject.timeout,
7774         scope   : AjaxObject
7775 };
7776 var callbackFullSync = {
7777         success : AjaxObject.fullSyncCleanup,
7778         failure : AjaxObject.handleFailure,
7779         timeout : 9999999999999,
7780         scope   : AjaxObject
7781 };
7782 var callbackGeneric = {
7783         success : function() {
7784                 hideOverlay();
7785         },
7786         failure : AjaxObject.handleFailure,
7787         timeout : AjaxObject.timeout,
7788         scope   : AjaxObject
7789 };
7790 var callbackIeAccountRetrieve = {
7791         success : function(o) {
7792                 // return JSON encoding
7793                 hideOverlay();
7794                 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7795                 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7796         },
7797         failure : AjaxObject.handleFailure,
7798         timeout : AjaxObject.timeout,
7799         scope   : AjaxObject
7800 };
7801 var callbackImportOneEmail = {
7802         success :  AjaxObject.detailView.showImportForm,
7803         failure : AjaxObject.handleFailure,
7804         timeout : AjaxObject.timeout,
7805         scope   : AjaxObject
7806 };
7807 var callbackRelateEmail = {
7808     success : AjaxObject.detailView.showRelateForm,
7809     failure : AjaxObject.handleFailure,
7810     timeout : AjaxObject.timeout,
7811     scope   : AjaxObject
7812 }
7813 var callbackEmailDetailView = {
7814     success : AjaxObject.detailView.showEmailDetailView,
7815     failure : AjaxObject.handleFailure,
7816     timeout : AjaxObject.timeout,
7817     scope   : AjaxObject
7818 }
7819 var callbackAssignmentDialog = {
7820         success :  AjaxObject.detailView.showAssignmentDialogWithData,
7821         failure : AjaxObject.handleFailure,
7822         timeout : AjaxObject.timeout,
7823         scope   : AjaxObject    
7824 };
7825 var callbackAssignmentAction = {
7826         success :  function(o) {
7827                 SE.listView.refreshGrid();
7828                 hideOverlay();
7829                 if(o.responseText != '') {
7830                overlay('Assignment action result', o.responseText, 'alert');
7831             } // if
7832         } ,
7833         failure : AjaxObject.handleFailure,
7834         timeout : AjaxObject.timeout,
7835         scope   : AjaxObject
7836 };
7837 var callbackMoveEmails = {
7838         success :  function(o) {
7839             SE.listView.refreshGrid();
7840                 hideOverlay();
7841                 if(o.responseText != '') {
7842                overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7843             } // if
7844         } ,
7845         failure : AjaxObject.handleFailure,
7846         timeout : AjaxObject.timeout,
7847         scope   : AjaxObject
7848 };
7849 var callbackLoadAttachments = {
7850         success : AjaxObject.loadAttachments,
7851         failure : AjaxObject.handleFailure,
7852         timeout : AjaxObject.timeout,
7853         scope   : AjaxObject
7854 };
7855 var callbackLoadRules = {
7856         success : AjaxObject.rules.loadRulesForSettings,
7857         failure : AjaxObject.handleFailure,
7858         timeout : AjaxObject.timeout,
7859         scope   : AjaxObject
7860 };
7861 var callbackLoadSignature = {
7862         success : AjaxObject.loadSignature,
7863         failure : AjaxObject.handleFailure,
7864         timeout : AjaxObject.timeout,
7865         scope   : AjaxObject
7866 };
7867 var callbackDeleteSignature = {
7868         success : AjaxObject.handleDeleteSignature,
7869         failure : AjaxObject.handleFailure,
7870         timeout : AjaxObject.timeout,
7871         scope   : AjaxObject
7872 };
7873 /*var callbackMoveEmails = {
7874     success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7875     failure : AjaxObject.handleFailure,
7876     timeout : AjaxObject.timeout,
7877     scope   : AjaxObject
7878 }*/
7879 var callbackOutboundSave = {
7880         success : AjaxObject.accounts.saveOutboundCleanup,
7881         failure : AjaxObject.handleFailure,
7882         timeout : AjaxObject.timeout,
7883         scope   : AjaxObject
7884 };
7885 var callbackDefaultOutboundSave = {
7886         success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7887         failure : AjaxObject.handleFailure,
7888         timeout : AjaxObject.timeout,
7889         scope   : AjaxObject
7890 };
7891 var callbackQuickCreate = {
7892         success : AjaxObject.detailView.showQuickCreateForm,
7893         failure : AjaxObject.handleFailure,
7894         timeout : AjaxObject.timeout,
7895         scope   : AjaxObject
7896 };
7897 var callbackQuickCreateSave = {
7898         success : AjaxObject.detailView.saveQuickCreateForm,
7899         failure : AjaxObject.handleFailure,
7900         timeout : AjaxObject.timeout,
7901         scope   : AjaxObject
7902 };
7903 var callbackQuickCreateSaveAndAddToAddressBook = {
7904         success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7905         failure : AjaxObject.handleFailure,
7906         timeout : AjaxObject.timeout,
7907         scope   : AjaxObject
7908 };
7909 var callbackQuickCreateSaveAndReply = {
7910     success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7911     failure : AjaxObject.handleFailure,
7912     timeout : AjaxObject.timeout,
7913     scope   : AjaxObject
7914 }
7915 var callbackQuickCreateSaveAndReplyCase = {
7916     success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7917     failure : AjaxObject.handleFailure,
7918     timeout : AjaxObject.timeout,
7919     scope   : AjaxObject
7920 }
7921 var callbackRebuildShowAccountList = {
7922         success : AjaxObject.rebuildShowFolders,
7923         failure : AjaxObject.handleFailure,
7924         timeout : AjaxObject.timeout,
7925         scope   : AjaxObject
7926 };
7927
7928 var callbackRefreshSugarFolders = {
7929         success : function(o) {
7930                 var t = JSON.parse(o.responseText);
7931                 SUGAR.email2.folders.setSugarFoldersEnd(t);
7932         },
7933         failure : AjaxObject.handleFailure,
7934         timeout : AjaxObject.timeout,
7935         scope   : AjaxObject
7936 };
7937 var callbackReplyForward = {
7938         success : AjaxObject.handleReplyForward,
7939         finish : function(a, retryCount) {
7940                 if (typeof(retryCount) == 'undefined') {
7941                         retryCount = 0;
7942                 } else {
7943                         retryCount++;
7944                 }
7945                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7946                 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7947         try {
7948                         var html = t.getContent();
7949
7950             if (a.type != 'draft') {
7951                         if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7952                                 html += "&nbsp;<div><hr></div>" + a.description;
7953                         } else {
7954                                 html =  "&nbsp;<div><hr></div>" + a.description + html;
7955                         }
7956             }else {
7957                 html = a.description;
7958             }
7959
7960                         t.setContent(html);//
7961
7962                 } catch(e) {
7963                         if (retryCount < 5) {
7964                                 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7965                                 return;
7966                         }
7967                 }
7968                 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7969                 if (tabArray != null && tabArray.length > 0) {
7970                         for (i = 0 ; i < tabArray.length ; i++) {
7971                                 var tabObject = tabArray[i];
7972                                 if (tabObject.get("id") == ("composeTab" + idx)) {
7973                                         var tabLabel = a.name;
7974                                 if (tabLabel != null && tabLabel.length > 25) {
7975                                         tabLabel = tabLabel.substring(0, 25) + "...";
7976                                 } // if
7977                                         tabObject.get("labelEl").firstChild.data = tabLabel;
7978                                         break;
7979                                 }
7980                         }
7981                 }
7982                 
7983                 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
7984                 if (a.parent_name != null && a.parent_name != "") {
7985                         document.getElementById('data_parent_name' + idx).value = a.parent_name;
7986                 }
7987                 if (a.parent_type != null && a.parent_type != "") {
7988                         document.getElementById('data_parent_type' + idx).value = a.parent_type;
7989                 }
7990                 if (a.parent_id != null && a.parent_id != "") {
7991                         document.getElementById('data_parent_id' + idx).value = a.parent_id;
7992                 }
7993                 if (a.fromAccounts.status) {
7994                         var addressFrom = document.getElementById('addressFrom' + idx);
7995                 SUGAR.email2.util.emptySelectOptions(addressFrom);
7996                 var fromAccountOpts = a.fromAccounts.data;
7997                 for(i=0; i<fromAccountOpts.length; i++) {
7998                       var key = fromAccountOpts[i].value;
7999                       var display = fromAccountOpts[i].text;
8000                       var opt = new Option(display, key);
8001                       if (fromAccountOpts[i].selected) {
8002                         opt.selected = true;
8003                       }
8004                       addressFrom.options.add(opt);
8005                 }                       
8006                 } // if
8007                 hideOverlay();
8008
8009         },
8010         failure : AjaxObject.handleFailure,
8011         timeout : AjaxObject.timeout,
8012         scope   : AjaxObject,
8013         argument        : [sendType]
8014 };
8015 var callbackSendEmail = {
8016         success : AjaxObject.sendEmailCleanUp,
8017         failure : AjaxObject.handleFailure,
8018         timeout : AjaxObject.timeout,
8019         scope   : AjaxObject
8020 };
8021 var callbackSettings = {
8022         success : AjaxObject.updateUserPrefs,
8023         failure : AjaxObject.handleFailure,
8024         timeout : AjaxObject.timeout,
8025         scope   : AjaxObject
8026 };
8027 var callbackSettingsFolderRefresh = {
8028         success : AjaxObject.settingsFolderRefresh,
8029         failure : AjaxObject.handleFailure,
8030         timeout : AjaxObject.timeout,
8031         scope   : AjaxObject
8032 };
8033 var callbackLoadSettingFolder = {
8034         success : function(o) {
8035                 AjaxObject.settingsFolderRefresh(o);
8036                 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8037         },
8038         failure : AjaxObject.handleFailure,
8039         timeout : AjaxObject.timeout,
8040         scope   : AjaxObject
8041
8042 };
8043 var callbackUploadAttachment = {
8044         success : AjaxObject.uploadAttachmentSuccessful,
8045         upload  : AjaxObject.uploadAttachmentSuccessful,
8046         failure : AjaxObject.handleFailure,
8047         timeout : AjaxObject.timeout,
8048         scope   : AjaxObject
8049 };
8050 var callbackUserPrefs = {
8051         success : function(o) {
8052                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8053         },
8054         failure : AjaxObject.handleFailure,
8055         timeout : AjaxObject.timeout,
8056         scope   : AjaxObject
8057 };
8058
8059 var callbackContextmenus = {
8060         markUnread : {
8061                 success : AjaxObject.markEmailCleanup,
8062                 failure : AjaxObject.handleFailure,
8063                 timeout : AjaxObject.timeout,
8064                 scope   : AjaxObject
8065         }
8066 };
8067
8068 var callbackCheckEmail2 = {
8069         success : function(o) {
8070                 var ret = JSON.parse(o.responseText);
8071                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8072
8073
8074         },
8075         failure : AjaxObject.handleFailure,
8076         timeout : AjaxObject.timeout,
8077         scope   : AjaxObject
8078 }// End of File modules/Emails/javascript/ajax.js
8079                                 
8080 /*********************************************************************************
8081  * SugarCRM is a customer relationship management program developed by
8082  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8083  * 
8084  * This program is free software; you can redistribute it and/or modify it under
8085  * the terms of the GNU Affero General Public License version 3 as published by the
8086  * Free Software Foundation with the addition of the following permission added
8087  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8088  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8089  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8090  * 
8091  * This program is distributed in the hope that it will be useful, but WITHOUT
8092  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8093  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8094  * details.
8095  * 
8096  * You should have received a copy of the GNU Affero General Public License along with
8097  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8098  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8099  * 02110-1301 USA.
8100  * 
8101  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8102  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8103  * 
8104  * The interactive user interfaces in modified source and object code versions
8105  * of this program must display Appropriate Legal Notices, as required under
8106  * Section 5 of the GNU Affero General Public License version 3.
8107  * 
8108  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8109  * these Appropriate Legal Notices must retain the display of the "Powered by
8110  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8111  * technical reasons, the Appropriate Legal Notices must display the words
8112  * "Powered by SugarCRM".
8113  ********************************************************************************/
8114
8115 function gridInit() {
8116         if(SUGAR.email2.grid) {
8117                 SUGAR.email2.grid.destroy();
8118         }
8119         
8120         e2Grid = {
8121                 init : function() {
8122                 
8123                         var Ck = YAHOO.util.Cookie;
8124                         var widths = [ 10, 10, 150, 250, 175, 125 ];
8125
8126                         if (Ck.get("EmailGridWidths")) {
8127                                 for (var i=0; i < widths.length; i++) {
8128                                         widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8129                                 }
8130                         } else {
8131                                 for (var i=0; i < widths.length; i++) {
8132                                         Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8133                                 }
8134                         }
8135                         
8136                         // changes "F" to an icon
8137                         function flaggedIcon(cell, record, column, value) {
8138                                 if(value != "") {
8139                                         cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8140                                 }
8141                         }
8142                         // changes "A" to replied icon
8143                         function repliedIcon(cell, record, column, value) {
8144                                 if(value != "") {
8145                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8146                                 }
8147                         }
8148                 function attachIcon(cell, record, column, value) {
8149                                 if(value == "1") {
8150                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8151                                 }
8152                         }
8153
8154                         var colModel = 
8155                                 [
8156                                         {
8157                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>", 
8158                                                 width: 10, 
8159                                                 sortable: false, 
8160                                                 fixed: true,
8161                                                 resizeable: true,
8162                                                 formatter: attachIcon,
8163                                                 key: 'hasAttach'
8164                                         }, 
8165                                     {
8166                                                 label: "<span style='color: #f00; font-weight:bold;'>!</span>", 
8167                                                 width: widths[0], 
8168                                                 sortable: true, 
8169                                                 fixed: true,
8170                                                 resizeable: true,
8171                                                 formatter: flaggedIcon,
8172                                                 key: 'flagged'
8173                                         }, 
8174                                         {
8175                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>", 
8176                                                 width: widths[1], 
8177                                                 sortable: true, 
8178                                                 fixed: true,
8179                                                 resizeable: true,
8180                                                 formatter: repliedIcon,
8181                                                 key: 'status'
8182                                         },
8183                                         {
8184                                                 label: app_strings.LBL_EMAIL_FROM, 
8185                                                 width: widths[2],
8186                                                 sortable: true,
8187                                                 resizeable: true,
8188                                                 key: 'from'
8189                                         }, 
8190                                         {
8191                                                 label: app_strings.LBL_EMAIL_SUBJECT,
8192                                                 width: widths[3], 
8193                                                 sortable: true,
8194                                                 resizeable: true,
8195                                                 key: 'subject'
8196                                         }, 
8197                                         {
8198                                                 label: mod_strings.LBL_LIST_DATE,
8199                                                 width: widths[4], 
8200                                                 sortable: true,
8201                                                 resizeable: true,
8202                         key: 'date'
8203                                         }, 
8204                                         {
8205                                                 label: app_strings.LBL_EMAIL_TO,
8206                                                 width: widths[5], 
8207                                                 sortable: false,
8208                                                 resizeable: true,
8209                         key: 'to_addrs'
8210                                         }, 
8211                                         {
8212                                                 label: 'uid',
8213                                                 hidden: true,
8214                         key: 'uid'
8215                                         }, 
8216                                         {
8217                                                 label: 'mbox',
8218                                                 hidden: true,
8219                         key: 'mbox'
8220                                         }, 
8221                                         {
8222                                                 label: 'ieId',
8223                                                 hidden: true,
8224                         key: 'ieId'
8225                                         }, 
8226                                         {       
8227                                                 label: 'site_url',
8228                                                 hidden: true,
8229                         key: 'site_url'
8230                                         },
8231                                         {       label: 'seen',
8232                                                 hidden: true,
8233                         key: 'seen'
8234                                         },
8235                                         {       label: 'type',
8236                                                 hidden: true,
8237                         key: 'type'
8238                                         }
8239                                 ];
8240                         
8241                         var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8242                                 responseType: YAHOO.util.DataSource.TYPE_JSON,
8243                                 responseSchema: {
8244                                     resultsList: 'Email',
8245                             fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8246                             metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8247                                 }
8248                     });
8249                         var params = {
8250                                         to_pdf : "true",
8251                                         module : "Emails",
8252                                         action : "EmailUIAjax",
8253                                         emailUIAction : "getMessageList",
8254                                         mbox : "INBOX",
8255                                         ieId : "",
8256                                         forceRefresh : "false"
8257                         };
8258                         if(lazyLoadFolder != null) {
8259                                 params['mbox'] = lazyLoadFolder.folder;
8260                                 params['ieId'] = lazyLoadFolder.ieId;
8261                                 //Check if the folder is a Sugar Folder
8262                                 var test = new String(lazyLoadFolder.folder);
8263                                 if(test.match(/SUGAR\./)) {
8264                                         params['emailUIAction'] = 'getMessageListSugarFolders';
8265                                         params['mbox'] = test.substr(6);
8266                                 }
8267                         }
8268                         //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8269         
8270                         // create the Grid
8271                         var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8272                                 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8273                                 dynamicData: true,
8274                                 paginator: new YAHOO.widget.Paginator({ 
8275                                         rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),  
8276                                         containers : ["dt-pag-nav"],
8277                                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8278                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8279                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8280                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8281                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8282                                 }),
8283                                 initialRequest:SUGAR.util.paramsToUrl(params),
8284                                 width:  "800px",
8285                                 height: "400px"
8286                         });
8287
8288                         initRowDD();
8289
8290                         //Override Paging request construction
8291                         grid.set("generateRequest", function(oState, oSelf) {
8292                     oState = oState || {pagination:null, sortedBy:null};
8293                     var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8294                     var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8295                     var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8296                     var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8297                     // Build the request 
8298                     var ret = 
8299                             SUGAR.util.paramsToUrl(oSelf.params) + 
8300                             "&sort=" + sort +
8301                         "&dir=" + dir +
8302                         "&start=" + startIndex +
8303                         ((results !== null) ? "&limit=" + results : "");
8304                     return  ret;
8305                 });
8306                         
8307                         
8308                         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8309                                 oPayload = oPayload || { };
8310                                 
8311                                 oPayload.totalRecords = oResponse.meta.total;
8312                                 oPayload.unreadRecords = oResponse.meta.unread;
8313                                 
8314                         var tabObject = SE.innerLayout.get("tabs")[0];
8315                         var mboxTitle = "";
8316                         if (this.params.mbox != null) {
8317                                 mboxTitle = this.params.mbox;
8318                         }
8319                         var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8320                         tabObject.get("labelEl").firstChild.data = tabtext;
8321                         
8322                         if (SE.tree) {
8323                                 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8324                                 if (node) {
8325                                         node.data.unseen = oResponse.meta.unread;
8326                                         SE.accounts.renderTree();
8327                                 }
8328                         }
8329                                 return oPayload; 
8330                         }
8331                         
8332                         var resize = grid.resizeGrid = function () {
8333                                 SUGAR.email2.grid.set("width",  SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8334                                 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8335                         }
8336                         grid.convertDDRows = function() {
8337                                 var rowEl = this.getFirstTrEl();
8338                                 while (rowEl != null) {
8339                                         new this.DDRow(this, this.getRecord(rowEl), rowEl);
8340                                         rowEl = this.getNextTrEl(rowEl);
8341                                 }
8342                         }
8343                         
8344                         
8345                         grid.on("columnResizeEvent", function(o) {
8346                                 //Find the index of the column
8347                                 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8348                                 for (var i=0; i < colSet.length; i++) {
8349                                         if (o.column == colSet[i]) {
8350                                                 //Store it in the cookie
8351                                                 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8352                                         }
8353                                 }
8354                                 //this.resizeGrid();
8355                         }, null, grid); 
8356                         
8357                         grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8358                         grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);  
8359                         grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);  
8360                         grid.render();
8361                         SUGAR.email2.listViewLayout.on("render", resize);
8362                         resize();
8363                         
8364                         //Setup the default load parameters
8365                         SUGAR.email2.grid.params = params;
8366                         
8367                         grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8368                         dataModel.subscribe("requestEvent", grid.disable, grid, true);
8369                         dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8370                 }
8371         };
8372         e2Grid.init();
8373 };
8374
8375
8376 function initRowDD() {
8377         var sg = SUGAR.email2.grid,
8378         Dom = YAHOO.util.Dom;
8379         sg.DDRow = function(oDataTable, oRecord, elTr) {
8380                 if(oDataTable && oRecord && elTr) {
8381                         this.ddtable = oDataTable;
8382                 this.table = oDataTable.getTableEl();
8383                 this.row = oRecord;
8384                 this.rowEl = elTr;
8385                 this.newIndex = null;
8386                 this.init(elTr);
8387                 this.initFrame(); // Needed for DDProxy
8388                 this.invalidHandleTypes = {};
8389             }   
8390         };
8391         
8392         YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8393             _resizeProxy: function() {
8394                 this.constructor.superclass._resizeProxy.apply(this, arguments);
8395                 var dragEl = this.getDragEl(),
8396                     el = this.getEl();
8397                 var xy = Dom.getXY(el);
8398                 
8399                 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8400                 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8401                 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8402                 Dom.setStyle(dragEl, 'display', "");
8403             },
8404             
8405             startDrag: function(x, y) { 
8406                 //Check if we should be dragging a set of rows rather than just the one.
8407                 var selectedRows = this.ddtable.getSelectedRows();
8408                 var iSelected = false;
8409                 for (var i in selectedRows) {
8410                         if (this.rowEl.id == selectedRows[i]) {
8411                                 iSelected = true;
8412                                 break
8413                         }
8414                 }
8415                 if (iSelected) {
8416                         this.rows = [];
8417                         for (var i in selectedRows) {
8418                                 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8419                         }
8420                 } else {
8421                         this.rows = [this.row];
8422                         this.ddtable.unselectAllRows();
8423                         this.ddtable.selectRow(this.row);
8424                 }
8425                 
8426                 //Initialize the dragable proxy
8427                 var dragEl = this.getDragEl(); 
8428                 var clickEl = this.getEl(); 
8429                 Dom.setStyle(clickEl, "opacity", "0.25"); 
8430                 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>"; 
8431                 Dom.addClass(dragEl, "yui-dt-liner");
8432                 Dom.setStyle(dragEl, "opacity", "0.5"); 
8433                 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8434                 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); 
8435                     Dom.setStyle(dragEl, "border", "2px solid gray"); 
8436             },
8437             
8438             clickValidator: function(e) {
8439                 if (this.row.getData()[0] == " ")
8440                         return false;
8441                 var target = YAHOO.util.Event.getTarget(e);
8442                 return ( this.isValidHandleChild(target) && 
8443                                 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8444             },
8445             /**
8446              * This funciton checks that the target of the drag is a table row in this
8447              * DDGroup and simply moves the sourceEL to that location as a preview.
8448              */
8449             onDragOver: function(ev, id) {
8450                 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8451                 if (node && node != this.targetNode) {
8452                         this.targetNode = node;
8453                         SUGAR.email2.folders.unhighliteAll();
8454                         node.highlight();
8455                 }
8456             },
8457             
8458             onDragOut: function(e, id) {
8459                 if (this.targetNode) {
8460                         SUGAR.email2.folders.unhighliteAll();
8461                         this.targetNode = false;
8462                 }
8463             },
8464             endDrag: function() {
8465                 Dom.setStyle(this.getEl(), "opacity", "");
8466                 Dom.setStyle(this.getDragEl(), "display", "none"); 
8467                 if (this.targetNode) {
8468                         SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8469                 }
8470                 SUGAR.email2.folders.unhighliteAll();
8471                 this.rows = null;
8472             }
8473         });
8474 }
8475
8476 function AddressSearchGridInit() {
8477     function moduleIcon(elCell, oRecord, oColumn, oData) {
8478         elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8479     };
8480     function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8481         elCell.innerHTML =  '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8482     };
8483     var checkHeader = '<input type="checkbox" ';
8484     if (SUGAR.email2.util.isIe()) {
8485         checkHeader += 'style="top:-5px" ';
8486     }
8487     checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8488     var colModel = 
8489             [{
8490                 label: checkHeader,
8491             width: 30,
8492             formatter: selectionCheckBox,
8493             key: 'bean_id'
8494         },
8495             {
8496                 label: mod_strings.LBL_LIST_TYPE,
8497                 width: 25,
8498                 formatter: moduleIcon,
8499                 key: 'bean_module'
8500         },
8501             {
8502                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME, 
8503                 width: 180,
8504                 sortable: true,
8505                 key: 'name'
8506             }, 
8507             {
8508                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8509                 width: 300, 
8510                 sortable: true,
8511                 key: 'email'
8512             }];
8513     
8514     var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8515                 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8516         responseSchema: {
8517             resultsList: 'Person',
8518             fields: ['name', 'email', 'bean_id', 'bean_module'],
8519                     metaFields: {total: 'TotalCount'}
8520         },
8521         //enable sorting on the server accross all data
8522         remoteSort: true
8523     });
8524     dataModel.params = {
8525                 to_pdf          : true,
8526                 module          : "Emails",
8527                 action          : "EmailUIAjax",
8528                 emailUIAction:"getAddressSearchResults"
8529     }
8530     var rb = document.getElementById('hasRelatedBean').checked;
8531         if (rb) {
8532                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8533                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8534                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8535                 dataModel.params['related_bean_id'] = relatedBeanId;
8536                 dataModel.params['related_bean_type'] = relatedBeanType;
8537                 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8538         }
8539     SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8540     
8541     var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8542         MSG_EMPTY: "&nbsp;", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8543                 dynamicData: true,
8544                 paginator: new YAHOO.widget.Paginator({ 
8545                         rowsPerPage: 25,  
8546                         containers : ["dt-pag-nav-addressbook"],
8547                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8548                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8549                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8550                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8551                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8552                 }),
8553                 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8554                 width:  "560px",
8555                 height: "250px"
8556     });
8557         //Override Paging request construction
8558         grid.set("generateRequest", function(oState, oSelf) {
8559         oState = oState || {pagination:null, sortedBy:null};
8560         var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8561         var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8562         var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8563         var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8564         // Build the request 
8565         var ret = 
8566             SUGAR.util.paramsToUrl(oSelf.getDataSource().params) + 
8567             "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8568             ((results !== null) ? "&limit=" + results : "");
8569         return  ret;
8570     });
8571     
8572         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8573                 oPayload = oPayload || { };
8574                 oPayload.totalRecords = oResponse.meta.total;
8575                 return oPayload; 
8576         }
8577         
8578         grid.clickToggleSelect= function(args) {
8579                 var isIE = (args.event.target == null);
8580                 var targetElement = isIE ? args.event.srcElement : args.event.target;
8581                 if(targetElement.type == null || targetElement.type != 'checkbox') {
8582                         SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8583                 }
8584         }
8585         
8586         grid.reSelectRowsOnRender = function (){
8587             var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8588         for (var i = 0; i < rows.length; i++) 
8589         {
8590                 var emailAddress = rows[i].getData("email");
8591             var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8592             if(alreadyAdded)
8593             {
8594                 rows[i].setData("selected",  true);
8595                         SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8596             }
8597             else
8598             {
8599                 rows[i].setData("selected",  false);
8600                 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8601             }
8602         }
8603         }
8604         grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow); 
8605         grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow); 
8606         grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8607     grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8608     
8609     grid.render();
8610     dataModel.subscribe("requestEvent", grid.disable, grid, true);
8611     dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8612     
8613     grid.toggleSelectCheckbox = function(id,checked){
8614         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8615         row.setData("checked",checked);
8616     };
8617     grid.toggleSelect = function(id, checked) {
8618         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8619         checked = row.getData("selected");
8620         if (!checked)
8621         {
8622             SUGAR.email2.addressBook.grid.selectRow(row);
8623             SE.addressBook.insertContactRowToResultTable(id,null)
8624         } else 
8625         {
8626             SUGAR.email2.addressBook.grid.unselectRow(row);
8627             SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8628         }
8629         row.setData("selected", !checked);
8630     };
8631     
8632     grid.toggleSelectAll = function(checked) {
8633         rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8634         for (var i = 0; i < rows.length; i++) {
8635                         if (typeof(rows[i]) != "undefined")
8636                                 rows[i].setData("checked",  checked);
8637         }
8638         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8639         for (var i = 0; i < checkBoxes.length; i++) {
8640             checkBoxes[i].checked = checked;
8641         }
8642     };
8643     
8644     //Initialize the grid result table.
8645     AddressSearchResultsGridInit();
8646 }
8647
8648
8649
8650 /**
8651 *  Initalize the results table for the address book selection.
8652 *
8653 */
8654 function AddressSearchResultsGridInit()
8655 {
8656     
8657     /* Full name sort funciton to compare by last name if available */
8658     var fullNameSort = function(a, b, desc) {
8659         // Deal with empty values
8660         if(!YAHOO.lang.isValue(a))
8661             return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8662         else if(!YAHOO.lang.isValue(b))
8663             return -1;
8664
8665         var aNames = a.getData("name").split(' ');
8666         var bNames = b.getData("name").split(' ');
8667
8668         var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8669         var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8670
8671         return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8672
8673     };
8674     
8675     var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8676                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8677                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')]; 
8678               
8679     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})},
8680                      {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8681      
8682      var myDataSource = new YAHOO.util.DataSource([]); 
8683          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
8684          myDataSource.responseSchema = { 
8685                     fields: ["name","type","email_address","display_email_address","bean_id","idx"] 
8686                 };                                                                 
8687     
8688          var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8689                         width:  "350px",height: "250px", MSG_EMPTY: "&nbsp;"});
8690     
8691      var highlightEditableCell = function(oArgs) {
8692             var elCell = oArgs.target;
8693             if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8694                 this.highlightCell(elCell);
8695             }
8696         };
8697       
8698      gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8699      gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8700      gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8701      gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow); 
8702          gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow); 
8703      
8704      //Setup the context menus
8705      var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) { 
8706              var task = p_aArgs[1]; 
8707              if(task) 
8708              { 
8709                  var elRow = this.contextEventTarget; 
8710                  elRow = p_myDataTable.getTrEl(elRow); 
8711          
8712                  if(elRow) 
8713                  { 
8714                      switch(task.index) 
8715                      { 
8716                          case 0:     
8717                              var oRecord = p_myDataTable.getRecord(elRow); 
8718                              p_myDataTable.deleteRow(elRow);  
8719                              SUGAR.email2.addressBook.grid.reSelectRowsOnRender();    
8720                      } 
8721                  } 
8722              } 
8723          };
8724      var contextMenu = new YAHOO.widget.ContextMenu("contextmenu", 
8725                         {trigger:gridResults.getTbodyEl()}); 
8726          contextMenu.addItem(app_strings.LBL_EMAIL_DELETE); 
8727          contextMenu.render("addrSearchResultGrid"); 
8728          contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults); 
8729 }
8730 // End of File modules/Emails/javascript/grid.js
8731                                 
8732 /*********************************************************************************
8733  * SugarCRM is a customer relationship management program developed by
8734  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8735  * 
8736  * This program is free software; you can redistribute it and/or modify it under
8737  * the terms of the GNU Affero General Public License version 3 as published by the
8738  * Free Software Foundation with the addition of the following permission added
8739  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8740  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8741  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8742  * 
8743  * This program is distributed in the hope that it will be useful, but WITHOUT
8744  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8745  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8746  * details.
8747  * 
8748  * You should have received a copy of the GNU Affero General Public License along with
8749  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8750  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8751  * 02110-1301 USA.
8752  * 
8753  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8754  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8755  * 
8756  * The interactive user interfaces in modified source and object code versions
8757  * of this program must display Appropriate Legal Notices, as required under
8758  * Section 5 of the GNU Affero General Public License version 3.
8759  * 
8760  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8761  * these Appropriate Legal Notices must retain the display of the "Powered by
8762  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8763  * technical reasons, the Appropriate Legal Notices must display the words
8764  * "Powered by SugarCRM".
8765  ********************************************************************************/
8766
8767 /**
8768   Complex layout init
8769  */
8770 function complexLayoutInit() {
8771         var se = SUGAR.email2;
8772         var Dom = YAHOO.util.Dom;
8773         se.e2Layout = {
8774         getInnerLayout : function(rows) {
8775                 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8776                 parent: se.complexLayout,  
8777                         border:true,
8778                     hideOnLayout: true,
8779                     height: 400,
8780                                 units: [{
8781                                         position: "center",
8782                                     scroll:false, // grid should autoScroll itself
8783                                     split:true,
8784                                     body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8785                                 },{
8786                                         position: "bottom",
8787                                     scroll:true,
8788                                     collapse: false,
8789                                     resize: true,
8790                                     useShim:true,
8791                                     height:'250',
8792                                     body: "<div id='listBottom' />"
8793                                 },{
8794                                     position: "right",
8795                                     scroll:true,
8796                                     collapse: false,
8797                                     resize: true,
8798                                     useShim:true,
8799                                     width:'250',
8800                                     body: "<div id='listRight' />",
8801                                     titlebar: false //,header: "right"
8802                                 }]
8803             });
8804                 se.complexLayout.on("render", function(){
8805                         var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8806                                 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8807                                 SUGAR.email2.listViewLayout.set("height", height);
8808                                 SUGAR.email2.listViewLayout.render();
8809                 });
8810             se.listViewLayout.render();
8811             //CSS hack for now
8812             se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8813             var rp = se.listViewLayout.resizePreview = function() {
8814                 var pre = Dom.get("displayEmailFramePreview");
8815                 if (pre) {
8816                         var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8817                         pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8818                 }
8819             };
8820             se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8821             se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8822             se.e2Layout.setPreviewPanel(rows);
8823             se.previewLayout = se.listViewLayout;
8824             return se.listViewLayout;
8825         },
8826         
8827         getInnerLayout2Rows : function() {
8828             return this.getInnerLayout(true);
8829         },
8830         getInnerLayout2Columns : function() {
8831             return this.getInnerLayout(false);
8832         },
8833         
8834         init : function(){
8835             // initialize state manager, we will use cookies
8836 //                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8837                 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8838                 se.complexLayout = new YAHOO.widget.Layout("container", {
8839                         border:true,
8840                 hideOnLayout: true,
8841                 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8842                 width: Dom.getViewportWidth() - 40,
8843                 units: [{
8844                         position: "center",
8845                     scroll:false,
8846                     body: "<div id='emailtabs'></div>"
8847                 },
8848                 {
8849                         position: "left",
8850                         scroll: true,
8851                         body: "<div id='lefttabs'></div>",
8852                     collapse: true,
8853                     width: 210,
8854                     minWidth: 100,
8855                     resize:true,
8856                     useShim:true,
8857                     titlebar: true,
8858                     header: "&nbsp;"
8859                 },
8860                 {
8861                     header: Dom.get('footerLinks').innerHTML,
8862                                         position: 'bottom',
8863                                         id: 'mbfooter',
8864                                         height: 22,
8865                                         border: false
8866                 }]
8867             });
8868                 se.complexLayout.render();
8869                 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8870                         tp.addTab(new YAHOO.widget.Tab({ 
8871                                 label: "Inbox",
8872                                 scroll : true,
8873                                 content : "<div id='listViewDiv'/>",
8874                                 id : "center",
8875                                 active : true
8876                         }));
8877                 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8878                         tp.appendTo(centerEl);
8879                         //CSS hack for now
8880                         tp.get("element").style.borderRight = "1px solid #666"
8881                         
8882                         var listV =  this.getInnerLayout2Rows();
8883                         listV.set("height", tp.get("element").clientHeight - 25);
8884                         listV.render();
8885                 
8886             se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8887             var folderTab = new YAHOO.widget.Tab({ 
8888                                 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8889                                 scroll : true,
8890                                 content : "<div id='emailtree'/>",
8891                                 id : "tree",
8892                                 active : true
8893                         });
8894             folderTab.on("activeChange", function(o){ 
8895                 if (o.newValue) {
8896                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8897                 }
8898             });
8899             se.leftTabs.addTab(folderTab);
8900             
8901             var tabContent = SUGAR.util.getAndRemove("searchTab");
8902             var searchTab = new YAHOO.widget.Tab({ 
8903                                 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8904                                 scroll : true,
8905                                 content : tabContent.innerHTML,
8906                                 id : tabContent.id
8907                         });
8908             searchTab.on("activeChange", function(o){ 
8909                 if (o.newValue) 
8910                 {
8911                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8912                    //Setup the calendars if needed
8913                        Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_from", singleClick : true, step : 1, weekNumbers:false});
8914                        Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_to", singleClick : true, step : 1, weekNumbers:false});
8915                    
8916                        //Initalize sqs object for assigned user name 
8917                        se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');  
8918                        
8919                        //Attach event handler for when the relate module option is selected for the correct sqs object
8920                        var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8921                                                 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8922                        YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){ 
8923                            SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8924                        
8925                        //If enter key is pressed, perform search
8926                        var  addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8927                        for(var i=0; i < addKeyPressFields.length;i++)
8928                        {
8929                        YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8930                                 if (e.keyCode == 13) {
8931                                         YAHOO.util.Event.stopEvent(e);
8932                                         SUGAR.email2.search.searchAdvanced();
8933                                 }
8934                        });
8935                        }
8936                                    //Initiate quick search for the search tab.  Do this only when the tab is selected rather than onDomLoad for perf. gains.
8937                        enableQS(true);
8938                        //Clear parent values if selecting another parent type.
8939                        YAHOO.util.Event.addListener('data_parent_type_search','change', 
8940                            function(){ 
8941                                document.getElementById('data_parent_id_search').value =''; 
8942                                document.getElementById('data_parent_name_search').value =''; 
8943                            });
8944                 
8945                 }
8946             });
8947             se.leftTabs.addTab(searchTab);
8948             
8949             var resizeTabBody = function() {
8950                 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8951                                 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8952             }
8953             resizeTabBody();
8954             se.complexLayout.on("render", resizeTabBody);
8955             se.leftTabs.on("activeTabChange", resizeTabBody);
8956                         //hack to allow left pane scroll bar to fully show
8957                 var lefttabsDiv = document.getElementById('lefttabs');
8958                         var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8959                         var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8960                         lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8961           
8962         },
8963         initSQSObject: function(formName,fieldName)
8964         {
8965             var fullFieldName = formName + '_' + fieldName; //SQS Convention
8966             var resultName = fullFieldName + '_' + 'results';
8967             
8968             if (QSFieldsArray[fullFieldName] != null) 
8969             {
8970                 QSFieldsArray[fullFieldName].destroy();
8971                 delete QSFieldsArray[fullFieldName];
8972             }
8973             if (QSProcessedFieldsArray[fullFieldName])
8974             QSProcessedFieldsArray[fullFieldName] = false;
8975
8976             if( Dom.get(resultName) )
8977             {
8978                 var obj = document.getElementById(resultName);
8979                 obj.parentNode.removeChild(obj);
8980             }
8981         },
8982         setPreviewPanel: function(rows) {
8983                 if (rows) {
8984                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
8985                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
8986                 Dom.get("listRight").innerHTML = "";
8987                 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
8988             } else {
8989                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
8990                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
8991                 Dom.get("listBottom").innerHTML = "";
8992                 Dom.get("listRight").innerHTML = "<div id='_blank' />";
8993             }
8994         }
8995     };
8996         se.e2Layout.init();
8997 }
8998
8999 var myBufferedListenerObject = new Object();
9000 myBufferedListenerObject.refit = function() {
9001     if(SUGAR.email2.grid) {
9002         SUGAR.email2.grid.autoSize();
9003     }
9004 }
9005 // End of File modules/Emails/javascript/complexLayout.js
9006                                 
9007 /*********************************************************************************
9008  * SugarCRM is a customer relationship management program developed by
9009  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9010  * 
9011  * This program is free software; you can redistribute it and/or modify it under
9012  * the terms of the GNU Affero General Public License version 3 as published by the
9013  * Free Software Foundation with the addition of the following permission added
9014  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9015  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9016  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9017  * 
9018  * This program is distributed in the hope that it will be useful, but WITHOUT
9019  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9020  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9021  * details.
9022  * 
9023  * You should have received a copy of the GNU Affero General Public License along with
9024  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9025  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9026  * 02110-1301 USA.
9027  * 
9028  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9029  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9030  * 
9031  * The interactive user interfaces in modified source and object code versions
9032  * of this program must display Appropriate Legal Notices, as required under
9033  * Section 5 of the GNU Affero General Public License version 3.
9034  * 
9035  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9036  * these Appropriate Legal Notices must retain the display of the "Powered by
9037  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9038  * technical reasons, the Appropriate Legal Notices must display the words
9039  * "Powered by SugarCRM".
9040  ********************************************************************************/
9041
9042
9043 /******************************************************************************
9044  * Initialize Email 2.0 Application
9045  */
9046
9047 //Override Sugar Languge so quick creates work properly
9048
9049
9050 function email2init() {
9051
9052         //Init Tiny MCE
9053     // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9054     //             "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9055     if (!SUGAR.util.isTouchScreen()) {
9056          tinyMCE.init({
9057                  convert_urls : false,
9058          theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9059          width: tinyConfig.width,
9060          theme: tinyConfig.theme,
9061          theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9062          theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9063          theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9064          theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9065          plugins : tinyConfig.plugins,
9066          elements : tinyConfig.elements,
9067          language : tinyConfig.language,
9068          extended_valid_elements : tinyConfig.extended_valid_elements,
9069          mode: tinyConfig.mode,
9070          strict_loading_mode : true,
9071                  force_br_newlines : true,
9072          forced_root_block : ''
9073      });
9074     }
9075          //alert('loadedTiny');
9076
9077     // initialze message overlay
9078     SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9079             //iframe        : true,
9080             modal       : false,
9081             autoTabs    : true,
9082             width       : 300,
9083             height      : 120,
9084             shadow      : true
9085         }
9086     );
9087         // Hide Sugar menu
9088         if (SUGAR.themes.tempHideLeftCol)
9089         SUGAR.themes.tempHideLeftCol();
9090
9091         // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9092 //      YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9093
9094         // set defaults for YAHOO.util.DragDropManager
9095         YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9096
9097         SUGAR.email2.nextYear = new Date();
9098         SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9099
9100         
9101     // initialize and display UI framework (complexLayout.js)
9102     complexLayoutInit();
9103     
9104     // initialize and display grid (grid.js)
9105     gridInit();
9106     
9107     // initialize treeview for folders
9108         //onloadTreeinit();
9109         SUGAR.email2.folders.rebuildFolders(true);
9110         
9111         
9112     //Setup the Message Box overlay
9113     /*Ext.MessageBox.maxWidth = 350;
9114     Ext.MessageBox.minProgressWidth = 350;
9115
9116         ///////////////////////////////////////////////////////////////////////////
9117         ////    CONTEXT MENUS
9118         // detailView array
9119         SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9120 */
9121         var SEC = SUGAR.email2.contextMenus; 
9122         
9123         //Grid menu
9124         var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9125                 trigger: SUGAR.email2.grid.get("element"),
9126                 lazyload: true
9127         });
9128         emailMenu.subscribe("beforeShow", function() {
9129                 var oTarget = this.contextEventTarget;
9130                 if (typeof(oTarget) == "undefined")
9131                   return;
9132                 var grid = SUGAR.email2.grid;
9133                 var selectedRows = grid.getSelectedRows();
9134                 var multipleSelected = (selectedRows.length > 1) ? true: false;
9135                 if (!multipleSelected)
9136                 {
9137                         grid.unselectAllRows();
9138                         grid.selectRow(oTarget);
9139                         SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));    
9140                 }
9141                 else if(multipleSelected)
9142                 {
9143                     SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9144                 }
9145         });
9146         
9147         //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9148         //us to access individual elements easier by name rather than by index
9149         emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2,  'reply' : 3,'replyAll' : 4,'forward' : 5,
9150                                    'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9151         emailMenu.addItems([
9152         {
9153             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9154             id: 'showDetailView',
9155             onclick: { fn: SEC.showDetailView }
9156         },
9157         {
9158             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9159             onclick: { fn: SEC.openMultiple }
9160         },
9161         {
9162             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9163             onclick: { fn: SEC.archiveToSugar }
9164         },
9165         {
9166             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9167             id: 'reply',
9168             onclick: { fn: SEC.replyForwardEmailContext }
9169         },
9170         {
9171             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9172             id: 'replyAll',
9173             onclick: { fn: SEC.replyForwardEmailContext }
9174         },
9175         {
9176             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9177             id: 'forward',
9178             onclick: { fn: SEC.replyForwardEmailContext }
9179         },
9180         {
9181             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9182             id: 'delete',
9183             onclick: { fn: SEC.markDeleted }
9184         },
9185         {
9186             text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9187             id: 'print',
9188             onclick: { fn: SEC.viewPrintable }
9189         },                
9190         // Mark... submenu
9191         {
9192             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9193             submenu: {
9194                         id: "markEmailMenu",
9195                 itemdata : [
9196                     {
9197                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9198                         onclick: { fn: SEC.markUnread }
9199                     },
9200                     {
9201                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9202                         onclick: { fn: SEC.markRead }
9203                     },
9204                     {
9205                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9206                         onclick: { fn: SEC.markFlagged }
9207                     },
9208                     {
9209                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9210                         onclick: {  fn: SEC.markUnflagged }
9211                     }
9212                 ]
9213             }
9214          },
9215         {
9216             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9217                 id: 'assignTo',
9218                 onclick: { fn: SEC.assignEmailsTo }
9219          },
9220          {
9221             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9222             id: 'relateTo',
9223             onclick: { fn: SEC.relateTo }
9224          }
9225     ]);
9226         SEC.emailListContextMenu.render();
9227         
9228         //Handle the Tree folder menu trigger ourselves
9229         YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9230
9231         
9232         //Folder Menu
9233     SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9234                 trigger: "",
9235                 lazyload: true 
9236         });
9237     SEC.frameFoldersContextMenu.addItems([
9238                 {   text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9239                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9240                         onclick: {  fn: function() {
9241                         var node = SUGAR.email2.clickedFolderNode;
9242                         if (node.data.ieId) {
9243                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9244                     }}
9245                 },
9246                 {   text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9247                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9248                         onclick: {  fn: function() {
9249                         var node = SUGAR.email2.clickedFolderNode;
9250                         if (node.data.ieId) {
9251                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9252                     }}
9253                 },
9254                 {
9255                     text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9256                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9257                     onclick: {  fn: SUGAR.email2.folders.folderAdd }
9258                 },
9259                 {
9260                     text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9261                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9262                     onclick: {  fn: SUGAR.email2.folders.folderDelete }
9263                 },
9264                 {
9265                     text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9266                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9267                     onclick: {  fn: SUGAR.email2.folders.folderRename }
9268                  },
9269                  {
9270                     text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9271                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9272                     onclick: {  fn: SUGAR.email2.folders.emptyTrash }
9273                   },
9274                  {
9275                     text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9276                     onclick: {  fn: function() {
9277                         var node = SUGAR.email2.clickedFolderNode;
9278                         if (node.data.ieId) {
9279                             SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9280                     }}
9281                   } 
9282         ]);
9283     SEC.frameFoldersContextMenu.render();
9284     
9285     SEC.initContactsMenu = function() {
9286         // contacts
9287         SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9288                 trigger: "contacts",
9289                 lazyload: true
9290         });
9291         SEC.contactsContextMenu.addItems([
9292                 {
9293                         text: app_strings.LBL_EMAIL_MENU_REMOVE,
9294                         onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9295                 },
9296                 {
9297                         text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9298                         onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9299                 }
9300         ]);
9301         SEC.contactsContextMenu.subscribe("beforeShow", function() {
9302                 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9303                 if (oTarget && !grid.isSelected(oTarget)) {
9304                         grid.unselectAllRows();
9305                         grid.selectRow(oTarget);
9306                 }
9307         });
9308         SEC.contactsContextMenu.render();
9309         }
9310         
9311         
9312         // set auto-check timer
9313         SUGAR.email2.folders.startCheckTimer();
9314         // check if we're coming from an email-link click
9315         setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9316         
9317         YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9318         
9319         //Init fix for YUI 2.7.0 datatable sort.
9320         SUGAR.email2.addressBook.initFixForDatatableSort();
9321 }
9322
9323 function createTreePanel(treeData, params) {
9324         var tree = new YAHOO.widget.TreeView(params.id);
9325         var root = tree.getRoot();
9326         
9327         //if (treeData.nodes && treeData[0].id == "Home")
9328         //      treeData = treeData[0];
9329
9330         addChildNodes(root, treeData);
9331         
9332         return tree;
9333 }
9334
9335 function addChildNodes(parentNode, parentData) {
9336         var Ck = YAHOO.util.Cookie;
9337         var nextyear = SUGAR.email2.nextYear;
9338         var nodes = parentData.nodes || parentData.children;
9339         for (i in nodes) {
9340                 if (typeof(nodes[i]) == 'object') {
9341                         if (nodes[i].data) {
9342                                 nodes[i].data.href = '#';
9343                                 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9344                                 node.action = nodes[i].data.action;
9345                         } else {
9346                                 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9347                                         addChildNodes(parentNode, nodes[i]);
9348                                         return;
9349                                 }
9350                                 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9351                                 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9352                                 if (nodes[i].cls) {
9353                                         nodes[i].className = nodes[i].cls;
9354                                 }
9355                                 nodes[i].href = "#";
9356                                 if (nodes[i].text) nodes[i].label = nodes[i].text;
9357                                 //Override YUI child node creation
9358                                 if (nodes[i].children) {
9359                                         nodes[i].nodes = nodes[i].children;
9360                                         nodes[i].children = [ ];
9361                                 }
9362                                 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9363                         }
9364                         
9365                         if (typeof(nodes[i].nodes) == 'object') {
9366                                 addChildNodes(node, nodes[i]);
9367                         }
9368                 }
9369         }
9370 }
9371
9372 /**
9373  * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9374  */
9375 function email2treeinit(tree, treedata, treediv, params) {
9376         //ensure the tree data is not corrupt
9377         if (!treedata) {
9378            return;
9379         }
9380         if (SUGAR.email2.tree) {
9381                 SUGAR.email2.tree.destroy();
9382                 SUGAR.email2.tree = null;
9383         }
9384         
9385         var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9386                 id: 'emailtree'
9387         });
9388         
9389         tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9390         tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9391         tree.subscribe("expandComplete", function(node){
9392                 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9393                 for (var i in node.children) {
9394                         SE.accounts.setupDDTarget(node.children[i]);
9395                 }
9396         });
9397         tree.setCollapseAnim("TVSlideOut");
9398         tree.setExpandAnim("TVSlideIn");
9399         var root = tree.root;
9400         while (root.hasChildren()) {
9401                 var node = root.children[0];
9402                 node.destroy();
9403                 tree.removeNode(root.children[0], false);
9404         }
9405         addChildNodes(root, treedata);
9406         tree.render();
9407         SUGAR.email2.accounts.renderTree();
9408 }
9409
9410 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9411         SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9412 };
9413
9414
9415 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {    
9416     startDrag: function(x, y) {
9417                 var Dom = YAHOO.util.Dom;       
9418                 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9419                 
9420                 this.dragId = "";
9421                 var dragEl = this.getDragEl();  
9422         var clickEl = this.getEl(); 
9423         Dom.setStyle(clickEl, "color", "#AAA");
9424         Dom.setStyle(clickEl, "opacity", "0.25"); 
9425         dragEl.innerHTML = clickEl.innerHTML; 
9426          
9427         Dom.addClass(dragEl, "ygtvcell");
9428         Dom.addClass(dragEl, "ygtvcontent");
9429         Dom.addClass(dragEl, "folderDragProxy");
9430         Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9431         Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9432         Dom.setStyle(dragEl, "backgroundColor", "#FFF"); 
9433         Dom.setStyle(dragEl, "opacity", "0.5"); 
9434             Dom.setStyle(dragEl, "border", "1px solid #AAA");
9435     },
9436     
9437     onDragOver: function(ev, id) {
9438         var Dom = YAHOO.util.Dom;
9439         if (id != this.dragId)
9440         {
9441                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9442                 if(node.data.cls != "sugarFolder") {
9443                         SUGAR.email2.folders.unhighliteAll();
9444                         return;
9445                 }
9446                 this.dragId = id;
9447                 this.targetNode = node;
9448                 SUGAR.email2.folders.unhighliteAll();
9449                 node.highlight();
9450         }
9451     },
9452     
9453     onDragOut: function(e, id) {
9454         if (this.targetNode) {
9455                 SUGAR.email2.folders.unhighliteAll();
9456                 this.targetNode = false;
9457                 this.dragId = false;
9458         }
9459     },
9460     
9461     endDrag: function() { 
9462         YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9463         if (this.targetNode) {
9464                 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9465         }
9466     }
9467 });// End of File modules/Emails/javascript/init.js
9468                                 
9469 /*********************************************************************************
9470  * SugarCRM is a customer relationship management program developed by
9471  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9472  * 
9473  * This program is free software; you can redistribute it and/or modify it under
9474  * the terms of the GNU Affero General Public License version 3 as published by the
9475  * Free Software Foundation with the addition of the following permission added
9476  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9477  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9478  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9479  * 
9480  * This program is distributed in the hope that it will be useful, but WITHOUT
9481  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9482  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9483  * details.
9484  * 
9485  * You should have received a copy of the GNU Affero General Public License along with
9486  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9487  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9488  * 02110-1301 USA.
9489  * 
9490  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9491  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9492  * 
9493  * The interactive user interfaces in modified source and object code versions
9494  * of this program must display Appropriate Legal Notices, as required under
9495  * Section 5 of the GNU Affero General Public License version 3.
9496  * 
9497  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9498  * these Appropriate Legal Notices must retain the display of the "Powered by
9499  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9500  * technical reasons, the Appropriate Legal Notices must display the words
9501  * "Powered by SugarCRM".
9502  ********************************************************************************/
9503
9504 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9505 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9506 '       <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9507 '               <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9508 '               <input type="hidden" id="uid{idx}" name="uid" value="">' +
9509 '               <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9510 '               <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9511 '               <input type="hidden" id="type{idx}" name="type" value="">' +
9512 '               <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9513 '               <input type="hidden" id="composeType" name="composeType">' +
9514 '               <input type="hidden" id="fromAccount" name="fromAccount">' +
9515 '               <input type="hidden" id="sendSubject" name="sendSubject">' +
9516 '               <input type="hidden" id="sendDescription" name="sendDescription">' +
9517 '               <input type="hidden" id="sendTo" name="sendTo">' +
9518 '               <input type="hidden" id="sendBcc" name="sendBcc">' +
9519 '               <input type="hidden" id="sendCc" name="sendCc">' +
9520 '               <input type="hidden" id="setEditor" name="setEditor">' +
9521 '               <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9522 '               <input type="hidden" id="parent_id" name="parent_id">' +
9523 '               <input type="hidden" id="parent_type" name="parent_type">' +
9524 '               <input type="hidden" id="attachments" name="attachments">' +
9525 '               <input type="hidden" id="documents" name="documents">' +
9526 '               <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9527 '               <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9528 '               <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9529 '               <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9530 '                       <tr>' +
9531 '                               <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9532 '                                       <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>' +
9533 '                                       <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>' +
9534 '                                       <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>' +
9535 '                                       <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>' +
9536 '</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>' + 
9537 '&nbsp;</td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9538 '<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>' +
9539 '                       </td></tr></tbody></table></th>'     +
9540 '                       </tr>' +
9541 '                       <tr>' +
9542 '                               <td>' +
9543 '                                       <div style="margin:5px;">' +
9544 '                                       <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9545 '                                               <tr>' +
9546 '                                                       <td class="emailUILabel" NOWRAP >' +
9547 '                                                               {app_strings.LBL_EMAIL_FROM}:' +
9548 '                                                       </td>' +
9549 '                                                       <td class="emailUIField" NOWRAP>' +
9550 '                                                               <div>' +
9551 '                                                                       &nbsp;&nbsp;<select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9552 '                                                               </div>' +
9553 '                                                       </td>' +
9554 '                                               </tr>' +
9555 '                                               <tr>' +
9556 '                                                       <td class="emailUILabel" NOWRAP>' +
9557 '                                                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' + 
9558 '                                   {app_strings.LBL_EMAIL_TO}:' +
9559 '                               </button>' + 
9560 '                                                       </td>' +
9561 '                                                       <td class="emailUIField" NOWRAP>' +
9562 '                                                               <div class="ac_autocomplete">' +
9563 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9564 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}">&nbsp;</span></a> </span>' +
9565 '                                                                       <div class="ac_container" id="addressToAC{idx}"></div>' +
9566 '                                                               </div>' +
9567 '                                                       </td>' +
9568 '                                               </tr>' +
9569 '                                               <tr id="add_addr_options_tr{idx}">' +
9570 '                                                       <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>'+
9571 '                                               </tr>'+
9572 '                                               <tr class="yui-hidden" id="cc_tr{idx}">' +
9573 '                                                       <td class="emailUILabel" NOWRAP>' +
9574 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' + 
9575 '                                                               {app_strings.LBL_EMAIL_CC}:' +
9576 '                               </button>' + 
9577 '                                                       </td>' +
9578 '                                                       <td class="emailUIField" NOWRAP>' +
9579 '                                                               <div class="ac_autocomplete">' +
9580 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9581 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#"  style="display: none;">+<span id="DetailaddressCC{idx}">&nbsp;</span></a> </span>' + 
9582 '                                                                       <div class="ac_container" id="addressCcAC{idx}"></div>' +
9583 '                                                               </div>' +
9584 '                                                       </td>' +
9585 '                                               </tr>' +
9586 '                                               <tr class="yui-hidden" id="bcc_tr{idx}">' +
9587 '                                                       <td class="emailUILabel" NOWRAP>' +
9588 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' + 
9589 '                               {app_strings.LBL_EMAIL_BCC}:' +
9590 '                               </button>' + 
9591 '                                                       </td>' +
9592 '                                                       <td class="emailUIField" NOWRAP>' +
9593 '                                                               <div class="ac_autocomplete">' +
9594 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9595 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}">&nbsp;</span></a> </span>' +
9596 '                                                                       <div class="ac_container" id="addressBccAC{idx}"></div>' +
9597 '                                                               </div>' +
9598 '                                                       </td>' +
9599 '                                               </tr>' +
9600 '                                               <tr>' +
9601 '                                                       <td class="emailUILabel" NOWRAP width="1%">' +
9602 '                                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9603 '                                                       </td>' +
9604 '                                                       <td class="emailUIField" NOWRAP width="99%">' +
9605 '                                                               <div class="ac_autocomplete">' +
9606 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9607 '                                                               </div>' +
9608 '                                                       </td>' +
9609 '                                               </tr>' +
9610 '                                       </table>' +
9611 '                                       </div>' +
9612 '                               </td>'   +
9613 '                       </tr>' +
9614 '               </table>' +
9615 '               <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9616 '               <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9617 '                       <div style="padding:5px;">' +
9618 '                               <table cellpadding="2" cellspacing="0" border="0">' +
9619 '                                       <tr>' +
9620 '                                               <th>' +
9621 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9622 '                                                       <br />' +
9623 '                                                       &nbsp;' +
9624 '                                               </th>' +
9625 '                                       </tr>' +
9626 '                                       <tr>' +
9627 '                                               <td>' +
9628 '                                                       <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9629 '                                                       <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9630 '                                               </td>' +
9631 '                                       </tr>' +
9632 '                                       <tr>' +
9633 '                                               <td>' +
9634 '                                                       &nbsp;' +
9635 '                                                       <br />' +
9636 '                                                       &nbsp;' +
9637 '                                               </td>' +
9638 '                                       </tr>' +
9639 '                                       <tr>' +
9640 '                                               <th>' +
9641 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9642 '                                                       <br />' +
9643 '                                                       &nbsp;' +
9644 '                                               </th>' +
9645 '                                       </tr>' +
9646 '                                       <tr>' +
9647 '                                               <td>' +
9648 '                                                       <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9649 '                                                       <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>' +
9650 '                                               </td>' +
9651 '                                       </tr>' +
9652 '                                       <tr>' +
9653 '                                               <td>' +
9654 '                                                       &nbsp;' +
9655 '                                                       <br />' +
9656 '                                                       &nbsp;' +
9657 '                                               </td>' +
9658 '                                       </tr>' +
9659 '                                       <tr>' +
9660 '                                               <th>' +
9661 '                                                       <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9662 '                                                       <br />' +
9663 '                                                       &nbsp;' +
9664 '                                               </th>' +
9665 '                                       </tr>' +
9666 '                                       <tr>' +
9667 '                                               <td>' +
9668 '                                                       <div id="addedTemplateAttachments{idx}"></div>' +
9669 '                                               </td>' +
9670 '                                       </tr>' +
9671 '                               </table>' +
9672 '                       </div>' +
9673 '               </div>' +
9674 '       </form>' +
9675 '               <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9676 '             <div style="padding:5px;">' +
9677 '                       <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' + 
9678 '                               <table border="0" width="100%">' +
9679 '                                       <tr>' +
9680 '                                               <td NOWRAP style="padding:2px;">' +
9681 '                                                       <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9682 '                                               </td>' +
9683 '                                       </tr>' +
9684 '                                       <tr>' +
9685 '                                               <td NOWRAP style="padding:2px;">' +
9686 '                                                       <select name="email_template{idx}" id="email_template{idx}"  onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9687 '                                               </td>' +
9688 '                                       </tr>' +
9689 '                               </table>' +
9690 '                               <br />' +
9691 '                               <table border="0" width="100%">' +
9692 '                                       <tr>' +
9693 '                                               <td NOWRAP style="padding:2px;">' +
9694 '                                                       <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9695 '                                               </td>' +
9696 '                                       </tr>' +
9697 '                                       <tr>' +
9698 '                                               <td NOWRAP style="padding:2px;">' +
9699 '                                                       <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9700 '                                               </td>' +
9701 '                                       </tr>' +
9702 '                               </table>' +
9703 '                               <table border="0" width="100%">' +
9704 '                                       <tr>' +
9705 '                                               <td NOWRAP style="padding:2px;">' +
9706 '                                                       <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/>&nbsp;' +
9707 '                                                       <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9708 '                                               </td>' +
9709 '                                       </tr>' +
9710 '                               </table>' +
9711 '         </form>' +
9712 '                       </div> ' +
9713 '               </div>' +
9714 '</div>';
9715 // End of File modules/Emails/javascript/composeEmailTemplate.js
9716                                 
9717 /*********************************************************************************
9718  * SugarCRM is a customer relationship management program developed by
9719  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9720  * 
9721  * This program is free software; you can redistribute it and/or modify it under
9722  * the terms of the GNU Affero General Public License version 3 as published by the
9723  * Free Software Foundation with the addition of the following permission added
9724  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9725  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9726  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9727  * 
9728  * This program is distributed in the hope that it will be useful, but WITHOUT
9729  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9730  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9731  * details.
9732  * 
9733  * You should have received a copy of the GNU Affero General Public License along with
9734  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9735  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9736  * 02110-1301 USA.
9737  * 
9738  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9739  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9740  * 
9741  * The interactive user interfaces in modified source and object code versions
9742  * of this program must display Appropriate Legal Notices, as required under
9743  * Section 5 of the GNU Affero General Public License version 3.
9744  * 
9745  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9746  * these Appropriate Legal Notices must retain the display of the "Powered by
9747  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9748  * technical reasons, the Appropriate Legal Notices must display the words
9749  * "Powered by SugarCRM".
9750  ********************************************************************************/
9751
9752 SUGAR.email2.templates['displayOneEmail'] = 
9753 '<div class="emailDetailTable" style="height:100%">' +
9754 '<div id="viewMenuDiv{idx}"></div>' + 
9755 '<div width="100%" class="displayEmailValue">' +
9756 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.c0_replyForwardEmail(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\', \'reply\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_reply.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_REPLY}</button>' +
9757 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.c0_replyForwardEmail(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\', \'replyAll\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_replyall.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_REPLY_ALL}</button>' +
9758 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.c0_replyForwardEmail(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\', \'forward\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_forward.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_FORWARD}</button>' +
9759 '                                       <button type="button" class="button" onclick="SUGAR.email2.detailView.emailDeleteSingle(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_delete.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_DELETE}</button>' +
9760 '                                       <button type="button" class="button" onclick="SUGAR.email2.detailView.viewPrintable(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=Print_Email.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_PRINT}</button>' +
9761 '                                       <button id="btnEmailView{idx}" type="button" class="button" onclick="SUGAR.email2.detailView.showViewMenu(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_view.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_VIEW} <img src="themes/default/images/more.gif" align="absmiddle" border="0"></button>' +
9762 '                                       <button id="archiveEmail{idx}" type="button" class="button" onclick="SUGAR.email2.detailView.importEmail(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="themes/default/images/icon_email_archive.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_IMPORT_EMAIL}</button>' +
9763 '                                       <button id="quickCreateSpan{meta.panelId}" type="button" class="button" onclick="SUGAR.email2.detailView.showQuickCreate(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="themes/default/images/icon_email_create.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_QUICK_CREATE} <img src="themes/default/images/more.gif" align="absmiddle" border="0"></button>' +
9764 '                                       <button type="button" id="showDeialViewForEmail{meta.panelId}" class="button" onclick="SUGAR.email2.contextMenus.showEmailDetailViewInPopup(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="themes/default/images/icon_email_relate.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS}</button>' +
9765 '</div>' +
9766 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9767 '                               <tr>' +
9768 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9769 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9770 '                                       </td>' +
9771 '                                       <td width="99%" class="displayEmailValue">' +
9772 '                                               {email.from_addr}' +
9773 '                                       </td>' +
9774 '                               </tr>' +
9775 '                               <tr>' +
9776 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9777 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9778 '                                       </td>' +
9779 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9780 '                                               <b>{email.name}</b>' +
9781 '                                       </td>' +
9782 '                               </tr>' +
9783 '                               <tr>' +
9784 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9785 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9786 '                                       </td>' +
9787 '                                       <td class="displayEmailValue">' +
9788 '                                               {email.date_start} {email.time_start}' +
9789 '                                       </td>' +
9790 '                               </tr>' +
9791 '                               <tr>' +
9792 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9793 '                                               {app_strings.LBL_EMAIL_TO}:' +
9794 '                                       </td>' +
9795 '                                       <td class="displayEmailValue">' +
9796 '                                               {email.toaddrs}' +
9797 '                                       </td>' +
9798 '                               </tr>' +
9799 '                               <tr>{meta.cc}</tr>' +
9800 '                               <tr>{email.attachments}</tr>' +
9801 '                       </table>' +
9802 '                       <div id="displayEmailFrameDiv{idx}" name="displayEmailFrameDiv{idx}"><iframe id="displayEmailFrame{idx}" src="modules/Emails/templates/_blank.html" width="100%" height="100%" frameborder="0"></iframe></div>' +
9803 //'                           {email.description}' +
9804 '</div>'
9805 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9806                                 
9807 /*********************************************************************************
9808  * SugarCRM is a customer relationship management program developed by
9809  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9810  * 
9811  * This program is free software; you can redistribute it and/or modify it under
9812  * the terms of the GNU Affero General Public License version 3 as published by the
9813  * Free Software Foundation with the addition of the following permission added
9814  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9815  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9816  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9817  * 
9818  * This program is distributed in the hope that it will be useful, but WITHOUT
9819  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9820  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9821  * details.
9822  * 
9823  * You should have received a copy of the GNU Affero General Public License along with
9824  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9825  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9826  * 02110-1301 USA.
9827  * 
9828  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9829  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9830  * 
9831  * The interactive user interfaces in modified source and object code versions
9832  * of this program must display Appropriate Legal Notices, as required under
9833  * Section 5 of the GNU Affero General Public License version 3.
9834  * 
9835  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9836  * these Appropriate Legal Notices must retain the display of the "Powered by
9837  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9838  * technical reasons, the Appropriate Legal Notices must display the words
9839  * "Powered by SugarCRM".
9840  ********************************************************************************/
9841
9842 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9843 '<body onload="javascript:window.print();">' + 
9844 '<style>' + 
9845 'body {' + 
9846 '       margin: 0px;' + 
9847 '       font-family: helvetica, impact, sans-serif;' +
9848 '       font-size : 12pt;' +
9849 '} ' +
9850 'table {' +
9851 '       padding:10px;' +
9852 '}' +
9853 '</style>' +
9854 '<div>' +
9855 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9856 '       <tr>' +
9857 '               <td>' +
9858 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9859 '                               <tr>' +
9860 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9861 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9862 '                                       </td>' +
9863 '                                       <td width="99%" class="displayEmailValue">' +
9864 '                                               {email.from_name} &lt;{email.from_addr}&gt;' +
9865 '                                       </td>' +
9866 '                               </tr>' +
9867 '                               <tr>' +
9868 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9869 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9870 '                                       </td>' +
9871 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9872 '                                               <b>{email.name}</b>' +
9873 '                                       </td>' +
9874 '                               </tr>' +
9875 '                               <tr>' +
9876 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9877 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9878 '                                       </td>' +
9879 '                                       <td class="displayEmailValue">' +
9880 '                                               {email.date_start} {email.time_start}' +
9881 '                                       </td>' +
9882 '                               </tr>' +
9883 '                               <tr>' +
9884 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9885 '                                               {app_strings.LBL_EMAIL_TO}:' +
9886 '                                       </td>' +
9887 '                                       <td class="displayEmailValue">' +
9888 '                                               {email.toaddrs}' +
9889 '                                       </td>' +
9890 '                               </tr>' +
9891 '                               {email.cc}' +
9892 '                               {email.attachments}' +
9893 '                       </table>' +
9894 '               </td>' +
9895 '       </tr>' +
9896 '       <tr>' +
9897 '               <td>' +
9898 '                       <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9899 '                               <tr>' +
9900 '                                       <td style="border-top: 1px solid #333;">' +
9901 '                                               <div style="padding:5px;">' +
9902                                                         '{email.description}' +
9903 '                                               </div>' +
9904 '                                       </td>' +
9905 '                               </tr>' +
9906 '                       </table>' +
9907 '               </td>' +
9908 '       </tr>' +
9909 '</table>' +
9910 '</div>' +
9911 '</body></html>';
9912 // End of File modules/Emails/javascript/viewPrintable.js
9913                                 
9914 /*********************************************************************************
9915  * SugarCRM is a customer relationship management program developed by
9916  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9917  *
9918  * This program is free software; you can redistribute it and/or modify it under
9919  * the terms of the GNU Affero General Public License version 3 as published by the
9920  * Free Software Foundation with the addition of the following permission added
9921  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9922  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9923  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9924  *
9925  * This program is distributed in the hope that it will be useful, but WITHOUT
9926  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9927  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9928  * details.
9929  *
9930  * You should have received a copy of the GNU Affero General Public License along with
9931  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9932  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9933  * 02110-1301 USA.
9934  *
9935  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9936  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9937  *
9938  * The interactive user interfaces in modified source and object code versions
9939  * of this program must display Appropriate Legal Notices, as required under
9940  * Section 5 of the GNU Affero General Public License version 3.
9941  *
9942  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9943  * these Appropriate Legal Notices must retain the display of the "Powered by
9944  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9945  * technical reasons, the Appropriate Legal Notices must display the words
9946  * "Powered by SugarCRM".
9947  ********************************************************************************/
9948 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9949 var Dom=YAHOO.util.Dom;var qsFields=Dom.getElementsByClassName('sqsEnabled');for(qsField in qsFields){if(typeof qsFields[qsField]=='function'||typeof qsFields[qsField].id=='undefined'){continue;}
9950 form_id=qsFields[qsField].form.getAttribute('id');if(typeof form_id=='object'&&qsFields[qsField].form.getAttribute('real_id')){form_id=qsFields[qsField].form.getAttribute('real_id');}
9951 qs_index_id=form_id+'_'+qsFields[qsField].name;if(typeof sqs_objects[qs_index_id]=='undefined'){qs_index_id=qsFields[qsField].name;if(typeof sqs_objects[qs_index_id]=='undefined'){continue;}}
9952 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9953 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9954 if(!document.forms[qs_obj.form].elements[qsFields[qsField].id].readOnly&&qs_obj['disable']!=true){combo_id=qs_obj.form+'_'+qsFields[qsField].id;if(Dom.get(combo_id+"_results")){loaded=true}
9955 if(!loaded){QSProcessedFieldsArray[qs_index_id]=true;qsFields[qsField].form_id=form_id;var sqs=sqs_objects[qs_index_id];var resultDiv=document.createElement('div');resultDiv.id=combo_id+"_results";Dom.insertAfter(resultDiv,qsFields[qsField]);var fields=qs_obj.field_list.slice();fields[fields.length]="module";var ds=new YAHOO.util.DataSource("index.php?",{responseType:YAHOO.util.XHRDataSource.TYPE_JSON,responseSchema:{resultsList:'fields',total:'totalCount',fields:fields,metaNode:"fields",metaFields:{total:'totalCount',fields:"fields"}},connMethodPost:true});var forceSelect=!((qsFields[qsField].form&&typeof(qsFields[qsField].form)=='object'&&qsFields[qsField].form.name=='search_form')||qsFields[qsField].className.match('sqsNoAutofill')!=null);var search=new YAHOO.widget.AutoComplete(qsFields[qsField],resultDiv,ds,{typeAhead:forceSelect,forceSelection:forceSelect,fields:fields,sqs:sqs,animSpeed:0.25,qs_obj:qs_obj,generateRequest:function(sQuery){var out=SUGAR.util.paramsToUrl({to_pdf:'true',module:'Home',action:'quicksearchQuery',data:encodeURIComponent(YAHOO.lang.JSON.stringify(this.sqs)),query:sQuery});return out;},setFields:function(data,filter){for(var i in this.fields){for(var key in this.qs_obj.field_list){if(this.fields[i]==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&this.qs_obj.populate_list[key].match(filter)){document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value=data[i];}}}},clearFields:function(){for(var key in this.qs_obj.field_list){if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]){document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";}}
9956 this.oldValue="";}});if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9957 search.itemSelectEvent.subscribe(function(e,args){var data=args[2];var fields=this.fields;this.setFields(data,/\S/);if(typeof(this.qs_obj['post_onblur_function'])!='undefined'){collection_extended=new Array();for(var i in fields){for(var key in this.qs_obj.field_list){if(fields[i]==this.qs_obj.field_list[key]){collection_extended[this.qs_obj.field_list[key]]=data[i];}}}
9958 eval(this.qs_obj['post_onblur_function']+'(collection_extended, this.qs_obj.id)');}});search.textboxFocusEvent.subscribe(function(){this.oldValue=this.getInputEl().value;});search.selectionEnforceEvent.subscribe(function(e,args){if(this.oldValue!=args[1]){this.clearFields();}else{this.getInputEl().value=this.oldValue;}});search.dataReturnEvent.subscribe(function(e,args){if(this.getInputEl().value.length==0&&args[2].length>0){var data=[];for(var key in this.qs_obj.field_list){data[data.length]=args[2][0][this.qs_obj.field_list[key]];}
9959 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
9960 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9961 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js
9962