2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
5 * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6 * dragged element is inserted before the dragged-over element.
8 * @extends YAHOO.util.DDProxy
10 * @param {String} id the id of the linked element
11 * @param {String} sGroup the group of related DragDrop objects
13 function ygDDList(id, sGroup) {
16 this.init(id, sGroup);
18 //this.logger = new ygLogger("ygDDList");
21 var s = this.getDragEl().style;
22 s.borderColor = "transparent";
23 s.backgroundColor = "#f6f5e5";
25 s.filter = "alpha(opacity=76)";
28 ygDDList.prototype = new YAHOO.util.DDProxy();
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
33 ygDDList.prototype.startDrag = function(x, y) {
34 //this.logger.debug(this.id + " startDrag");
36 var dragEl = this.getDragEl();
37 var clickEl = this.getEl();
39 dragEl.innerHTML = clickEl.innerHTML;
40 dragElObjects = dragEl.getElementsByTagName('object');
43 dragEl.className = clickEl.className;
44 dragEl.style.color = clickEl.style.color;
45 dragEl.style.border = "1px solid #aaa";
47 // save the style of the object
48 clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
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';
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';
61 clickEl.appendChild(this.borderDiv);
64 ygDDList.prototype.endDrag = function(e) {
65 // disable moving the linked element
66 var clickEl = this.getEl();
68 clickEl.removeChild(this.borderDiv); // remove border div
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];
77 clickEl.style.height = this.clickHeight;
79 clickEl.style.height = '';
82 clickEl.style.border = this.clickBorder;
84 clickEl.style.border = '';
86 dragEl = this.getDragEl();
87 dragEl.innerHTML = '';
92 ygDDList.prototype.afterEndDrag = function(e) {
96 ygDDList.prototype.onDrag = function(e, id) {
100 ygDDList.prototype.onDragOver = function(e, id) {
101 // this.logger.debug(this.id.toString() + " onDragOver " + id);
104 if ("string" == typeof id) {
105 el = YAHOO.util.DDM.getElement(id);
107 el = YAHOO.util.DDM.getBestMatch(id).getEl();
110 dragEl = this.getDragEl();
111 elRegion = YAHOO.util.Dom.getRegion(el);
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);
119 // this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " < " + mid);
120 // this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
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);
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);
134 ygDDList.prototype.onDragEnter = function(e, id) {
135 // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136 // this.getDragEl().style.border = "1px solid #449629";
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";
144 /////////////////////////////////////////////////////////////////////////////
146 function ygDDListBoundary(id, sGroup) {
148 this.init(id, sGroup);
149 //this.logger = new ygLogger("ygDDListBoundary");
150 this.isBoundary = true;
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
157 /*********************************************************************************
158 * SugarCRM Community Edition is a customer relationship management program developed by
159 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
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.
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
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
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.
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.
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> </span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&themeName=Sugar&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(''',"'");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())){if(/save|full|cancel|change/.test(elm.value.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);if(this.verifyElementValue==null||typeof(this.verifyElementValue)=='undefined'){return false;}
199 this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
200 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
201 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)
202 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)
203 return;this.addInProgress=true;if(!address)
204 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag=document.createElement("input");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);}
205 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'];}
206 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;}}}
207 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;}}
208 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;}}
209 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=' ';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
210 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);}
211 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');}
212 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
213 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
214 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
215 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
216 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};if(YAHOO.env.ua.ie>0){var emailcontainer=Dom.getAncestorByTagName(insertInto,'span');YAHOO.util.Event.addListener(newContent,"change",function(ev,el){SUGAR.util.callOnChangeListers(el);},emailcontainer);}
217 this.EmailAddressValidation(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},EmailAddressValidation:function(ev,fn,r,stR){YAHOO.util.Event.onContentReady(fn,function(){addToValidate(ev,fn,'email',r,stR);});},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));}
218 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
219 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
220 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));}}
221 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
222 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
223 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
224 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
225 if(YAHOO.env.ua.ie){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;}}
226 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
227 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView.indexOf('DCQuickCreate')>0){DCMenu.save(theForm.id);}else if(this.emailView.indexOf('QuickCreate')>=0){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value+'_subpanel_save_button');}}}};emailAddressWidgetLoaded=true;})();
228 // End of File include/SugarEmailAddress/SugarEmailAddress.js
230 /*********************************************************************************
231 * SugarCRM Community Edition is a customer relationship management program developed by
232 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
234 * This program is free software; you can redistribute it and/or modify it under
235 * the terms of the GNU Affero General Public License version 3 as published by the
236 * Free Software Foundation with the addition of the following permission added
237 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
238 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
239 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
241 * This program is distributed in the hope that it will be useful, but WITHOUT
242 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
243 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
246 * You should have received a copy of the GNU Affero General Public License along with
247 * this program; if not, see http://www.gnu.org/licenses or write to the Free
248 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
251 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
252 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
254 * The interactive user interfaces in modified source and object code versions
255 * of this program must display Appropriate Legal Notices, as required under
256 * Section 5 of the GNU Affero General Public License version 3.
258 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
259 * these Appropriate Legal Notices must retain the display of the "Powered by
260 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
261 * technical reasons, the Appropriate Legal Notices must display the words
262 * "Powered by SugarCRM".
263 ********************************************************************************/
264 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)
265 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_","_")]);}
266 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
267 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;}
268 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();}
269 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';}
270 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='';}
271 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){var clone_id=this.form+'_'+this.field+'_collection_0';YAHOO.util.Event.onContentReady(clone_id,function(c){c.create_clone();enableQS();c.changePrimary(true);for(key in c.secondaries_values){if(isInteger(key)){c.add(c.secondaries_values[key]);}}
272 c.js_more();initEditView(document.forms[c.form]);},this);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
273 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
274 var count=this.fields_count;var Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
275 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
276 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&¤tNode.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';}
277 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(typeof(input_els[x].id)=='undefined'||input_els[x].id==''){input_els[x].id=currentNode.id;}
278 if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);var new_id=currentNode.id.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
279 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);}}}
280 currentNode.name=new_name;currentNode.id=new_id;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_id.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_id;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_id;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_id;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
281 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
282 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='';}}
284 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects!='undefined'&&typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
286 if(!has_primary){return false;}
288 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match(fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
289 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;}}}}
290 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;}
291 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects!='undefined'&&typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
292 if(noAdd){enableQS(false);}
293 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field_element_name+"_collection_"+i);var id_field=document.getElementById("id_"+this.field_element_name+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].name==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
295 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
296 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=='';}
297 return false;}};SUGAR.collection.safe_clone=function(e,recursive)
298 {if(e.nodeName=="#text")
299 {return document.createTextNode(e.data);}
300 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];if(SUGAR.isIE7&&e.tagName.toLowerCase()=='input')
301 {var properties=['class','style','name','type','valign','border','width','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}else{var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}
302 for(var i in properties)
303 {if(e[properties[i]])
304 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
305 newNode[properties[i]]=e[properties[i]];}}
307 {for(var i in e.childNodes)
308 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
309 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
311 // End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
313 /*********************************************************************************
314 * SugarCRM Community Edition is a customer relationship management program developed by
315 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
317 * This program is free software; you can redistribute it and/or modify it under
318 * the terms of the GNU Affero General Public License version 3 as published by the
319 * Free Software Foundation with the addition of the following permission added
320 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
321 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
322 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
324 * This program is distributed in the hope that it will be useful, but WITHOUT
325 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
326 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
329 * You should have received a copy of the GNU Affero General Public License along with
330 * this program; if not, see http://www.gnu.org/licenses or write to the Free
331 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
334 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
335 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
337 * The interactive user interfaces in modified source and object code versions
338 * of this program must display Appropriate Legal Notices, as required under
339 * Section 5 of the GNU Affero General Public License version 3.
341 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
342 * these Appropriate Legal Notices must retain the display of the "Powered by
343 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
344 * technical reasons, the Appropriate Legal Notices must display the words
345 * "Powered by SugarCRM".
346 ********************************************************************************/
347 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);}
348 return s;},init:function(){if(Rot13.map!=null)
349 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
350 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
351 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
352 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='';}
353 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='';}
354 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='';}}
356 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName,ie_id)
357 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
358 if(typeof(ie_id)=='undefined'||ie_id=='')
359 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id.value:'';URL='index.php?'
360 +'module='+module_name
363 +'&target='+pageTarget
364 +'&target1='+pageTarget
365 +'&server_url='+mail_server
366 +'&email_user='+words[0]
367 +'&protocol='+protocol
369 +'&email_password='+words[1]
370 +'&mailbox='+words[2]
373 +'&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)
374 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
375 this.body.style.width=w}}
376 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
377 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();}
378 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'));}
379 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
380 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
381 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
382 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
383 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";}
385 alert(out);return false;}else{return true;}}
386 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?'
387 +'module='+module_name
390 +'&target='+pageTarget
391 +'&target1='+pageTarget
392 +'&server_url='+mail_server
393 +'&email_user='+words[0]
394 +'&protocol='+protocol
396 +'&email_password='+words[1]
397 +'&mailbox='+words[2]
399 +'&personal='+isPersonal
400 +'&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)
401 this.body.style.width=w}}
402 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();}
403 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;}}}
404 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';}}}
405 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='';}
406 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";}}
407 // End of File modules/InboundEmail/InboundEmail.js
409 /*********************************************************************************
410 * SugarCRM Community Edition is a customer relationship management program developed by
411 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
413 * This program is free software; you can redistribute it and/or modify it under
414 * the terms of the GNU Affero General Public License version 3 as published by the
415 * Free Software Foundation with the addition of the following permission added
416 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
417 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
418 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
420 * This program is distributed in the hope that it will be useful, but WITHOUT
421 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
422 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
425 * You should have received a copy of the GNU Affero General Public License along with
426 * this program; if not, see http://www.gnu.org/licenses or write to the Free
427 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
430 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
431 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
433 * The interactive user interfaces in modified source and object code versions
434 * of this program must display Appropriate Legal Notices, as required under
435 * Section 5 of the GNU Affero General Public License version 3.
437 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
438 * these Appropriate Legal Notices must retain the display of the "Powered by
439 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
440 * technical reasons, the Appropriate Legal Notices must display the words
441 * "Powered by SugarCRM".
442 ********************************************************************************/
445 cache : new Object(),
446 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
447 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
450 currentHtmleditor : ''
454 * preserves hits from email server
456 _setDetailCache : function(ret) {
458 var compKey = ret.meta.mbox + ret.meta.uid;
460 if(!SUGAR.email2.cache[compKey]) {
461 SUGAR.email2.cache[compKey] = ret;
466 autoSetLayout : function() {
467 var c = document.getElementById('container');
468 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
469 //Ensure a minimum height.
470 tHeight = Math.max(tHeight, 550);
471 c.style.height = tHeight + "px";
472 SUGAR.email2.complexLayout.set('height', tHeight);
473 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
474 SUGAR.email2.complexLayout.render();
475 SUGAR.email2.listViewLayout.resizePreview();
481 * Shows overlay progress message
485 SUGAR.showMessageBoxModal = function(title, body) {
486 SUGAR.showMessageBox(title, body);
490 SUGAR.showMessageBox = function(reqtitle, body, type, additconfig) {
492 if (typeof(additconfig) == "object") {
493 var config = additconfig;
496 config.title = reqtitle;
498 YAHOO.SUGAR.MessageBox.show(config);
502 SUGAR.hideMessageBox = function() {
503 YAHOO.SUGAR.MessageBox.hide();
505 // End of File modules/Emails/javascript/EmailUIShared.js
507 /*********************************************************************************
508 * SugarCRM Community Edition is a customer relationship management program developed by
509 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
511 * This program is free software; you can redistribute it and/or modify it under
512 * the terms of the GNU Affero General Public License version 3 as published by the
513 * Free Software Foundation with the addition of the following permission added
514 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
515 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
516 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
518 * This program is distributed in the hope that it will be useful, but WITHOUT
519 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
520 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
523 * You should have received a copy of the GNU Affero General Public License along with
524 * this program; if not, see http://www.gnu.org/licenses or write to the Free
525 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
528 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
529 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
531 * The interactive user interfaces in modified source and object code versions
532 * of this program must display Appropriate Legal Notices, as required under
533 * Section 5 of the GNU Affero General Public License version 3.
535 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
536 * these Appropriate Legal Notices must retain the display of the "Powered by
537 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
538 * technical reasons, the Appropriate Legal Notices must display the words
539 * "Powered by SugarCRM".
540 ********************************************************************************/
544 var sw = YAHOO.SUGAR,
545 Event = YAHOO.util.Event,
546 Connect = YAHOO.util.Connect,
550 ///////////////////////////////////////////////////////////////////////////////
553 outboundDialog : null,
554 inboundAccountEditDialog : null,
555 inboundAccountsSettingsTable : null,
556 outboundAccountsSettingsTable : null,
557 testOutboundDialog : null,
558 errorStyle : 'input-error',
560 newAddedOutboundId : '',
563 * makes async call to retrieve an outbound instance for editting
566 editOutbound : function(obi) {
568 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
571 deleteOutbound : function(obi) {
573 if(obi.match(/^(add|line|sendmail)+/)) {
574 alert('Invalid Operation');
576 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
577 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
581 getReplyAddress : function() {
584 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
585 var addy = SE.userPrefs.current_user.emailAddresses[i];
587 if(addy.primary_address == "1") {
588 primary = addy.email_address;
591 if(addy.reply_to == "1") {
592 return addy.email_address;
600 * Called on "Accounts" tab activation event
602 lazyLoad : function() {
604 this._setupInboundAccountTable();
605 this._setupOutboundAccountTable();
609 _setupInboundAccountTable: function()
611 //Setup the inbound mail settings
612 if(!this.inboundAccountsSettingsTable)
614 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
615 var clckEvent = oColumn.key;
617 var is_group = oRecord.getData("is_group");
620 if(oColumn.key == 'edit')
622 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
623 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
625 else if(oColumn.key == 'delete')
627 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
628 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
630 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
634 this.showBoolean = function(el, oRecord, oColumn, oData)
636 var is_group = oRecord.getData("is_group");
637 var bChecked = oData;
638 bChecked = (bChecked) ? " checked" : "";
641 el.innerHTML = "<input type=\"radio\"" + bChecked +
642 " name=\"col" + oColumn.getId() + "-radio\"" +
643 " class=\"yui-dt-radio\">";
648 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
649 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
651 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
652 '<img border="0" src="themes/default/images/helpInline.gif">' +
653 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
656 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
657 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
658 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
659 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
660 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
661 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
662 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
663 this.ieDataSource = new YAHOO.util.DataSource(query);
664 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
665 this.ieDataSource.responseSchema = {
666 resultsList: "account_list",
667 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
669 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
670 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
672 var elCheckbox = oArgs.target;
673 var oColumn = this.getColumn(elCheckbox);
674 if(oColumn.key == 'is_active')
676 var oRecord = this.getRecord(elCheckbox);
677 oRecord.setData("is_active",elCheckbox.checked);
678 var t_id = oRecord.getData('id');
679 var isGroupFolder = oRecord.getData('has_groupfolder');
682 SUGAR.email2.folders.updateSubscriptions();
684 SUGAR.email2.folders.setFolderSelection();
688 var lastDefaultSelectedId = "";
689 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
691 var elRadio = oArgs.target;
692 var oColumn = this.getColumn(elRadio);
693 if(oColumn.key == 'is_default')
695 var oRecord = this.getRecord(elRadio);
696 var t_id = oRecord.getData('id');
697 var t_isGroup = oRecord.getData('is_group');
698 if(t_id != lastDefaultSelectedId && !t_isGroup)
700 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
701 lastDefaultSelectedId = t_id;
702 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
705 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
710 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
711 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
714 _setupOutboundAccountTable: function()
716 if(!this.outboundAccountsSettingsTable)
718 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
719 var clckEvent = oColumn.key;
721 var isEditable = oRecord.getData("is_editable");
722 var type = oRecord.getData("type");
725 if(oColumn.key == 'edit')
727 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
728 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
730 else if(oColumn.key == 'delete' && type == 'user')
732 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
733 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
736 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
740 //Custom formatter to display any error messages.
741 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
743 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
744 SUGAR.email2.composeLayout.outboundAccountErrors = {};
746 var id = oRecord.getData('id');
747 var message = oRecord.getData("errors");
750 elLiner.innerHTML = '<span class="required">' + message + '</span>';
751 //Add the id and message for all outbound accounts.
752 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
756 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
757 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
760 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
761 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
763 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
764 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
765 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
766 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
768 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
769 this.obDataSource = new YAHOO.util.DataSource(query);
770 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
771 this.obDataSource.responseSchema = {
773 resultsList: "outbound_account_list",
774 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
777 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
780 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
781 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
782 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
786 * Displays a modal diaglogue to edit outbound account settings
788 showEditInboundAccountDialogue : function(clear) {
790 if(!this.inboundAccountEditDialog) {
791 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
795 constraintoviewport: true,
799 EAD.showEvent.subscribe(function() {
800 var el = this.element;
801 var viewH = YAHOO.util.Dom.getViewportHeight();
802 if (this.header && el && viewH - 50 < el.clientHeight) {
803 var body = this.header.nextElementSibling;
804 body.style.overflow = "hidden";
805 body.style.height = "100%";
808 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
809 Dom.removeClass("editAccountDialogue", "yui-hidden");
813 if(clear == undefined || clear == true)
815 SE.accounts.clearInboundAccountEditScreen();
816 //Set default protocol to IMAP when creating new records
817 document.forms['ieAccount'].elements['protocol'].value = "imap";
818 SE.accounts.setPortDefault();
821 //Check if we should display username/password fields for outbound account if errors were detected.
822 this.checkOutBoundSelection();
824 this.inboundAccountEditDialog.render();
825 this.inboundAccountEditDialog.show();
826 SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
830 * Set all fields on the outbound edit form to either enabled/disabled
831 * except for the username/password.
834 toggleOutboundAccountDisabledFields: function(disable)
836 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
837 for(var i=0;i<fields.length;i++)
839 document.getElementById(fields[i]).disabled = disable;
842 Dom.addClass("mail_smtpssl_row", "yui-hidden");
844 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
848 * Refresh the inbound accounts table.
850 refreshInboundAccountTable : function()
852 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
854 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
855 scope: this.inboundAccountsSettingsTable }
859 * Refresh the outbound accounts table.
861 refreshOuboundAccountTable : function()
863 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
865 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
866 scope: this.outboundAccountsSettingsTable }
870 * Displays a modal diaglogue to add a SMTP server
872 showAddSmtp : function() {
873 // lazy load dialogue
874 if(!this.outboundDialog) {
875 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
879 constraintoviewport: true,
883 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
884 this.outboundDialog.hideEvent.subscribe(function(){
885 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
886 var out = Dom.get("outbound_email");
887 if (out && out.value == "SYSTEM_ADD")
889 out.value = out.options[0].value;
891 //Check if we should display username/password for system account.
892 SE.accounts.checkOutBoundSelection();
896 Dom.removeClass("outboundDialog", "yui-hidden");
900 var form = document.getElementById('outboundEmailForm');
901 for(i=0; i<form.elements.length; i++) {
902 if(form.elements[i].name == 'mail_smtpport') {
903 form.elements[i].value = 25;
904 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
905 form.elements[i].value = '';
906 } else if(form.elements[i].type == 'checkbox') {
907 form.elements[i].checked = false;
910 //Render the SMTP buttons
911 if ( !SUGAR.smtpButtonGroup ) {
912 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
913 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
915 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
916 document.getElementById('smtp_settings').style.display = '';
917 form.mail_smtptype.value = e.newValue.get('value');
919 YAHOO.widget.Button.addHiddenFieldsToForm(form);
921 //Hide Username/Password
922 SUGAR.email2.accounts.smtp_authenticate_field_display();
923 //Unset readonly fields
924 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
925 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
926 this.outboundDialog.render();
927 this.outboundDialog.show();
931 * Accounts' Advanced Settings view toggle
933 toggleAdv : function() {
934 var adv = document.getElementById("ie_adv");
935 if(adv.style.display == 'none') {
936 adv.style.display = "";
938 adv.style.display = 'none';
942 smtp_authenticate_field_display : function() {
943 var smtpauth_req = document.getElementById("mail_smtpauth_req");
944 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
945 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
948 smtp_setDefaultSMTPPort : function() {
949 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
951 if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
952 document.getElementById("mail_smtpport").value = '465';
954 if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
955 document.getElementById("mail_smtpport").value = '25';
960 * Changes the display used in the outbound email SMTP dialog to match the
962 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
964 document.getElementById("smtpButtonGroupTD").style.display = '';
965 document.getElementById("chooseEmailProviderTD").style.display = '';
966 document.getElementById("mailsettings1").style.display = '';
967 document.getElementById("mailsettings2").style.display = '';
968 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
969 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
970 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
971 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
975 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
976 document.getElementById("mail_smtpport").value = '465';
977 document.getElementById("mail_smtpauth_req").checked = true;
978 var ssl = document.getElementById("mail_smtpssl");
979 for(var j=0;j<ssl.options.length;j++) {
980 if(ssl.options[j].text == 'SSL') {
981 ssl.options[j].selected = true;
985 document.getElementById("mailsettings1").style.display = 'none';
986 document.getElementById("mailsettings2").style.display = 'none';
987 document.getElementById("mail_smtppass_label").innerHTML =
988 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
989 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
992 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
993 document.getElementById("mail_smtpport").value = '587';
994 document.getElementById("mail_smtpauth_req").checked = true;
995 var ssl = document.getElementById("mail_smtpssl");
996 for(var j=0;j<ssl.options.length;j++) {
997 if(ssl.options[j].text == 'TLS') {
998 ssl.options[j].selected = true;
1002 document.getElementById("mailsettings1").style.display = 'none';
1003 document.getElementById("mailsettings2").style.display = 'none';
1004 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
1005 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
1008 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
1009 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
1010 document.getElementById("mail_smtpserver").value = '';
1012 document.getElementById("mail_smtpport").value = '25';
1013 document.getElementById("mail_smtpauth_req").checked = true;
1014 document.getElementById("mailsettings1").style.display = '';
1015 document.getElementById("mailsettings2").style.display = '';
1016 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1017 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1018 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1019 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1022 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1024 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1025 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1026 document.getElementById("mailsettings2").style.display = 'none';
1029 SUGAR.email2.accounts.smtp_authenticate_field_display();
1030 SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1034 * Fill the gmail default values for inbound accounts.
1036 fillInboundGmailDefaults: function () {
1038 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1039 document.forms['ieAccount'].elements['ssl'].checked = true;
1040 document.forms['ieAccount'].elements['protocol'].value = "imap";
1041 SUGAR.email2.accounts.setPortDefault();
1042 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1045 * Sets Port field to selected protocol and SSL settings defaults
1047 setPortDefault : function() {
1048 var prot = document.getElementById('protocol');
1049 var ssl = document.getElementById('ssl');
1050 var port = document.getElementById('port');
1051 var stdPorts= new Array("110", "143", "993", "995");
1052 var stdBool = new Boolean(false);
1053 var mailboxdiv = document.getElementById("mailboxdiv");
1054 var trashFolderdiv = document.getElementById("trashFolderdiv");
1055 var sentFolderdiv = document.getElementById("sentFolderdiv");
1056 var monitoredFolder = document.getElementById("subscribeFolderButton");
1057 if(port.value == '') {
1058 stdBool.value = true;
1060 for(i=0; i<stdPorts.length; i++) {
1061 if(stdPorts[i] == port.value) {
1062 stdBool.value = true;
1067 if(stdBool.value == true) {
1068 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1070 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1072 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1074 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1079 if (prot.value == 'imap') {
1080 mailboxdiv.style.display = "";
1081 trashFolderdiv.style.display = "";
1082 sentFolderdiv.style.display = "";
1083 monitoredFolder.style.display = "";
1084 if (document.getElementById('mailbox').value == "") {
1085 document.getElementById('mailbox').value = "INBOX";
1088 mailboxdiv.style.display = "none";
1089 trashFolderdiv.style.display = "none";
1090 sentFolderdiv.style.display = "none";
1091 monitoredFolder.style.display = "none";
1092 document.getElementById('mailbox').value = "";
1097 * Draws/removes red boxes around required fields.
1099 ieAccountError : function(style) {
1100 document.getElementById('server_url').className = style;
1101 document.getElementById('email_user').className = style;
1102 document.getElementById('email_password').className = style;
1103 document.getElementById('protocol').className = style;
1104 document.getElementById('port').className = style;
1107 checkOutBoundSelection: function() {
1108 var select = Dom.get('outbound_email');
1109 if (!select || select.selectedIndex == -1) { return; }
1111 var v = select.options[select.selectedIndex].value;
1115 select.options[select.selectedIndex].selected = false;
1116 v = select.options[0].value;
1118 else if (v == 'SYSTEM_ADD')
1119 SUGAR.email2.accounts.showAddSmtp();
1121 var foundError = false;
1122 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1123 for(i in errorAccounts)
1132 //Should username/password fields for outbound account.
1134 this.toggleInboundOutboundFields(true);
1136 this.toggleInboundOutboundFields(false);
1141 toggleInboundOutboundFields : function (display)
1145 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1146 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1150 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1151 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1155 * rebuilds the select options for mailer options
1157 rebuildMailerOptions : function() {
1158 var select = document.forms['ieAccount'].elements['outbound_email'];
1159 SE.util.emptySelectOptions(select);
1161 //Get the available sugar mailers
1162 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1164 for(i=0;i<a_outbound.length;i++)
1166 var t_record = a_outbound[i];
1167 var key = t_record.getData('id');
1168 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1170 var opt = new Option(display, key);
1171 select.options.add(opt);
1172 if (key == SE.accounts.newAddedOutboundId) {
1173 select.options.selectedIndex = i;
1177 select.options.add(new Option('',''));
1178 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1179 //Hide/Show username password fields if necessary.
1180 SE.accounts.checkOutBoundSelection();
1183 * Empties all the fields in the accounts edit view
1185 clearInboundAccountEditScreen:function() {
1187 document.getElementById('ie_id').value = '';
1188 document.getElementById('ie_name').value = '';
1189 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1190 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1191 document.getElementById('reply_to_addr').value = '';
1192 document.getElementById('server_url').value = '';
1193 document.getElementById('email_user').value = '';
1194 document.getElementById('email_password').value = '';
1195 document.getElementById('port').value = '';
1196 document.getElementById('inbound_mail_smtpuser').value = '';
1197 document.getElementById('inbound_mail_smtppass').value = '';
1198 document.ieAccount.protocol.options[0].selected = true;
1200 document.getElementById('ssl').checked = false;
1201 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1205 * Populates an account's fields in Settings->Accounts
1207 fillIeAccount:function(jsonstr) {
1208 var o = YAHOO.lang.JSON.parse(jsonstr);
1210 document.getElementById('ie_id').value = o.id;
1211 document.getElementById('ie_name').value = o.name;
1212 if (o.stored_options != null) {
1213 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1214 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1215 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1216 if (o.stored_options.trashFolder != null) {
1217 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1219 if (o.stored_options.sentFolder != null) {
1220 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1223 document.getElementById('server_url').value = o.server_url;
1224 document.getElementById('email_user').value = o.email_user;
1225 document.getElementById('port').value = o.port;
1226 document.getElementById('group_id').value = o.group_id;
1227 document.getElementById('mailbox').value = o.mailbox;
1233 if(typeof(o.service[2]) != 'undefined') {
1234 document.getElementById('ssl').checked = true;
1238 if(document.getElementById('protocol').value != o.protocol) {
1239 var prot = document.getElementById('protocol');
1240 for(i=0; i<prot.options.length; i++) {
1241 if(prot.options[i].value == o.service[3]) {
1242 prot.options[i].selected = true;
1243 this.setPortDefault();
1247 // handle SMTP selection
1248 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1249 var opts = document.getElementById('outbound_email').options;
1250 for(i=0; i<opts.length; i++) {
1251 if(opts[i].value == o.stored_options.outbound_email) {
1252 opts[i].selected = true;
1258 deleteIeAccount : function(IeAccountID,IeGroupID) {
1259 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1261 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1263 AjaxObject.target = 'frameFlex';
1264 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1265 SUGAR.email2.accounts.refreshInboundAccountTable();
1269 // Null check for Outbound Settings.
1270 checkOutboundSettings: function() {
1271 var errorMessage = '';
1272 var isError = false;
1273 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1274 var mailName = document.getElementById('mail_name').value;
1275 var smtpServer = document.getElementById('mail_smtpserver').value;
1276 var smtpPort = document.getElementById('mail_smtpport').value;
1278 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1279 if(trim(mailName) == '') {
1281 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1283 if(trim(smtpServer) == '') {
1285 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1287 if(trim(smtpPort) == '') {
1289 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1291 if(mailsmtpauthreq.checked) {
1292 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1294 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1299 SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1306 testOutboundSettings: function() {
1307 var errorMessage = '';
1308 var isError = false;
1309 var fromAddress = document.getElementById("outboundtest_from_address").value;
1310 if (trim(fromAddress) == "") {
1311 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1312 SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1316 else if (!isValidEmail(fromAddress)) {
1317 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1318 SUGAR.showMessageBox(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1322 //Hide the dialogue and show an in progress indicator.
1323 SE.accounts.testOutboundDialog.hide();
1324 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1326 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1327 //nothing is sent in the request.
1328 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1329 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1331 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1332 if(outboundType == 'system-override')
1333 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1335 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1336 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1340 testOutboundSettingsDialog: function() {
1341 //Ensure that all settings are correct before proceeding to send test email.
1342 if(!SE.accounts.checkOutboundSettings())
1345 // lazy load dialogue
1346 if(!SE.accounts.testOutboundDialog) {
1347 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1351 constraintoviewport: true,
1355 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1356 Dom.removeClass("testOutboundDialog", "yui-hidden");
1358 SE.accounts.testOutboundDialog.render();
1359 SE.accounts.testOutboundDialog.show();
1363 * Saves Outbound email settings
1365 saveOutboundSettings : function() {
1366 if(SE.accounts.checkOutboundSettings()) {
1367 //Enable the form fields for the post.
1368 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1369 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1370 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1376 saveIeAccount : function() {
1378 //Before saving check if there are any error messages associated with the outbound account.
1379 var outboundID = document.getElementById('outbound_email').value;
1381 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1382 'validateSMTPCreds':true}) )
1384 document.getElementById('saveButton').disabled = true;
1386 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1388 var formObject = document.getElementById('ieAccount');
1389 YAHOO.util.Connect.setForm(formObject);
1391 AjaxObject._reset();
1392 AjaxObject.target = 'frameFlex';
1393 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1397 testSettings : function() {
1398 form = document.getElementById('ieAccount');
1400 if(SE.accounts.checkIeCreds()) {
1401 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", form.ie_id.value);
1405 getFoldersListForInboundAccountForEmail2 : function() {
1406 form = document.getElementById('ieAccount');
1407 if(SE.accounts.checkIeCreds()) {
1408 var mailBoxValue = form.mailbox.value;
1409 if (form.searchField.value.length > 0) {
1412 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 );
1417 checkIeCreds : function(validateRules) {
1418 if(typeof(validateRules) == 'undefined')
1421 var errors = new Array();
1422 var out = new String();
1424 var ie_name = Dom.get('ie_name').value;
1425 var fromAddress = Dom.get('ie_from_addr').value;
1426 var server_url = Dom.get('server_url').value;
1427 var email_user = Dom.get('email_user').value;
1428 var email_password = Dom.get('email_password').value;
1429 var protocol = Dom.get('protocol').value;
1430 var port = Dom.get('port').value;
1431 var oe = Dom.get('outbound_email');
1433 // Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
1434 // other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
1435 // return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
1436 var oe_value = (typeof(oe.options[oe.selectedIndex]) === 'undefined' || typeof(oe.options[oe.selectedIndex]) === 'unknown' || typeof(oe.options[oe.selectedIndex]) === null) ? "" : oe.options[oe.selectedIndex].value;
1438 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1439 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1441 //If the username and password were provided then ignore the error messge
1443 var outboundCredentialsFound = false;
1445 if(outboundUserName != "" && outboundPass != "")
1446 outboundCredentialsFound = true;
1448 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1450 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1451 && validateSMTPCreds)
1453 if(trim(outboundUserName) == "") {
1454 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1456 if(trim(outboundPass) == "") {
1457 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1461 if(trim(ie_name) == "") {
1462 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1465 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1467 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1468 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1473 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1474 || trim(oe_value) == "SYSTEM_ADD") ) {
1475 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1477 if(trim(server_url) == "") {
1478 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1480 if(trim(email_user) == "") {
1481 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1483 if(protocol == "") {
1484 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1486 if (protocol == 'imap') {
1487 var mailbox = document.getElementById('mailbox').value;
1488 if (trim(mailbox) == "") {
1489 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1491 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1492 var trashFolder = document.getElementById('trashFolder').value;
1493 if (trim(trashFolder) == "") {
1494 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1499 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1502 if(errors.length > 0) {
1503 out = app_strings.LBL_EMAIL_ERROR_DESC;
1504 for(i=0; i<errors.length; i++) {
1519 getIeAccount : function(ieId) {
1523 SUGAR.showMessageBox(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1524 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1526 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1530 * Iterates through TreeView nodes to apply styles dependent nature of node
1532 renderTree:function() {
1533 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1537 //Sets the style for any nodes that need it.
1538 setNodeStyle : function(node) {
1539 if (!node.data.origText) {
1540 node.data.origText = node.data.text;
1543 if (typeof(node.data.unseen) != 'undefined') {
1544 if (node.data.unseen > 0) {
1545 node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
1546 // Add bold style to label, kinda hacky
1547 node.labelStyle += " ygtvlabelbold";
1550 node.setUpLabel(node.data.origText);
1553 node.setUpLabel(node.data.origText);
1555 SE.accounts.setupDDTarget(node);
1558 setupDDTarget : function(node) {
1559 if (node.ddTarget) {
1560 node.ddTarget.removeFromGroup();
1561 delete node.ddTarget;
1563 var id = node.getElId();
1564 var num = id.substring(4);
1565 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1566 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1567 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1569 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1571 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1572 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1577 * Async call to rebuild the folder list. After a folder delete or account delete
1579 rebuildFolderList : function() {
1580 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1581 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1585 * Returns the number of remote accounts the user has active.
1587 getAccountCount : function() {
1590 for(i=0; i<tree._nodes.length; i++) {
1591 var node = tree._nodes[i];
1593 if(typeof(node) != 'undefined' && node.data.ieId) {
1601 ///////////////////////////////////////////////////////////////////////////////
1606 ///////////////////////////////////////////////////////////////////////////////
1607 //// CONTEXT MENU CALLS
1610 assignToDialogue : null,
1612 * Archives from context menu
1614 * @param string ieId
1615 * @param string folder
1617 _archiveToSugar : function(uids, ieId, folder) {
1620 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1621 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1624 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1628 * Archives from context menu
1630 archiveToSugar : function(menuItem) {
1631 SE.contextMenus.emailListContextMenu.hide();
1633 var rows = SE.grid.getSelectedRows();
1635 /* iterate through available rows JIC a row is deleted - use first available */
1636 for(var i=0; i<rows.length; i++) {
1637 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1639 var data = SE.grid.getRecord(rows[0]).getData();
1640 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1644 * Popup the printable version and start system's print function.
1646 viewPrintable : function(menuItem) {
1647 var rows = SE.grid.getSelectedRows();
1648 var data = SE.grid.getRecord(rows[0]).getData();
1649 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1653 * Marks email flagged on mail server
1655 markRead : function(type, contextMenuId) {
1656 SE.contextMenus.markEmail('read');
1660 * Assign this emails to people based on assignment rules
1662 assignEmailsTo : function(type, contextMenuId) {
1663 if(!SE.contextMenus.assignToDialogue)
1665 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1669 constraintoviewport: true,
1673 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1677 Dom.removeClass("assignToDiv", "yui-hidden");
1678 SE.contextMenus.assignToDialogue.render();
1679 SE.contextMenus.assignToDialogue.show();
1683 * Marks email flagged on mail server
1685 markFlagged : function(contextMenuId) {
1686 SE.contextMenus.markEmail('flagged');
1690 * Marks email unflagged on mail server
1692 markUnflagged : function(contextMenuId) {
1693 SE.contextMenus.markEmail('unflagged');
1697 * Marks email unread on mail server
1699 markUnread : function() {
1700 SE.contextMenus.markEmail('unread');
1704 * Deletes an email from context menu
1706 markDeleted : function() {
1707 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1708 document.getElementById('_blank').innerHTML = "";
1709 SE.contextMenus.markEmail('deleted');
1714 * generic call API to apply a flag to emails on the server and on sugar
1715 * @param string type "read" | "unread" | "flagged" | "deleted"
1717 markEmail : function(type) {
1718 SE.contextMenus.emailListContextMenu.hide();
1720 //var dm = SE.grid.getStore();
1721 //var uids = SE.grid.getSelectedRowIds();
1722 //var indexes = SE.grid.getSelectedRowIndexes();
1723 var rows = SE.grid.getSelectedRows();
1724 if (rows.length == 0)
1725 rows = [SE.contextMenus.currentRow];
1728 for(var i=0; i<rows.length; i++) {
1729 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1732 ser = YAHOO.lang.JSON.stringify(ser);
1734 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1735 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1741 if(type == 'read' || type == 'deleted') {
1743 for(var j=0; j<rows.length; j++) {
1744 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1746 SE.grid.getRecord(rows[j]).setData("seen", "1");
1749 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1751 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1752 var unseenCount = node.data.unseen;
1753 if (isNaN(unseenCount)) {
1756 var finalCount = parseInt(unseenCount) - count;
1757 node.data.unseen = finalCount;
1759 SE.accounts.renderTree();
1761 } else if(type == 'unread') {
1763 for(var j=0; j<rows.length; j++) {
1764 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1769 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1770 var unseenCount = node.data.unseen;
1771 if (isNaN(unseenCount)) {
1774 var finalCount = parseInt(unseenCount) + count;
1775 node.data.unseen = finalCount;
1776 SE.accounts.renderTree();
1779 if (type == 'unread') {
1780 for(var i=0; i<rows.length; i++) {
1781 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1785 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1786 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1790 * refreshes the ListView to show changes to cache
1792 markEmailCleanup : function() {
1793 SE.accounts.renderTree();
1794 SUGAR.hideMessageBox();
1795 SE.listView.refreshGrid();
1798 showAssignmentDialog : function() {
1799 if (SE.contextMenus.assignmentDialog == null) {
1800 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1802 SE.contextMenus.assignmentDialog.show();
1807 * shows the import dialog with only relate visible.
1809 relateTo : function() {
1810 SE.contextMenus.emailListContextMenu.hide();
1812 var rows = SE.grid.getSelectedRows();
1813 var data = SE.grid.getRecord(rows[0]).getData();
1814 var ieId = data.ieId;
1815 var folder = data.mbox;
1817 /* iterate through available rows JIC a row is deleted - use first available */
1818 for(var i=0; i<rows.length; i++) {
1819 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1821 var ser = YAHOO.lang.JSON.stringify(uids);
1823 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1827 * shows the import dialog with only relate visible.
1829 showDetailView : function() {
1830 SE.contextMenus.emailListContextMenu.hide();
1831 var rows = SE.grid.getSelectedRows();
1832 if (rows.length > 1) {
1833 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1836 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1837 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1838 /* iterate through available rows JIC a row is deleted - use first available */
1839 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1840 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1846 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1847 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1848 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1852 * Opens multiple messages from ListView context click
1854 openMultiple : function() {
1855 SE.contextMenus.emailListContextMenu.hide();
1857 var rows = SE.grid.getSelectedRows();
1858 var uids = SE.listView.getUidsFromSelection();
1860 if(uids.length > 0) {
1861 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1862 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1863 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1868 * Replies/forwards email
1870 replyForwardEmailContext : function() {
1871 SE.contextMenus.emailListContextMenu.hide();
1873 var indexes = SE.grid.getSelectedRows();
1874 //var dm = SE.grid.getDataModel();
1877 for(var i=0; i<indexes.length; i++) {
1878 var row = SE.grid.getRecord(indexes[i]).getData();
1879 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1883 //show menu functions
1884 showEmailsListMenu : function(grid, row) {
1886 var data = row.getData();
1887 var draft = (data.type == "draft");
1888 var menu = SE.contextMenus.emailListContextMenu;
1893 if (data.mbox == 'sugar::Emails')
1894 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1896 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1898 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1899 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1900 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1901 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1903 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1906 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1908 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1909 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1910 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1911 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1912 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1915 if (data.mbox == "sugar::Emails")
1917 //Allow users to reassign imported emails
1918 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1919 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1920 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1921 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1925 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1926 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1930 showFolderMenu : function(grid, rowIndex, event) {
1932 var coords = event.getXY();
1933 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1937 SE.contextMenus.dv = {
1938 archiveToSugar : function(contextMenuId) {
1940 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1943 replyForwardEmailContext : function(all) {
1944 SE.contextMenus.detailViewContextMenu.hide();
1953 //// END SE.contextMenus
1954 ///////////////////////////////////////////////////////////////////////////////
1958 ///////////////////////////////////////////////////////////////////////////////
1961 consumeMetaDetail : function(ret) {
1962 // handling if the Email drafts
1963 if(ret.type == 'draft') {
1964 SE.composeLayout.c0_composeDraft();
1969 // cache contents browser-side
1970 SE._setDetailCache(ret);
1972 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1973 // 2 below must be in global context
1975 meta['panelId'] = SE.util.getPanelId();
1977 email = ret.meta.email;
1978 var out = displayTemplate.exec({
1979 'app_strings' : app_strings,
1981 'idx' : targetDiv.id,
1983 'email' : meta.email,
1984 'linkBeans' : linkBeans
1986 var tabLabel = meta.email.name;
1987 if (tabLabel != null && tabLabel.length > 25) {
1988 tabLabel = tabLabel.substring(0, 25) + "...";
1990 targetDiv.set("label", tabLabel);
1991 targetDiv.set("content", out);
1993 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1994 if (SUGAR.email2.util.isIe()) {
1995 displayEmailFrameDiv.style.height = "390px";
1997 displayEmailFrameDiv.style.height = "410px";
2000 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
2001 displayFrame.contentWindow.document.write(email.description);
2002 displayFrame.contentWindow.document.close();
2004 // hide archive links
2005 if(ret.meta.is_sugarEmail) {
2006 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
2007 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
2009 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
2010 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
2015 consumeMetaPreview : function(ret) {
2016 // cache contents browser-side
2017 SE._setDetailCache(ret);
2021 var currrow = SE.grid.getLastSelectedRecord();
2022 currrow = SE.grid.getRecord(currrow);
2024 document.getElementById('_blank').innerHTML = '';
2027 // handling if the Email drafts
2028 if(ret.type == 'draft'){
2029 if (currrow.getData().uid == ret.uid) {
2030 SE.composeLayout.c0_composeDraft();
2035 if (currrow.getData().uid != ret.meta.uid) {
2039 // remove loading sprite
2040 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2041 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2043 meta['panelId'] = SE.util.getPanelId();
2044 email = ret.meta.email;
2046 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2047 'app_strings' : app_strings,
2051 'email' :meta.email,
2052 'linkBeans' : linkBeans
2054 // document.getElementById('_blank').innerHTML = meta.email;
2055 /* displayTemplate.append('_blank', {
2056 'app_strings' : app_strings,
2060 'email' :meta.email,
2061 'linkBeans' : linkBeans
2064 var displayFrame = document.getElementById('displayEmailFramePreview');
2065 displayFrame.contentWindow.document.write(email.description);
2066 displayFrame.contentWindow.document.close();
2068 SE.listViewLayout.resizePreview();
2070 // hide archive links
2071 if(ret.meta.is_sugarEmail) {
2072 document.getElementById("archiveEmailPreview").innerHTML = " ";
2073 document.getElementById("btnEmailViewPreview").style.display = "none";
2074 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2076 //hide view relationship link
2077 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2082 * wraps emailDelete() for single messages, comes from preview or tab
2084 emailDeleteSingle : function(ieId, uid, mbox) {
2085 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2086 // find active panel and close if the user double clicked the email to view.
2087 var activeTabId = SE.util.getPanelId();
2088 if(activeTabId != 'Preview')
2089 SE.innerLayout.get("activeTab").close();
2091 document.getElementById('_blank').innerHTML = "";
2094 uid = YAHOO.lang.JSON.stringify(ser);
2095 this.emailDelete(ieId, uid, mbox);
2100 * Sends async call to delete a given message
2103 emailDelete : function(ieId, uid, mbox) {
2104 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2105 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2106 uid + "&ieId=" + ieId + "&folder=" + mbox);
2110 * retrieves one email to display in the preview pane.
2112 getEmailPreview : function() {
2113 var row = SUGAR.email2.listView.currentRow;
2114 var data = row.getData();
2115 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2116 var setRead = (data['seen'] == 0) ? true : false;
2117 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2118 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2123 * Imports one email into Sugar
2125 importEmail : function(ieId, uid, mbox) {
2126 SE.util.clearHiddenFieldValues('emailUIForm');
2128 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2130 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2131 AjaxObject.target = '';
2132 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2136 * Populates the frameFlex div with the contents of an email
2138 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2139 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2141 var mboxStr = new String(mbox);
2142 var compKey = mbox + uid;
2144 if(setRead == true) {
2145 SE.listView.boldUnreadRows()
2146 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2149 if(destination == SE.innerLayout) {
2151 * loading email into a tab, peer with ListView
2152 * targetDiv must remain in the global namespace as it is used by AjaxObject
2154 //Check if we already have a tab of the email open
2155 var tabs = SE.innerLayout.get("tabs");
2156 for (var t in tabs) {
2157 if (tabs[t].id && tabs[t].id == uid) {
2158 SE.innerLayout.set("activeTab", tabs[t]);
2163 targetDiv = new YAHOO.SUGAR.ClosableTab({
2164 label: loadingSprite,
2170 SE.innerLayout.addTab(targetDiv);
2172 // use cache if available
2173 if(SE.cache[compKey]) {
2174 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2176 // open email as peer-tab to listView
2177 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2178 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2181 // loading email into preview pane
2182 document.getElementById('_blank').innerHTML = loadingSprite;
2184 // use cache if available
2185 if(SE.cache[compKey]) {
2186 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2188 AjaxObject.forceAbort = true;
2189 // open in preview window
2190 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2191 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2196 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2198 if(mboxStr.substring(0,7) == 'sugar::') {
2199 // display an email from Sugar
2200 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2202 // display an email from an email server
2203 document.getElementById('emailUIAction').value = 'getSingleMessage';
2205 document.getElementById('mbox').value = mbox;
2206 document.getElementById('ieId').value = ieId;
2207 document.getElementById('uid').value = uid;
2209 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2211 AjaxObject.forceAbort = true;
2212 AjaxObject.target = '_blank';
2213 AjaxObject.startRequest(callback, null);
2217 * Retrieves multiple emails for DetailView
2219 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2220 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2221 SE.util.clearHiddenFieldValues('emailUIForm');
2223 var mboxStr = new String(mbox);
2225 uids = SE.util.cleanUids(uids);
2227 if(mboxStr.substring(0,7) == 'sugar::') {
2228 // display an email from Sugar
2229 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2230 document.getElementById('uid').value = uids;
2232 // display an email from an email server
2233 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2234 document.getElementById('mbox').value = mbox;
2235 document.getElementById('ieId').value = ieId;
2236 document.getElementById('uid').value = uids;
2239 var formObject = document.getElementById('emailUIForm');
2240 YAHOO.util.Connect.setForm(formObject);
2242 AjaxObject.target = 'frameFlex';
2243 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2245 if(setRead == true) {
2246 var c = uids.split(",");
2247 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2252 * Makes async call to get QuickCreate form
2253 * Renders a modal edit view for a given module
2255 quickCreate : function(module, ieId, uid, mailbox) {
2256 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2258 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2259 get += "&sugarEmail=true";
2262 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2266 * Makes async call to save a quick create
2269 saveQuickCreate : function(action) {
2270 var qcd = SE.detailView.quickCreateDialog;
2271 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2272 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2273 var theCallback = callbackQuickCreateSave;
2274 var accountType = '&sugarEmail=true';
2275 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2276 accountType = '&ieId=' + qcd.ieId;
2279 if (action == 'reply') {
2280 theCallback = callbackQuickCreateSaveAndReply;
2281 } else if (action == true) {
2282 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2284 formObject.action.value = 'EmailUIAjax';
2285 YAHOO.util.Connect.setForm(formObject);
2286 SUGAR.showMessageBox('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2287 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2288 accountType + '&mbox=' + qcd.mbox);
2293 * Code to show/hide long list of email address in DetailView
2295 showCroppedEmailList : function(el) {
2296 el.style.display = 'none';
2297 el.previousSibling.style.display = 'inline'
2299 showFullEmailList : function(el) {
2300 el.style.display = 'none';
2301 el.nextSibling.style.display = 'inline';
2305 * Shows the QuickCreate overlay
2306 * @param string ieId
2308 * @param string mailbox
2310 showQuickCreate : function(ieId, uid, mailbox) {
2311 var panelId = SE.util.getPanelId();
2312 var context = document.getElementById("quickCreateSpan" + panelId);
2314 if (!SE.detailView.cqMenus)
2315 SE.detailView.cqMenus = {};
2317 if (SE.detailView.cqMenus[context])
2318 SE.detailView.cqMenus[context].destroy();
2320 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2322 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2325 for (var i=0; i < this.qcmodules.length; i++) {
2326 var module = this.qcmodules[i];
2328 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2331 onclick: { fn: function() {
2332 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2338 menu.render(document.body);
2343 * Displays the "View" submenu in the detailView
2344 * @param string ieId
2346 * @param string mailbox
2348 showViewMenu : function(ieId, uid, mailbox) {
2349 var panelId = SE.util.getPanelId();
2350 var context = "btnEmailView" + panelId;
2351 if (!SE.detailView.viewMenus)
2352 SE.detailView.viewMenus = {};
2354 if (SE.detailView.viewMenus[context])
2355 SE.detailView.viewMenus[context].destroy();
2357 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2359 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2363 (ieId == 'null' || ieId == null) ?
2364 //No ieId - Sugar Email
2366 text: app_strings.LBL_EMAIL_VIEW_RAW,
2367 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2370 //IeID exists, on a remote server
2372 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2373 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2375 text: app_strings.LBL_EMAIL_VIEW_RAW,
2376 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2379 menu.render(document.body);
2384 //#23108 jchi@07/17/2008
2385 menu.render('quickCreateSpan'+ panelId);*/
2386 //this.viewMenu = menu;
2387 //this.viewMenu.show(context);
2390 * Makes async call to get an email's headers
2392 viewHeaders : function(ieId, uid, mailbox) {
2393 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2394 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2398 * Makes async call to get a printable version
2400 viewPrintable : function(ieId, uid, mailbox) {
2401 if(mailbox == 'sugar::Emails') {
2402 // display an email from Sugar
2403 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2405 // display an email from an email server
2406 var emailUIAction = '&emailUIAction=getSingleMessage';
2409 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2410 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2414 * Makes async call to get an email's raw source
2416 viewRaw : function(ieId, uid, mailbox) {
2417 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2418 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2422 * Display all email addresses in detailview.
2424 displayAllAddrs : function(el) {
2425 el.style.display = 'none';
2426 Dom.getNextSibling(el).style.display = 'inline';
2429 //// END SE.detailView
2430 ///////////////////////////////////////////////////////////////////////////////
2434 ///////////////////////////////////////////////////////////////////////////////
2437 contextMenuFocus : new Object(),
2440 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2441 * SugarFolder ID - folder strings
2443 _createFolderId : function(node) {
2449 if(node.data.ieId) {
2450 /* we have a local Sugar folder */
2451 if(node.data.ieId == 'folder') {
2452 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2453 } else if(node.data.ieId.match(SE.reGUID)) {
2454 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2463 addChildNode : function(parentNode, childNode) {
2464 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2465 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2466 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2468 if(childNode.nodes) {
2469 if(childNode.nodes.length > 0) {
2470 for(j=0; j<childNode.nodes.length; j++) {
2471 var newChildNode = childNode.nodes[j];
2472 this.addChildNode(node, newChildNode);
2479 * Builds and returns a new TreeView Node
2480 * @param string name
2482 * @param int is_group
2485 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2486 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2488 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2489 node.expanded = expanded;
2490 node.data = new Object;
2491 node.data['id'] = id;
2492 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2493 node.data['label'] = name;
2494 node.data['ieId'] = 'folder';
2495 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2496 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2497 node.data['unseen'] = unseen;
2502 * ensures that a new folder has a valid name
2504 checkFolderName : function(name) {
2508 this.folderAdd(name);
2512 * Pings email servers for new email - forces refresh of folder pane
2514 checkEmailAccounts : function() {
2515 this.checkEmailAccountsSilent(true);
2518 checkEmailAccountsSilent : function(showOverlay) {
2519 if(typeof(SE.folders.checkingMail)) {
2520 clearTimeout(SE.folders.checkingMail);
2523 // don't stomp an on-going request
2524 if(AjaxObject.currentRequestObject.conn == null) {
2526 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW,
2527 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2529 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2531 // wait 5 secs before trying again.
2532 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2537 * Starts check of all email Accounts using a loading bar for large POP accounts
2539 startEmailAccountCheck : function() {
2540 // don't do two checks at the same time
2541 if(!AjaxObject.requestInProgress()) {
2542 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2543 SE.accounts.ieIds = SE.folders.getIeIds();
2544 if (SE.accounts.ieIds.length > 0) {
2545 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2546 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2548 SUGAR.hideMessageBox();
2551 // wait 5 secs before trying again.
2552 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2557 * Checks a single Account check based on passed ieId
2559 startEmailCheckOneAccount : function(ieId, synch) {
2566 var node = SE.clickedFolderNode;
2567 if (node && !synch) {
2568 mbox = node.data.mbox;
2570 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2571 SE.accounts.ieIds = [ieId];
2572 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2573 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2578 * Empties trash for subscribed accounts
2580 emptyTrash : function() {
2581 SE.contextMenus.frameFoldersContextMenu.hide();
2582 SUGAR.showMessageBox(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2583 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2587 * Clears Cache files of the inboundemail account
2589 clearCacheFiles : function(ieId) {
2590 SE.contextMenus.frameFoldersContextMenu.hide();
2591 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2592 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2597 * Returns an array of all the active accounts in the folder view
2599 getIeIds : function() {
2601 var root = SE.tree.getRoot();
2602 for(i=0; i < root.children.length; i++) {
2603 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2604 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2605 ieIds.push(root.children[i].children[0].data.ieId);
2612 * loads folder lists in Settings->Folders
2614 lazyLoadSettings : function() {
2615 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2616 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2620 * After the add new folder is done via folders tab on seetings, this function should get called
2621 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2623 loadSettingFolder : function() {
2624 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2625 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2629 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2631 removeSugarFolders : function() {
2633 var root = tree.getRoot();
2634 var folder = SE.util.findChildNode(root, "ieId", "folder");
2636 tree.removeNode(folder);
2637 folder = SE.util.findChildNode(root, "ieId", "folder");
2639 if (!root.childrenRendered) {
2640 root.childrenRendered = true;
2644 rebuildFolders : function(silent) {
2645 if (!silent) SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2646 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2652 * Updates TreeView with Sugar Folders
2654 setSugarFolders : function(delay) {
2655 this.removeSugarFolders();
2656 //AjaxObject.forceAbort = true;
2657 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2661 * Takes async data object and creates the sugar folders in TreeView
2663 setSugarFoldersEnd : function(o) {
2664 var root = SE.tree.getRoot();
2665 addChildNodes(root, {nodes: o});
2666 SE.accounts.renderTree();
2667 //If nothing is loaded in the grid, load "My Inbox"
2668 if (SE.grid.params.ieId == "undefined") {
2669 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2673 startCheckTimer : function() {
2674 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2675 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2677 if(typeof(SE.folders.checkTimer) != 'undefined') {
2678 clearTimeout(SE.folders.checkTimer);
2681 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2682 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2684 SE.userPrefs.emailSettings.firstAutoCheck = true;
2685 SE.folders.checkEmailAccountsSilent(false);
2691 * makes an async call to save user preference and refresh folder view
2692 * @param object SELECT list object
2694 setFolderSelection : function() {
2695 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2697 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2698 var a_active_accnts = "";
2699 for(i=0;i<a_rs.length;i++)
2701 var t_record = a_rs[i];
2702 var is_active = t_record.getData('is_active');
2704 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2707 if(a_active_accnts == "")
2708 a_active_accnts = "&ieIdShow[]=";
2710 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2712 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2716 * makes async call to save user preference for a given node's open state
2717 * @param object node YUI TextNode object
2719 setOpenState : function(node) {
2720 SE.util.clearHiddenFieldValues('emailUIForm');
2721 var nodePath = node.data.id;
2722 var nodeParent = node.parent;
2724 while(nodeParent != null) {
2725 // root node has no ID param
2726 if(nodeParent.data != null) {
2727 nodePath = nodeParent.data.id + "::" + nodePath;
2730 var nodeParent = nodeParent.parent;
2733 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2734 document.getElementById('focusFolder').value = nodePath;
2736 if(node.expanded == true) {
2737 document.getElementById('focusFolderOpen').value = 'open';
2739 document.getElementById('focusFolderOpen').value = 'closed';
2742 var formObject = document.getElementById('emailUIForm');
2743 YAHOO.util.Connect.setForm(formObject);
2745 AjaxObject.startRequest(null, null);
2748 getNodeFromMboxPath : function(path) {
2749 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2750 var a = YAHOO.lang.JSON.parse(path);
2752 var node = tree.getRoot();
2755 while(i < a.length) {
2756 node = this.getChildNodeFromLabel(node, a[i]);
2763 getChildNodeFromLabel : function(node, nodeLabel) {
2764 for(i=0; i<node.children.length; i++) {
2765 if(node.children[i].data.id == nodeLabel) {
2766 return node.children[i];
2772 * returns the node that presumably under the user's right-click
2774 getNodeFromContextMenuFocus : function() {
2775 //// get the target(parent) node
2776 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2778 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2780 // filter local folders
2781 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2782 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2783 if(target.id == '') {
2784 target = target.parentNode;
2791 var targetNode = document.getElementById(target.id);
2792 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2795 var matches = re.exec(targetNode.id);
2797 return document.getElementById(ygtvlabelel1);
2803 // usually parent node
2804 matches = re.exec(targetNode.parentNode.id);
2811 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2812 parentNode.expand();
2818 * Decrements the Unread Email count in folder text
2819 * @param string ieId ID to look for
2820 * @param string mailbox name
2821 * @param count how many to decrement
2823 decrementUnreadCount : function(ieId, mbox, count) {
2828 if(mbox.indexOf("sugar::") === 0) {
2829 var node = this.getNodeFromId(ieId);
2831 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2834 var unseen = node.data.unseen;
2836 var check = unseen - count;
2837 var finalCount = (check >= 0) ? check : 0;
2838 node.data.unseen = finalCount;
2840 SE.accounts.renderTree();
2845 * gets the TreeView node with a given ID/ieId
2846 * @param string id ID to look for
2847 * @return object Node
2849 getNodeFromId : function(id) {
2850 SE.folders.focusNode = null;
2851 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2852 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2853 SE.folders.focusNode = this;
2857 return SE.folders.focusNode;
2861 * Uses ieId and mailbox to try to find a node in the tree
2863 getNodeFromIeIdAndMailbox : function(id, mbox) {
2864 SE.folders.focusNode = null;
2865 if (mbox == "sugar::Emails") {
2869 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2870 if (varsarray instanceof Array) {
2871 if (this.data.ieId && this.data.ieId == varsarray[0]
2872 && this.data.mbox == varsarray[1]) {
2873 SE.folders.focusNode = this;
2877 if (this.data.ieId && this.data.ieId == varsarray) {
2878 SE.folders.focusNode = this;
2882 }, null, [id, mbox]);
2883 return SE.folders.focusNode;
2886 unhighliteAll : function() {
2887 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2891 * Displays a short form
2893 folderAdd : function() {
2894 SE.contextMenus.frameFoldersContextMenu.hide();
2896 var node = SE.clickedFolderNode;
2898 if(node != null && node.data) {
2899 SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2900 app_strings.LBL_EMAIL_SETTINGS_NAME,
2901 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2903 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2907 folderAddRegisterEnter : function() {
2908 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2909 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2910 this.buttons[1].handler);
2912 this.enterKeyListener.enable();
2915 folderRemoveRegisterEnter : function() {
2916 this.enterKeyListener.disable();
2919 folderAddXmlCall : function(name) {
2920 if (trim(name) == "") {
2921 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2924 name = escape(name);
2928 var parentNode = SE.clickedFolderNode;
2930 this.contextMenuFocus = parentNode;
2932 if(parentNode.data.ieId) {
2933 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2937 if(type == 'imap') {
2938 // make an IMAP folder
2939 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2940 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2941 } else if(type == 'sugar') {
2942 // make a Sugar folder
2943 if(SE.folders.isUniqueFolderName(name)) {
2944 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2945 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2947 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2948 SE.folders.folderAdd();
2952 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2955 // hide add-folder diaglogue
2956 SE.e2overlay.hide();
2960 * Removes either an IMAP folder or a Sugar Folder
2962 folderDelete : function() {
2963 SE.contextMenus.frameFoldersContextMenu.hide();
2965 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2967 var parentNode = SE.clickedFolderNode;
2969 if(parentNode != null && parentNode.data) {
2970 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2971 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2975 AjaxObject.target = 'frameFlex';
2977 if(parentNode.data.ieId != 'folder') {
2978 // delete an IMAP folder
2979 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2981 // delete a sugar folder
2982 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2984 SUGAR.showMessageBox("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2985 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2987 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2993 * Rename folder form
2996 folderRename : function() {
2997 SE.contextMenus.frameFoldersContextMenu.hide();
2998 var node = SE.clickedFolderNode;
3001 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
3002 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
3006 SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
3007 app_strings.LBL_EMAIL_SETTINGS_NAME,
3009 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
3011 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
3016 * fills an Object with key-value pairs of available folders
3018 getAvailableFoldersObject : function() {
3019 var ret = new Object();
3020 var tree = SE.tree.root;
3023 for(var i=0; i<tree.children.length; i++) {
3024 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3027 ret['none'] = app_strings.LBL_NONE;
3034 * Fills in key-value pairs for dependent dropdowns
3035 * @param object ret Associative array
3036 * @param object node TreeView node in focus
3037 * @param string currentPath Built up path thus far
3038 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3040 getFolderFromChild : function(ret, node, currentPath, spacer) {
3041 if(node.data != null && node.depth > 0) {
3042 /* handle visual separtors differentiating b/t mailserver and local */
3043 if(node.data.ieId && node.data.ieId == 'folder') {
3044 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3048 ret['spacer0'] = spacer;
3049 } else if(ret.spacer0 != spacer) {
3050 ret['spacer1'] = spacer
3053 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3054 var depthMarker = currentPath;
3055 var retIndex = SE.folders._createFolderId(node);
3056 ret[retIndex] = depthMarker + theLabel;
3059 if(node.children != null) {
3061 currentPath += theLabel + "/";
3064 for(var i=0; i<node.children.length; i++) {
3065 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3073 * Wrapper to refresh folders tree
3075 getFolders : function() {
3076 SE.accounts.rebuildFolderList();
3080 * handles events around folder-rename input field changes
3081 * @param object YUI event object
3083 handleEnter : function(e) {
3084 switch(e.browserEvent.type) {
3086 e.preventDefault(); // click in text field
3090 SE.folders.submitFolderRename(e);
3094 var kc = e.browserEvent.keyCode;
3098 SE.folders.submitFolderRename(e);
3102 e.preventDefault(e);
3103 SE.folders.cancelFolderRename(e);
3110 * Called when a node is clicked on in the folder tree
3111 * @param node, The node clicked on
3112 * @param e, The click event
3114 handleClick : function(o) {
3116 //If the click was on a sugar folder
3117 if (node.data.ieId == "folder") {
3118 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3121 SE.listView.populateListFrame(node, node.data.ieId, false);
3123 //eval(node.data.click);
3128 * Called when a node is right-clicked on in the folder tree
3130 handleRightClick : function(e) {
3131 YAHOO.util.Event.preventDefault(e);
3133 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3134 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3136 //If the click was on a sugar folder
3137 SE.clickedFolderNode = node;
3138 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3139 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3140 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3141 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3142 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3143 menu.getItem(3).cfg.setProperty("disabled", false);
3144 menu.getItem(4).cfg.setProperty("disabled", false);
3145 menu.getItem(5).cfg.setProperty("disabled", false);
3146 menu.getItem(6).cfg.setProperty("disabled", true);
3148 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3149 menu.getItem(0).cfg.setProperty("disabled", true);
3150 menu.getItem(1).cfg.setProperty("disabled", true);
3151 menu.getItem(2).cfg.setProperty("disabled", true);
3152 menu.getItem(3).cfg.setProperty("disabled", true);
3153 menu.getItem(4).cfg.setProperty("disabled", true);
3155 if (node.data.protocol != null) {
3156 menu.getItem(6).cfg.setProperty("disabled", false);
3158 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3159 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3160 //Sent or Draft folders
3161 menu.getItem(3).cfg.setProperty("disabled", true);
3162 menu.getItem(4).cfg.setProperty("disabled", true);
3163 menu.getItem(5).cfg.setProperty("disabled", true);
3166 //For group with auto inbound, disable everything.
3167 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3169 menu.getItem(0).cfg.setProperty("disabled", true);
3170 menu.getItem(1).cfg.setProperty("disabled", true);
3171 menu.getItem(2).cfg.setProperty("disabled", true);
3172 menu.getItem(3).cfg.setProperty("disabled", true);
3173 menu.getItem(4).cfg.setProperty("disabled", true);
3174 menu.getItem(5).cfg.setProperty("disabled", true);
3175 menu.getItem(6).cfg.setProperty("disabled", true);
3178 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3183 * Called when a row is dropped on a node
3185 handleDrop : function(rows, targetFolder) {
3186 var rowData = rows[0].getData();
3187 if (rowData.mbox != targetFolder.data.mbox) {
3188 var srcIeId = rowData.ieId;
3189 var srcFolder = rowData.mbox;
3190 var destIeId = targetFolder.data.ieId;
3191 var destFolder = targetFolder.data.mbox;
3193 for(var i=0; i<rows.length; i++) {
3194 uids[i] = rows[i].getData().uid;
3196 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3201 * Called when something is dragged over a Folder Node
3203 dragOver : function(dragObject) {
3208 * Determines if a folder name is unique to the folder tree
3209 * @param string name
3211 isUniqueFolderName : function(name) {
3212 uniqueFolder = true;
3213 var root = SE.tree.getRoot();
3214 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3215 if (this.attributes && this.attributes.ieId == "folder") {
3216 if (this.attributes.text == name) {
3217 uniqueFolder = false;
3222 return uniqueFolder;
3226 * Makes async call to rename folder in focus
3227 * @param object e Event Object
3229 submitFolderRename : function(newName) {
3230 if (trim(newName) == "") {
3231 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3234 newName = escape(newName);
3235 var node = SE.clickedFolderNode;
3236 var origName = node.data.text
3238 if (newName == origName) {
3241 if(SE.folders.isUniqueFolderName(newName)) {
3242 SUGAR.showMessageBox(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3243 if (node.data.ieId == "folder") {
3245 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3248 //IMAP folder or POP mailbox
3249 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3250 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3251 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3255 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3260 moveFolder : function(folderId, parentFolderId) {
3261 if (folderId != parentFolderId)
3263 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3264 + folderId + "&newParentId=" + parentFolderId);
3269 * makes async call to do a full synchronization of all accounts
3271 synchronizeAccounts : function() {
3272 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3273 SUGAR.showMessageBoxModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3274 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3279 * Updates user's folder subscriptsion (Sugar only)
3280 * @param object SELECT DOM object in focus
3281 * @param string type of Folder selection
3283 updateSubscriptions : function() {
3284 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3288 select = document.getElementById('userFolders');
3290 for(i=0; i<select.options.length; i++) {
3291 var opt = select.options[i];
3292 if(opt.selected && opt.value != "") {
3296 active += opt.value;
3300 //Add the group folder ids.
3301 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3302 for(i=0; i<group_folders.length; i++)
3304 active += ("::" + group_folders[i]);
3307 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3310 * Updates user's group folder subscriptsion (Sugar only)
3311 * @param ieID The group folder to add to the tree view
3313 retrieveGroupFolderSubscriptions : function() {
3315 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3316 var activeGroupFolders = "";
3317 var activeGroupIds = [];
3318 for(i=0;i<a_rs.length;i++)
3320 var t_record = a_rs[i];
3321 var is_active = t_record.getData('is_active');
3322 var isGroupFolder = t_record.getData('has_groupfolder');
3323 var ieID = t_record.getData('id');
3327 activeGroupIds.push(ieID);
3331 return activeGroupIds;
3336 SE.folders.checkEmail2 = function() {
3337 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3339 //// END FOLDERS OBJECT
3340 ///////////////////////////////////////////////////////////////////////////////
3343 ///////////////////////////////////////////////////////////////////////////////
3346 * Keypress Event capture and processing
3349 overall : function(e) {
3350 switch(e.charCode) {
3352 if(e.ctrlKey || e.altKey) {
3353 var focusRegion = SE.innerLayout.regions.center;
3354 if(focusRegion.activePanel.closable == true) {
3355 focusRegion.remove(focusRegion.activePanel);
3363 ///////////////////////////////////////////////////////////////////////////////
3366 ///////////////////////////////////////////////////////////////////////////////
3369 * ListView object methods and attributes
3375 * Fills the ListView pane with detected messages.
3377 populateListFrame : function(node, ieId, forceRefresh) {
3378 SE.innerLayout.selectTab(0);
3379 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3381 Dom.get('_blank').innerHTML = "";
3382 SE.grid.params['emailUIAction'] = 'getMessageList';
3383 SE.grid.params['mbox'] = node.data.mbox;
3384 SE.grid.params['ieId'] = ieId;
3385 forcePreview = true; // loads the preview pane with first item in grid
3386 SE.listView.refreshGrid();
3390 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3392 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3393 SE.innerLayout.selectTab(0);
3394 Dom.get('_blank').innerHTML = "";
3395 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3396 SE.grid.params['ieId'] = node.data.id;
3397 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3398 SE.listView.refreshGrid();
3402 * Sets sort order as user preference
3405 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3407 ieName = ieNamePassed;
3408 focusFolder = focusFolderPassed;
3410 SE.util.clearHiddenFieldValues('emailUIForm');
3411 var previousSort = document.getElementById('sortBy').value;
3413 document.getElementById('sortBy').value = sortBy;
3414 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3415 document.getElementById('focusFolder').value = focusFolder;
3416 document.getElementById('ieId').value = ieId;
3418 if(sortBy == previousSort) {
3419 document.getElementById('reverse').value = '1';
3422 var formObject = document.getElementById('emailUIForm');
3423 YAHOO.util.Connect.setForm(formObject);
3425 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3430 * Enables click/arrow select of grid items which then populate the preview pane.
3432 selectFirstRow : function() {
3433 SE.grid.selModel.selectFirstRow();
3436 selectLastRow : function() {
3437 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3440 setEmailListStyles : function() {
3441 SE.listView.boldUnreadRows();
3443 var ds = SE.grid.getStore();
3444 if (SE.grid.getSelections().length == 0) {
3445 document.getElementById('_blank').innerHTML = '';
3449 if(typeof(ds.baseParams.mbox) != 'undefined') {
3450 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3451 var cm = SE.grid.getColumnModel();
3452 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3453 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3455 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3456 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3460 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3461 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3463 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3464 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3465 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3466 if (node) node.data.unseen = unread;
3468 SE.accounts.renderTree();
3471 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3472 if(forcePreview && ds.totalCount > 0) {
3473 SE.detailView.getEmailPreview();
3474 forcePreview = false;
3479 * Removes a row if found via its UID
3481 removeRowByUid : function(uid) {
3482 uid = new String(uid);
3483 uids = uid.split(',');
3484 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3486 for(j=0; j<uids.length; j++) {
3487 var theUid = uids[j];
3488 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3489 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3490 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3496 displaySelectedEmails : function(rows) {
3497 var dm = SE.grid.getDataModel();
3500 for(i=0; i<rows.length; i++) {
3501 var rowIndex = rows[i].rowIndex;
3502 var metadata = dm.data[rowIndex];
3507 uids += metadata[5];
3509 // unbold unseen email
3510 this.unboldRow(rowIndex);
3513 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3517 * exception handler for data load failures
3519 loadException : function(dataModel, ex, response) {
3524 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3525 * @param string sourceIeId Email's source I-E id
3526 * @param string sourceFolder Email's current folder
3527 * @param destinationIeId Destination I-E id
3528 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3530 * @param array emailUids Array of email's UIDs
3532 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3533 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3534 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3536 SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3537 // remove rows from visibility
3538 for(row in selectedRows) {
3539 //SE.grid.getStore().remove(row);
3542 var baseUrl = '&sourceIeId=' + sourceIeId +
3543 '&sourceFolder=' + sourceFolder +
3544 '&destinationIeId=' + destinationIeId +
3545 '&destinationFolder=' + destinationFolder;
3548 for(i=0; i<emailUids.length; i++) {
3550 uids += app_strings.LBL_EMAIL_DELIMITER;
3552 uids += emailUids[i];
3554 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3555 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3557 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3563 * Unbolds text in the grid view to denote read status
3565 markRead : function(index, record) {
3566 // unbold unseen email
3567 var row = SE.grid.getRecord(record);
3568 row.getData().seen = 1;
3569 SE.grid.getTrEl(record).style.fontWeight = "normal";
3573 * grid row output, bolding unread emails
3575 boldUnreadRows : function() {
3576 // bold unread emails
3577 var trEl = SE.grid.getFirstTrEl();
3578 while(trEl != null) {
3579 if(SE.grid.getRecord(trEl).getData().seen == "0")
3580 trEl.style.fontWeight = "bold";
3582 trEl.style.fontWeight = "";
3583 trEl = SE.grid.getNextTrEl(trEl);
3588 * Show preview for an email if 1 and only 1 is selected
3589 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3591 handleRowSelect : function(e) {
3592 if(e.selectedRows.length == 1) {
3593 SE.detailView.getEmailPreview();
3597 handleDrop : function(e, dd, targetId, e2) {
3599 case 'htmleditordiv':
3600 var rows = SE.grid.getSelectedRows();
3601 if(rows.length > 0) {
3602 SE.listView.displaySelectedEmails(rows);
3607 var targetElId = new String(targetId);
3608 var targetIndex = targetElId.replace('ygtvlabelel',"");
3609 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3610 var dm = SE.grid.getDataModel();
3611 var emailUids = new Array();
3612 var destinationIeId = targetNode.data.ieId;
3613 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3616 var rows = SE.grid.getSelectedRows();
3617 // iterate through dragged rows
3618 for(i=0; i<rows.length; i++) {
3619 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3620 var rowIndex = rows[i].rowIndex;
3621 var dataModelRow = dm.data[rowIndex];
3622 var sourceIeId = dataModelRow[7];
3623 var sourceFolder = dataModelRow[6];
3624 emailUids[i] = dataModelRow[5];
3627 // event wrapped call - need FQ
3628 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3629 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3635 * Hack-around to get double-click and single clicks to work on the grid
3636 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3638 handleClick : function(o) {
3639 SUGAR.email2.grid.clearTextSelection();
3641 var el = SUGAR.email2.grid.getSelectedRows();
3643 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3644 if ( el.length == 1)
3647 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3648 SUGAR.email2.listView.currentRowIndex = rowId;
3649 clearTimeout(SUGAR.email2.detailView.previewTimer);
3650 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3655 * Custom handler for double-click/enter
3656 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3658 getEmail : function(e) {
3659 var rows = SE.grid.getSelectedRows();
3660 var row = SE.grid.getRecord(rows[0]).getData();
3662 clearTimeout(SE.detailView.previewTimer);
3663 document.getElementById("_blank").innerHTML = "";
3665 if(row.type != "draft") {
3666 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3668 // circumventing yui-ext tab generation, let callback handler build new view
3669 SE.util.clearHiddenFieldValues('emailUIForm');
3670 //function(uid, mbox, ieId, setRead, destination) {
3671 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3672 document.getElementById('uid').value = row.uid; // uid;
3673 document.getElementById('mbox').value = row.mbox; // mbox;
3674 document.getElementById('ieId').value = row.ieId; // ieId;
3676 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3677 AjaxObject.target = '_blank';
3678 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3683 * Retrieves a row if found via its UID
3687 getRowIndexByUid : function(uid) {
3688 uid = new String(uid);
3689 uids = uid.split(',');
3691 for(j=0; j<uids.length; j++) {
3692 var theUid = uids[j];
3694 for(i=0; i<SE.grid.getStore().data.length; i++) {
3695 if(SE.grid.getStore().data[i].id == theUid) {
3703 * Returns the UID's of the seleted rows
3706 getUidsFromSelection : function() {
3707 var rows = SE.grid.getSelectedRows();
3709 /* iterate through available rows JIC a row is deleted - use first available */
3710 for(var i=0; i<rows.length; i++) {
3711 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3716 refreshGrid : function() {
3717 SE.grid.getDataSource().sendRequest(
3718 SUGAR.util.paramsToUrl(SE.grid.params),
3719 SE.grid.onDataReturnInitializeTable,
3725 //// END SE.listView
3726 ///////////////////////////////////////////////////////////////////////////////
3728 ///////////////////////////////////////////////////////////////////////////////
3732 * sends search criteria
3733 * @param reference element search field
3735 search : function(el) {
3736 var searchCriteria = new String(el.value);
3738 if(searchCriteria == '') {
3739 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3743 var safeCriteria = escape(searchCriteria);
3745 var accountListSearch = document.getElementById('accountListSearch');
3747 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3748 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3749 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3750 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3751 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3756 * sends advanced search criteria
3758 searchAdvanced : function() {
3759 var formObject = document.getElementById('advancedSearchForm');
3762 //Set assigned user id to blank if name is not present.
3763 if (formObject.elements['assigned_user_name'].value == "")
3764 formObject.elements['assigned_user_id'].value = "";
3766 for(i=0; i<formObject.elements.length; i++) {
3767 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3770 if(formObject.elements[i].type == 'text') {
3771 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3773 if(formObject.elements[i].type == 'hidden') {
3774 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3776 if(formObject.elements[i].type == 'select-one') {
3777 var el = formObject.elements[i];
3778 var v = el.options[el.selectedIndex].value;
3781 SE.grid.params[el.name] = v;
3784 //Clear previous search results if necessary
3785 if(typeof( SE.grid.params[el.name]) != 'undefined')
3786 delete SE.grid.params[el.name]
3793 if(! this.validateSearchFormInput() )
3796 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3797 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3798 var accountListSearch = document.getElementById('accountListSearch');
3799 SE.listView.refreshGrid();
3801 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3806 * Validates the search form inputs to ensure all parameters are valid
3809 validateSearchFormInput: function()
3811 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3812 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3813 var dateCheck = check_form('advancedSearchForm');
3815 //If the parent type is selected ensure the user selected a parent_id.
3816 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3822 * Toggles the advanced options, either hidding or showing the selection.
3824 toggleAdvancedOptions: function()
3826 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3828 for(var i=0;i<el.length;i++)
3830 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3831 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3833 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3837 * clears adv search form fields
3839 searchClearAdvanced : function() {
3840 var form = document.getElementById('advancedSearchForm');
3842 for(i=0; i<form.elements.length; i++) {
3843 if(form.elements[i].type != 'button') {
3844 form.elements[i].value = '';
3850 //////////////////////////////////////////////////////////////////////////////
3853 //////////////////////////////////////////////////////////////////////////////
3856 /******************************************************************************
3857 * USER SIGNATURES calls stolen from Users module
3858 *****************************************************************************/
3859 createSignature : function(record, the_user_id) {
3860 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3862 URL += "&record="+record;
3864 if(the_user_id != "") {
3865 URL += "&the_user_id="+the_user_id;
3867 var windowName = 'email_signature';
3868 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3870 var win = window.open(URL, windowName, windowFeatures);
3871 if(win && win.focus) {
3872 // put the focus on the popup if the browser supports the focus() method
3877 deleteSignature : function() {
3878 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3879 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3880 var singature_id = document.getElementById('signature_id').value;
3881 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3885 saveOptionsGeneral : function(displayMessage) {
3886 var formObject = document.getElementById('formEmailSettingsGeneral');
3887 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3888 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3891 YAHOO.util.Connect.setForm(formObject);
3892 SE.composeLayout.emailTemplates = null;
3894 AjaxObject.target = 'frameFlex';
3895 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3898 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3900 SE.settings.settingsDialog.hide();
3904 * Shows settings container screen
3906 showSettings : function() {
3907 if(!SE.settings.settingsDialog) {
3908 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3914 constraintoviewport: true
3916 dlg.showEvent.subscribe( function (){
3917 var el = this.element;
3918 var viewH = YAHOO.util.Dom.getViewportHeight();
3919 if (this.header && el && viewH - 50 < el.clientHeight) {
3920 var body = this.header.nextElementSibling;
3921 body.style.overflow = "auto";
3922 body.style.height = (viewH - 50) + "px";
3925 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3926 dlg.setBody('<div id="settingsTabDiv"/>');
3927 dlg.beforeRenderEvent.subscribe(function() {
3928 var dd = new YAHOO.util.DDProxy(dlg.element);
3929 dd.setHandleElId(dlg.header);
3930 dd.on('endDragEvent', function() {
3936 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3937 var tabContent = Dom.get("tab_general");
3938 tp.addTab(new YAHOO.widget.Tab({
3939 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3941 content : tabContent.innerHTML,
3942 id : "generalSettings",
3945 tabContent.parentNode.removeChild(tabContent);
3946 tabContent = Dom.get("tab_accounts");
3947 var accountTab = new YAHOO.widget.Tab({
3948 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3950 content : tabContent.innerHTML,
3951 id : "accountSettings"
3953 tp.addTab(accountTab);
3954 tabContent.parentNode.removeChild(tabContent);
3956 tp.appendTo(dlg.body);
3959 SE.settings.settingsDialog.show();
3960 SE.folders.lazyLoadSettings();
3961 SE.accounts.lazyLoad();
3965 lazyLoadRules : function() {
3966 if(false/*!SE.settings.rules*/) {
3967 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3972 //// END SE.settings
3973 ///////////////////////////////////////////////////////////////////////////////
3976 /******************************************************************************
3978 *****************************************************************************/
3979 function removeHiddenNodes(nodes, grid) {
3981 for(var i = nodes.length - 1; i > -1; i--) {
3982 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3983 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3989 function strpad(val) {
3990 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3993 function refreshTodos() {
3994 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3995 AjaxObject.target = 'todo';
3996 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3999 /******************************************************************************
4000 * MUST STAY IN GLOBAL NAMESPACE
4001 *****************************************************************************/
4002 function refresh_signature_list(signature_id, signature_name) {
4003 var field=document.getElementById('signature_id');
4005 for (var i=0; i < field.options.length; i++) {
4006 if (field.options[i].value == signature_id) {
4007 if (field.options[i].selected==false) {
4008 field.options[i].selected=true;
4013 //add item to selection list.
4015 var newElement=document.createElement('option');
4016 newElement.text=signature_name;
4017 newElement.value=signature_id;
4018 field.options.add(newElement);
4019 newElement.selected=true;
4022 //enable the edit button.
4023 var field1=document.getElementById('edit_sig');
4024 field1.style.visibility="inherit";
4025 var deleteButt = document.getElementById('delete_sig');
4026 deleteButt.style.visibility="inherit";
4029 function setDefaultSigId(id) {
4030 var checkbox = document.getElementById("signature_default");
4031 var default_sig = document.getElementById("signatureDefault");
4033 if(checkbox.checked) {
4034 default_sig.value = id;
4036 default_sig.value = "";
4040 function setSigEditButtonVisibility() {
4041 var field = document.getElementById('signature_id');
4042 var editButt = document.getElementById('edit_sig');
4043 var deleteButt = document.getElementById('delete_sig');
4044 if(field.value != '') {
4045 editButt.style.visibility = "inherit";
4046 deleteButt.style.visibility = "inherit";
4048 editButt.style.visibility = "hidden";
4049 deleteButt.style.visibility = "hidden";
4051 }// End of File modules/Emails/javascript/EmailUI.js
4053 /*********************************************************************************
4054 * SugarCRM Community Edition is a customer relationship management program developed by
4055 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4057 * This program is free software; you can redistribute it and/or modify it under
4058 * the terms of the GNU Affero General Public License version 3 as published by the
4059 * Free Software Foundation with the addition of the following permission added
4060 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4061 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4062 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4064 * This program is distributed in the hope that it will be useful, but WITHOUT
4065 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4066 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4069 * You should have received a copy of the GNU Affero General Public License along with
4070 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4071 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4074 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4075 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4077 * The interactive user interfaces in modified source and object code versions
4078 * of this program must display Appropriate Legal Notices, as required under
4079 * Section 5 of the GNU Affero General Public License version 3.
4081 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4082 * these Appropriate Legal Notices must retain the display of the "Powered by
4083 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4084 * technical reasons, the Appropriate Legal Notices must display the words
4085 * "Powered by SugarCRM".
4086 ********************************************************************************/
4089 var sw = YAHOO.SUGAR,
4090 Event = YAHOO.util.Event,
4091 Connect = YAHOO.util.Connect,
4092 Dom = YAHOO.util.Dom
4095 ///////////////////////////////////////////////////////////////////////////////
4098 _contactCache : new Array(), // cache of contacts
4099 _dd : new Array(), // filtered list, same format as _contactCache
4100 _ddLists : new Array(), // list of Lists
4101 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4102 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4103 clickBubble : true, // hack to get around onclick event bubbling
4105 relatedBeanType : '',
4108 itemSpacing : 'white-space:nowrap; padding:2px;',
4114 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4116 initFixForDatatableSort: function () {
4117 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4118 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4119 var oColumn = this._oColumnSet.getColumn(column);
4122 // Validate TD element
4123 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4125 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4127 // Validate TH element
4129 elCell = this.getThEl(column);
4132 var allColumns = this._oColumnSet.flat;
4133 for(var i=0, len=allColumns.length; i<len; i++) {
4134 if(allColumns[i].getThEl().id === elCell.id) {
4135 oColumn = allColumns[i];
4146 cancelEdit : function() {
4147 if(this.editContactDialog)
4148 this.editContactDialog.hide();
4149 if(this.editMailingListDialog)
4150 this.editMailingListDialog.hide();
4154 * Clears filter form
4156 clear : function() {
4157 var t = document.getElementById('contactsFilter');
4163 * handle context-menu Compose-to call
4164 * @param string type 'contacts' or 'lists'
4166 composeTo : function(type, waited) {
4167 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4168 if (activePanel.substring(0, 10) != "composeTab") {
4169 SE.composeLayout.c0_composeNewEmail();
4170 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4171 SE.contextMenus.contactsContextMenu.hide();
4174 var idx = activePanel.substring(10);
4177 // determine if we have a selection to work with
4178 if(type == 'contacts') {
4179 var ids = SE.contactView.getSelectedRows();
4180 for (var i in ids) {
4181 rows[i] = SE.contactView.getRecord(ids[i]);
4183 removeHiddenNodes(rows, SE.contactView);
4187 if(rows.length > 0) {
4188 SE.composeLayout.handleDrop(
4189 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4190 null, rows, 'addressTO' + idx );
4192 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4196 editContact : function() {
4197 SE.contextMenus.contactsContextMenu.hide();
4198 var element = SE.contactView.getSelectedNodes()[0];
4200 if (element.className.indexOf('address-contact') > -1) {
4201 elementId = element.id;
4202 } else if (element.className.indexOf('address-exp-contact') > -1) {
4203 elementId = element.id.substring(2);
4209 * Filters contact entries based on user input
4211 filter : function(inputEl) {
4212 var ret = new Object();
4213 var re = new RegExp(inputEl.value, "gi");
4215 for(var i in this._contactCache) {
4216 if(this._contactCache[i].name.match(re)) {
4217 ret[i] = this._contactCache[i];
4221 this.buildContactList(ret);
4224 fullForm : function(id, module) {
4225 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4229 * returns a formatted email address from the addressBook cache
4231 getFormattedAddress : function(id) {
4232 var o = this._contactCache[id];
4233 var primaryEmail = '';
4235 for(var i=0; i<o.email.length; i++) {
4236 var currentEmail = o.email[i].email_address;
4238 if(o.email[i].primary_address == 1) {
4239 primaryEmail = o.email[i].email_address;
4243 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4244 var name = new String(o.name);
4245 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4246 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4252 * Sets up async call to query for matching contacts, users, etc.
4254 searchContacts : function() {
4255 var fn = document.getElementById('input_searchField').value;
4256 var pe = document.getElementById('input_searchPerson').value;
4258 var rb = document.getElementById('hasRelatedBean').checked;
4261 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4262 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4263 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4264 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4266 this.addressBookDataModel.params['related_bean_id'] = '';
4269 this.addressBookDataModel.params['search_field'] = fn;
4270 this.addressBookDataModel.params['person'] = pe;
4271 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4272 this.grid._oDataSource = this.addressBookDataModel;
4273 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4277 * Clear Search Crieteria For Addressbook
4279 clearAddressBookSearch : function() {
4280 document.getElementById('input_searchField').value = "";
4281 document.getElementById('input_searchPerson').selectedIndex = 0;
4285 * Opens modal select window to add contacts to addressbook
4287 selectContactsDialogue : function(destId) {
4288 if(!this.contactsDialogue) {
4289 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4293 constraintoviewport: true,
4295 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4296 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4298 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4300 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4301 dlg.setBody(body.innerHTML);
4302 dlg.renderEvent.subscribe(function() {
4303 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4304 if (iev && !SUGAR.isIE) {
4305 this.body.style.width = "950px";
4310 dlg.beforeRenderEvent.subscribe(function() {
4311 var dd = new YAHOO.util.DDProxy(dlg.element);
4312 dd.setHandleElId(dlg.header);
4313 dd.on('endDragEvent', function() {
4319 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4321 var tabContent = SUGAR.util.getAndRemove("searchForm");
4322 tp.addTab(new YAHOO.widget.Tab({
4323 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4325 content : tabContent.innerHTML,
4326 id : "addressSearchTab",
4330 var addListenerFields = ['input_searchPerson','input_searchField' ]
4331 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4332 if (e.keyCode == 13) {
4333 YAHOO.util.Event.stopEvent(e);
4334 SUGAR.email2.addressBook.searchContacts();
4338 this.contactsDialogue.render();
4341 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4342 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4346 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4347 var idx = activePanel.substring(10);
4349 SE.addressBook.idx = idx;
4352 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4353 document.getElementById('relatedBeanColumn').style.display = '';
4354 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4355 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4356 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4357 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4358 SE.addressBook.relatedBeanType = relatedBeanType;
4360 document.getElementById('relatedBeanColumn').style.display = 'none';
4361 document.getElementById('hasRelatedBean').checked = false;
4364 if (!SE.addressBook.grid)
4366 if (hasRelatedBeanId) {
4367 document.getElementById('hasRelatedBean').checked = true;
4369 AddressSearchGridInit();
4370 SE.addressBook.relatedBeanId = relatedBeanId;
4374 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4376 SE.addressBook.relatedBeanId = relatedBeanId;
4377 document.getElementById('hasRelatedBean').checked = true;
4379 if (document.getElementById('hasRelatedBean').checked == true)
4381 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4382 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4384 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4385 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4387 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4388 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4389 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4392 //Remove any lingering rows in the result set table if the module was closed.
4393 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4395 SE.addressBook.populateResulstTableEmailAddresses();
4397 this.contactsDialogue.show();
4400 * Clear all email addresses from result table.
4403 clearAllEmailAddressFieldsFromResultTable: function () {
4404 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4405 //Unhighlight any rows currently selected if the emails were cleared.
4406 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4407 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4410 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4411 * results table. This function is called when the address book is displayed.
4413 populateResulstTableEmailAddresses: function () {
4415 var idx = SE.addressBook.idx;
4416 var emailFields = ['to','cc','bcc'];
4418 for(var k=0;k<emailFields.length;k++)
4420 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4421 var allEmails = document.getElementById(elKey).value;
4425 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4427 for (var i=0; i<formatedEmails.length; i++)
4429 var t_name = formatedEmails[i].name;
4430 var t_emailAddr = formatedEmails[i].email_address;
4431 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4433 t_name = displayEmail = t_emailAddr;
4435 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4436 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4437 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4443 * Checks all entries in the result table against a particular email address, returning true
4444 * if the email address is found, false otherwise.
4446 doesEmailAdddressExistInResultTable: function(emailAddress)
4448 if(trim(emailAddress) == '')
4451 var emailAddressFound = false;
4452 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4453 for (var i=0; i < contacts.length; i++)
4455 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4456 //If we are adding to cc or bcc fields, make them visible.
4457 if(data.email_address == emailAddress)
4459 emailAddressFound = true;
4464 return emailAddressFound;
4467 * Takes all email addresses that the users wishes to add from the address book and populates the To
4468 * fields on the compose tab.
4470 populateEmailAddressFieldsFromResultTable: function()
4472 //Clear the fields first, all email addresses are stored in the address book
4473 var idx = SE.addressBook.idx;
4474 var emailFields = ['to','cc','bcc'];
4475 for(var k=0;k<emailFields.length;k++)
4477 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4478 document.getElementById(elKey).value = "";
4481 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4482 for (var i=0; i < contacts.length; i++)
4484 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4486 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4487 //If we are adding to cc or bcc fields, make them visible.
4488 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4489 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4490 //Construct the target id
4491 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4493 var target = document.getElementById(target_id);
4494 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4497 //Delete all rows from the result set table
4498 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4501 SE.addressBook.contactsDialogue.hide()
4504 * Insert contacts into the result table.
4506 insertContactToResultTable : function(event,address_type) {
4508 var contactsDialogue = SE.addressBook.contactsDialogue;
4509 var contacts = SE.addressBook.grid.getSelectedRows();
4511 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4512 for (var i = 0; i < rows.length; i++)
4514 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4516 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4517 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4518 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4519 rows[i].setData("selected",true);
4522 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4523 for (var i = 0; i < checkBoxes.length; i++) {
4524 checkBoxes[i].checked = false;
4530 insertContactRowToResultTable : function(rowId, addressType) {
4531 var data = SE.addressBook.grid.getRecord(rowId).getData();
4532 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4534 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4535 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4536 if(addressType == null)
4537 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4538 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});
4541 * Remove a row from the gridsResult table.
4543 removeRowFromGridResults : function(rowId,emailAddress)
4545 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4546 for (var i=0; i < contacts.length; i++)
4548 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4549 var data = rec.getData();
4550 if(data.email_address == emailAddress)
4552 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4557 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4560 * Translates between the addressType To|Cc|Bcc labels/keys.
4562 translateAddresType: function(addressType,fromKey)
4564 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4565 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4566 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4567 var mappingObject = {};
4570 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4573 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4574 mappingObject[displayCc] = 'cc';
4575 mappingObject[displayBcc] = 'bcc';
4578 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4584 toggleSearchRowIcon : function(rowId,show)
4588 var idToShow = rowId + '_add_img';
4589 var idToHide = rowId + '_rm_img';
4593 var idToShow = rowId + '_rm_img';
4594 var idToHide = rowId + '_add_img';
4598 Dom.addClass(idToHide, "yui-hidden");
4599 Dom.removeClass(idToShow, "yui-hidden");
4602 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4604 doesGridResultsEntryExist: function(emailAddrs)
4607 var contactExists = false;
4608 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4609 for (var i=0; i < contacts.length; i++)
4611 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4612 if(data.email_address == emailAddrs)
4614 contactExists = true;
4618 return contactExists;
4622 * adds an email address to a string, but first checks if it exists
4623 * @param string concat The string we are appending email addresses to
4624 * @param string addr Email address to add
4627 smartAddEmailAddressToComposeField : function(concat, addr) {
4628 var re = new RegExp(addr);
4630 if(!concat.match(re)) {
4632 concat += "; " + addr;
4641 //// END ADDRESS BOOK
4642 ///////////////////////////////////////////////////////////////////////////////
4646 ///////////////////////////////////////////////////////////////////////////////
4649 * Auto-complete object
4653 delimChar : [";", ","],
4657 prehighlightClassName : "yui-ac-prehighlight",
4660 instances : new Array(),
4663 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4664 * @param object Contact from AddressBook
4667 getPrimaryAddress : function(contact) {
4668 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4670 for(var eIndex in contact.email) {
4671 address = contact.email[eIndex].email_address;
4672 if(contact.email[eIndex].primary_address == 1) {
4673 return contact.email[eIndex].email_address;
4681 * initializes autocomplete widgets for a given compose view
4684 init : function(idx) {
4685 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4686 "queryMatchContains" : false,
4687 "queryMatchSubset" : true
4690 this.instances[idx] = {
4697 // instantiate the autoComplete widgets
4698 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4699 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4700 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4702 // enable hiding of interfering textareas
4703 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4704 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4705 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4707 // enable reshowing of hidden textareas
4708 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4709 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4710 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4712 // enable refreshes of contact lists
4713 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4714 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4715 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4718 refreshDataSource : function(sType, aArgs) {
4719 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4721 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4723 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4724 idx = textBoxId.substr(9);
4726 idx = textBoxId.substr(10);
4729 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4730 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4731 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4735 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4737 returnDataSource : function(contacts) {
4738 var ret = new Array();
4739 for(var id in contacts) {
4740 if (contacts[id].name) {
4741 var primary = this.getPrimaryAddress(contacts[id]);
4743 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4744 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4746 for(var emailIndex in contacts[id].email) {
4747 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4756 * Hides address textareas to prevent autocomplete dropdown from being obscured
4758 toggleTextareaHide : function(sType, aArgs) {
4759 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4763 if(textBoxId.indexOf("addressTO") > -1) {
4765 } else if(textBoxId.indexOf("addressCC") > -1) {
4768 idx = textBoxId.substr(9);
4770 // follow through if not BCC
4772 var cc = document.getElementById("addressCC" + idx);
4773 var bcc = document.getElementById("addressBCC" + idx);
4777 cc.style.visibility = 'hidden';
4779 bcc.style.visibility = 'hidden';
4786 * Redisplays the textareas after an address is commited
4788 toggleTextareaShow : function(sType, aArgs) {
4789 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4793 if(textBoxId.indexOf("addressTO") > -1) {
4795 } else if(textBoxId.indexOf("addressCC") > -1) {
4798 idx = textBoxId.substr(9);
4800 // follow through if not BCC
4802 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4803 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4808 //// END AUTOCOMPLETE
4809 ///////////////////////////////////////////////////////////////////////////////
4811 ///////////////////////////////////////////////////////////////////////////////
4814 * expands the options sidebar
4816 SE.composeLayout = {
4817 currentInstanceId : 0,
4820 outboundAccountErrors : null,
4821 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4823 showAddressDetails : function(e) {
4824 var linkElement = document.getElementById("More"+e.id);
4825 var spanElement = document.getElementById("Detail"+e.id);
4826 var emailAddressList = e.value;
4827 if(e.value.length > 96)
4829 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4830 var displayArray = [];
4831 for (var i=0; i<resultArray.length; i++)
4833 var t_name = resultArray[i].name;
4834 var t_emailAddr = resultArray[i].email_address;
4836 displayArray.push('<br/><' + t_emailAddr + '>');
4838 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4841 var result = displayArray.join('<br/>');
4843 linkElement.style.display = "inline";
4844 linkElement.style.height="10px";
4845 linkElement.style.overflow="visible";
4846 spanElement.innerHTML = result;
4849 linkElement.style.display = "none";
4854 * Given a string of email address, return an array containing the name portion (if available)
4855 * and email portion.
4857 _getEmailArrayFromString : function (emailAddressList){
4860 while ((results = reg.exec(emailAddressList)) != null)
4862 orignial = results[0];
4863 parsedResult = results[0].replace(';', ':::::');
4864 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4868 while ((results = reg.exec(emailAddressList)) != null)
4870 orignial = results[0];
4871 parsedResult = results[0].replace(',', ':::::');
4872 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4874 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4875 var emailArr = emailAddressList.split(":::::");
4876 var resultsArray = [];
4878 for (var i=0; i<emailArr.length; i++)
4880 var rposition = emailArr[i].indexOf('<');
4881 var lposition = emailArr[i].indexOf('>');
4883 if(trim(emailArr[i]) != '')
4885 if(rposition != -1 && lposition != -1)
4887 var t_name = emailArr[i].substr(0, rposition-1);
4888 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4889 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4893 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4897 return resultsArray;
4899 ///////////////////////////////////////////////////////////////////////////
4902 * Prepare bucket DIV and yui-ext tab panels
4904 _0_yui : function() {
4905 var idx = this.currentInstanceId;
4907 var composeTab = new YAHOO.SUGAR.ClosableTab({
4908 label: mod_strings.LNK_NEW_SEND_EMAIL,
4910 content : "<div id='htmleditordiv" + idx + "'/>",
4911 id : "composeTab" + idx,
4912 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4915 SE.innerLayout.addTab(composeTab);
4917 // get template engine with template
4918 if (!SE.composeLayout.composeTemplate) {
4919 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4922 // create Tab inner layout
4923 var composePanel = this.getComposeLayout();
4924 composePanel.getUnitByPosition("right").collapse();
4925 composePanel.autoSize();
4929 * Generate the quick compose layout
4930 * @method getQuickComposeLayout
4931 * @param {Pannel} parentPanel Parent pannel
4932 * @param {Object} o Options
4935 getQuickComposeLayout : function (parentPanel,o) {
4936 var idx = SE.composeLayout.currentInstanceId;
4938 //Before rendering the parent pannel we need to initalize the grid layout
4939 parentPanel.beforeRenderEvent.subscribe(function() {
4941 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4942 SE.composeLayout._createComposeLayout(idx);
4943 SE.composeLayout[idx].set('height', 350);
4944 SE.composeLayout[idx].render();
4948 //Wait until the Compose Layout has rendered, then add the
4949 //options tab and perform the tiny initialization.
4950 parentPanel.renderEvent.subscribe(function() {
4952 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4953 SE.composeLayout._initComposeOptionTabs(idx);
4954 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4955 //Initialize tinyMCE
4956 SE.composeLayout._1_tiny(false);
4958 //Init templates and address book
4959 SE.composeLayout._2_final();
4961 SE.composeLayout.quickCreateComposePackage(o);
4966 //Check if we have the div override for the shortcut bar
4967 if(typeof o.menu_id != 'undefined') {
4968 parentPanel.render(o.menu_id);
4970 parentPanel.render(document.body);
4973 return SE.composeLayout[idx];
4976 * Fill in all fields into the quick compose layout.
4977 * @method quickCreateComposePackage
4978 * @param {Object} o Options
4981 quickCreateComposePackage: function(o)
4983 //If we have a compose package fill in defaults.
4984 if (typeof(o.composePackage) != 'undefined')
4986 composePackage = o.composePackage; //Set the compose data object
4987 //Hijack this method called by composePackage as it's not need for quick creates.
4988 SE.composeLayout.c0_composeNewEmail = function(){};
4989 SE.composeLayout.composePackage(); //Fill in defaults.
4992 getComposeLayout : function() {
4993 var idx = SE.composeLayout.currentInstanceId;
4995 this._createComposeLayout(idx);
4996 SE.composeLayout[idx].render();
4997 this._initComposeOptionTabs(idx);
4999 return SE.composeLayout[idx];
5003 * Create the layout manager for the compose window.
5005 _createComposeLayout : function(idx)
5007 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
5008 parent: SE.complexLayout,
5018 SE.composeLayout.composeTemplate.exec({
5019 'app_strings':app_strings,
5020 'mod_strings':mod_strings,
5021 'linkbeans_options' : linkBeans,
5022 'idx' : SE.composeLayout.currentInstanceId
5033 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5036 header: app_strings.LBL_EMAIL_OPTIONS
5042 * Create compose tab which will populate the 'right' container in the compose window.
5044 _initComposeOptionTabs : function(idx)
5046 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5047 var tab = new YAHOO.widget.Tab({
5048 label: app_strings.LBL_EMAIL_ATTACHMENT,
5050 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5051 id : "divAttachments" + idx,
5055 tab.layout = SE.composeLayout[idx];
5057 tab.on("activeChange", function(o){
5059 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5065 tab = new YAHOO.widget.Tab({
5066 label: app_strings.LBL_EMAIL_OPTIONS,
5068 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5069 id : "divOptions" + idx,
5073 tab.layout = SE.composeLayout[idx];
5074 tab.on("activeChange", function(o){
5076 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5081 SE.composeLayout[idx].autoSize = function() {
5082 var pEl = this.get("element").parentNode.parentNode.parentNode;
5083 this.set("height", pEl.clientHeight-30);
5087 SE.composeLayout[idx].rightTabs = cTabs;
5089 isParentTypeValid : function(idx) {
5090 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5091 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5092 if (trim(parentTypeValue) == ""){
5093 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5099 isParentTypeAndNameValid : function(idx) {
5100 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5101 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5102 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5103 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5104 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5105 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5111 callopenpopupForEmail2 : function(idx,options) {
5113 var formName = 'emailCompose' + idx;
5115 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5116 formName = options.form_name;
5118 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5119 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5120 if (!SE.composeLayout.isParentTypeValid(idx)) {
5123 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5125 call_back_function:"SE.composeLayout.popupAddEmail",
5127 field_to_name_array:{
5128 id:'data_parent_id' + idx,
5129 name:'data_parent_name' + idx,
5134 popupAddEmail : function(o)
5136 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5137 var data = o.name_to_value_array;
5138 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5139 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5141 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5142 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5149 _1_tiny : function(isReplyForward) {
5150 var idx = SE.composeLayout.currentInstanceId;
5151 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5152 SE.tinyInstances[elId] = { };
5153 SE.tinyInstances[elId].ready = false;
5155 if (!SUGAR.util.isTouchScreen()) {
5156 var t = tinyMCE.getInstanceById(elId);
5158 if(typeof(t) == 'undefined') {
5159 if (!SUGAR.util.isTouchScreen()) {
5160 tinyMCE.execCommand('mceAddControl', false, elId);
5162 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5163 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
5168 resizeEditorSetSignature : function(idx,setSignature)
5170 var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5172 if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
5173 setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+setSignature+"');",500);
5177 SE.composeLayout.resizeEditor(idx);
5179 setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
5184 resizeEditor : function(idx)
5186 var cof = Dom.get('composeOverFrame' + idx);
5187 var head = Dom.get('composeHeaderTable' + idx);
5188 var targetHeight = cof.clientHeight - head.clientHeight;
5189 var instance = SE.util.getTiny('htmleditor' + idx);
5192 var parentEl = Dom.get(instance.editorId + '_parent');
5193 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5194 var contentEl = instance.contentAreaContainer;
5195 var iFrame = contentEl.firstChild;
5196 var tinMceToolbarOffset = 18;
5197 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5200 setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
5205 * Initializes d&d, auto-complete, email templates
5207 _2_final : function() {
5208 var idx = SE.composeLayout.currentInstanceId;
5210 if(this.emailTemplates) {
5211 this.setComposeOptions(idx);
5213 //populate email template cache
5214 AjaxObject.target = '';
5215 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5218 // handle drop targets for addressBook
5219 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5220 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5221 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5222 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5224 // auto-complete setup
5225 SE.autoComplete.init(idx);
5228 document.getElementById("addressTO" + idx).focus();
5232 * hide tinyMCE tool bar if send email as plaintext is checked
5234 renderTinyMCEToolBar : function (idx, hide) {
5236 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5238 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5242 c1_composeEmail : function(isReplyForward, retry) {
5246 if (!SUGAR.util.isTouchScreen() && (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined')){
5247 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5249 this._1_tiny(isReplyForward);
5252 if(isReplyForward) {
5253 this.replyForwardEmailStage2();
5259 * takes draft info and prepopulates
5261 c0_composeDraft : function() {
5262 this.getNewInstanceId();
5264 document.getElementById('_blank').innerHTML = '';
5265 var idx = SE.composeLayout.currentInstanceId;
5266 SE.composeLayout.draftObject = new Object();
5267 SE.composeLayout.draftObject.id = idx;
5268 SE.composeLayout.draftObject.isDraft = true;
5269 SE.composeLayout.currentInstanceId = idx;
5270 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5271 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5272 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5274 SE.composeLayout._0_yui();
5275 SE.composeLayout._1_tiny(true);
5278 SE.composeLayout._2_final();
5280 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5281 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5285 * Strip & Prep editor hidden fields
5287 c0_composeNewEmail : function() {
5288 this.getNewInstanceId();
5289 this.c1_composeEmail(false);
5293 * Sends async request to get the compose view.
5294 * Requests come from "reply" or "forwards"
5296 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5297 SE.composeLayout.replyForwardObj = new Object();
5298 SE.composeLayout.replyForwardObj.ieId = ieId;
5299 SE.composeLayout.replyForwardObj.uid = uid;
5300 SE.composeLayout.replyForwardObj.mbox = mbox;
5301 SE.composeLayout.replyForwardObj.type = type;
5303 if(mbox == 'sugar::Emails') {
5304 SE.composeLayout.replyForwardObj.sugarEmail = true;
5307 SE.composeLayout.getNewInstanceId();
5308 SE.composeLayout.c1_composeEmail(true);
5310 //// END COMPOSE FLOW
5311 ///////////////////////////////////////////////////////////////////////////
5314 * Called when a contact, email, or mailinglist is dropped
5315 * into one of the compose fields.
5317 handleDrop : function (source, event, data, target) {
5320 target = event.getTarget();
5322 data.nodes = [data.nodes];
5326 target = document.getElementById(target);
5330 if (target.id.indexOf('address') > -1) {
5331 // dropped onto email to/cc/bcc field
5332 for(var i in nodes) {
5333 var node = nodes[i].getData();
5335 if (node[1].indexOf('contact') > -1) {
5336 email = SE.addressBook.getFormattedAddress(node[0]);
5337 } else if (node[1].indexOf('address-email') > -1){
5338 email = node[3].replace(/ /gi, '');
5339 email = email.replace('<', '<').replace('>', '>');
5340 var tr = source.getTrEl(nodes[i]);
5341 while (tr && !Dom.hasClass(tr, "address-contact")) {
5342 tr = source.getPreviousTrEl(tr);
5344 var CID = source.getRecord(tr).getData()[0];
5345 var o = SE.addressBook._contactCache[CID];
5346 var name = new String(o.name);
5347 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5348 email = finalName + email;
5350 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5356 /*/////////////////////////////////////////////////////////////////////////////
5357 /// EMAIL TEMPLATE CODE
5359 applyEmailTemplate : function (idx, id) {
5362 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5363 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5364 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5367 var to_addr = document.getElementById('addressTO'+idx);
5368 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
5370 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5371 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5374 // id is selected index of email template drop-down
5375 if(id == '' || id == "0") {
5376 YAHOO.SUGAR.MessageBox.show({
5381 if(btn=='no'){return;};
5382 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5389 YAHOO.SUGAR.MessageBox.show({
5394 if(btn=='no'){return;};
5395 SUGAR.email2.composeLayout.processResult(idx, id);},
5401 processNoneResult : function(idx, id) {
5402 var tiny = SE.util.getTiny('htmleditor' + idx);
5403 var tinyHTML = tiny.getContent();
5404 var openTag = '<div><span><span>';
5405 var htmllow = tinyHTML.toLowerCase();
5406 var start = htmllow.indexOf(openTag);
5408 tinyHTML = tinyHTML.substr(start);
5409 tiny.setContent(tinyHTML);
5411 tiny.setContent('');
5415 processResult : function(idx , id){
5416 var post_data = {"module":"EmailTemplates","record":id};
5417 var global_rpcClient = new SugarRPCClient();
5419 result = global_rpcClient.call_method('retrieve', post_data, true);
5420 if(!result['record']) return;
5421 json_objects['email_template_object'] = result['record'];
5422 this.appendEmailTemplateJSON();
5424 // get attachments if any
5425 AjaxObject.target = '';
5426 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5429 appendEmailTemplateJSON : function() {
5430 var idx = SE.composeLayout.currentInstanceId; // post increment
5432 // query based on template, contact_id0,related_to
5433 //jchi 09/10/2008 refix #7743
5434 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5435 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5438 if(json_objects['email_template_object']['fields']['text_only'] == 1){
5439 text = "<p>" + decodeURI(encodeURI(json_objects['email_template_object']['fields']['body'])).replace(/<BR>/ig, '</p><p>').replace(/<br>/gi, "</p><p>").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"') + "</p>";
5440 document.getElementById("setEditor1").checked = true;
5441 SUGAR.email2.composeLayout.renderTinyMCEToolBar('1', 1);
5444 text = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body_html'])).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
5445 document.getElementById("setEditor1").checked = false;
5446 SUGAR.email2.composeLayout.renderTinyMCEToolBar('1', 0);
5450 var tiny = SE.util.getTiny('htmleditor' + idx);
5451 var tinyHTML = tiny.getContent();
5452 var openTag = '<div><span><span>';
5453 var closeTag = '</span></span></div>';
5454 var htmllow = tinyHTML.toLowerCase();
5455 var start = htmllow.indexOf(openTag);
5457 var htmlPart2 = tinyHTML.substr(start);
5458 tinyHTML = text + htmlPart2;
5459 tiny.setContent(tinyHTML);
5461 tiny.setContent(text);
5466 * Writes out the signature in the email editor
5468 setSignature : function(idx) {
5471 var hide = document.getElementById('setEditor' + idx).checked;
5472 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5473 //wait for signatures to load before trying to set them
5474 if (!SE.composeLayout.signatures) {
5475 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5480 var sel = document.getElementById('signatures' + idx);
5482 var sel = document.getElementById('signature_id');
5483 idx = SE.tinyInstances.currentHtmleditor;
5486 //Ensure that the tinyMCE html has been rendered.
5487 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5488 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5495 signature = sel.options[sel.selectedIndex].value;
5500 var openTag = '<div><span> </span>';
5501 var closeTag = '<span> </span></div>';
5502 var t = tinyMCE.getInstanceById('htmleditor' + idx);
5504 if(typeof(t) != 'undefined')
5506 t.contentDocument = t.contentWindow.document;
5507 var html = t.getContent();
5514 var htmllow = html.toLowerCase();
5515 var start = htmllow.indexOf(openTag);
5516 var end = htmllow.indexOf(closeTag) + closeTag.length;
5518 // selected "none" - remove signature from email
5519 if(signature == '') {
5521 var htmlPart1 = html.substr(0, start);
5522 var htmlPart2 = html.substr(end, html.length);
5524 html = htmlPart1 + htmlPart2;
5527 SE.signatures.lastAttemptedLoad = '';
5531 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5532 SE.signatures.lastAttemptedLoad = '';
5534 SE.signatures.lastAttemptedLoad = signature;
5536 if(typeof(SE.signatures[signature]) == 'undefined') {
5538 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5539 SE.signatures.targetInstance = (idx) ? idx : "";
5540 AjaxObject.target = '';
5541 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5543 var newSignature = this.prepareSignature(SE.signatures[signature]);
5545 // clear out old signature
5546 if(SE.signatures.lastAttemptedLoad && start > -1) {
5547 var htmlPart1 = html.substr(0, start);
5548 var htmlPart2 = html.substr(end, html.length);
5550 html = htmlPart1 + htmlPart2;
5554 start = html.indexOf('<div><hr></div>');
5555 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5556 var htmlPart1 = html.substr(0, start);
5557 var htmlPart2 = html.substr(start, html.length);
5558 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5559 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5564 //remove custom spacing
5565 var spacing = '<span id="spacing"><br /><br /><br /></span> ';
5566 var customSpacingStart = html.indexOf(spacing);
5568 if (customSpacingStart > -1)
5570 var part1 = newHtml.substr(0, customSpacingStart);
5571 var part2 = newHtml.substr(customSpacingStart+spacing.length, newHtml.length);
5572 newHtml = part1 + part2;
5576 var bodyStartTag = '<body>';
5577 var body = newHtml.indexOf(bodyStartTag);
5581 var part1 = newHtml.substr(0, body+bodyStartTag.length);
5582 var part2 = newHtml.substr(body+bodyStartTag.length, newHtml.length);
5583 newHtml = part1 + spacing + openTag + newSignature + closeTag + part2;
5587 newHtml = openTag + newSignature + closeTag + newHtml;
5591 var body = html.indexOf('</body>');
5593 var part1 = html.substr(0, body);
5594 var part2 = html.substr(body, html.length);
5595 var newHtml = part1 + openTag + newSignature + closeTag + part2;
5597 var newHtml = html + openTag + newSignature + closeTag;
5600 //tinyMCE.setContent(newHtml);
5601 t.setContent(newHtml);
5605 prepareSignature : function(str) {
5606 var signature = new String(str);
5608 signature = signature.replace(/</gi, '<');
5609 signature = signature.replace(/>/gi, '>');
5615 showAttachmentPanel : function(idx) {
5616 var east = SE.composeLayout[idx].getUnitByPosition("right");
5617 var tabs = SE.composeLayout[idx].rightTabs;
5619 tabs.set("activeTab", tabs.getTab(0));
5623 * expands sidebar and displays options panel
5625 showOptionsPanel : function(idx) {
5626 var east = SE.composeLayout[idx].getUnitByPosition("right");
5627 var tabs = SE.composeLayout[idx].rightTabs;
5629 tabs.set("activeTab", tabs.getTab(1));
5633 * Selects the Contacts tab
5635 showContactsPanel : function() {
5636 SE.complexLayout.regions.west.showPanel("contactsTab");
5640 * Generates fields for Select Document
5642 addDocumentField : function(idx) {
5643 var basket = document.getElementById('addedDocuments' + idx);
5645 var index = (basket.childNodes.length / 7) - 1;
5652 var test = document.getElementById('documentId' + idx + index);
5654 while(test != null) {
5656 test = document.getElementById('documentId' + idx + index);
5659 var documentCup = document.createElement("div");
5660 documentCup.id = 'documentCup' + idx + index;
5661 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5662 // document id field
5663 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5664 // document name field
5665 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5667 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5668 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5669 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5671 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5672 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5673 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5676 basket.appendChild(documentCup);
5677 //basket.innerHTML += out;
5682 * Makes async call to save a draft of the email
5683 * @param int Instance index
5685 saveDraft : function(tinyInstance) {
5686 this.sendEmail(tinyInstance, true);
5689 selectDocument : function(target) {
5690 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5691 windowName = 'selectDocument';
5692 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5694 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5696 // put the focus on the popup if the browser supports the focus() method
5702 * Modal popup for file attachment dialogue
5704 addFileField : function() {
5705 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5706 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5710 constraintoviewport: true,
5712 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5713 fn:function(){SE.addFileDialog.hide();}
5716 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5717 SE.addFileDialog.render();
5718 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5720 Dom.removeClass("addFileDialog", "yui-hidden");
5722 SE.addFileDialog.show();
5726 * Async upload of file to temp dir
5728 uploadAttachment : function() {
5729 if(document.getElementById('email_attachment').value != "") {
5730 var formObject = document.getElementById('uploadAttachment');
5731 YAHOO.util.Connect.setForm(formObject, true, true);
5732 AjaxObject.target = '';
5733 AjaxObject.startRequest(callbackUploadAttachment, null);
5735 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5740 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5741 * @param string target in focus compose layout
5743 setDocument : function(idx, target, documentId, documentName, docRevId) {
5744 // fields are named/id'd [fieldName][instanceId][index]
5745 var addedDocs = document.getElementById("addedDocuments" + idx);
5746 var docId = document.getElementById('documentId' + idx + target);
5747 var docName = document.getElementById('documentName' + idx + target);
5748 var docRevisionId = document.getElementById('document' + idx + target);
5749 docId.value = documentId;
5750 docName.value = documentName;
5751 docRevisionId.value = docRevId;
5755 * Removes the bucket div containing the document input fields
5757 deleteDocumentField : function(documentCup) {
5758 var f0 = document.getElementById(documentCup);
5759 f0.parentNode.removeChild(f0);
5763 * Removes a Template Attachment field
5767 deleteTemplateAttachmentField : function(idx, index) {
5768 // create not-in-array values for removal filtering
5769 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5775 r += document.getElementById('templateAttachmentId' + idx + index).value;
5776 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5778 var target = 'templateAttachmentCup' + idx + index;
5779 d = document.getElementById(target);
5780 d.parentNode.removeChild(d);
5784 * Async removal of uploaded temp file
5785 * @param string index Should be a concatenation of idx and index
5788 deleteUploadAttachment : function(index, file) {
5789 var d = document.getElementById('email_attachment_bucket' + index);
5790 d.parentNode.removeChild(d);
5792 // make async call to delete cached file
5793 AjaxObject.target = '';
5794 AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5798 * Attaches files coming from Email Templates
5800 addTemplateAttachmentField : function(idx) {
5802 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5804 var basket = document.getElementById('addedTemplateAttachments' + idx);
5807 var index = basket.childNodes.length;
5814 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5816 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5817 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5818 idx + "\",\"" + index + "\");'/>" +
5820 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5821 // templateAttachment field
5822 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5824 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5826 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5827 "<br id='br" + index + "></br>" +
5828 "<br id='brdoc" + index + "></br>" +
5830 basket.innerHTML = basket.innerHTML + out;
5836 * Sends one email via async call
5837 * @param int idx Editor instance ID
5838 * @param bool isDraft
5840 sendEmail : function(idx, isDraft) {
5842 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5843 var obAccountID = document.getElementById('addressFrom' + idx).value;
5845 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5847 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5852 var form = document.getElementById('emailCompose' + idx);
5853 var composeOptionsFormName = "composeOptionsForm" + idx;
5856 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5857 if (t != null || typeof(t) != "undefined") {
5858 var html = t.getContent();
5860 var html = "<p>" + document.getElementById('htmleditor' + idx).value + "</p>";
5863 var subj = document.getElementById('emailSubject' + idx).value;
5864 var to = trim(document.getElementById('addressTO' + idx).value);
5865 var cc = trim(document.getElementById('addressCC' + idx).value);
5866 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5867 var email_id = document.getElementById('email_id' + idx).value;
5868 var composeType = document.getElementById('composeType').value;
5869 var parent_type = document.getElementById("parent_type").value;
5870 var parent_id = document.getElementById("parent_id").value;
5872 var el_uid = document.getElementById("uid");
5873 var uid = (el_uid == null) ? '' : el_uid.value;
5875 var el_ieId = document.getElementById("ieId");
5876 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5878 var el_mbox = document.getElementById("mbox");
5879 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5881 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5882 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5886 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5889 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5890 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5891 parent_id = parentIdValue;
5892 parent_type = parentTypeValue;
5894 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5895 // baseline viability check
5897 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5898 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5900 } else if(subj == '' && !isDraft) {
5901 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5904 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5906 } else if(html == '' && !isDraft) {
5907 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5912 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5913 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5914 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5915 SUGAR.showMessageBox(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5916 html = html.replace(/</ig, "sugarLessThan");
5917 html = html.replace(/>/ig, "sugarGreaterThan");
5919 form.sendDescription.value = html;
5920 form.sendSubject.value = subj;
5921 form.sendTo.value = to;
5922 form.sendCc.value = cc;
5923 form.sendBcc.value = bcc;
5924 form.email_id.value = email_id;
5925 form.composeType.value = composeType;
5926 form.composeLayoutId.value = 'composeLayout' + idx;
5927 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5928 form.saveToSugar.value = 1;
5929 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5930 form.parent_type.value = parent_type;
5931 form.parent_id.value = parent_id;
5932 form.uid.value = uid;
5933 form.ieId.value = ieId;
5934 form.mbox.value = mbox;
5936 // email attachments
5937 var addedFiles = document.getElementById('addedFiles' + idx);
5939 for(i=0; i<addedFiles.childNodes.length; i++) {
5940 var bucket = addedFiles.childNodes[i];
5942 for(j=0; j<bucket.childNodes.length; j++) {
5943 var node = bucket.childNodes[j];
5944 var nName = new String(node.name);
5946 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5947 if(form.attachments.value != '') {
5948 form.attachments.value += "::";
5950 form.attachments.value += node.value;
5957 var addedDocs = document.getElementById('addedDocuments' + idx);
5959 for(i=0; i<addedDocs.childNodes.length; i++) {
5960 var cNode = addedDocs.childNodes[i];
5961 for(j=0; j<cNode.childNodes.length; j++) {
5962 var node = cNode.childNodes[j];
5963 var nName = new String(node.name);
5964 if(node.type == 'hidden' && nName.match(/documentId/)) {
5965 if(form.documents.value != '') {
5966 form.documents.value += "::";
5968 form.documents.value += node.value;
5974 // template attachments
5975 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5976 if(addedTemplateAttachments) {
5977 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5978 var cNode = addedTemplateAttachments.childNodes[i];
5979 for(j=0; j<cNode.childNodes.length; j++) {
5980 var node = cNode.childNodes[j];
5981 var nName = new String(node.name);
5982 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5983 if(form.templateAttachments.value != "") {
5984 form.templateAttachments.value += "::";
5986 form.templateAttachments.value += node.value;
5992 // remove attachments
5993 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5995 YAHOO.util.Connect.setForm(form);
5997 AjaxObject.target = 'frameFlex';
5999 // sending a draft email
6000 if(!isDraft && in_draft) {
6002 SE.listView.removeRowByUid(email_id);
6005 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
6006 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
6008 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
6012 * Handles clicking the email address link from a given view
6014 composePackage : function() {
6015 if(composePackage != null) {
6016 SE.composeLayout.c0_composeNewEmail();
6019 if(composePackage.to_email_addrs) {
6020 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
6022 if (composePackage.subject != null && composePackage.subject.length > 0) {
6023 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
6026 //If no parent fields are set in the composePackage, ensure they are cleared.
6027 var parentFields = ['parent_type','parent_name','parent_id'];
6028 for(var i=0;i<parentFields.length;i++)
6030 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
6031 composePackage[parentFields[i]] = "";
6034 document.getElementById("parent_type").value = composePackage.parent_type;
6035 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
6036 document.getElementById("parent_id").value = composePackage.parent_id;
6037 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
6038 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
6040 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
6041 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
6043 if (composePackage.body != null && composePackage.body.length > 0) {
6044 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6045 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
6046 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
6048 if (composePackage.attachments != null) {
6049 SE.composeLayout.loadAttachments(composePackage.attachments);
6052 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
6053 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
6054 SE.util.emptySelectOptions(addressFrom);
6055 var fromAccountOpts = composePackage.fromAccounts.data;
6056 for(i=0; i<fromAccountOpts.length; i++) {
6057 var key = fromAccountOpts[i].value;
6058 var display = fromAccountOpts[i].text;
6059 var opt = new Option(display, key);
6060 if (fromAccountOpts[i].selected) {
6061 opt.selected = true;
6063 addressFrom.options.add(opt);
6070 setContentOnThisTiny : function() {
6071 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6072 var tinyHTML = tiny.getContent();
6073 composePackage.body = decodeURI(encodeURI(composePackage.body));
6074 // cn: bug 14361 - text-only templates don't fill compose screen
6075 if(composePackage.body == '') {
6076 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
6078 //Flag determines if we should clear the tiny contents or just append
6079 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
6081 SE.composeLayout.tinyHTML = '';
6086 //check tinyHTML for closing tags
6087 var body = tinyHTML.lastIndexOf('</body>');
6088 spacing = '<span id="spacing"><br /><br /><br /></span> ';
6092 var part1 = tinyHTML.substr(0, body);
6093 var part2 = tinyHTML.substr(body, tinyHTML.length);
6094 var newHtml = part1 + spacing + composePackage.body + part2;
6098 var newHtml = tinyHTML + spacing + composePackage.body;
6102 SE.composeLayout.tinyHTML = newHtml;
6105 tiny.setContent(SE.composeLayout.tinyHTML);
6106 //Indicate that the contents has been loaded successfully.
6107 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
6110 * Confirms closure of a compose screen if "x" is clicked
6112 confirmClose : function(panel) {
6113 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6114 SE.composeLayout.closeCompose(panel.id);
6122 * forces close of a compose screen
6124 forceCloseCompose : function(id) {
6125 SE.composeLayout.closeCompose(id);
6127 // handle flow back to originating view
6128 if(composePackage) {
6129 // check if it's a module we need to return to
6130 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6131 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6132 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6133 window.location = url;
6140 * closes the editor that just sent email
6141 * @param string id ID of composeLayout tab
6143 closeCompose : function(id) {
6144 // destroy tinyMCE instance
6145 var idx = id.substr(13, id.length);
6146 var instanceId = "htmleditor" + idx;
6147 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6149 // nullify DOM and namespace values.
6151 SE.composeLayout[idx] = null;
6152 SE.tinyInstances[instanceId] = null;
6153 var tabsArray = SE.innerLayout.get("tabs");
6154 for (i = 0 ; i < tabsArray.length ; i++) {
6155 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6156 tabsArray[i].close();
6160 //SE.innerLayout.getTab(idx).close();
6164 * Enable the quick search for the compose relate field or search tab
6166 enableQuickSearchRelate: function(idx,overides){
6168 if(typeof overides != 'undefined')
6170 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6171 var newModule = document.getElementById(newModuleID).value;
6172 var formName = overides['formName'];
6173 var fieldName = overides['fieldName'];
6174 var fieldId = overides['fieldId'];
6175 var fullName = formName + "_" + fieldName;
6176 var postBlurFunction = null;
6180 var newModule = document.getElementById('data_parent_type'+idx).value;
6181 var formName = 'emailCompose'+idx;
6182 var fieldName = 'data_parent_name'+idx;
6183 var fieldId = 'data_parent_id'+idx;
6184 var fullName = formName + "_" + fieldName;
6185 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6188 if(typeof sqs_objects == 'undefined')
6189 window['sqs_objects'] = new Array;
6191 window['sqs_objects'][fullName] = {
6194 modules:[newModule],
6196 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6197 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6198 post_onblur_function: postBlurFunction,
6199 order:"name","limit":"30","no_match_text":"No Match"};
6202 if(typeof QSProcessedFieldsArray != 'undefined')
6203 QSProcessedFieldsArray[fullName] = false;
6204 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6205 QSFieldsArray[fullName].destroy();
6206 delete QSFieldsArray[fullName];
6208 if (Dom.get(fullName + "_results")) {
6209 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6215 qsAddAddress : function(o) {
6216 if (o.name != "" && o.email1 != "")
6218 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6219 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6223 * Returns a new instance ID, 0-index
6225 getNewInstanceId : function() {
6226 this.currentInstanceId = this.currentInstanceId + 1;
6227 return this.currentInstanceId;
6231 * 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.
6233 loadAttachments : function(result) {
6234 var idx = SE.composeLayout.currentInstanceId;
6236 if(typeof(result) == 'object') {
6237 //jchi #20680. Clean the former template attachments;
6238 var basket = document.getElementById('addedTemplateAttachments' + idx);
6239 if(basket.innerHTML != ''){
6240 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6242 basket.innerHTML = '';
6247 if(typeof result[i] == 'object') {
6248 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6249 var bean = result[i];
6250 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6251 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6258 * fills drop-down values for email templates and signatures
6260 setComposeOptions : function(idx) {
6261 // send from accounts
6262 var addressFrom = document.getElementById('addressFrom' + idx);
6264 if (addressFrom.options.length <= 0) {
6265 SE.util.emptySelectOptions(addressFrom);
6266 var fromAccountOpts = SE.composeLayout.fromAccounts;
6267 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6268 var key = fromAccountOpts[id].value;
6269 var display = fromAccountOpts[id].text;
6270 var is_default = false;
6271 if(key == SUGAR.default_inbound_accnt_id)
6273 var opt = new Option(display, key);
6274 addressFrom.options.add(opt);
6275 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6280 var et = document.getElementById('email_template' + idx);
6281 SE.util.emptySelectOptions(et);
6283 for(var key in this.emailTemplates) { // iterate through assoc array
6284 var display = this.emailTemplates[key];
6285 var opt = new Option(display, key);
6286 et.options.add(opt);
6290 var sigs = document.getElementById('signatures' + idx);
6291 SE.util.emptySelectOptions(sigs);
6293 for(var key in this.signatures) { // iterate through assoc array
6294 var display = this.signatures[key];
6295 var opt = new Option(display, key);
6297 if(key == SE.userPrefs.signatures.signature_default) {
6298 opt.selected = true;
6301 sigs.options.add(opt);
6304 // html/plain email?
6305 var htmlEmail = document.getElementById('setEditor' + idx);
6306 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6307 htmlEmail.checked = true;
6309 htmlEmail.checked = false;
6312 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6316 * After compose screen is rendered, async call to get email body from Sugar
6318 replyForwardEmailStage2 : function() {
6319 SE.util.clearHiddenFieldValues('emailUIForm');
6320 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6322 var ieId = SE.composeLayout.replyForwardObj.ieId;
6323 var uid = SE.composeLayout.replyForwardObj.uid;
6324 var mbox = SE.composeLayout.replyForwardObj.mbox;
6325 var type = SE.composeLayout.replyForwardObj.type;
6326 var idx = SE.composeLayout.currentInstanceId;
6328 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6330 document.getElementById('emailSubject' + idx).value = type;
6331 document.getElementById('emailUIAction').value = 'composeEmail';
6332 document.getElementById('composeType').value = type;
6333 document.getElementById('ieId').value = ieId;
6334 document.getElementById('uid').value = uid;
6335 document.getElementById('mbox').value = mbox;
6336 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6337 var formObject = document.getElementById('emailUIForm');
6338 YAHOO.util.Connect.setForm(formObject);
6340 var sendType = type;
6341 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6345 * Show the hidden cc or bcc fields
6347 showHiddenAddress: function(addrType,idx){
6349 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6350 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6351 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6352 this[addrType+'Hidden'+idx] = false;
6354 //After bcc or cc is added, move options below last addr field
6355 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6357 //If both cc and bcc hidden, remove the empty row containing text.
6358 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6359 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6360 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6362 // SE.composeLayout.resizeEditor(idx);
6365 * Hide the cc and bcc fields if they were shown.
6367 hideHiddenAddresses: function(idx){
6369 var addrTypes = ['cc','bcc'];
6370 for(var i = 0;i<addrTypes.length;i++)
6372 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6373 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6374 this[addrTypes[i] + 'Hidden'+idx] = true
6377 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6378 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6379 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6383 //// END SE.composeLayout
6384 ///////////////////////////////////////////////////////////////////////////////
6385 ///////////////////////////////////////////////////////////////////////////////
6389 * Cleans serialized UID lists of duplicates
6393 cleanUids : function(str) {
6394 var seen = new Object();
6396 var arr = new String(str).split(",");
6398 for(var i=0; i<arr.length; i++) {
6403 clean += (clean != "") ? "," : "";
6405 seen[arr[i]] = true;
6412 * Clears hidden field values
6413 * @param string id ID of form element to clear
6415 clearHiddenFieldValues : function(id) {
6416 var form = document.getElementById(id);
6418 for(i=0; i<form.elements.length; i++) {
6419 if(form.elements[i].type == 'hidden') {
6420 var e = form.elements[i];
6421 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6429 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6431 emptySelectOptions : function(el) {
6433 for(i=el.childNodes.length - 1; i >= 0; i--) {
6434 if(el.childNodes[i]) {
6435 el.removeChild(el.childNodes[i]);
6442 * Returns the MBOX path in the manner php_imap expects:
6443 * ie: INBOX.DEBUG.test
6444 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6446 generateMboxPath : function(str) {
6447 var ex = str.split("::");
6449 /* we have a serialized MBOX path */
6453 for(var i=0; i<ex.length; i++) {
6454 if(ex[i] == 'INBOX') {
6466 /* we have a Sugar folder GUID - do nothing */
6474 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6475 * @param HTMLElement el
6476 * @return string GUID of found element or empty on failure
6478 getGuidFromElement : function(el) {
6484 for(var i=0; i<iterations; i++) {
6486 if(el.id.match(SE.reGUID)) {
6498 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6501 getPanelId : function() {
6502 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6506 * wrapper to handle weirdness with IE
6507 * @param string instanceId
6508 * @return tinyMCE Controller object
6510 getTiny : function(instanceId) {
6511 if(instanceId == '') {
6515 var t = tinyMCE.getInstanceById(instanceId);
6519 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6525 * Simple check for MSIE browser
6529 var nav = new String(navigator.appVersion);
6530 if(nav.match(/MSIE/)) {
6537 * Recursively removes an element from the DOM
6538 * @param HTMLElement
6540 removeElementRecursive : function(el) {
6541 this.emptySelectOptions(el);
6548 sleep : function(secs) {
6549 setTimeout("void(0);", secs);
6553 * Converts a <select> element to an Ext.form.combobox
6555 convertSelect : function(select) {
6556 alert('in convertSelect');
6557 if (typeof(select) == "string") {
6558 select = document.getElementById(select);
6562 findChildNode : function (parent, property, value) {
6563 for (i in parent.children) {
6564 var child = parent.children[i];
6565 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6567 var searchChild = SE.util.findChildNode(child, property, value);
6574 cascadeNodes : function (parent, fn, scope, args) {
6575 for (i in parent.children) {
6576 var child = parent.children[i];
6577 var s = scope ? scope : child;
6578 var a = args ? args : child;
6580 SE.util.cascadeNodes(child, fn, scope, args);
6587 ///////////////////////////////////////////////////////////////////////////////
6590 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6592 /*********************************************************************************
6593 * SugarCRM Community Edition is a customer relationship management program developed by
6594 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6596 * This program is free software; you can redistribute it and/or modify it under
6597 * the terms of the GNU Affero General Public License version 3 as published by the
6598 * Free Software Foundation with the addition of the following permission added
6599 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6600 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6601 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6603 * This program is distributed in the hope that it will be useful, but WITHOUT
6604 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6605 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6608 * You should have received a copy of the GNU Affero General Public License along with
6609 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6610 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6613 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6614 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6616 * The interactive user interfaces in modified source and object code versions
6617 * of this program must display Appropriate Legal Notices, as required under
6618 * Section 5 of the GNU Affero General Public License version 3.
6620 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6621 * these Appropriate Legal Notices must retain the display of the "Powered by
6622 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6623 * technical reasons, the Appropriate Legal Notices must display the words
6624 * "Powered by SugarCRM".
6625 ********************************************************************************/
6628 if (typeof console == "undefined")
6629 console = { log: function(o) {alert(o)} };
6633 currentRequestObject : null,
6634 //timeout : 30000, // 30 second timeout default
6635 timeout : 9999999999, // 30 second timeout default
6637 trail : new Array(),
6641 _reset : function() {
6642 this.timeout = 30000;
6643 this.forceAbort = false;
6646 folderRenameCleanup : function() {
6647 SUGAR.email2.folders.setSugarFolders();
6650 fullSyncCleanup : function(o) {
6651 this.folders.checkMailCleanup(o);
6652 SUGAR.email2.settings.settingsDialog.hide();
6657 composeCache : function(o) {
6658 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6659 // get email templates and user signatures
6660 var ret = YAHOO.lang.JSON.parse(o.responseText);
6662 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6663 SUGAR.email2.composeLayout.signatures = ret.signatures;
6664 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6666 SUGAR.email2.composeLayout.setComposeOptions(idx);
6668 //Set the error array so we can notify the user when they try to hit send if any errors
6669 //are present. We will also notify them now (after hitting compose button).
6670 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6673 //if error element is returning an array, then check the length to make sure we have error messages
6674 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6675 //add error messages for display
6676 for(i in ret.errorArray)
6677 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6678 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6679 //if error element is returning an object, and the object value is not empty or null, then display error message
6680 for(i in ret.errorArray)
6681 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6684 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6686 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6688 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6694 handleDeleteSignature : function(o) {
6695 SUGAR.hideMessageBox();
6696 var ret = YAHOO.lang.JSON.parse(o.responseText);
6697 SUGAR.email2.composeLayout.signatures = ret.signatures;
6698 var field = document.getElementById('signature_id');
6699 SUGAR.email2.util.emptySelectOptions(field);
6701 for(var i in ret.signatures) { // iterate through assoc array
6702 var opt = new Option(ret.signatures[i], i);
6703 field.options.add(opt);
6705 setSigEditButtonVisibility();
6710 handleDeleteReturn : function(o) {
6711 // force refresh ListView
6712 SUGAR.hideMessageBox();
6713 if(document.getElementById('focusEmailMbox')) {
6714 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6717 // need to display success message before calling next async call?
6718 document.getElementById(this.target).innerHTML = o.responseText;
6723 handleFailure : function(o) {
6725 SUGAR.showMessageBox('Exception occurred...', o.statusText, 'alert');
6726 if(document.getElementById('saveButton')) {
6727 document.getElementById('saveButton').disabled = false;
6731 handleReplyForward : function(o) {
6732 var a = YAHOO.lang.JSON.parse(o.responseText);
6734 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6736 document.getElementById('email_id' + idx).value = a.uid;
6737 document.getElementById('emailSubject' + idx).value = a.name;
6738 document.getElementById('addressTO' + idx).value = a.from;
6739 document.getElementById('uid' + idx).value = a.uid;
6741 document.getElementById('addressCC' + idx).value = a.cc;
6742 SE.composeLayout.showHiddenAddress('cc', idx);
6746 document.getElementById('type' + idx).value = a.type;
6749 // apply attachment values
6750 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6752 setTimeout("callbackReplyForward.finish(globalA);", 500);
6755 handleReplyForwardForDraft : function(o) {
6756 var a = YAHOO.lang.JSON.parse(o.responseText);
6758 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6760 document.getElementById('email_id' + idx).value = a.uid;
6761 document.getElementById('emailSubject' + idx).value = a.name;
6762 document.getElementById('addressTO' + idx).value = a.to;
6765 document.getElementById('addressCC' + idx).value = a.cc;
6766 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6770 document.getElementById('addressBCC' + idx).value = a.bcc;
6771 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6776 document.getElementById('type' + idx).value = a.type;
6780 // apply attachment values
6781 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6783 setTimeout("callbackReplyForward.finish(globalA);", 500);
6788 handleSuccess : function(o) {
6789 document.getElementById(this.target).innerHTML = o.responseText;
6790 SUGAR.hideMessageBox();
6795 ieDeleteSuccess : function(o) {
6796 SUGAR.hideMessageBox();
6797 SUGAR.email2.accounts.refreshInboundAccountTable();
6798 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6799 SUGAR.email2.accounts.rebuildFolderList();
6804 ieSaveSuccess : function(o) {
6805 document.getElementById('saveButton').disabled = false;
6806 var a = YAHOO.lang.JSON.parse(o.responseText);
6809 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6810 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6812 resp = YAHOO.lang.JSON.parse(o.responseText);
6813 SUGAR.email2.accounts.refreshInboundAccountTable();
6814 SUGAR.email2.accounts.refreshOuboundAccountTable();
6815 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6816 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6819 SUGAR.hideMessageBox();
6820 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6827 loadAttachments : function(o) {
6828 var result = YAHOO.lang.JSON.parse(o.responseText);
6830 SUGAR.email2.composeLayout.loadAttachments(result);
6835 loadSignature : function(o) {
6836 var ret = YAHOO.lang.JSON.parse(o.responseText);
6837 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6838 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6842 * Follow up to mark email read|unread|flagged
6844 markEmailCleanup : function(o) {
6845 var ret = YAHOO.lang.JSON.parse(o.responseText);
6846 if (!ret['status']) {
6847 SUGAR.hideMessageBox();
6848 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6850 SUGAR.email2.contextMenus.markEmailCleanup();
6856 rebuildShowFolders : function(o) {
6857 var t = YAHOO.lang.JSON.parse(o.responseText);
6858 var show = document.getElementById('ieAccountListShow');
6860 SUGAR.email2.util.emptySelectOptions(show);
6862 for(i=0; i<t.length; i++) { // iterate through assoc array
6863 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6864 opt.selected = t[i].selected;
6865 show.options.add(opt);
6868 SUGAR.email2.accounts.renderTree();
6872 saveListViewSortOrderPart2 : function() {
6873 // create the JSON string the func expects
6874 focusFolderPath = '[ "Home", "' + ieName + '"';
6876 var f = new String(focusFolder);
6877 var fEx = f.split('.');
6879 for(i=0; i<fEx.length; i++) {
6880 focusFolderPath += ', "' + fEx[i] +'"'
6883 focusFolderPath += ']';
6885 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6886 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6892 sendEmailCleanUp : function(o) {
6894 SUGAR.hideMessageBox();
6897 ret = YAHOO.lang.JSON.parse(o.responseText);
6898 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6899 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6901 if (o.responseText) {
6902 SUGAR.showMessageBox(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6904 // Else we have an error here.
6907 if (typeof(SE.grid) != 'undefined')
6908 SE.listView.refreshGrid();
6909 //Disabled while address book is disabled
6911 //If this call back was initiated by quick compose from a Detail View page, refresh the
6912 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6913 //close the shortcut bar menu
6914 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6915 if(action_sugar_grp1 == 'DetailView') {
6916 showSubPanel('history',null,true);
6917 } else if(action_sugar_grp1 == 'quickcreate') {
6918 closeEmailOverlay();
6924 ieSendSuccess : function(o) {
6925 SUGAR.hideMessageBox();
6926 SUGAR.showMessageBox(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6931 settingsFolderRefresh : function(o) {
6932 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6933 var ret = YAHOO.lang.JSON.parse(o.responseText);
6934 var user = document.getElementById('userFolders');
6936 SUGAR.email2.util.emptySelectOptions(user);
6938 for(i=0; i<ret.userFolders.length; i++) {
6939 var display = ret.userFolders[i].name;
6940 var value = ret.userFolders[i].id;
6941 var selected = (ret.userFolders[i].selected != "") ? true : false;
6942 var opt = new Option(display, value, selected);
6943 opt.selected = selected;
6944 user.options.add(opt);
6950 startRequest : function(callback, args, forceAbort) {
6951 if(this.currentRequestObject != null) {
6952 if(this.forceAbort == true) {
6953 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6956 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6960 requestInProgress : function() {
6961 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6966 updateFolderSubscriptions : function() {
6967 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6968 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6969 SUGAR.hideMessageBox();
6974 updateFrameFolder : function() {
6975 SUGAR.email2.folders.checkEmailAccounts();
6980 updateUserPrefs : function(o) {
6981 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
6982 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6987 uploadAttachmentSuccessful : function(o) {
6989 document.getElementById('email_attachment').value = '';
6991 var ret = YAHOO.lang.JSON.parse(o.responseText);
6992 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6993 var overall = document.getElementById('addedFiles' + idx);
6994 var index = overall.childNodes.length;
6996 "<div id='email_attachment_bucket" + idx + index + "'>" +
6998 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6999 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
7000 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
7002 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
7003 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
7005 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
7007 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
7010 overall.innerHTML += out;
7011 if(SUGAR.email2.util.isIe()) {
7012 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
7016 SUGAR.email2.addFileDialog.hide();
7017 // focus attachments
7018 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
7023 ///////////////////////////////////////////////////////////////////////////
7024 //// PER MODULE CALLBACK OBJECTS
7025 AjaxObject.accounts = {
7026 saveOutboundCleanup : function(o) {
7027 SUGAR.email2.accounts.refreshOuboundAccountTable();
7028 SUGAR.email2.accounts.outboundDialog.hide();
7029 var id = o.responseText;
7030 SUGAR.email2.accounts.newAddedOutboundId = id;
7032 saveDefaultOutboundCleanup: function(o){
7035 callbackEditOutbound : {
7036 success : function(o)
7038 var ret = YAHOO.lang.JSON.parse(o.responseText);
7040 SUGAR.email2.accounts.showAddSmtp();
7043 document.getElementById("mail_id").value = ret.id;
7044 document.getElementById("type").value = ret.type;
7045 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
7046 document.getElementById("mail_name").value = ret.name;
7047 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
7048 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
7049 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
7050 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
7051 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
7052 SUGAR.email2.accounts.smtp_authenticate_field_display();
7053 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
7055 if(ret.type == 'system-override') {
7056 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
7057 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
7060 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
7061 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
7063 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
7066 failure : AjaxObject.handleFailure,
7067 timeout : AjaxObject.timeout,
7070 callbackDeleteOutbound : {
7071 success : function(o) {
7072 var ret = YAHOO.lang.JSON.parse(o.responseText);
7075 if(confirm(ret.error_message))
7077 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
7078 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
7081 SUGAR.hideMessageBox();
7085 SUGAR.hideMessageBox();
7086 SUGAR.email2.accounts.refreshOuboundAccountTable();
7090 failure : AjaxObject.handleFailure,
7091 timeout : AjaxObject.timeout,
7095 callbackCheckMailProgress : {
7096 success : function(o) {
7097 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
7098 SUGAR.email2.accounts.totalMsgCount = -1;
7101 //Check for server timeout / errors
7102 var ret = YAHOO.lang.JSON.parse(o.responseText);
7105 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
7106 SUGAR.hideMessageBox();
7107 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7108 SUGAR.email2.accounts.totalMsgCount = -1;
7109 //SUGAR.email2.folders.rebuildFolders();
7113 var currIeId = ret['ieid'];
7116 var serverCount = ret.count;
7118 if (ret['status'] == 'done') {
7119 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7120 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7124 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7125 //Go to next account
7126 currIeId = SUGAR.email2.accounts.ieIds[i+1];
7128 SUGAR.email2.accounts.totalMsgCount = -1;
7133 else if (ret.mbox && ret.totalcount && ret.count) {
7134 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7135 if (ret.count >= ret.totalcount) {
7138 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7139 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7141 SUGAR.hideMessageBox();
7142 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7143 SUGAR.email2.accounts.totalMsgCount = -1;
7148 SUGAR.email2.accounts.totalMsgCount = -1;
7149 SUGAR.hideMessageBox();
7150 SUGAR.email2.folders.rebuildFolders();
7151 SE.listView.refreshGrid();
7152 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7153 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7154 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7155 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7157 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7158 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7159 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7160 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7161 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7164 failure : AjaxObject.handleFailure,
7165 timeout : AjaxObject.timeout,
7170 ///////////////////////////////////////////////////////////////////////////////
7172 AjaxObject.composeLayout = {
7174 * Populates the record id
7176 saveDraftCleanup : function(o) {
7178 SUGAR.hideMessageBox();
7181 ret = YAHOO.lang.JSON.parse(o.responseText);
7182 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7184 if (o.responseText) {
7185 SUGAR.showMessageBox(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7191 AjaxObject.composeLayout.callback = {
7193 success : AjaxObject.composeLayout.saveDraftCleanup,
7194 failure : AjaxObject.handleFailure,
7195 timeout : AjaxObject.timeout,
7200 AjaxObject.detailView = {
7202 * Pops-up a printable view of an email
7204 displayPrintable : function(o) {
7205 var ret = YAHOO.lang.JSON.parse(o.responseText);
7206 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7207 // 2 below must be in global context
7209 meta['panelId'] = SUGAR.email2.util.getPanelId();
7210 email = ret.meta.email;
7211 if (typeof(email.cc) == 'undefined') {
7215 var out = displayTemplate.exec({
7216 'app_strings' : app_strings,
7220 'email' : meta.email
7223 // open popup window
7224 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7225 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7227 popup.document.write(out);
7228 popup.document.close();
7232 * Takes formatted response and creates a modal pop-over containing a title and content
7234 displayView : function(o) {
7235 var SED = SUGAR.email2.detailView;
7236 var ret = YAHOO.lang.JSON.parse(o.responseText);
7238 if(!SED.viewDialog) {
7239 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7243 constraintoviewport: true,
7246 SED.viewDialog.renderEvent.subscribe(function() {
7247 var content = this.body.firstChild;
7248 var viewH = YAHOO.util.Dom.getViewportHeight();
7250 this.body.style.overflow = "auto";
7251 this.body.style.width = "800px";
7252 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7256 SED.viewDialog.setHeader(ret.title);
7257 SED.viewDialog.setBody(ret.html);
7258 SED.viewDialog.render();
7259 SED.viewDialog.show();
7263 * Generates a modal popup to populate with the contents of bean's full EditView
7265 showQuickCreateForm : function(o) {
7266 var SED = SUGAR.email2.detailView;
7267 var ret = YAHOO.lang.JSON.parse(o.responseText);
7269 if(!SED.quickCreateDialog) {
7270 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7274 constraintoviewport: true,
7278 SED.quickCreateDialog.renderEvent.subscribe(function() {
7279 var viewH = YAHOO.util.Dom.getViewportHeight();
7281 for (var i in this.body.childNodes) {
7282 if (this.body.childNodes[i].clientHeight) {
7283 contH += this.body.childNodes[i].clientHeight;
7284 } else if (this.body.childNodes[i].offsetHeight) {
7285 contH += this.body.childNodes[i].offsetHeight;
7288 this.body.style.width = "800px";
7289 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7290 this.body.style.overflow = "auto";
7291 }, SED.quickCreateDialog);
7293 SED.quickCreateDialog.hideEvent.subscribe(function(){
7294 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7295 /*for(var qsField in qsFields){
7296 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7297 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7300 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7303 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7305 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7306 SED.quickCreateDialog.render();
7307 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7309 SED.quickCreateDialog.ieId = ret.ieId;
7310 SED.quickCreateDialog.uid = ret.uid;
7311 SED.quickCreateDialog.mbox = ret.mbox;
7312 SED.quickCreateDialog.qcmodule = ret.module;
7314 SED.quickCreateDialog.show();
7316 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7318 editForm.module.value = 'Emails';
7319 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7320 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7321 var instId = ret.module + count;
7322 SED.quickCreateEmailsToAdd = ret.emailAddress;
7323 SED.quickCreateEmailCallback = function(instId, tableId) {
7324 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7325 if (typeof(eaw) == "undefined")
7326 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7327 + instId + "','" + tableId + "');", 100);
7328 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7330 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7331 + instId + "','" + tableId + "');", 100);
7335 saveQuickCreateForm : function(o) {
7336 SUGAR.hideMessageBox();
7337 SUGAR.email2.detailView.quickCreateDialog.hide();
7338 validate['EditView'] = [ ];
7341 saveQuickCreateFormAndReply : function(o) {
7342 SUGAR.hideMessageBox();
7343 var ret = YAHOO.lang.JSON.parse(o.responseText);
7344 SUGAR.email2.detailView.quickCreateDialog.hide();
7345 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7346 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7348 var emailID = ret.id;
7349 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7351 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7353 //Cean the validate cache to prevent errors on the next call
7354 validate['EditView'] = [ ];
7357 saveQuickCreateFormAndAddToAddressBook : function(o) {
7358 SUGAR.hideMessageBox();
7359 SUGAR.email2.detailView.quickCreateDialog.hide();
7360 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7361 validate['EditView'] = [ ];
7364 handleAssignmentDialogAssignAction : function() {
7367 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7369 var dist = 'direct';
7373 var found_teams = false;
7374 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7375 if(!found_teams && assign_user_id == '' )
7377 alert(warning_message);
7381 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7383 for(i=0; i<emailUids.length; i++) {
7385 uids += app_strings.LBL_EMAIL_DELIMITER;
7387 uids += emailUids[i];
7390 var row = SUGAR.email2.grid.getSelectedRows()[0];
7391 var data = SUGAR.email2.grid.getRecord(row).getData();
7392 var ieid = data.ieId;
7393 var mbox = data.mbox;
7394 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7395 SUGAR.email2.contextMenus.assignToDialogue.hide();
7396 SUGAR.showMessageBox('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7400 handleAssignmentDialogDeleteAction : function() {
7401 // TO pass list of UIDS/emailIds
7402 var uids = SUGAR.email2.listView.getUidsFromSelection();
7403 var row = SUGAR.email2.grid.getSelections()[0];
7404 var ieid = row.data.ieId;
7405 var mbox = row.data.mbox;
7406 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7407 SUGAR.email2.contextMenus.assignmentDialog.hide();
7408 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7414 showEmailDetailView : function(o) {
7415 SUGAR.hideMessageBox();
7416 var SED = SUGAR.email2.detailView;
7417 var ret = YAHOO.lang.JSON.parse(o.responseText);
7419 if(!SED.quickCreateDialog) {
7420 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7424 constraintoviewport: true,
7426 autofillheight: "body",
7429 SED.quickCreateDialog.renderEvent.subscribe(function() {
7430 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7432 for (var i in this.body.childNodes) {
7433 if (this.body.childNodes[i].offsetHeight)
7434 contH += this.body.childNodes[i].offsetHeight;
7436 this.body.style.overflow = "auto";
7437 this.body.style.width = "800px";
7438 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7440 }, SED.quickCreateDialog);
7442 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7443 SED.quickCreateDialog.setBody(ret.html);
7444 SED.quickCreateDialog.render();
7445 SUGAR.util.evalScript(ret.html);
7446 SED.quickCreateDialog.show();
7449 showAssignmentDialogWithData : function(o) {
7450 var SEC = SUGAR.email2.contextMenus;
7451 SUGAR.hideMessageBox();
7452 var ret = YAHOO.lang.JSON.parse(o.responseText);
7453 if (!SEC.assignmentDialog) {
7454 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7457 constraintoviewport: true,
7460 SEC.assignmentDialog.setBody("");
7461 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7462 SEC.assignmentDialog.renderEvent.subscribe(function() {
7463 var iev = YAHOO.util.Dom.get("Distribute");
7465 this.body.style.width = "700px";
7467 }, SEC.assignmentDialog);
7468 SEC.assignmentDialog.render();
7470 SEC.assignmentDialog.setBody(ret);
7471 SEC.assignmentDialog.render();
7473 SEC.assignmentDialog.show();
7474 SUGAR.util.evalScript(ret);
7477 showImportForm : function(o) {
7478 var SED = SUGAR.email2.detailView;
7479 var ret = YAHOO.lang.JSON.parse(o.responseText);
7481 document.getElementById('quickCreateContent').innerHTML = "";
7482 SUGAR.hideMessageBox();
7487 if(!SED.importDialog) {
7488 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7492 constraintoviewport: true,
7494 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7495 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7499 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7500 SED.importDialog.setBody("");
7501 SED.importDialog.hideEvent.subscribe(function(){
7502 for(var i in QSFieldsArray) {
7503 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7504 QSFieldsArray[i].destroy();
7505 delete QSFieldsArray[i];
7507 if (QSProcessedFieldsArray[i]) {
7508 QSProcessedFieldsArray[i] = false;
7512 SED.importDialog.renderEvent.subscribe(function() {
7513 var iev = YAHOO.util.Dom.get("ImportEditView");
7515 //this.body.style.height = (iev.clientHeight + 10) + "px";
7516 this.body.style.width = "600px";
7518 }, SED.importDialog);
7519 SED.importDialog.render();
7521 SED.importDialog.setBody(ret.html);
7522 SED.importDialog.ret = ret;
7523 SUGAR.util.evalScript(ret.html);
7524 SED.importDialog.render();
7526 SED.importDialog.show();
7527 SED.importDialog.focusFirstButton();
7529 getImportAction : function(ret) {
7530 if (!check_form('ImportEditView')) return false;
7531 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7532 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7536 var editView = document.getElementById('ImportEditView');
7537 if (editView.assigned_user_id != null) {
7538 get = get + "&user_id=" + editView.assigned_user_id.value
7539 //var user_id = editView.assigned_user_id.value;
7541 var parent_id = editView.parent_id.value;
7542 var parent_type = editView.parent_type.value;
7543 var row = SUGAR.email2.grid.getSelectedRows()[0];
7544 row = SUGAR.email2.grid.getRecord(row);
7545 var data = row.getData();
7546 var ieId = data.ieId;
7547 var mbox = data.mbox;
7548 var serverDelete = editView.serverDelete.checked;
7549 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7551 for(i=0; i<emailUids.length; i++) {
7553 uids += app_strings.LBL_EMAIL_DELIMITER;
7555 uids += emailUids[i];
7558 var action = 'importEmail&uid=';
7560 action = 'moveEmails';
7561 action = action + '&sourceFolder=' + ret['srcFolder'];
7562 action = action + '&sourceIeId=' + ret['srcIeId'];
7563 action = action + '&destinationFolder=' + ret['dstFolder'];
7564 action = action + '&destinationIeId=' + ret['dstIeId'];
7565 action = action + '&emailUids=';
7567 if (action.search(/importEmail/) != -1) {
7568 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7570 SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7573 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7574 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7575 SUGAR.email2.detailView.importDialog.hide();
7576 document.getElementById('importDialogContent').innerHTML = "";
7579 showRelateForm : function(o) {
7580 var SED = SUGAR.email2.detailView;
7581 var ret = YAHOO.lang.JSON.parse(o.responseText);
7582 document.getElementById('quickCreateContent').innerHTML = "";
7583 SUGAR.hideMessageBox();
7587 dialog_loaded = true;
7589 if(!SED.relateDialog) {
7590 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7595 constraintoviewport: true,
7597 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7598 if (!check_form('RelateEditView')) return false;
7600 var editView = document.getElementById('RelateEditView');
7601 var parent_id = editView.parent_id.value;
7602 var parent_type = editView.parent_type.value;
7603 var row = SUGAR.email2.grid.getSelectedRows()[0];
7604 row = SUGAR.email2.grid.getRecord(row);
7605 var ieId = row.getData().ieId;
7606 var mbox = row.getData().mbox;
7607 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7609 for(i=0; i<emailUids.length; i++) {
7611 uids += app_strings.LBL_EMAIL_DELIMITER;
7613 uids += emailUids[i];
7615 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7616 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7617 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7618 SED.relateDialog.hide();
7619 document.getElementById('relateDialogContent').innerHTML = "";
7624 SED.relateDialog.hideEvent.subscribe(function(){
7625 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7626 QSFieldsArray['ImportEditView_parent_name'].destroy();
7627 delete QSFieldsArray['ImportEditView_parent_name'];
7629 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7630 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7634 SED.relateDialog.renderEvent.subscribe(function() {
7635 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7637 for (var i in this.body.childNodes) {
7638 if (this.body.childNodes[i].clientHeight)
7639 contH += this.body.childNodes[i].clientHeight;
7641 }, SED.relateDialog);
7642 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7645 SED.relateDialog.setBody(ret.html);
7646 SED.relateDialog.render();
7647 SUGAR.util.evalScript(ret.html);
7648 SED.relateDialog.show();
7652 * DetailView callbacks
7654 AjaxObject.detailView.callback = {
7656 success : function(o) {
7658 var ret = YAHOO.lang.JSON.parse(o.responseText);
7659 SUGAR.email2.detailView.consumeMetaDetail(ret);
7661 argument: [targetDiv],
7662 failure : AjaxObject.handleFailure,
7667 success : function(o) {
7669 var ret = YAHOO.lang.JSON.parse(o.responseText);
7670 SUGAR.email2.detailView.consumeMetaPreview(ret);
7672 failure : AjaxObject.handleFailure,
7677 success : AjaxObject.detailView.displayPrintable,
7678 failure : AjaxObject.handleFailure,
7679 timeout : AjaxObject.timeout,
7683 success : AjaxObject.detailView.displayView,
7684 failure : AjaxObject.handleFailure,
7685 timeout : AjaxObject.timeout,
7694 AjaxObject.folders = {
7696 * check-mail post actions
7698 checkMailCleanup : function(o) {
7699 SUGAR.hideMessageBox();
7700 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7702 // refresh focus ListView
7703 SE.listView.refreshGrid();
7704 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7709 rebuildFolders : function(o) {
7710 SUGAR.hideMessageBox();
7712 var data = YAHOO.lang.JSON.parse(o.responseText);
7714 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7715 SUGAR.email2.folders.setSugarFolders();
7718 AjaxObject.folders.callback = {
7720 success : AjaxObject.folders.checkMailCleanup,
7721 failure : AjaxObject.handleFailure,
7722 timeout : 600000, // 5 mins
7727 AjaxObject.rules = {
7728 loadRulesForSettings : function(o) {
7729 document.getElementById("rulesListCell").innerHTML = o.responseText;
7730 // assume we have the class we need
7731 SUGAR.routing.getStrings();
7732 SUGAR.routing.getDependentDropdowns();
7735 //// END PER MODULE CALLBACK OBJECTS
7736 ///////////////////////////////////////////////////////////////////////////
7740 success : AjaxObject.handleSuccess,
7741 failure : AjaxObject.handleFailure,
7742 timeout : AjaxObject.timeout,
7745 var callbackAccount = {
7746 success : AjaxObject.ieSaveSuccess,
7747 failure : AjaxObject.handleFailure,
7748 timeout : AjaxObject.timeout,
7751 var callbackAccountDelete = {
7752 success : AjaxObject.ieDeleteSuccess,
7753 failure : AjaxObject.handleFailure,
7754 timeout : AjaxObject.timeout,
7757 var callbackOutboundTest = {
7758 success : AjaxObject.ieSendSuccess,
7759 failure : AjaxObject.handleFailure,
7760 timeout : AjaxObject.timeout,
7766 var callbackTeamInfoForSettings = {
7767 success : function (o) {
7768 var data = YAHOO.lang.JSON.parse(o.responseText);
7769 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7771 failure : AjaxObject.handleFailure,
7772 timeout : AjaxObject.timeout,
7777 var callbackStatusForImport = {
7778 success : function (o) {
7779 SUGAR.hideMessageBox();
7780 if (o.responseText != "") {
7781 var statusString = "";
7782 var data = YAHOO.lang.JSON.parse(o.responseText);
7783 for(i=0; i<data.length; i++) {
7784 statusString = statusString + data[i] + '<br/>';
7786 SUGAR.showMessageBox(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7788 SE.listView.refreshGrid();
7791 failure : AjaxObject.handleFailure,
7792 timeout : AjaxObject.timeout,
7796 var callbackComposeCache = {
7797 success : AjaxObject.composeCache,
7798 failure : AjaxObject.handleFailure,
7799 timeout : AjaxObject.timeout,
7802 var callbackDelete = {
7803 success : AjaxObject.handleDeleteReturn,
7804 failure : AjaxObject.handleFailure,
7805 timeout : AjaxObject.timeout,
7808 var callbackEmailDetailMultiple = {
7809 success : function(o) {
7810 SUGAR.hideMessageBox();
7811 var retMulti = YAHOO.lang.JSON.parse(o.responseText);
7812 var ret = new Object();
7814 for(var i=0; i<retMulti.length; i++) {
7817 SUGAR.email2._setDetailCache(ret);
7818 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7821 failure : AjaxObject.handleFailure,
7825 var callbackListViewSortOrderChange = {
7826 success : AjaxObject.saveListViewSortOrderPart2,
7827 failure : AjaxObject.handleFailure,
7828 timeout : AjaxObject.timeout,
7830 argument : [ieId, ieName, focusFolder]
7832 var callbackEmptyTrash = {
7833 success : function(o) {
7834 SUGAR.hideMessageBox();
7835 AjaxObject.folderRenameCleanup;
7837 failure : AjaxObject.handleFailure,
7838 timeout : AjaxObject.timeout,
7841 var callbackClearCacheFiles = {
7842 success : function(o) {
7843 SUGAR.hideMessageBox();
7845 failure : AjaxObject.handleFailure,
7846 timeout : AjaxObject.timeout,
7849 var callbackFolderRename = {
7850 success : function(o) {SUGAR.hideMessageBox();SUGAR.email2.folders.rebuildFolders();},
7851 failure : AjaxObject.handleFailure,
7852 timeout : AjaxObject.timeout,
7855 var callbackFolderDelete = {
7856 success : function(o) {
7857 var ret = YAHOO.lang.JSON.parse(o.responseText);
7859 if (ret.folder_id) {
7860 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7862 SUGAR.email2.tree.removeNode(node, true);
7863 } else if (ret.ieId && ret.mbox) {
7864 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7866 SUGAR.email2.tree.removeNode(node, true);
7868 SUGAR.hideMessageBox();
7869 //SUGAR.email2.folders.loadSettingFolder();
7871 SUGAR.hideMessageBox();
7872 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7875 failure : AjaxObject.handleFailure,
7876 timeout : AjaxObject.timeout,
7879 var callbackFolderSave = {
7880 success : function(o) {
7881 var ret = YAHOO.lang.JSON.parse(o.responseText);
7883 switch(ret.action) {
7884 case 'newFolderSave':
7885 SUGAR.email2.folders.rebuildFolders();
7889 failure : AjaxObject.handleFailure,
7890 timeout : AjaxObject.timeout,
7893 var callbackFolderSubscriptions = {
7894 success : AjaxObject.updateFolderSubscriptions,
7895 failure : AjaxObject.handleFailure,
7896 timeout : AjaxObject.timeout,
7899 var callbackFolderUpdate = {
7900 success : AjaxObject.updateFrameFolder,
7901 failure : AjaxObject.handleFailure,
7902 timeout : AjaxObject.timeout,
7905 var callbackFolders = {
7906 success : AjaxObject.folders.rebuildFolders,
7907 //success : void(true),
7908 failure : AjaxObject.handleFailure,
7909 timeout : AjaxObject.timeout,
7912 var callbackFullSync = {
7913 success : AjaxObject.fullSyncCleanup,
7914 failure : AjaxObject.handleFailure,
7915 timeout : 9999999999999,
7918 var callbackGeneric = {
7919 success : function() {
7920 SUGAR.hideMessageBox();
7922 failure : AjaxObject.handleFailure,
7923 timeout : AjaxObject.timeout,
7926 var callbackIeAccountRetrieve = {
7927 success : function(o) {
7928 // return JSON encoding
7929 SUGAR.hideMessageBox();
7930 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7931 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7933 failure : AjaxObject.handleFailure,
7934 timeout : AjaxObject.timeout,
7937 var callbackImportOneEmail = {
7938 success : AjaxObject.detailView.showImportForm,
7939 failure : AjaxObject.handleFailure,
7940 timeout : AjaxObject.timeout,
7943 var callbackRelateEmail = {
7944 success : AjaxObject.detailView.showRelateForm,
7945 failure : AjaxObject.handleFailure,
7946 timeout : AjaxObject.timeout,
7949 var callbackEmailDetailView = {
7950 success : AjaxObject.detailView.showEmailDetailView,
7951 failure : AjaxObject.handleFailure,
7952 timeout : AjaxObject.timeout,
7955 var callbackAssignmentDialog = {
7956 success : AjaxObject.detailView.showAssignmentDialogWithData,
7957 failure : AjaxObject.handleFailure,
7958 timeout : AjaxObject.timeout,
7961 var callbackAssignmentAction = {
7962 success : function(o) {
7963 SE.listView.refreshGrid();
7964 SUGAR.hideMessageBox();
7965 if(o.responseText != '') {
7966 SUGAR.showMessageBox('Assignment action result', o.responseText, 'alert');
7969 failure : AjaxObject.handleFailure,
7970 timeout : AjaxObject.timeout,
7973 var callbackMoveEmails = {
7974 success : function(o) {
7975 SE.listView.refreshGrid();
7976 SUGAR.hideMessageBox();
7977 if(o.responseText != '') {
7978 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7981 failure : AjaxObject.handleFailure,
7982 timeout : AjaxObject.timeout,
7985 var callbackLoadAttachments = {
7986 success : AjaxObject.loadAttachments,
7987 failure : AjaxObject.handleFailure,
7988 timeout : AjaxObject.timeout,
7991 var callbackLoadRules = {
7992 success : AjaxObject.rules.loadRulesForSettings,
7993 failure : AjaxObject.handleFailure,
7994 timeout : AjaxObject.timeout,
7997 var callbackLoadSignature = {
7998 success : AjaxObject.loadSignature,
7999 failure : AjaxObject.handleFailure,
8000 timeout : AjaxObject.timeout,
8003 var callbackDeleteSignature = {
8004 success : AjaxObject.handleDeleteSignature,
8005 failure : AjaxObject.handleFailure,
8006 timeout : AjaxObject.timeout,
8009 /*var callbackMoveEmails = {
8010 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
8011 failure : AjaxObject.handleFailure,
8012 timeout : AjaxObject.timeout,
8015 var callbackOutboundSave = {
8016 success : AjaxObject.accounts.saveOutboundCleanup,
8017 failure : AjaxObject.handleFailure,
8018 timeout : AjaxObject.timeout,
8021 var callbackDefaultOutboundSave = {
8022 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
8023 failure : AjaxObject.handleFailure,
8024 timeout : AjaxObject.timeout,
8027 var callbackQuickCreate = {
8028 success : AjaxObject.detailView.showQuickCreateForm,
8029 failure : AjaxObject.handleFailure,
8030 timeout : AjaxObject.timeout,
8033 var callbackQuickCreateSave = {
8034 success : AjaxObject.detailView.saveQuickCreateForm,
8035 failure : AjaxObject.handleFailure,
8036 timeout : AjaxObject.timeout,
8039 var callbackQuickCreateSaveAndAddToAddressBook = {
8040 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
8041 failure : AjaxObject.handleFailure,
8042 timeout : AjaxObject.timeout,
8045 var callbackQuickCreateSaveAndReply = {
8046 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
8047 failure : AjaxObject.handleFailure,
8048 timeout : AjaxObject.timeout,
8051 var callbackQuickCreateSaveAndReplyCase = {
8052 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
8053 failure : AjaxObject.handleFailure,
8054 timeout : AjaxObject.timeout,
8057 var callbackRebuildShowAccountList = {
8058 success : AjaxObject.rebuildShowFolders,
8059 failure : AjaxObject.handleFailure,
8060 timeout : AjaxObject.timeout,
8064 var callbackRefreshSugarFolders = {
8065 success : function(o) {
8066 var t = YAHOO.lang.JSON.parse(o.responseText);
8067 SUGAR.email2.folders.setSugarFoldersEnd(t);
8069 failure : AjaxObject.handleFailure,
8070 timeout : AjaxObject.timeout,
8073 var callbackReplyForward = {
8074 success : AjaxObject.handleReplyForward,
8075 finish : function(a, retryCount) {
8076 if (typeof(retryCount) == 'undefined') {
8081 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8082 var t = tinyMCE.getInstanceById('htmleditor' + idx);
8084 var html = t.getContent();
8086 if(typeof a.type != 'undefined' && a.type == 'draft'){
8087 html = a.description;
8090 html = " <br><div><hr></div>" + a.description;
8094 t.setContent(html);//
8096 if (a.type != 'draft') {
8097 // Next step, attach signature
8098 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
8102 if (retryCount < 5) {
8103 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
8107 var tabArray = SUGAR.email2.innerLayout.get("tabs");
8108 if (tabArray != null && tabArray.length > 0) {
8109 for (i = 0 ; i < tabArray.length ; i++) {
8110 var tabObject = tabArray[i];
8111 if (tabObject.get("id") == ("composeTab" + idx)) {
8112 var tabLabel = a.name;
8113 if (tabLabel != null && tabLabel.length > 25) {
8114 tabLabel = tabLabel.substring(0, 25) + "...";
8116 tabObject.get("labelEl").firstChild.data = tabLabel;
8122 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8123 if (a.parent_name != null && a.parent_name != "") {
8124 document.getElementById('data_parent_name' + idx).value = a.parent_name;
8126 if (a.parent_type != null && a.parent_type != "") {
8127 document.getElementById('data_parent_type' + idx).value = a.parent_type;
8129 if (a.parent_id != null && a.parent_id != "") {
8130 document.getElementById('data_parent_id' + idx).value = a.parent_id;
8132 if (a.fromAccounts.status) {
8133 var addressFrom = document.getElementById('addressFrom' + idx);
8134 SUGAR.email2.util.emptySelectOptions(addressFrom);
8135 var fromAccountOpts = a.fromAccounts.data;
8136 for(i=0; i<fromAccountOpts.length; i++) {
8137 var key = fromAccountOpts[i].value;
8138 var display = fromAccountOpts[i].text;
8139 var opt = new Option(display, key);
8140 if (fromAccountOpts[i].selected) {
8141 opt.selected = true;
8143 addressFrom.options.add(opt);
8146 SUGAR.hideMessageBox();
8149 failure : AjaxObject.handleFailure,
8150 timeout : AjaxObject.timeout,
8152 argument : [sendType]
8154 var callbackSendEmail = {
8155 success : AjaxObject.sendEmailCleanUp,
8156 failure : AjaxObject.handleFailure,
8157 timeout : AjaxObject.timeout,
8160 var callbackSettings = {
8161 success : AjaxObject.updateUserPrefs,
8162 failure : AjaxObject.handleFailure,
8163 timeout : AjaxObject.timeout,
8166 var callbackSettingsFolderRefresh = {
8167 success : AjaxObject.settingsFolderRefresh,
8168 failure : AjaxObject.handleFailure,
8169 timeout : AjaxObject.timeout,
8172 var callbackLoadSettingFolder = {
8173 success : function(o) {
8174 AjaxObject.settingsFolderRefresh(o);
8175 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8177 failure : AjaxObject.handleFailure,
8178 timeout : AjaxObject.timeout,
8182 var callbackUploadAttachment = {
8183 success : AjaxObject.uploadAttachmentSuccessful,
8184 upload : AjaxObject.uploadAttachmentSuccessful,
8185 failure : AjaxObject.handleFailure,
8186 timeout : AjaxObject.timeout,
8189 var callbackUserPrefs = {
8190 success : function(o) {
8191 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
8193 failure : AjaxObject.handleFailure,
8194 timeout : AjaxObject.timeout,
8198 var callbackContextmenus = {
8200 success : AjaxObject.markEmailCleanup,
8201 failure : AjaxObject.handleFailure,
8202 timeout : AjaxObject.timeout,
8207 var callbackCheckEmail2 = {
8208 success : function(o) {
8209 var ret = YAHOO.lang.JSON.parse(o.responseText);
8210 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8214 failure : AjaxObject.handleFailure,
8215 timeout : AjaxObject.timeout,
8217 }// End of File modules/Emails/javascript/ajax.js
8219 /*********************************************************************************
8220 * SugarCRM Community Edition is a customer relationship management program developed by
8221 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8223 * This program is free software; you can redistribute it and/or modify it under
8224 * the terms of the GNU Affero General Public License version 3 as published by the
8225 * Free Software Foundation with the addition of the following permission added
8226 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8227 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8228 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8230 * This program is distributed in the hope that it will be useful, but WITHOUT
8231 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8232 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8235 * You should have received a copy of the GNU Affero General Public License along with
8236 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8237 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8240 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8241 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8243 * The interactive user interfaces in modified source and object code versions
8244 * of this program must display Appropriate Legal Notices, as required under
8245 * Section 5 of the GNU Affero General Public License version 3.
8247 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8248 * these Appropriate Legal Notices must retain the display of the "Powered by
8249 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8250 * technical reasons, the Appropriate Legal Notices must display the words
8251 * "Powered by SugarCRM".
8252 ********************************************************************************/
8254 function gridInit() {
8255 if(SUGAR.email2.grid) {
8256 SUGAR.email2.grid.destroy();
8262 var Ck = YAHOO.util.Cookie;
8263 var widths = [ 10, 10, 150, 250, 175, 125 ];
8265 if (Ck.get("EmailGridWidths")) {
8266 for (var i=0; i < widths.length; i++) {
8267 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8270 for (var i=0; i < widths.length; i++) {
8271 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8275 // changes "F" to an icon
8276 function flaggedIcon(cell, record, column, value) {
8278 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8281 // changes "A" to replied icon
8282 function repliedIcon(cell, record, column, value) {
8284 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8287 function attachIcon(cell, record, column, value) {
8289 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8296 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8301 formatter: attachIcon,
8305 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8310 formatter: flaggedIcon,
8314 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8319 formatter: repliedIcon,
8323 label: app_strings.LBL_EMAIL_FROM,
8330 label: app_strings.LBL_EMAIL_SUBJECT,
8337 label: mod_strings.LBL_LIST_DATE,
8344 label: app_strings.LBL_EMAIL_TO,
8380 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8381 responseType: YAHOO.util.DataSource.TYPE_JSON,
8383 resultsList: 'Email',
8384 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8385 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8391 action : "EmailUIAjax",
8392 emailUIAction : "getMessageList",
8395 forceRefresh : "false"
8397 if(lazyLoadFolder != null) {
8398 params['mbox'] = lazyLoadFolder.folder;
8399 params['ieId'] = lazyLoadFolder.ieId;
8400 //Check if the folder is a Sugar Folder
8401 var test = new String(lazyLoadFolder.folder);
8402 if(test.match(/SUGAR\./)) {
8403 params['emailUIAction'] = 'getMessageListSugarFolders';
8404 params['mbox'] = test.substr(6);
8407 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8410 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8411 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8413 paginator: new YAHOO.widget.Paginator({
8414 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8415 containers : ["dt-pag-nav"],
8416 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8417 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8418 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8419 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8420 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8422 initialRequest:SUGAR.util.paramsToUrl(params),
8429 //Override Paging request construction
8430 grid.set("generateRequest", function(oState, oSelf) {
8431 oState = oState || {pagination:null, sortedBy:null};
8432 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[5].getKey();
8433 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_ASC) ? "asc" : "desc";
8434 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8435 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8436 // Build the request
8438 SUGAR.util.paramsToUrl(oSelf.params) +
8441 "&start=" + startIndex +
8442 ((results !== null) ? "&limit=" + results : "");
8447 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8448 oPayload = oPayload || { };
8450 oPayload.totalRecords = oResponse.meta.total;
8451 oPayload.unreadRecords = oResponse.meta.unread;
8453 var tabObject = SE.innerLayout.get("tabs")[0];
8455 if (this.params.mbox != null) {
8456 mboxTitle = this.params.mbox;
8458 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8459 tabObject.get("labelEl").firstChild.data = tabtext;
8462 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8464 node.data.unseen = oResponse.meta.unread;
8465 SE.accounts.renderTree();
8471 var resize = grid.resizeGrid = function () {
8472 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8473 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8475 grid.convertDDRows = function() {
8476 var rowEl = this.getFirstTrEl();
8477 while (rowEl != null) {
8478 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8479 rowEl = this.getNextTrEl(rowEl);
8484 grid.on("columnResizeEvent", function(o) {
8485 //Find the index of the column
8486 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8487 for (var i=0; i < colSet.length; i++) {
8488 if (o.column == colSet[i]) {
8489 //Store it in the cookie
8490 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8493 //this.resizeGrid();
8496 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8497 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8498 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8500 SUGAR.email2.listViewLayout.on("render", resize);
8503 //Setup the default load parameters
8504 SUGAR.email2.grid.params = params;
8506 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8507 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8508 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8515 function initRowDD() {
8516 var sg = SUGAR.email2.grid,
8517 Dom = YAHOO.util.Dom;
8518 sg.DDRow = function(oDataTable, oRecord, elTr) {
8519 if(oDataTable && oRecord && elTr) {
8520 this.ddtable = oDataTable;
8521 this.table = oDataTable.getTableEl();
8524 this.newIndex = null;
8526 this.initFrame(); // Needed for DDProxy
8527 this.invalidHandleTypes = {};
8531 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8532 _resizeProxy: function() {
8533 this.constructor.superclass._resizeProxy.apply(this, arguments);
8534 var dragEl = this.getDragEl(),
8536 var xy = Dom.getXY(el);
8538 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8539 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8540 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8541 Dom.setStyle(dragEl, 'display', "");
8544 startDrag: function(x, y) {
8545 //Check if we should be dragging a set of rows rather than just the one.
8546 var selectedRows = this.ddtable.getSelectedRows();
8547 var iSelected = false;
8548 for (var i in selectedRows) {
8549 if (this.rowEl.id == selectedRows[i]) {
8556 for (var i in selectedRows) {
8557 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8560 this.rows = [this.row];
8561 this.ddtable.unselectAllRows();
8562 this.ddtable.selectRow(this.row);
8565 //Initialize the dragable proxy
8566 var dragEl = this.getDragEl();
8567 var clickEl = this.getEl();
8568 Dom.setStyle(clickEl, "opacity", "0.25");
8569 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8570 Dom.addClass(dragEl, "yui-dt-liner");
8571 Dom.setStyle(dragEl, "opacity", "0.5");
8572 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8573 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8574 Dom.setStyle(dragEl, "border", "2px solid gray");
8577 clickValidator: function(e) {
8578 if (this.row.getData()[0] == " ")
8580 var target = YAHOO.util.Event.getTarget(e);
8581 return ( this.isValidHandleChild(target) &&
8582 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8585 * This funciton checks that the target of the drag is a table row in this
8586 * DDGroup and simply moves the sourceEL to that location as a preview.
8588 onDragOver: function(ev, id) {
8589 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8590 if (node && node != this.targetNode) {
8591 this.targetNode = node;
8592 SUGAR.email2.folders.unhighliteAll();
8597 onDragOut: function(e, id) {
8598 if (this.targetNode) {
8599 SUGAR.email2.folders.unhighliteAll();
8600 this.targetNode = false;
8603 endDrag: function() {
8604 Dom.setStyle(this.getEl(), "opacity", "");
8605 Dom.setStyle(this.getDragEl(), "display", "none");
8606 if (this.targetNode) {
8607 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8609 SUGAR.email2.folders.unhighliteAll();
8615 function AddressSearchGridInit() {
8616 function moduleIcon(elCell, oRecord, oColumn, oData) {
8617 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8619 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8620 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8622 var checkHeader = '<input type="checkbox" ';
8623 if (SUGAR.email2.util.isIe()) {
8624 checkHeader += 'style="top:-5px" ';
8626 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8631 formatter: selectionCheckBox,
8635 label: mod_strings.LBL_LIST_TYPE,
8637 formatter: moduleIcon,
8641 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8647 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8653 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8654 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8656 resultsList: 'Person',
8657 fields: ['name', 'email', 'bean_id', 'bean_module'],
8658 metaFields: {total: 'TotalCount'}
8660 //enable sorting on the server accross all data
8663 dataModel.params = {
8666 action : "EmailUIAjax",
8667 emailUIAction:"getAddressSearchResults"
8669 var rb = document.getElementById('hasRelatedBean').checked;
8671 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8672 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8673 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8674 dataModel.params['related_bean_id'] = relatedBeanId;
8675 dataModel.params['related_bean_type'] = relatedBeanType;
8676 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8678 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8680 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8681 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8683 paginator: new YAHOO.widget.Paginator({
8685 containers : ["dt-pag-nav-addressbook"],
8686 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8687 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8688 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8689 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8690 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8692 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8696 //Override Paging request construction
8697 grid.set("generateRequest", function(oState, oSelf) {
8698 oState = oState || {pagination:null, sortedBy:null};
8699 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8700 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8701 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8702 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8703 // Build the request
8705 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8706 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8707 ((results !== null) ? "&limit=" + results : "");
8711 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8712 oPayload = oPayload || { };
8713 oPayload.totalRecords = oResponse.meta.total;
8717 grid.clickToggleSelect= function(args) {
8718 var isIE = (args.event.target == null);
8719 var targetElement = isIE ? args.event.srcElement : args.event.target;
8720 if(targetElement.type == null || targetElement.type != 'checkbox') {
8721 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8725 grid.reSelectRowsOnRender = function (){
8726 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8727 for (var i = 0; i < rows.length; i++)
8729 var emailAddress = rows[i].getData("email");
8730 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8733 rows[i].setData("selected", true);
8734 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8738 rows[i].setData("selected", false);
8739 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8743 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8744 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8745 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8746 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8749 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8750 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8752 grid.toggleSelectCheckbox = function(id,checked){
8753 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8754 row.setData("checked",checked);
8756 grid.toggleSelect = function(id, checked) {
8757 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8758 checked = row.getData("selected");
8761 SUGAR.email2.addressBook.grid.selectRow(row);
8762 SE.addressBook.insertContactRowToResultTable(id,null)
8765 SUGAR.email2.addressBook.grid.unselectRow(row);
8766 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8768 row.setData("selected", !checked);
8771 grid.toggleSelectAll = function(checked) {
8772 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8773 for (var i = 0; i < rows.length; i++) {
8774 if (typeof(rows[i]) != "undefined")
8775 rows[i].setData("checked", checked);
8777 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8778 for (var i = 0; i < checkBoxes.length; i++) {
8779 checkBoxes[i].checked = checked;
8783 //Initialize the grid result table.
8784 AddressSearchResultsGridInit();
8790 * Initalize the results table for the address book selection.
8793 function AddressSearchResultsGridInit()
8796 /* Full name sort funciton to compare by last name if available */
8797 var fullNameSort = function(a, b, desc) {
8798 // Deal with empty values
8799 if(!YAHOO.lang.isValue(a))
8800 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8801 else if(!YAHOO.lang.isValue(b))
8804 var aNames = a.getData("name").split(' ');
8805 var bNames = b.getData("name").split(' ');
8807 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8808 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8810 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8814 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8815 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8816 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8818 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})},
8819 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8821 var myDataSource = new YAHOO.util.DataSource([]);
8822 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8823 myDataSource.responseSchema = {
8824 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8827 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8828 width: "350px",height: "250px", MSG_EMPTY: " "});
8830 var highlightEditableCell = function(oArgs) {
8831 var elCell = oArgs.target;
8832 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8833 this.highlightCell(elCell);
8837 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8838 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8839 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8840 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8841 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8843 //Setup the context menus
8844 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8845 var task = p_aArgs[1];
8848 var elRow = this.contextEventTarget;
8849 elRow = p_myDataTable.getTrEl(elRow);
8856 var oRecord = p_myDataTable.getRecord(elRow);
8857 p_myDataTable.deleteRow(elRow);
8858 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8863 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8864 {trigger:gridResults.getTbodyEl()});
8865 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8866 contextMenu.render("addrSearchResultGrid");
8867 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8869 // End of File modules/Emails/javascript/grid.js
8871 /*********************************************************************************
8872 * SugarCRM Community Edition is a customer relationship management program developed by
8873 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8875 * This program is free software; you can redistribute it and/or modify it under
8876 * the terms of the GNU Affero General Public License version 3 as published by the
8877 * Free Software Foundation with the addition of the following permission added
8878 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8879 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8880 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8882 * This program is distributed in the hope that it will be useful, but WITHOUT
8883 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8884 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8887 * You should have received a copy of the GNU Affero General Public License along with
8888 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8889 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8892 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8893 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8895 * The interactive user interfaces in modified source and object code versions
8896 * of this program must display Appropriate Legal Notices, as required under
8897 * Section 5 of the GNU Affero General Public License version 3.
8899 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8900 * these Appropriate Legal Notices must retain the display of the "Powered by
8901 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8902 * technical reasons, the Appropriate Legal Notices must display the words
8903 * "Powered by SugarCRM".
8904 ********************************************************************************/
8907 /******************************************************************************
8908 * Initialize Email 2.0 Application
8911 //Override Sugar Languge so quick creates work properly
8914 function email2init() {
8917 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
8918 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
8919 if (!SUGAR.util.isTouchScreen()) {
8921 convert_urls : false,
8922 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
8923 width: tinyConfig.width,
8924 theme: tinyConfig.theme,
8925 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
8926 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
8927 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
8928 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
8929 plugins : tinyConfig.plugins,
8930 elements : tinyConfig.elements,
8931 language : tinyConfig.language,
8932 extended_valid_elements : tinyConfig.extended_valid_elements,
8933 mode: tinyConfig.mode,
8934 strict_loading_mode : true,
8935 force_br_newlines : true,
8936 forced_root_block : '',
8937 directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
8941 // initialze message overlay
8942 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
8952 if (SUGAR.themes.tempHideLeftCol)
8953 SUGAR.themes.tempHideLeftCol();
8955 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
8956 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
8958 // set defaults for YAHOO.util.DragDropManager
8959 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
8961 SUGAR.email2.nextYear = new Date();
8962 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
8965 // initialize and display UI framework (complexLayout.js)
8966 complexLayoutInit();
8968 // initialize and display grid (grid.js)
8971 // initialize treeview for folders
8973 SUGAR.email2.folders.rebuildFolders(true);
8976 //Setup the Message Box overlay
8977 /*Ext.MessageBox.maxWidth = 350;
8978 Ext.MessageBox.minProgressWidth = 350;
8980 ///////////////////////////////////////////////////////////////////////////
8983 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
8985 var SEC = SUGAR.email2.contextMenus;
8988 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
8989 trigger: SUGAR.email2.grid.get("element"),
8992 emailMenu.subscribe("beforeShow", function() {
8993 var oTarget = this.contextEventTarget;
8994 if (typeof(oTarget) == "undefined")
8996 var grid = SUGAR.email2.grid;
8997 var selectedRows = grid.getSelectedRows();
8998 var multipleSelected = (selectedRows.length > 1) ? true: false;
8999 if (!multipleSelected)
9001 grid.unselectAllRows();
9002 grid.selectRow(oTarget);
9003 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9005 else if(multipleSelected)
9007 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9011 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9012 //us to access individual elements easier by name rather than by index
9013 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
9014 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9015 emailMenu.addItems([
9017 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9018 id: 'showDetailView',
9019 onclick: { fn: SEC.showDetailView }
9022 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9023 onclick: { fn: SEC.openMultiple }
9026 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9027 onclick: { fn: SEC.archiveToSugar }
9030 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9032 onclick: { fn: SEC.replyForwardEmailContext }
9035 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9037 onclick: { fn: SEC.replyForwardEmailContext }
9040 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9042 onclick: { fn: SEC.replyForwardEmailContext }
9045 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9047 onclick: { fn: SEC.markDeleted }
9050 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9052 onclick: { fn: SEC.viewPrintable }
9056 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9058 id: "markEmailMenu",
9061 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9062 onclick: { fn: SEC.markUnread }
9065 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9066 onclick: { fn: SEC.markRead }
9069 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9070 onclick: { fn: SEC.markFlagged }
9073 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9074 onclick: { fn: SEC.markUnflagged }
9080 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9082 onclick: { fn: SEC.assignEmailsTo }
9085 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9087 onclick: { fn: SEC.relateTo }
9090 SEC.emailListContextMenu.render();
9092 //Handle the Tree folder menu trigger ourselves
9093 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9097 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9101 SEC.frameFoldersContextMenu.addItems([
9102 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9103 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9104 onclick: { fn: function() {
9105 var node = SUGAR.email2.clickedFolderNode;
9106 if (node.data.ieId) {
9107 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9110 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9111 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9112 onclick: { fn: function() {
9113 var node = SUGAR.email2.clickedFolderNode;
9114 if (node.data.ieId) {
9115 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9119 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9120 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9121 onclick: { fn: SUGAR.email2.folders.folderAdd }
9124 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9125 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9126 onclick: { fn: SUGAR.email2.folders.folderDelete }
9129 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9130 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9131 onclick: { fn: SUGAR.email2.folders.folderRename }
9134 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9135 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9136 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9139 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9140 onclick: { fn: function() {
9141 var node = SUGAR.email2.clickedFolderNode;
9142 if (node.data.ieId) {
9143 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9147 SEC.frameFoldersContextMenu.render();
9149 SEC.initContactsMenu = function() {
9151 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9152 trigger: "contacts",
9155 SEC.contactsContextMenu.addItems([
9157 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9158 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9161 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9162 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9165 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9166 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9167 if (oTarget && !grid.isSelected(oTarget)) {
9168 grid.unselectAllRows();
9169 grid.selectRow(oTarget);
9172 SEC.contactsContextMenu.render();
9176 // set auto-check timer
9177 SUGAR.email2.folders.startCheckTimer();
9178 // check if we're coming from an email-link click
9179 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9181 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9183 //Init fix for YUI 2.7.0 datatable sort.
9184 SUGAR.email2.addressBook.initFixForDatatableSort();
9187 function createTreePanel(treeData, params) {
9188 var tree = new YAHOO.widget.TreeView(params.id);
9189 var root = tree.getRoot();
9191 //if (treeData.nodes && treeData[0].id == "Home")
9192 // treeData = treeData[0];
9196 function addChildNodes(parentNode, parentData) {
9197 var Ck = YAHOO.util.Cookie;
9198 var nextyear = SUGAR.email2.nextYear;
9199 var nodes = parentData.nodes || parentData.children;
9201 if (typeof(nodes[i]) == 'object') {
9202 if (nodes[i].data) {
9203 // See comment about href below.
9204 // nodes[i].data.href = '#';
9205 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode);
9206 node.action = nodes[i].data.action;
9208 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9209 addChildNodes(parentNode, nodes[i]);
9212 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9213 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9215 nodes[i].className = nodes[i].cls;
9217 // Previously, span was added in the label so it was rendering in the tree.
9218 // Default behavior is to wrap in span if no href property, and since this href
9219 // doesn't do anything, remove it so that it will be wrapped in spans.
9220 // nodes[i].href = "#";
9221 if (nodes[i].text) nodes[i].label = nodes[i].text;
9222 //Override YUI child node creation
9223 if (nodes[i].children) {
9224 nodes[i].nodes = nodes[i].children;
9225 nodes[i].children = [ ];
9227 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9230 if (typeof(nodes[i].nodes) == 'object') {
9231 addChildNodes(node, nodes[i]);
9238 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9240 function email2treeinit(tree, treedata, treediv, params) {
9241 //ensure the tree data is not corrupt
9245 if (SUGAR.email2.tree) {
9246 SUGAR.email2.tree.destroy();
9247 SUGAR.email2.tree = null;
9250 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9254 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9255 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9256 tree.subscribe("expandComplete", function(node){
9257 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9258 for (var i in node.children) {
9259 SE.accounts.setupDDTarget(node.children[i]);
9262 tree.setCollapseAnim("TVSlideOut");
9263 tree.setExpandAnim("TVSlideIn");
9264 var root = tree.root;
9265 while (root.hasChildren()) {
9266 var node = root.children[0];
9268 tree.removeNode(root.children[0], false);
9270 addChildNodes(root, treedata);
9272 SUGAR.email2.accounts.renderTree();
9275 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9276 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9280 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9281 startDrag: function(x, y) {
9282 var Dom = YAHOO.util.Dom;
9283 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9286 var dragEl = this.getDragEl();
9287 var clickEl = this.getEl();
9288 Dom.setStyle(clickEl, "color", "#AAA");
9289 Dom.setStyle(clickEl, "opacity", "0.25");
9290 dragEl.innerHTML = clickEl.innerHTML;
9292 Dom.addClass(dragEl, "ygtvcell");
9293 Dom.addClass(dragEl, "ygtvcontent");
9294 Dom.addClass(dragEl, "folderDragProxy");
9295 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9296 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9297 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9298 Dom.setStyle(dragEl, "opacity", "0.5");
9299 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9302 onDragOver: function(ev, id) {
9303 var Dom = YAHOO.util.Dom;
9304 if (id != this.dragId)
9306 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9307 if(node.data.cls != "sugarFolder") {
9308 SUGAR.email2.folders.unhighliteAll();
9312 this.targetNode = node;
9313 SUGAR.email2.folders.unhighliteAll();
9318 onDragOut: function(e, id) {
9319 if (this.targetNode) {
9320 SUGAR.email2.folders.unhighliteAll();
9321 this.targetNode = false;
9322 this.dragId = false;
9326 endDrag: function() {
9327 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9328 if (this.targetNode) {
9329 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9332 });// End of File modules/Emails/javascript/init.js
9334 /*********************************************************************************
9335 * SugarCRM Community Edition is a customer relationship management program developed by
9336 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9338 * This program is free software; you can redistribute it and/or modify it under
9339 * the terms of the GNU Affero General Public License version 3 as published by the
9340 * Free Software Foundation with the addition of the following permission added
9341 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9342 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9343 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9345 * This program is distributed in the hope that it will be useful, but WITHOUT
9346 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9347 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9350 * You should have received a copy of the GNU Affero General Public License along with
9351 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9352 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9355 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9356 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9358 * The interactive user interfaces in modified source and object code versions
9359 * of this program must display Appropriate Legal Notices, as required under
9360 * Section 5 of the GNU Affero General Public License version 3.
9362 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9363 * these Appropriate Legal Notices must retain the display of the "Powered by
9364 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9365 * technical reasons, the Appropriate Legal Notices must display the words
9366 * "Powered by SugarCRM".
9367 ********************************************************************************/
9372 function complexLayoutInit() {
9373 var se = SUGAR.email2;
9374 var Dom = YAHOO.util.Dom;
9376 getInnerLayout : function(rows) {
9377 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
9378 parent: se.complexLayout,
9384 scroll:false, // grid should autoScroll itself
9386 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
9394 body: "<div id='listBottom' />"
9402 body: "<div id='listRight' />",
9403 titlebar: false //,header: "right"
9406 se.complexLayout.on("render", function(){
9407 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
9408 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9409 SUGAR.email2.listViewLayout.set("height", height);
9410 SUGAR.email2.listViewLayout.render();
9412 se.listViewLayout.render();
9414 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
9415 var rp = se.listViewLayout.resizePreview = function() {
9416 var pre = Dom.get("displayEmailFramePreview");
9418 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
9419 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
9422 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
9423 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
9424 se.e2Layout.setPreviewPanel(rows);
9425 se.previewLayout = se.listViewLayout;
9426 return se.listViewLayout;
9429 getInnerLayout2Rows : function() {
9430 return this.getInnerLayout(true);
9432 getInnerLayout2Columns : function() {
9433 return this.getInnerLayout(false);
9437 // initialize state manager, we will use cookies
9438 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
9439 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
9440 se.complexLayout = new YAHOO.widget.Layout("container", {
9443 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
9444 width: Dom.getViewportWidth() - 40,
9448 body: "<div id='emailtabs'></div>"
9453 body: "<div id='lefttabs'></div>",
9463 header: Dom.get('footerLinks').innerHTML,
9470 se.complexLayout.render();
9471 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
9472 tp.addTab(new YAHOO.widget.Tab({
9475 content : "<div id='listViewDiv'/>",
9479 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
9480 tp.appendTo(centerEl);
9482 tp.get("element").style.borderRight = "1px solid #666"
9484 var listV = this.getInnerLayout2Rows();
9485 listV.set("height", tp.get("element").clientHeight - 25);
9488 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
9489 var folderTab = new YAHOO.widget.Tab({
9490 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
9492 content : "<div id='emailtree'/>",
9496 folderTab.on("activeChange", function(o){
9498 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
9501 se.leftTabs.addTab(folderTab);
9503 var tabContent = SUGAR.util.getAndRemove("searchTab");
9504 var searchTab = new YAHOO.widget.Tab({
9505 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
9507 content : tabContent.innerHTML,
9510 searchTab.on("activeChange", function(o){
9513 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
9514 //Setup the calendars if needed
9515 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
9516 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
9518 //Initalize sqs object for assigned user name
9519 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
9521 //Attach event handler for when the relate module option is selected for the correct sqs object
9522 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
9523 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
9524 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
9525 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
9527 //If enter key is pressed, perform search
9528 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
9529 for(var i=0; i < addKeyPressFields.length;i++)
9531 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
9532 if (e.keyCode == 13) {
9533 YAHOO.util.Event.stopEvent(e);
9534 SUGAR.email2.search.searchAdvanced();
9538 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
9540 //Clear parent values if selecting another parent type.
9541 YAHOO.util.Event.addListener('data_parent_type_search','change',
9543 document.getElementById('data_parent_id_search').value ='';
9544 document.getElementById('data_parent_name_search').value ='';
9549 se.leftTabs.addTab(searchTab);
9551 var resizeTabBody = function() {
9552 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
9553 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9556 se.complexLayout.on("render", resizeTabBody);
9557 se.leftTabs.on("activeTabChange", resizeTabBody);
9558 //hack to allow left pane scroll bar to fully show
9559 var lefttabsDiv = document.getElementById('lefttabs');
9560 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
9561 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
9562 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
9565 initSQSObject: function(formName,fieldName)
9567 var fullFieldName = formName + '_' + fieldName; //SQS Convention
9568 var resultName = fullFieldName + '_' + 'results';
9570 if (QSFieldsArray[fullFieldName] != null)
9572 QSFieldsArray[fullFieldName].destroy();
9573 delete QSFieldsArray[fullFieldName];
9575 if (QSProcessedFieldsArray[fullFieldName])
9576 QSProcessedFieldsArray[fullFieldName] = false;
9578 if( Dom.get(resultName) )
9580 var obj = document.getElementById(resultName);
9581 obj.parentNode.removeChild(obj);
9584 setPreviewPanel: function(rows) {
9586 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9587 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9588 Dom.get("listRight").innerHTML = "";
9589 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9591 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9592 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9593 Dom.get("listBottom").innerHTML = "";
9594 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9601 var myBufferedListenerObject = new Object();
9602 myBufferedListenerObject.refit = function() {
9603 if(SUGAR.email2.grid) {
9604 SUGAR.email2.grid.autoSize();
9607 // End of File modules/Emails/javascript/complexLayout.js
9609 /*********************************************************************************
9610 * SugarCRM Community Edition is a customer relationship management program developed by
9611 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9613 * This program is free software; you can redistribute it and/or modify it under
9614 * the terms of the GNU Affero General Public License version 3 as published by the
9615 * Free Software Foundation with the addition of the following permission added
9616 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9617 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9618 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9620 * This program is distributed in the hope that it will be useful, but WITHOUT
9621 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9622 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9625 * You should have received a copy of the GNU Affero General Public License along with
9626 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9627 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9630 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9631 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9633 * The interactive user interfaces in modified source and object code versions
9634 * of this program must display Appropriate Legal Notices, as required under
9635 * Section 5 of the GNU Affero General Public License version 3.
9637 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9638 * these Appropriate Legal Notices must retain the display of the "Powered by
9639 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9640 * technical reasons, the Appropriate Legal Notices must display the words
9641 * "Powered by SugarCRM".
9642 ********************************************************************************/
9644 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9645 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9646 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9647 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9648 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9649 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9650 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9651 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9652 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9653 ' <input type="hidden" id="composeType" name="composeType">' +
9654 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9655 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9656 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9657 ' <input type="hidden" id="sendTo" name="sendTo">' +
9658 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9659 ' <input type="hidden" id="sendCc" name="sendCc">' +
9660 ' <input type="hidden" id="setEditor" name="setEditor">' +
9661 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9662 ' <input type="hidden" id="parent_id" name="parent_id">' +
9663 ' <input type="hidden" id="parent_type" name="parent_type">' +
9664 ' <input type="hidden" id="attachments" name="attachments">' +
9665 ' <input type="hidden" id="documents" name="documents">' +
9666 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9667 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9668 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9669 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9671 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9672 ' <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>' +
9673 ' <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>' +
9674 ' <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>' +
9675 ' <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>' +
9676 '</td><td style="padding: 0px !important;margin:0px; !important"> {mod_strings.LBL_EMAIL_RELATE}: <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>' +
9677 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9678 '<input class="sqsEnabled" id="data_parent_name{idx}" name="data_parent_name{idx}" type="text" value=""> <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>' +
9679 ' </td></tr></tbody></table></th>' +
9683 ' <div style="margin:5px;">' +
9684 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9686 ' <td class="emailUILabel" NOWRAP >' +
9687 ' {app_strings.LBL_EMAIL_FROM}:' +
9689 ' <td class="emailUIField" NOWRAP>' +
9691 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9696 ' <td class="emailUILabel" NOWRAP>' +
9697 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9698 ' {app_strings.LBL_EMAIL_TO}:' +
9701 ' <td class="emailUIField" NOWRAP>' +
9702 ' <div class="ac_autocomplete">' +
9703 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9704 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9705 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9709 ' <tr id="add_addr_options_tr{idx}">' +
9710 ' <td class="emailUILabel" NOWRAP> </td><td class="emailUIField" valign="top" NOWRAP> <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}"> {mod_strings.LBL_ADD_CC_BCC_SEP} </span><span id="bcc_span{idx}"><a href="#" onclick="SE.composeLayout.showHiddenAddress(\'bcc\',\'{idx}\');">{mod_strings.LBL_ADD_BCC}</a></span></td>'+
9712 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9713 ' <td class="emailUILabel" NOWRAP>' +
9714 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9715 ' {app_strings.LBL_EMAIL_CC}:' +
9718 ' <td class="emailUIField" NOWRAP>' +
9719 ' <div class="ac_autocomplete">' +
9720 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9721 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9722 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9726 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9727 ' <td class="emailUILabel" NOWRAP>' +
9728 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9729 ' {app_strings.LBL_EMAIL_BCC}:' +
9732 ' <td class="emailUIField" NOWRAP>' +
9733 ' <div class="ac_autocomplete">' +
9734 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9735 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9736 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9741 ' <td class="emailUILabel" NOWRAP width="1%">' +
9742 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9744 ' <td class="emailUIField" NOWRAP width="99%">' +
9745 ' <div class="ac_autocomplete">' +
9746 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9755 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9756 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9757 ' <div style="padding:5px;">' +
9758 ' <table cellpadding="2" cellspacing="0" border="0">' +
9761 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9768 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9769 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9781 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9788 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9789 ' <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>' +
9801 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9808 ' <div id="addedTemplateAttachments{idx}"></div>' +
9815 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9816 ' <div style="padding:5px;">' +
9817 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9818 ' <table border="0" width="100%">' +
9820 ' <td NOWRAP style="padding:2px;">' +
9821 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9825 ' <td NOWRAP style="padding:2px;">' +
9826 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9831 ' <table border="0" width="100%">' +
9833 ' <td NOWRAP style="padding:2px;">' +
9834 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9838 ' <td NOWRAP style="padding:2px;">' +
9839 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9843 ' <table border="0" width="100%">' +
9845 ' <td NOWRAP style="padding:2px;">' +
9846 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9847 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9855 // End of File modules/Emails/javascript/composeEmailTemplate.js
9857 /*********************************************************************************
9858 * SugarCRM Community Edition is a customer relationship management program developed by
9859 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9861 * This program is free software; you can redistribute it and/or modify it under
9862 * the terms of the GNU Affero General Public License version 3 as published by the
9863 * Free Software Foundation with the addition of the following permission added
9864 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9865 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9866 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9868 * This program is distributed in the hope that it will be useful, but WITHOUT
9869 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9870 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9873 * You should have received a copy of the GNU Affero General Public License along with
9874 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9875 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9878 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9879 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9881 * The interactive user interfaces in modified source and object code versions
9882 * of this program must display Appropriate Legal Notices, as required under
9883 * Section 5 of the GNU Affero General Public License version 3.
9885 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9886 * these Appropriate Legal Notices must retain the display of the "Powered by
9887 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9888 * technical reasons, the Appropriate Legal Notices must display the words
9889 * "Powered by SugarCRM".
9890 ********************************************************************************/
9892 SUGAR.email2.templates['displayOneEmail'] =
9893 '<div class="emailDetailTable" style="height:100%">' +
9894 '<div id="viewMenuDiv{idx}"></div>' +
9895 '<div width="100%" class="displayEmailValue">' +
9896 ' <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>' +
9897 ' <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>' +
9898 ' <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>' +
9899 ' <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>' +
9900 ' <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>' +
9901 ' <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>' +
9902 ' <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>' +
9903 ' <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>' +
9904 ' <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>' +
9906 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9908 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9909 ' {app_strings.LBL_EMAIL_FROM}:' +
9911 ' <td width="99%" class="displayEmailValue">' +
9912 ' {email.from_addr}' +
9916 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9917 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9919 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9920 ' <b>{email.name}</b>' +
9924 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9925 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9927 ' <td class="displayEmailValue">' +
9928 ' {email.date_start} {email.time_start}' +
9932 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9933 ' {app_strings.LBL_EMAIL_TO}:' +
9935 ' <td class="displayEmailValue">' +
9936 ' {email.toaddrs}' +
9939 ' <tr>{meta.cc}</tr>' +
9940 ' <tr>{email.attachments}</tr>' +
9942 ' <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>' +
9943 //' {email.description}' +
9945 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9947 /*********************************************************************************
9948 * SugarCRM Community Edition is a customer relationship management program developed by
9949 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9951 * This program is free software; you can redistribute it and/or modify it under
9952 * the terms of the GNU Affero General Public License version 3 as published by the
9953 * Free Software Foundation with the addition of the following permission added
9954 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9955 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9956 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9958 * This program is distributed in the hope that it will be useful, but WITHOUT
9959 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9960 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9963 * You should have received a copy of the GNU Affero General Public License along with
9964 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9965 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9968 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9969 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9971 * The interactive user interfaces in modified source and object code versions
9972 * of this program must display Appropriate Legal Notices, as required under
9973 * Section 5 of the GNU Affero General Public License version 3.
9975 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9976 * these Appropriate Legal Notices must retain the display of the "Powered by
9977 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9978 * technical reasons, the Appropriate Legal Notices must display the words
9979 * "Powered by SugarCRM".
9980 ********************************************************************************/
9982 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9983 '<body onload="javascript:window.print();">' +
9987 ' font-family: helvetica, impact, sans-serif;' +
9988 ' font-size : 12pt;' +
9995 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9998 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
10000 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
10001 ' {app_strings.LBL_EMAIL_FROM}:' +
10003 ' <td width="99%" class="displayEmailValue">' +
10004 ' {email.from_name} <{email.from_addr}>' +
10008 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
10009 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
10011 ' <td NOWRAP valign="top" class="displayEmailValue">' +
10012 ' <b>{email.name}</b>' +
10016 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
10017 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
10019 ' <td class="displayEmailValue">' +
10020 ' {email.date_start} {email.time_start}' +
10024 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
10025 ' {app_strings.LBL_EMAIL_TO}:' +
10027 ' <td class="displayEmailValue">' +
10028 ' {email.toaddrs}' +
10032 ' {email.attachments}' +
10038 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
10040 ' <td style="border-top: 1px solid #333;">' +
10041 ' <div style="padding:5px;">' +
10042 '{email.description}' +
10052 // End of File modules/Emails/javascript/viewPrintable.js
10054 /*********************************************************************************
10055 * SugarCRM Community Edition is a customer relationship management program developed by
10056 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
10058 * This program is free software; you can redistribute it and/or modify it under
10059 * the terms of the GNU Affero General Public License version 3 as published by the
10060 * Free Software Foundation with the addition of the following permission added
10061 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10062 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10063 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
10065 * This program is distributed in the hope that it will be useful, but WITHOUT
10066 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10067 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
10070 * You should have received a copy of the GNU Affero General Public License along with
10071 * this program; if not, see http://www.gnu.org/licenses or write to the Free
10072 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
10075 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
10076 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
10078 * The interactive user interfaces in modified source and object code versions
10079 * of this program must display Appropriate Legal Notices, as required under
10080 * Section 5 of the GNU Affero General Public License version 3.
10082 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
10083 * these Appropriate Legal Notices must retain the display of the "Powered by
10084 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
10085 * technical reasons, the Appropriate Legal Notices must display the words
10086 * "Powered by SugarCRM".
10087 ********************************************************************************/
10088 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
10089 var Dom=YAHOO.util.Dom;var qsFields=Dom.getElementsByClassName('sqsEnabled');for(var qsField in qsFields){if(typeof qsFields[qsField]=='function'||typeof qsFields[qsField].id=='undefined'){continue;}
10090 var 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');}
10091 var 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;}}
10092 if(QSProcessedFieldsArray[qs_index_id]){skipSTR='collection_0';if(qs_index_id.lastIndexOf(skipSTR)!=(qs_index_id.length-skipSTR.length)){continue;}}
10093 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
10094 if(!document.forms[qs_obj.form].elements[qsFields[qsField].id].readOnly&&qs_obj['disable']!=true){var combo_id=qs_obj.form+'_'+qsFields[qsField].id;if(Dom.get(combo_id+"_results")){loaded=true}
10095 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,inputElement:qsFields[qsField],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){this.updateFields(data,filter);},updateFields: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)){var displayValue=data[i].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value=displayValue;SUGAR.util.callOnChangeListers(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]);}}}
10096 SUGAR.util.callOnChangeListers(this._elTextbox);},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="";SUGAR.util.callOnChangeListers(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]);}}
10097 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
10098 {search.clearFields=function(){for(var i in{name:0,id:1}){for(var key in this.qs_obj.field_list){if(i==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]])
10099 {document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";}}}};search.setFields=function(data,filter)
10100 {var label_str='';var label_data_str='';var current_label_data_str='';var label_data_hash=new Array();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]]&&document.getElementById(this.qs_obj.populate_list[key]+'_label')&&this.qs_obj.populate_list[key].match(filter)){var displayValue=data[i].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');var data_label=document.getElementById(this.qs_obj.populate_list[key]+'_label').innerHTML.replace(/\n/gi,'');label_and_data=data_label+' '+displayValue;if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&!label_data_hash[data_label])
10101 {label_str+=data_label+' \n';label_data_str+=label_and_data+'\n';label_data_hash[data_label]=true;current_label_data_str+=data_label+' '+document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value+'\n';}}}}
10102 if(label_str!=current_label_data_str&¤t_label_data_str!=label_data_str){module_key=(typeof document.forms[form_id].elements['module']!='undefined')?document.forms[form_id].elements['module'].value:'app_strings';warning_label=SUGAR.language.translate(module_key,'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM')+'\n\n'+label_data_str;if(!confirm(warning_label))
10103 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
10104 {if(this.inputElement.id=='shipping_account_name')
10105 {filter=Dom.get('shipping_checkbox').checked?/(account_id|office_phone)/:filter;}else if(this.inputElement.id=='billing_account_name'){filter=Dom.get('shipping_checkbox').checked?filter:/(account_id|office_phone|billing)/;}}else if(Dom.get('alt_checkbox')){filter=Dom.get('alt_checkbox').checked?filter:/^(?!alt)/;}
10106 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
10107 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
10108 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];}}}
10109 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]];}
10110 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});search.typeAheadEvent.subscribe(function(e,args){this.getInputEl().value=this.getInputEl().value.replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
10111 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
10112 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}
10113 // End of File include/javascript/quicksearch.js