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;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects!='undefined'&&typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
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 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id:'';URL='index.php?'
359 +'module='+module_name
362 +'&target='+pageTarget
363 +'&target1='+pageTarget
364 +'&server_url='+mail_server
365 +'&email_user='+words[0]
366 +'&protocol='+protocol
368 +'&email_password='+words[1]
369 +'&mailbox='+words[2]
372 +'&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)
373 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
374 this.body.style.width=w}}
375 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
376 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();}
377 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'));}
378 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
379 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
380 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
381 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
382 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";}
384 alert(out);return false;}else{return true;}}
385 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?'
386 +'module='+module_name
389 +'&target='+pageTarget
390 +'&target1='+pageTarget
391 +'&server_url='+mail_server
392 +'&email_user='+words[0]
393 +'&protocol='+protocol
395 +'&email_password='+words[1]
396 +'&mailbox='+words[2]
398 +'&personal='+isPersonal
399 +'&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)
400 this.body.style.width=w}}
401 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();}
402 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;}}}
403 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';}}}
404 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='';}
405 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";}}
406 // End of File modules/InboundEmail/InboundEmail.js
408 /*********************************************************************************
409 * SugarCRM Community Edition is a customer relationship management program developed by
410 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
412 * This program is free software; you can redistribute it and/or modify it under
413 * the terms of the GNU Affero General Public License version 3 as published by the
414 * Free Software Foundation with the addition of the following permission added
415 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
416 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
417 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
419 * This program is distributed in the hope that it will be useful, but WITHOUT
420 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
421 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
424 * You should have received a copy of the GNU Affero General Public License along with
425 * this program; if not, see http://www.gnu.org/licenses or write to the Free
426 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
429 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
430 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
432 * The interactive user interfaces in modified source and object code versions
433 * of this program must display Appropriate Legal Notices, as required under
434 * Section 5 of the GNU Affero General Public License version 3.
436 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
437 * these Appropriate Legal Notices must retain the display of the "Powered by
438 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
439 * technical reasons, the Appropriate Legal Notices must display the words
440 * "Powered by SugarCRM".
441 ********************************************************************************/
444 cache : new Object(),
445 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
446 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
449 currentHtmleditor : ''
453 * preserves hits from email server
455 _setDetailCache : function(ret) {
457 var compKey = ret.meta.mbox + ret.meta.uid;
459 if(!SUGAR.email2.cache[compKey]) {
460 SUGAR.email2.cache[compKey] = ret;
465 autoSetLayout : function() {
466 var c = document.getElementById('container');
467 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
468 //Ensure a minimum height.
469 tHeight = Math.max(tHeight, 550);
470 c.style.height = tHeight + "px";
471 SUGAR.email2.complexLayout.set('height', tHeight);
472 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
473 SUGAR.email2.complexLayout.render();
474 SUGAR.email2.listViewLayout.resizePreview();
480 * Shows overlay progress message
484 SUGAR.showMessageBoxModal = function(title, body) {
485 SUGAR.showMessageBox(title, body);
489 SUGAR.showMessageBox = function(reqtitle, body, type, additconfig) {
491 if (typeof(additconfig) == "object") {
492 var config = additconfig;
495 config.title = reqtitle;
497 YAHOO.SUGAR.MessageBox.show(config);
501 SUGAR.hideMessageBox = function() {
502 YAHOO.SUGAR.MessageBox.hide();
504 // End of File modules/Emails/javascript/EmailUIShared.js
506 /*********************************************************************************
507 * SugarCRM Community Edition is a customer relationship management program developed by
508 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
510 * This program is free software; you can redistribute it and/or modify it under
511 * the terms of the GNU Affero General Public License version 3 as published by the
512 * Free Software Foundation with the addition of the following permission added
513 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
514 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
515 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
517 * This program is distributed in the hope that it will be useful, but WITHOUT
518 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
519 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
522 * You should have received a copy of the GNU Affero General Public License along with
523 * this program; if not, see http://www.gnu.org/licenses or write to the Free
524 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
527 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
528 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
530 * The interactive user interfaces in modified source and object code versions
531 * of this program must display Appropriate Legal Notices, as required under
532 * Section 5 of the GNU Affero General Public License version 3.
534 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
535 * these Appropriate Legal Notices must retain the display of the "Powered by
536 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
537 * technical reasons, the Appropriate Legal Notices must display the words
538 * "Powered by SugarCRM".
539 ********************************************************************************/
543 var sw = YAHOO.SUGAR,
544 Event = YAHOO.util.Event,
545 Connect = YAHOO.util.Connect,
549 ///////////////////////////////////////////////////////////////////////////////
552 outboundDialog : null,
553 inboundAccountEditDialog : null,
554 inboundAccountsSettingsTable : null,
555 outboundAccountsSettingsTable : null,
556 testOutboundDialog : null,
557 errorStyle : 'input-error',
559 newAddedOutboundId : '',
562 * makes async call to retrieve an outbound instance for editting
565 editOutbound : function(obi) {
567 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
570 deleteOutbound : function(obi) {
572 if(obi.match(/^(add|line|sendmail)+/)) {
573 alert('Invalid Operation');
575 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
576 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
580 getReplyAddress : function() {
583 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
584 var addy = SE.userPrefs.current_user.emailAddresses[i];
586 if(addy.primary_address == "1") {
587 primary = addy.email_address;
590 if(addy.reply_to == "1") {
591 return addy.email_address;
599 * Called on "Accounts" tab activation event
601 lazyLoad : function() {
603 this._setupInboundAccountTable();
604 this._setupOutboundAccountTable();
608 _setupInboundAccountTable: function()
610 //Setup the inbound mail settings
611 if(!this.inboundAccountsSettingsTable)
613 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
614 var clckEvent = oColumn.key;
616 var is_group = oRecord.getData("is_group");
619 if(oColumn.key == 'edit')
621 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
622 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
624 else if(oColumn.key == 'delete')
626 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
627 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
629 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
633 this.showBoolean = function(el, oRecord, oColumn, oData)
635 var is_group = oRecord.getData("is_group");
636 var bChecked = oData;
637 bChecked = (bChecked) ? " checked" : "";
640 el.innerHTML = "<input type=\"radio\"" + bChecked +
641 " name=\"col" + oColumn.getId() + "-radio\"" +
642 " class=\"yui-dt-radio\">";
647 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
648 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
650 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
651 '<img border="0" src="themes/default/images/helpInline.gif">' +
652 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
655 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
656 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
657 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
658 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
659 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
660 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
661 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
662 this.ieDataSource = new YAHOO.util.DataSource(query);
663 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
664 this.ieDataSource.responseSchema = {
665 resultsList: "account_list",
666 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
668 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
669 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
671 var elCheckbox = oArgs.target;
672 var oColumn = this.getColumn(elCheckbox);
673 if(oColumn.key == 'is_active')
675 var oRecord = this.getRecord(elCheckbox);
676 oRecord.setData("is_active",elCheckbox.checked);
677 var t_id = oRecord.getData('id');
678 var isGroupFolder = oRecord.getData('has_groupfolder');
681 SUGAR.email2.folders.updateSubscriptions();
683 SUGAR.email2.folders.setFolderSelection();
687 var lastDefaultSelectedId = "";
688 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
690 var elRadio = oArgs.target;
691 var oColumn = this.getColumn(elRadio);
692 if(oColumn.key == 'is_default')
694 var oRecord = this.getRecord(elRadio);
695 var t_id = oRecord.getData('id');
696 var t_isGroup = oRecord.getData('is_group');
697 if(t_id != lastDefaultSelectedId && !t_isGroup)
699 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
700 lastDefaultSelectedId = t_id;
701 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
704 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
709 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
710 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
713 _setupOutboundAccountTable: function()
715 if(!this.outboundAccountsSettingsTable)
717 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
718 var clckEvent = oColumn.key;
720 var isEditable = oRecord.getData("is_editable");
721 var type = oRecord.getData("type");
724 if(oColumn.key == 'edit')
726 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
727 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
729 else if(oColumn.key == 'delete' && type == 'user')
731 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
732 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
735 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
739 //Custom formatter to display any error messages.
740 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
742 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
743 SUGAR.email2.composeLayout.outboundAccountErrors = {};
745 var id = oRecord.getData('id');
746 var message = oRecord.getData("errors");
749 elLiner.innerHTML = '<span class="required">' + message + '</span>';
750 //Add the id and message for all outbound accounts.
751 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
755 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
756 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
759 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
760 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
762 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
763 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
764 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
765 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
767 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
768 this.obDataSource = new YAHOO.util.DataSource(query);
769 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
770 this.obDataSource.responseSchema = {
772 resultsList: "outbound_account_list",
773 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
776 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
779 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
780 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
781 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
785 * Displays a modal diaglogue to edit outbound account settings
787 showEditInboundAccountDialogue : function(clear) {
789 if(!this.inboundAccountEditDialog) {
790 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
794 constraintoviewport: true,
798 EAD.showEvent.subscribe(function() {
799 var el = this.element;
800 var viewH = YAHOO.util.Dom.getViewportHeight();
801 if (this.header && el && viewH - 50 < el.clientHeight) {
802 var body = this.header.nextElementSibling;
803 body.style.overflow = "hidden";
804 body.style.height = "100%";
807 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
808 Dom.removeClass("editAccountDialogue", "yui-hidden");
812 if(clear == undefined || clear == true)
814 SE.accounts.clearInboundAccountEditScreen();
815 //Set default protocol to IMAP when creating new records
816 document.forms['ieAccount'].elements['protocol'].value = "imap";
817 SE.accounts.setPortDefault();
820 //Check if we should display username/password fields for outbound account if errors were detected.
821 this.checkOutBoundSelection();
823 this.inboundAccountEditDialog.render();
824 this.inboundAccountEditDialog.show();
825 SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
829 * Set all fields on the outbound edit form to either enabled/disabled
830 * except for the username/password.
833 toggleOutboundAccountDisabledFields: function(disable)
835 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
836 for(var i=0;i<fields.length;i++)
838 document.getElementById(fields[i]).disabled = disable;
841 Dom.addClass("mail_smtpssl_row", "yui-hidden");
843 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
847 * Refresh the inbound accounts table.
849 refreshInboundAccountTable : function()
851 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
853 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
854 scope: this.inboundAccountsSettingsTable }
858 * Refresh the outbound accounts table.
860 refreshOuboundAccountTable : function()
862 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
864 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
865 scope: this.outboundAccountsSettingsTable }
869 * Displays a modal diaglogue to add a SMTP server
871 showAddSmtp : function() {
872 // lazy load dialogue
873 if(!this.outboundDialog) {
874 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
878 constraintoviewport: true,
882 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
883 this.outboundDialog.hideEvent.subscribe(function(){
884 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
885 var out = Dom.get("outbound_email");
886 if (out && out.value == "SYSTEM_ADD")
888 out.value = out.options[0].value;
890 //Check if we should display username/password for system account.
891 SE.accounts.checkOutBoundSelection();
895 Dom.removeClass("outboundDialog", "yui-hidden");
899 var form = document.getElementById('outboundEmailForm');
900 for(i=0; i<form.elements.length; i++) {
901 if(form.elements[i].name == 'mail_smtpport') {
902 form.elements[i].value = 25;
903 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
904 form.elements[i].value = '';
905 } else if(form.elements[i].type == 'checkbox') {
906 form.elements[i].checked = false;
909 //Render the SMTP buttons
910 if ( !SUGAR.smtpButtonGroup ) {
911 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
912 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
914 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
915 document.getElementById('smtp_settings').style.display = '';
916 form.mail_smtptype.value = e.newValue.get('value');
918 YAHOO.widget.Button.addHiddenFieldsToForm(form);
920 //Hide Username/Password
921 SUGAR.email2.accounts.smtp_authenticate_field_display();
922 //Unset readonly fields
923 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
924 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
925 this.outboundDialog.render();
926 this.outboundDialog.show();
930 * Accounts' Advanced Settings view toggle
932 toggleAdv : function() {
933 var adv = document.getElementById("ie_adv");
934 if(adv.style.display == 'none') {
935 adv.style.display = "";
937 adv.style.display = 'none';
941 smtp_authenticate_field_display : function() {
942 var smtpauth_req = document.getElementById("mail_smtpauth_req");
943 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
944 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
947 smtp_setDefaultSMTPPort : function() {
948 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
950 if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
951 document.getElementById("mail_smtpport").value = '465';
953 if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
954 document.getElementById("mail_smtpport").value = '25';
959 * Changes the display used in the outbound email SMTP dialog to match the
961 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
963 document.getElementById("smtpButtonGroupTD").style.display = '';
964 document.getElementById("chooseEmailProviderTD").style.display = '';
965 document.getElementById("mailsettings1").style.display = '';
966 document.getElementById("mailsettings2").style.display = '';
967 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
968 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
969 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
970 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
974 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
975 document.getElementById("mail_smtpport").value = '465';
976 document.getElementById("mail_smtpauth_req").checked = true;
977 var ssl = document.getElementById("mail_smtpssl");
978 for(var j=0;j<ssl.options.length;j++) {
979 if(ssl.options[j].text == 'SSL') {
980 ssl.options[j].selected = true;
984 document.getElementById("mailsettings1").style.display = 'none';
985 document.getElementById("mailsettings2").style.display = 'none';
986 document.getElementById("mail_smtppass_label").innerHTML =
987 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
988 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
991 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
992 document.getElementById("mail_smtpport").value = '587';
993 document.getElementById("mail_smtpauth_req").checked = true;
994 var ssl = document.getElementById("mail_smtpssl");
995 for(var j=0;j<ssl.options.length;j++) {
996 if(ssl.options[j].text == 'TLS') {
997 ssl.options[j].selected = true;
1001 document.getElementById("mailsettings1").style.display = 'none';
1002 document.getElementById("mailsettings2").style.display = 'none';
1003 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
1004 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
1007 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
1008 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
1009 document.getElementById("mail_smtpserver").value = '';
1011 document.getElementById("mail_smtpport").value = '25';
1012 document.getElementById("mail_smtpauth_req").checked = true;
1013 document.getElementById("mailsettings1").style.display = '';
1014 document.getElementById("mailsettings2").style.display = '';
1015 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1016 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1017 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1018 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1021 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1023 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1024 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1025 document.getElementById("mailsettings2").style.display = 'none';
1028 SUGAR.email2.accounts.smtp_authenticate_field_display();
1029 SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1033 * Fill the gmail default values for inbound accounts.
1035 fillInboundGmailDefaults: function () {
1037 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1038 document.forms['ieAccount'].elements['ssl'].checked = true;
1039 document.forms['ieAccount'].elements['protocol'].value = "imap";
1040 SUGAR.email2.accounts.setPortDefault();
1041 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1044 * Sets Port field to selected protocol and SSL settings defaults
1046 setPortDefault : function() {
1047 var prot = document.getElementById('protocol');
1048 var ssl = document.getElementById('ssl');
1049 var port = document.getElementById('port');
1050 var stdPorts= new Array("110", "143", "993", "995");
1051 var stdBool = new Boolean(false);
1052 var mailboxdiv = document.getElementById("mailboxdiv");
1053 var trashFolderdiv = document.getElementById("trashFolderdiv");
1054 var sentFolderdiv = document.getElementById("sentFolderdiv");
1055 var monitoredFolder = document.getElementById("subscribeFolderButton");
1056 if(port.value == '') {
1057 stdBool.value = true;
1059 for(i=0; i<stdPorts.length; i++) {
1060 if(stdPorts[i] == port.value) {
1061 stdBool.value = true;
1066 if(stdBool.value == true) {
1067 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1069 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1071 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1073 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1078 if (prot.value == 'imap') {
1079 mailboxdiv.style.display = "";
1080 trashFolderdiv.style.display = "";
1081 sentFolderdiv.style.display = "";
1082 monitoredFolder.style.display = "";
1083 if (document.getElementById('mailbox').value == "") {
1084 document.getElementById('mailbox').value = "INBOX";
1087 mailboxdiv.style.display = "none";
1088 trashFolderdiv.style.display = "none";
1089 sentFolderdiv.style.display = "none";
1090 monitoredFolder.style.display = "none";
1091 document.getElementById('mailbox').value = "";
1096 * Draws/removes red boxes around required fields.
1098 ieAccountError : function(style) {
1099 document.getElementById('server_url').className = style;
1100 document.getElementById('email_user').className = style;
1101 document.getElementById('email_password').className = style;
1102 document.getElementById('protocol').className = style;
1103 document.getElementById('port').className = style;
1106 checkOutBoundSelection: function() {
1107 var select = Dom.get('outbound_email');
1108 if (!select || select.selectedIndex == -1) { return; }
1110 var v = select.options[select.selectedIndex].value;
1114 select.options[select.selectedIndex].selected = false;
1115 v = select.options[0].value;
1117 else if (v == 'SYSTEM_ADD')
1118 SUGAR.email2.accounts.showAddSmtp();
1120 var foundError = false;
1121 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1122 for(i in errorAccounts)
1131 //Should username/password fields for outbound account.
1133 this.toggleInboundOutboundFields(true);
1135 this.toggleInboundOutboundFields(false);
1140 toggleInboundOutboundFields : function (display)
1144 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1145 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1149 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1150 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1154 * rebuilds the select options for mailer options
1156 rebuildMailerOptions : function() {
1157 var select = document.forms['ieAccount'].elements['outbound_email'];
1158 SE.util.emptySelectOptions(select);
1160 //Get the available sugar mailers
1161 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1163 for(i=0;i<a_outbound.length;i++)
1165 var t_record = a_outbound[i];
1166 var key = t_record.getData('id');
1167 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1169 var opt = new Option(display, key);
1170 select.options.add(opt);
1171 if (key == SE.accounts.newAddedOutboundId) {
1172 select.options.selectedIndex = i;
1176 select.options.add(new Option('',''));
1177 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1178 //Hide/Show username password fields if necessary.
1179 SE.accounts.checkOutBoundSelection();
1182 * Empties all the fields in the accounts edit view
1184 clearInboundAccountEditScreen:function() {
1186 document.getElementById('ie_id').value = '';
1187 document.getElementById('ie_name').value = '';
1188 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1189 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1190 document.getElementById('reply_to_addr').value = '';
1191 document.getElementById('server_url').value = '';
1192 document.getElementById('email_user').value = '';
1193 document.getElementById('email_password').value = '';
1194 document.getElementById('port').value = '';
1195 document.getElementById('inbound_mail_smtpuser').value = '';
1196 document.getElementById('inbound_mail_smtppass').value = '';
1197 document.ieAccount.protocol.options[0].selected = true;
1199 document.getElementById('ssl').checked = false;
1200 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1204 * Populates an account's fields in Settings->Accounts
1206 fillIeAccount:function(jsonstr) {
1207 var o = YAHOO.lang.JSON.parse(jsonstr);
1209 document.getElementById('ie_id').value = o.id;
1210 document.getElementById('ie_name').value = o.name;
1211 if (o.stored_options != null) {
1212 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1213 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1214 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1215 if (o.stored_options.trashFolder != null) {
1216 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1218 if (o.stored_options.sentFolder != null) {
1219 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1222 document.getElementById('server_url').value = o.server_url;
1223 document.getElementById('email_user').value = o.email_user;
1224 document.getElementById('port').value = o.port;
1225 document.getElementById('group_id').value = o.group_id;
1226 document.getElementById('mailbox').value = o.mailbox;
1232 if(typeof(o.service[2]) != 'undefined') {
1233 document.getElementById('ssl').checked = true;
1237 if(document.getElementById('protocol').value != o.protocol) {
1238 var prot = document.getElementById('protocol');
1239 for(i=0; i<prot.options.length; i++) {
1240 if(prot.options[i].value == o.service[3]) {
1241 prot.options[i].selected = true;
1242 this.setPortDefault();
1246 // handle SMTP selection
1247 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1248 var opts = document.getElementById('outbound_email').options;
1249 for(i=0; i<opts.length; i++) {
1250 if(opts[i].value == o.stored_options.outbound_email) {
1251 opts[i].selected = true;
1257 deleteIeAccount : function(IeAccountID,IeGroupID) {
1258 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1260 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1262 AjaxObject.target = 'frameFlex';
1263 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1264 SUGAR.email2.accounts.refreshInboundAccountTable();
1268 // Null check for Outbound Settings.
1269 checkOutboundSettings: function() {
1270 var errorMessage = '';
1271 var isError = false;
1272 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1273 var mailName = document.getElementById('mail_name').value;
1274 var smtpServer = document.getElementById('mail_smtpserver').value;
1275 var smtpPort = document.getElementById('mail_smtpport').value;
1277 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1278 if(trim(mailName) == '') {
1280 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1282 if(trim(smtpServer) == '') {
1284 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1286 if(trim(smtpPort) == '') {
1288 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1290 if(mailsmtpauthreq.checked) {
1291 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1293 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1298 SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1305 testOutboundSettings: function() {
1306 var errorMessage = '';
1307 var isError = false;
1308 var fromAddress = document.getElementById("outboundtest_from_address").value;
1309 if (trim(fromAddress) == "") {
1310 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1311 SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1315 else if (!isValidEmail(fromAddress)) {
1316 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1317 SUGAR.showMessageBox(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1321 //Hide the dialogue and show an in progress indicator.
1322 SE.accounts.testOutboundDialog.hide();
1323 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1325 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1326 //nothing is sent in the request.
1327 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1328 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1330 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1331 if(outboundType == 'system-override')
1332 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1334 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1335 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1339 testOutboundSettingsDialog: function() {
1340 //Ensure that all settings are correct before proceeding to send test email.
1341 if(!SE.accounts.checkOutboundSettings())
1344 // lazy load dialogue
1345 if(!SE.accounts.testOutboundDialog) {
1346 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1350 constraintoviewport: true,
1354 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1355 Dom.removeClass("testOutboundDialog", "yui-hidden");
1357 SE.accounts.testOutboundDialog.render();
1358 SE.accounts.testOutboundDialog.show();
1362 * Saves Outbound email settings
1364 saveOutboundSettings : function() {
1365 if(SE.accounts.checkOutboundSettings()) {
1366 //Enable the form fields for the post.
1367 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1368 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1369 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1375 saveIeAccount : function() {
1377 //Before saving check if there are any error messages associated with the outbound account.
1378 var outboundID = document.getElementById('outbound_email').value;
1380 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1381 'validateSMTPCreds':true}) )
1383 document.getElementById('saveButton').disabled = true;
1385 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1387 var formObject = document.getElementById('ieAccount');
1388 YAHOO.util.Connect.setForm(formObject);
1390 AjaxObject._reset();
1391 AjaxObject.target = 'frameFlex';
1392 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1396 testSettings : function() {
1397 form = document.getElementById('ieAccount');
1399 if(SE.accounts.checkIeCreds()) {
1400 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);
1404 getFoldersListForInboundAccountForEmail2 : function() {
1405 form = document.getElementById('ieAccount');
1406 if(SE.accounts.checkIeCreds()) {
1407 var mailBoxValue = form.mailbox.value;
1408 if (form.searchField.value.length > 0) {
1411 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 );
1416 checkIeCreds : function(validateRules) {
1417 if(typeof(validateRules) == 'undefined')
1420 var errors = new Array();
1421 var out = new String();
1423 var ie_name = Dom.get('ie_name').value;
1424 var fromAddress = Dom.get('ie_from_addr').value;
1425 var server_url = Dom.get('server_url').value;
1426 var email_user = Dom.get('email_user').value;
1427 var email_password = Dom.get('email_password').value;
1428 var protocol = Dom.get('protocol').value;
1429 var port = Dom.get('port').value;
1430 var oe = Dom.get('outbound_email');
1432 // Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
1433 // other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
1434 // return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
1435 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;
1437 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1438 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1440 //If the username and password were provided then ignore the error messge
1442 var outboundCredentialsFound = false;
1444 if(outboundUserName != "" && outboundPass != "")
1445 outboundCredentialsFound = true;
1447 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1449 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1450 && validateSMTPCreds)
1452 if(trim(outboundUserName) == "") {
1453 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1455 if(trim(outboundPass) == "") {
1456 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1460 if(trim(ie_name) == "") {
1461 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1464 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1466 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1467 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1472 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1473 || trim(oe_value) == "SYSTEM_ADD") ) {
1474 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1476 if(trim(server_url) == "") {
1477 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1479 if(trim(email_user) == "") {
1480 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1482 if(protocol == "") {
1483 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1485 if (protocol == 'imap') {
1486 var mailbox = document.getElementById('mailbox').value;
1487 if (trim(mailbox) == "") {
1488 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1490 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1491 var trashFolder = document.getElementById('trashFolder').value;
1492 if (trim(trashFolder) == "") {
1493 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1498 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1501 if(errors.length > 0) {
1502 out = app_strings.LBL_EMAIL_ERROR_DESC;
1503 for(i=0; i<errors.length; i++) {
1518 getIeAccount : function(ieId) {
1522 SUGAR.showMessageBox(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1523 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1525 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1529 * Iterates through TreeView nodes to apply styles dependent nature of node
1531 renderTree:function() {
1532 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1536 //Sets the style for any nodes that need it.
1537 setNodeStyle : function(node) {
1538 if (!node.data.origText) {
1539 node.data.origText = node.data.text;
1542 if (typeof(node.data.unseen) != 'undefined') {
1543 if (node.data.unseen > 0) {
1544 node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
1545 // Add bold style to label, kinda hacky
1546 node.labelStyle += " ygtvlabelbold";
1549 node.setUpLabel(node.data.origText);
1552 node.setUpLabel(node.data.origText);
1554 SE.accounts.setupDDTarget(node);
1557 setupDDTarget : function(node) {
1558 if (node.ddTarget) {
1559 node.ddTarget.removeFromGroup();
1560 delete node.ddTarget;
1562 var id = node.getElId();
1563 var num = id.substring(4);
1564 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1565 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1566 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1568 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1570 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1571 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1576 * Async call to rebuild the folder list. After a folder delete or account delete
1578 rebuildFolderList : function() {
1579 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1580 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1584 * Returns the number of remote accounts the user has active.
1586 getAccountCount : function() {
1589 for(i=0; i<tree._nodes.length; i++) {
1590 var node = tree._nodes[i];
1592 if(typeof(node) != 'undefined' && node.data.ieId) {
1600 ///////////////////////////////////////////////////////////////////////////////
1605 ///////////////////////////////////////////////////////////////////////////////
1606 //// CONTEXT MENU CALLS
1609 assignToDialogue : null,
1611 * Archives from context menu
1613 * @param string ieId
1614 * @param string folder
1616 _archiveToSugar : function(uids, ieId, folder) {
1619 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1620 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1623 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1627 * Archives from context menu
1629 archiveToSugar : function(menuItem) {
1630 SE.contextMenus.emailListContextMenu.hide();
1632 var rows = SE.grid.getSelectedRows();
1634 /* iterate through available rows JIC a row is deleted - use first available */
1635 for(var i=0; i<rows.length; i++) {
1636 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1638 var data = SE.grid.getRecord(rows[0]).getData();
1639 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1643 * Popup the printable version and start system's print function.
1645 viewPrintable : function(menuItem) {
1646 var rows = SE.grid.getSelectedRows();
1647 var data = SE.grid.getRecord(rows[0]).getData();
1648 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1652 * Marks email flagged on mail server
1654 markRead : function(type, contextMenuId) {
1655 SE.contextMenus.markEmail('read');
1659 * Assign this emails to people based on assignment rules
1661 assignEmailsTo : function(type, contextMenuId) {
1662 if(!SE.contextMenus.assignToDialogue)
1664 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1668 constraintoviewport: true,
1672 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1676 Dom.removeClass("assignToDiv", "yui-hidden");
1677 SE.contextMenus.assignToDialogue.render();
1678 SE.contextMenus.assignToDialogue.show();
1682 * Marks email flagged on mail server
1684 markFlagged : function(contextMenuId) {
1685 SE.contextMenus.markEmail('flagged');
1689 * Marks email unflagged on mail server
1691 markUnflagged : function(contextMenuId) {
1692 SE.contextMenus.markEmail('unflagged');
1696 * Marks email unread on mail server
1698 markUnread : function() {
1699 SE.contextMenus.markEmail('unread');
1703 * Deletes an email from context menu
1705 markDeleted : function() {
1706 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1707 document.getElementById('_blank').innerHTML = "";
1708 SE.contextMenus.markEmail('deleted');
1713 * generic call API to apply a flag to emails on the server and on sugar
1714 * @param string type "read" | "unread" | "flagged" | "deleted"
1716 markEmail : function(type) {
1717 SE.contextMenus.emailListContextMenu.hide();
1719 //var dm = SE.grid.getStore();
1720 //var uids = SE.grid.getSelectedRowIds();
1721 //var indexes = SE.grid.getSelectedRowIndexes();
1722 var rows = SE.grid.getSelectedRows();
1723 if (rows.length == 0)
1724 rows = [SE.contextMenus.currentRow];
1727 for(var i=0; i<rows.length; i++) {
1728 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1731 ser = YAHOO.lang.JSON.stringify(ser);
1733 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1734 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1740 if(type == 'read' || type == 'deleted') {
1742 for(var j=0; j<rows.length; j++) {
1743 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1745 SE.grid.getRecord(rows[j]).setData("seen", "1");
1748 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1750 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1751 var unseenCount = node.data.unseen;
1752 if (isNaN(unseenCount)) {
1755 var finalCount = parseInt(unseenCount) - count;
1756 node.data.unseen = finalCount;
1758 SE.accounts.renderTree();
1760 } else if(type == 'unread') {
1762 for(var j=0; j<rows.length; j++) {
1763 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1768 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1769 var unseenCount = node.data.unseen;
1770 if (isNaN(unseenCount)) {
1773 var finalCount = parseInt(unseenCount) + count;
1774 node.data.unseen = finalCount;
1775 SE.accounts.renderTree();
1778 if (type == 'unread') {
1779 for(var i=0; i<rows.length; i++) {
1780 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1784 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1785 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1789 * refreshes the ListView to show changes to cache
1791 markEmailCleanup : function() {
1792 SE.accounts.renderTree();
1793 SUGAR.hideMessageBox();
1794 SE.listView.refreshGrid();
1797 showAssignmentDialog : function() {
1798 if (SE.contextMenus.assignmentDialog == null) {
1799 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1801 SE.contextMenus.assignmentDialog.show();
1806 * shows the import dialog with only relate visible.
1808 relateTo : function() {
1809 SE.contextMenus.emailListContextMenu.hide();
1811 var rows = SE.grid.getSelectedRows();
1812 var data = SE.grid.getRecord(rows[0]).getData();
1813 var ieId = data.ieId;
1814 var folder = data.mbox;
1816 /* iterate through available rows JIC a row is deleted - use first available */
1817 for(var i=0; i<rows.length; i++) {
1818 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1820 var ser = YAHOO.lang.JSON.stringify(uids);
1822 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1826 * shows the import dialog with only relate visible.
1828 showDetailView : function() {
1829 SE.contextMenus.emailListContextMenu.hide();
1830 var rows = SE.grid.getSelectedRows();
1831 if (rows.length > 1) {
1832 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1835 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1836 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1837 /* iterate through available rows JIC a row is deleted - use first available */
1838 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1839 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1845 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1846 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1847 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1851 * Opens multiple messages from ListView context click
1853 openMultiple : function() {
1854 SE.contextMenus.emailListContextMenu.hide();
1856 var rows = SE.grid.getSelectedRows();
1857 var uids = SE.listView.getUidsFromSelection();
1859 if(uids.length > 0) {
1860 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1861 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1862 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1867 * Replies/forwards email
1869 replyForwardEmailContext : function() {
1870 SE.contextMenus.emailListContextMenu.hide();
1872 var indexes = SE.grid.getSelectedRows();
1873 //var dm = SE.grid.getDataModel();
1876 for(var i=0; i<indexes.length; i++) {
1877 var row = SE.grid.getRecord(indexes[i]).getData();
1878 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1882 //show menu functions
1883 showEmailsListMenu : function(grid, row) {
1885 var data = row.getData();
1886 var draft = (data.type == "draft");
1887 var menu = SE.contextMenus.emailListContextMenu;
1892 if (data.mbox == 'sugar::Emails')
1893 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1895 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1897 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1898 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1899 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1900 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1902 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1905 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1907 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1908 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1909 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1910 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1911 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1914 if (data.mbox == "sugar::Emails")
1916 //Allow users to reassign imported emails
1917 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1918 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1919 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1920 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1924 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1925 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1929 showFolderMenu : function(grid, rowIndex, event) {
1931 var coords = event.getXY();
1932 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1936 SE.contextMenus.dv = {
1937 archiveToSugar : function(contextMenuId) {
1939 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1942 replyForwardEmailContext : function(all) {
1943 SE.contextMenus.detailViewContextMenu.hide();
1952 //// END SE.contextMenus
1953 ///////////////////////////////////////////////////////////////////////////////
1957 ///////////////////////////////////////////////////////////////////////////////
1960 consumeMetaDetail : function(ret) {
1961 // handling if the Email drafts
1962 if(ret.type == 'draft') {
1963 SE.composeLayout.c0_composeDraft();
1968 // cache contents browser-side
1969 SE._setDetailCache(ret);
1971 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1972 // 2 below must be in global context
1974 meta['panelId'] = SE.util.getPanelId();
1976 email = ret.meta.email;
1977 var out = displayTemplate.exec({
1978 'app_strings' : app_strings,
1980 'idx' : targetDiv.id,
1982 'email' : meta.email,
1983 'linkBeans' : linkBeans
1985 var tabLabel = meta.email.name;
1986 if (tabLabel != null && tabLabel.length > 25) {
1987 tabLabel = tabLabel.substring(0, 25) + "...";
1989 targetDiv.set("label", tabLabel);
1990 targetDiv.set("content", out);
1992 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1993 if (SUGAR.email2.util.isIe()) {
1994 displayEmailFrameDiv.style.height = "390px";
1996 displayEmailFrameDiv.style.height = "410px";
1999 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
2000 displayFrame.contentWindow.document.write(email.description);
2001 displayFrame.contentWindow.document.close();
2003 // hide archive links
2004 if(ret.meta.is_sugarEmail) {
2005 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
2006 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
2008 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
2009 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
2014 consumeMetaPreview : function(ret) {
2015 // cache contents browser-side
2016 SE._setDetailCache(ret);
2020 var currrow = SE.grid.getLastSelectedRecord();
2021 currrow = SE.grid.getRecord(currrow);
2023 document.getElementById('_blank').innerHTML = '';
2026 // handling if the Email drafts
2027 if(ret.type == 'draft'){
2028 if (currrow.getData().uid == ret.uid) {
2029 SE.composeLayout.c0_composeDraft();
2034 if (currrow.getData().uid != ret.meta.uid) {
2038 // remove loading sprite
2039 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2040 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2042 meta['panelId'] = SE.util.getPanelId();
2043 email = ret.meta.email;
2045 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2046 'app_strings' : app_strings,
2050 'email' :meta.email,
2051 'linkBeans' : linkBeans
2053 // document.getElementById('_blank').innerHTML = meta.email;
2054 /* displayTemplate.append('_blank', {
2055 'app_strings' : app_strings,
2059 'email' :meta.email,
2060 'linkBeans' : linkBeans
2063 var displayFrame = document.getElementById('displayEmailFramePreview');
2064 displayFrame.contentWindow.document.write(email.description);
2065 displayFrame.contentWindow.document.close();
2067 SE.listViewLayout.resizePreview();
2069 // hide archive links
2070 if(ret.meta.is_sugarEmail) {
2071 document.getElementById("archiveEmailPreview").innerHTML = " ";
2072 document.getElementById("btnEmailViewPreview").style.display = "none";
2073 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2075 //hide view relationship link
2076 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2081 * wraps emailDelete() for single messages, comes from preview or tab
2083 emailDeleteSingle : function(ieId, uid, mbox) {
2084 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2085 // find active panel and close if the user double clicked the email to view.
2086 var activeTabId = SE.util.getPanelId();
2087 if(activeTabId != 'Preview')
2088 SE.innerLayout.get("activeTab").close();
2090 document.getElementById('_blank').innerHTML = "";
2093 uid = YAHOO.lang.JSON.stringify(ser);
2094 this.emailDelete(ieId, uid, mbox);
2099 * Sends async call to delete a given message
2102 emailDelete : function(ieId, uid, mbox) {
2103 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2104 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2105 uid + "&ieId=" + ieId + "&folder=" + mbox);
2109 * retrieves one email to display in the preview pane.
2111 getEmailPreview : function() {
2112 var row = SUGAR.email2.listView.currentRow;
2113 var data = row.getData();
2114 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2115 var setRead = (data['seen'] == 0) ? true : false;
2116 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2117 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2122 * Imports one email into Sugar
2124 importEmail : function(ieId, uid, mbox) {
2125 SE.util.clearHiddenFieldValues('emailUIForm');
2127 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2129 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2130 AjaxObject.target = '';
2131 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2135 * Populates the frameFlex div with the contents of an email
2137 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2138 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2140 var mboxStr = new String(mbox);
2141 var compKey = mbox + uid;
2143 if(setRead == true) {
2144 SE.listView.boldUnreadRows()
2145 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2148 if(destination == SE.innerLayout) {
2150 * loading email into a tab, peer with ListView
2151 * targetDiv must remain in the global namespace as it is used by AjaxObject
2153 //Check if we already have a tab of the email open
2154 var tabs = SE.innerLayout.get("tabs");
2155 for (var t in tabs) {
2156 if (tabs[t].id && tabs[t].id == uid) {
2157 SE.innerLayout.set("activeTab", tabs[t]);
2162 targetDiv = new YAHOO.SUGAR.ClosableTab({
2163 label: loadingSprite,
2169 SE.innerLayout.addTab(targetDiv);
2171 // use cache if available
2172 if(SE.cache[compKey]) {
2173 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2175 // open email as peer-tab to listView
2176 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2177 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2180 // loading email into preview pane
2181 document.getElementById('_blank').innerHTML = loadingSprite;
2183 // use cache if available
2184 if(SE.cache[compKey]) {
2185 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2187 AjaxObject.forceAbort = true;
2188 // open in preview window
2189 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2190 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2195 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2197 if(mboxStr.substring(0,7) == 'sugar::') {
2198 // display an email from Sugar
2199 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2201 // display an email from an email server
2202 document.getElementById('emailUIAction').value = 'getSingleMessage';
2204 document.getElementById('mbox').value = mbox;
2205 document.getElementById('ieId').value = ieId;
2206 document.getElementById('uid').value = uid;
2208 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2210 AjaxObject.forceAbort = true;
2211 AjaxObject.target = '_blank';
2212 AjaxObject.startRequest(callback, null);
2216 * Retrieves multiple emails for DetailView
2218 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2219 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2220 SE.util.clearHiddenFieldValues('emailUIForm');
2222 var mboxStr = new String(mbox);
2224 uids = SE.util.cleanUids(uids);
2226 if(mboxStr.substring(0,7) == 'sugar::') {
2227 // display an email from Sugar
2228 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2229 document.getElementById('uid').value = uids;
2231 // display an email from an email server
2232 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2233 document.getElementById('mbox').value = mbox;
2234 document.getElementById('ieId').value = ieId;
2235 document.getElementById('uid').value = uids;
2238 var formObject = document.getElementById('emailUIForm');
2239 YAHOO.util.Connect.setForm(formObject);
2241 AjaxObject.target = 'frameFlex';
2242 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2244 if(setRead == true) {
2245 var c = uids.split(",");
2246 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2251 * Makes async call to get QuickCreate form
2252 * Renders a modal edit view for a given module
2254 quickCreate : function(module, ieId, uid, mailbox) {
2255 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2257 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2258 get += "&sugarEmail=true";
2261 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2265 * Makes async call to save a quick create
2268 saveQuickCreate : function(action) {
2269 var qcd = SE.detailView.quickCreateDialog;
2270 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2271 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2272 var theCallback = callbackQuickCreateSave;
2273 var accountType = '&sugarEmail=true';
2274 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2275 accountType = '&ieId=' + qcd.ieId;
2278 if (action == 'reply') {
2279 theCallback = callbackQuickCreateSaveAndReply;
2280 } else if (action == true) {
2281 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2283 formObject.action.value = 'EmailUIAjax';
2284 YAHOO.util.Connect.setForm(formObject);
2285 SUGAR.showMessageBox('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2286 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2287 accountType + '&mbox=' + qcd.mbox);
2292 * Code to show/hide long list of email address in DetailView
2294 showCroppedEmailList : function(el) {
2295 el.style.display = 'none';
2296 el.previousSibling.style.display = 'inline'
2298 showFullEmailList : function(el) {
2299 el.style.display = 'none';
2300 el.nextSibling.style.display = 'inline';
2304 * Shows the QuickCreate overlay
2305 * @param string ieId
2307 * @param string mailbox
2309 showQuickCreate : function(ieId, uid, mailbox) {
2310 var panelId = SE.util.getPanelId();
2311 var context = document.getElementById("quickCreateSpan" + panelId);
2313 if (!SE.detailView.cqMenus)
2314 SE.detailView.cqMenus = {};
2316 if (SE.detailView.cqMenus[context])
2317 SE.detailView.cqMenus[context].destroy();
2319 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2321 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2324 for (var i=0; i < this.qcmodules.length; i++) {
2325 var module = this.qcmodules[i];
2327 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2330 onclick: { fn: function() {
2331 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2337 menu.render(document.body);
2342 * Displays the "View" submenu in the detailView
2343 * @param string ieId
2345 * @param string mailbox
2347 showViewMenu : function(ieId, uid, mailbox) {
2348 var panelId = SE.util.getPanelId();
2349 var context = "btnEmailView" + panelId;
2350 if (!SE.detailView.viewMenus)
2351 SE.detailView.viewMenus = {};
2353 if (SE.detailView.viewMenus[context])
2354 SE.detailView.viewMenus[context].destroy();
2356 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2358 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2362 (ieId == 'null' || ieId == null) ?
2363 //No ieId - Sugar Email
2365 text: app_strings.LBL_EMAIL_VIEW_RAW,
2366 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2369 //IeID exists, on a remote server
2371 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2372 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2374 text: app_strings.LBL_EMAIL_VIEW_RAW,
2375 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2378 menu.render(document.body);
2383 //#23108 jchi@07/17/2008
2384 menu.render('quickCreateSpan'+ panelId);*/
2385 //this.viewMenu = menu;
2386 //this.viewMenu.show(context);
2389 * Makes async call to get an email's headers
2391 viewHeaders : function(ieId, uid, mailbox) {
2392 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2393 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2397 * Makes async call to get a printable version
2399 viewPrintable : function(ieId, uid, mailbox) {
2400 if(mailbox == 'sugar::Emails') {
2401 // display an email from Sugar
2402 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2404 // display an email from an email server
2405 var emailUIAction = '&emailUIAction=getSingleMessage';
2408 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2409 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2413 * Makes async call to get an email's raw source
2415 viewRaw : function(ieId, uid, mailbox) {
2416 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2417 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2421 * Display all email addresses in detailview.
2423 displayAllAddrs : function(el) {
2424 el.style.display = 'none';
2425 Dom.getNextSibling(el).style.display = 'inline';
2428 //// END SE.detailView
2429 ///////////////////////////////////////////////////////////////////////////////
2433 ///////////////////////////////////////////////////////////////////////////////
2436 contextMenuFocus : new Object(),
2439 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2440 * SugarFolder ID - folder strings
2442 _createFolderId : function(node) {
2448 if(node.data.ieId) {
2449 /* we have a local Sugar folder */
2450 if(node.data.ieId == 'folder') {
2451 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2452 } else if(node.data.ieId.match(SE.reGUID)) {
2453 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2462 addChildNode : function(parentNode, childNode) {
2463 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2464 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2465 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2467 if(childNode.nodes) {
2468 if(childNode.nodes.length > 0) {
2469 for(j=0; j<childNode.nodes.length; j++) {
2470 var newChildNode = childNode.nodes[j];
2471 this.addChildNode(node, newChildNode);
2478 * Builds and returns a new TreeView Node
2479 * @param string name
2481 * @param int is_group
2484 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2485 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2487 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2488 node.expanded = expanded;
2489 node.data = new Object;
2490 node.data['id'] = id;
2491 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2492 node.data['label'] = name;
2493 node.data['ieId'] = 'folder';
2494 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2495 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2496 node.data['unseen'] = unseen;
2501 * ensures that a new folder has a valid name
2503 checkFolderName : function(name) {
2507 this.folderAdd(name);
2511 * Pings email servers for new email - forces refresh of folder pane
2513 checkEmailAccounts : function() {
2514 this.checkEmailAccountsSilent(true);
2517 checkEmailAccountsSilent : function(showOverlay) {
2518 if(typeof(SE.folders.checkingMail)) {
2519 clearTimeout(SE.folders.checkingMail);
2522 // don't stomp an on-going request
2523 if(AjaxObject.currentRequestObject.conn == null) {
2525 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW,
2526 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2528 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2530 // wait 5 secs before trying again.
2531 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2536 * Starts check of all email Accounts using a loading bar for large POP accounts
2538 startEmailAccountCheck : function() {
2539 // don't do two checks at the same time
2540 if(!AjaxObject.requestInProgress()) {
2541 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2542 SE.accounts.ieIds = SE.folders.getIeIds();
2543 if (SE.accounts.ieIds.length > 0) {
2544 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2545 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2547 SUGAR.hideMessageBox();
2550 // wait 5 secs before trying again.
2551 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2556 * Checks a single Account check based on passed ieId
2558 startEmailCheckOneAccount : function(ieId, synch) {
2565 var node = SE.clickedFolderNode;
2566 if (node && !synch) {
2567 mbox = node.data.mbox;
2569 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2570 SE.accounts.ieIds = [ieId];
2571 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2572 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2577 * Empties trash for subscribed accounts
2579 emptyTrash : function() {
2580 SE.contextMenus.frameFoldersContextMenu.hide();
2581 SUGAR.showMessageBox(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2582 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2586 * Clears Cache files of the inboundemail account
2588 clearCacheFiles : function(ieId) {
2589 SE.contextMenus.frameFoldersContextMenu.hide();
2590 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2591 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2596 * Returns an array of all the active accounts in the folder view
2598 getIeIds : function() {
2600 var root = SE.tree.getRoot();
2601 for(i=0; i < root.children.length; i++) {
2602 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2603 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2604 ieIds.push(root.children[i].children[0].data.ieId);
2611 * loads folder lists in Settings->Folders
2613 lazyLoadSettings : function() {
2614 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2615 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2619 * After the add new folder is done via folders tab on seetings, this function should get called
2620 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2622 loadSettingFolder : function() {
2623 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2624 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2628 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2630 removeSugarFolders : function() {
2632 var root = tree.getRoot();
2633 var folder = SE.util.findChildNode(root, "ieId", "folder");
2635 tree.removeNode(folder);
2636 folder = SE.util.findChildNode(root, "ieId", "folder");
2638 if (!root.childrenRendered) {
2639 root.childrenRendered = true;
2643 rebuildFolders : function(silent) {
2644 if (!silent) SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2645 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2651 * Updates TreeView with Sugar Folders
2653 setSugarFolders : function(delay) {
2654 this.removeSugarFolders();
2655 //AjaxObject.forceAbort = true;
2656 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2660 * Takes async data object and creates the sugar folders in TreeView
2662 setSugarFoldersEnd : function(o) {
2663 var root = SE.tree.getRoot();
2664 addChildNodes(root, {nodes: o});
2665 SE.accounts.renderTree();
2666 //If nothing is loaded in the grid, load "My Inbox"
2667 if (SE.grid.params.ieId == "undefined") {
2668 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2672 startCheckTimer : function() {
2673 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2674 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2676 if(typeof(SE.folders.checkTimer) != 'undefined') {
2677 clearTimeout(SE.folders.checkTimer);
2680 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2681 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2683 SE.userPrefs.emailSettings.firstAutoCheck = true;
2684 SE.folders.checkEmailAccountsSilent(false);
2690 * makes an async call to save user preference and refresh folder view
2691 * @param object SELECT list object
2693 setFolderSelection : function() {
2694 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2696 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2697 var a_active_accnts = "";
2698 for(i=0;i<a_rs.length;i++)
2700 var t_record = a_rs[i];
2701 var is_active = t_record.getData('is_active');
2703 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2706 if(a_active_accnts == "")
2707 a_active_accnts = "&ieIdShow[]=";
2709 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2711 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2715 * makes async call to save user preference for a given node's open state
2716 * @param object node YUI TextNode object
2718 setOpenState : function(node) {
2719 SE.util.clearHiddenFieldValues('emailUIForm');
2720 var nodePath = node.data.id;
2721 var nodeParent = node.parent;
2723 while(nodeParent != null) {
2724 // root node has no ID param
2725 if(nodeParent.data != null) {
2726 nodePath = nodeParent.data.id + "::" + nodePath;
2729 var nodeParent = nodeParent.parent;
2732 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2733 document.getElementById('focusFolder').value = nodePath;
2735 if(node.expanded == true) {
2736 document.getElementById('focusFolderOpen').value = 'open';
2738 document.getElementById('focusFolderOpen').value = 'closed';
2741 var formObject = document.getElementById('emailUIForm');
2742 YAHOO.util.Connect.setForm(formObject);
2744 AjaxObject.startRequest(null, null);
2747 getNodeFromMboxPath : function(path) {
2748 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2749 var a = YAHOO.lang.JSON.parse(path);
2751 var node = tree.getRoot();
2754 while(i < a.length) {
2755 node = this.getChildNodeFromLabel(node, a[i]);
2762 getChildNodeFromLabel : function(node, nodeLabel) {
2763 for(i=0; i<node.children.length; i++) {
2764 if(node.children[i].data.id == nodeLabel) {
2765 return node.children[i];
2771 * returns the node that presumably under the user's right-click
2773 getNodeFromContextMenuFocus : function() {
2774 //// get the target(parent) node
2775 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2777 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2779 // filter local folders
2780 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2781 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2782 if(target.id == '') {
2783 target = target.parentNode;
2790 var targetNode = document.getElementById(target.id);
2791 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2794 var matches = re.exec(targetNode.id);
2796 return document.getElementById(ygtvlabelel1);
2802 // usually parent node
2803 matches = re.exec(targetNode.parentNode.id);
2810 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2811 parentNode.expand();
2817 * Decrements the Unread Email count in folder text
2818 * @param string ieId ID to look for
2819 * @param string mailbox name
2820 * @param count how many to decrement
2822 decrementUnreadCount : function(ieId, mbox, count) {
2827 if(mbox.indexOf("sugar::") === 0) {
2828 var node = this.getNodeFromId(ieId);
2830 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2833 var unseen = node.data.unseen;
2835 var check = unseen - count;
2836 var finalCount = (check >= 0) ? check : 0;
2837 node.data.unseen = finalCount;
2839 SE.accounts.renderTree();
2844 * gets the TreeView node with a given ID/ieId
2845 * @param string id ID to look for
2846 * @return object Node
2848 getNodeFromId : function(id) {
2849 SE.folders.focusNode = null;
2850 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2851 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2852 SE.folders.focusNode = this;
2856 return SE.folders.focusNode;
2860 * Uses ieId and mailbox to try to find a node in the tree
2862 getNodeFromIeIdAndMailbox : function(id, mbox) {
2863 SE.folders.focusNode = null;
2864 if (mbox == "sugar::Emails") {
2868 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2869 if (varsarray instanceof Array) {
2870 if (this.data.ieId && this.data.ieId == varsarray[0]
2871 && this.data.mbox == varsarray[1]) {
2872 SE.folders.focusNode = this;
2876 if (this.data.ieId && this.data.ieId == varsarray) {
2877 SE.folders.focusNode = this;
2881 }, null, [id, mbox]);
2882 return SE.folders.focusNode;
2885 unhighliteAll : function() {
2886 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2890 * Displays a short form
2892 folderAdd : function() {
2893 SE.contextMenus.frameFoldersContextMenu.hide();
2895 var node = SE.clickedFolderNode;
2897 if(node != null && node.data) {
2898 SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2899 app_strings.LBL_EMAIL_SETTINGS_NAME,
2900 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2902 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2906 folderAddRegisterEnter : function() {
2907 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2908 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2909 this.buttons[1].handler);
2911 this.enterKeyListener.enable();
2914 folderRemoveRegisterEnter : function() {
2915 this.enterKeyListener.disable();
2918 folderAddXmlCall : function(name) {
2919 if (trim(name) == "") {
2920 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2923 name = escape(name);
2927 var parentNode = SE.clickedFolderNode;
2929 this.contextMenuFocus = parentNode;
2931 if(parentNode.data.ieId) {
2932 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2936 if(type == 'imap') {
2937 // make an IMAP folder
2938 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2939 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2940 } else if(type == 'sugar') {
2941 // make a Sugar folder
2942 if(SE.folders.isUniqueFolderName(name)) {
2943 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2944 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2946 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2947 SE.folders.folderAdd();
2951 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2954 // hide add-folder diaglogue
2955 SE.e2overlay.hide();
2959 * Removes either an IMAP folder or a Sugar Folder
2961 folderDelete : function() {
2962 SE.contextMenus.frameFoldersContextMenu.hide();
2964 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2966 var parentNode = SE.clickedFolderNode;
2968 if(parentNode != null && parentNode.data) {
2969 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2970 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2974 AjaxObject.target = 'frameFlex';
2976 if(parentNode.data.ieId != 'folder') {
2977 // delete an IMAP folder
2978 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2980 // delete a sugar folder
2981 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2983 SUGAR.showMessageBox("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2984 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2986 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2992 * Rename folder form
2995 folderRename : function() {
2996 SE.contextMenus.frameFoldersContextMenu.hide();
2997 var node = SE.clickedFolderNode;
3000 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
3001 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
3005 SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
3006 app_strings.LBL_EMAIL_SETTINGS_NAME,
3008 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
3010 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
3015 * fills an Object with key-value pairs of available folders
3017 getAvailableFoldersObject : function() {
3018 var ret = new Object();
3019 var tree = SE.tree.root;
3022 for(var i=0; i<tree.children.length; i++) {
3023 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3026 ret['none'] = app_strings.LBL_NONE;
3033 * Fills in key-value pairs for dependent dropdowns
3034 * @param object ret Associative array
3035 * @param object node TreeView node in focus
3036 * @param string currentPath Built up path thus far
3037 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3039 getFolderFromChild : function(ret, node, currentPath, spacer) {
3040 if(node.data != null && node.depth > 0) {
3041 /* handle visual separtors differentiating b/t mailserver and local */
3042 if(node.data.ieId && node.data.ieId == 'folder') {
3043 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3047 ret['spacer0'] = spacer;
3048 } else if(ret.spacer0 != spacer) {
3049 ret['spacer1'] = spacer
3052 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3053 var depthMarker = currentPath;
3054 var retIndex = SE.folders._createFolderId(node);
3055 ret[retIndex] = depthMarker + theLabel;
3058 if(node.children != null) {
3060 currentPath += theLabel + "/";
3063 for(var i=0; i<node.children.length; i++) {
3064 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3072 * Wrapper to refresh folders tree
3074 getFolders : function() {
3075 SE.accounts.rebuildFolderList();
3079 * handles events around folder-rename input field changes
3080 * @param object YUI event object
3082 handleEnter : function(e) {
3083 switch(e.browserEvent.type) {
3085 e.preventDefault(); // click in text field
3089 SE.folders.submitFolderRename(e);
3093 var kc = e.browserEvent.keyCode;
3097 SE.folders.submitFolderRename(e);
3101 e.preventDefault(e);
3102 SE.folders.cancelFolderRename(e);
3109 * Called when a node is clicked on in the folder tree
3110 * @param node, The node clicked on
3111 * @param e, The click event
3113 handleClick : function(o) {
3115 //If the click was on a sugar folder
3116 if (node.data.ieId == "folder") {
3117 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3120 SE.listView.populateListFrame(node, node.data.ieId, false);
3122 //eval(node.data.click);
3127 * Called when a node is right-clicked on in the folder tree
3129 handleRightClick : function(e) {
3130 YAHOO.util.Event.preventDefault(e);
3132 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3133 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3135 //If the click was on a sugar folder
3136 SE.clickedFolderNode = node;
3137 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3138 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3139 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3140 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3141 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3142 menu.getItem(3).cfg.setProperty("disabled", false);
3143 menu.getItem(4).cfg.setProperty("disabled", false);
3144 menu.getItem(5).cfg.setProperty("disabled", false);
3145 menu.getItem(6).cfg.setProperty("disabled", true);
3147 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3148 menu.getItem(0).cfg.setProperty("disabled", true);
3149 menu.getItem(1).cfg.setProperty("disabled", true);
3150 menu.getItem(2).cfg.setProperty("disabled", true);
3151 menu.getItem(3).cfg.setProperty("disabled", true);
3152 menu.getItem(4).cfg.setProperty("disabled", true);
3154 if (node.data.protocol != null) {
3155 menu.getItem(6).cfg.setProperty("disabled", false);
3157 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3158 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3159 //Sent or Draft folders
3160 menu.getItem(3).cfg.setProperty("disabled", true);
3161 menu.getItem(4).cfg.setProperty("disabled", true);
3162 menu.getItem(5).cfg.setProperty("disabled", true);
3165 //For group with auto inbound, disable everything.
3166 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3168 menu.getItem(0).cfg.setProperty("disabled", true);
3169 menu.getItem(1).cfg.setProperty("disabled", true);
3170 menu.getItem(2).cfg.setProperty("disabled", true);
3171 menu.getItem(3).cfg.setProperty("disabled", true);
3172 menu.getItem(4).cfg.setProperty("disabled", true);
3173 menu.getItem(5).cfg.setProperty("disabled", true);
3174 menu.getItem(6).cfg.setProperty("disabled", true);
3177 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3182 * Called when a row is dropped on a node
3184 handleDrop : function(rows, targetFolder) {
3185 var rowData = rows[0].getData();
3186 if (rowData.mbox != targetFolder.data.mbox) {
3187 var srcIeId = rowData.ieId;
3188 var srcFolder = rowData.mbox;
3189 var destIeId = targetFolder.data.ieId;
3190 var destFolder = targetFolder.data.mbox;
3192 for(var i=0; i<rows.length; i++) {
3193 uids[i] = rows[i].getData().uid;
3195 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3200 * Called when something is dragged over a Folder Node
3202 dragOver : function(dragObject) {
3207 * Determines if a folder name is unique to the folder tree
3208 * @param string name
3210 isUniqueFolderName : function(name) {
3211 uniqueFolder = true;
3212 var root = SE.tree.getRoot();
3213 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3214 if (this.attributes && this.attributes.ieId == "folder") {
3215 if (this.attributes.text == name) {
3216 uniqueFolder = false;
3221 return uniqueFolder;
3225 * Makes async call to rename folder in focus
3226 * @param object e Event Object
3228 submitFolderRename : function(newName) {
3229 if (trim(newName) == "") {
3230 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3233 newName = escape(newName);
3234 var node = SE.clickedFolderNode;
3235 var origName = node.data.text
3237 if (newName == origName) {
3240 if(SE.folders.isUniqueFolderName(newName)) {
3241 SUGAR.showMessageBox(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3242 if (node.data.ieId == "folder") {
3244 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3247 //IMAP folder or POP mailbox
3248 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3249 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3250 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3254 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3259 moveFolder : function(folderId, parentFolderId) {
3260 if (folderId != parentFolderId)
3262 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3263 + folderId + "&newParentId=" + parentFolderId);
3268 * makes async call to do a full synchronization of all accounts
3270 synchronizeAccounts : function() {
3271 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3272 SUGAR.showMessageBoxModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3273 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3278 * Updates user's folder subscriptsion (Sugar only)
3279 * @param object SELECT DOM object in focus
3280 * @param string type of Folder selection
3282 updateSubscriptions : function() {
3283 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3287 select = document.getElementById('userFolders');
3289 for(i=0; i<select.options.length; i++) {
3290 var opt = select.options[i];
3291 if(opt.selected && opt.value != "") {
3295 active += opt.value;
3299 //Add the group folder ids.
3300 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3301 for(i=0; i<group_folders.length; i++)
3303 active += ("::" + group_folders[i]);
3306 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3309 * Updates user's group folder subscriptsion (Sugar only)
3310 * @param ieID The group folder to add to the tree view
3312 retrieveGroupFolderSubscriptions : function() {
3314 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3315 var activeGroupFolders = "";
3316 var activeGroupIds = [];
3317 for(i=0;i<a_rs.length;i++)
3319 var t_record = a_rs[i];
3320 var is_active = t_record.getData('is_active');
3321 var isGroupFolder = t_record.getData('has_groupfolder');
3322 var ieID = t_record.getData('id');
3326 activeGroupIds.push(ieID);
3330 return activeGroupIds;
3335 SE.folders.checkEmail2 = function() {
3336 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3338 //// END FOLDERS OBJECT
3339 ///////////////////////////////////////////////////////////////////////////////
3342 ///////////////////////////////////////////////////////////////////////////////
3345 * Keypress Event capture and processing
3348 overall : function(e) {
3349 switch(e.charCode) {
3351 if(e.ctrlKey || e.altKey) {
3352 var focusRegion = SE.innerLayout.regions.center;
3353 if(focusRegion.activePanel.closable == true) {
3354 focusRegion.remove(focusRegion.activePanel);
3362 ///////////////////////////////////////////////////////////////////////////////
3365 ///////////////////////////////////////////////////////////////////////////////
3368 * ListView object methods and attributes
3374 * Fills the ListView pane with detected messages.
3376 populateListFrame : function(node, ieId, forceRefresh) {
3377 SE.innerLayout.selectTab(0);
3378 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3380 Dom.get('_blank').innerHTML = "";
3381 SE.grid.params['emailUIAction'] = 'getMessageList';
3382 SE.grid.params['mbox'] = node.data.mbox;
3383 SE.grid.params['ieId'] = ieId;
3384 forcePreview = true; // loads the preview pane with first item in grid
3385 SE.listView.refreshGrid();
3389 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3391 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3392 SE.innerLayout.selectTab(0);
3393 Dom.get('_blank').innerHTML = "";
3394 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3395 SE.grid.params['ieId'] = node.data.id;
3396 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3397 SE.listView.refreshGrid();
3401 * Sets sort order as user preference
3404 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3406 ieName = ieNamePassed;
3407 focusFolder = focusFolderPassed;
3409 SE.util.clearHiddenFieldValues('emailUIForm');
3410 var previousSort = document.getElementById('sortBy').value;
3412 document.getElementById('sortBy').value = sortBy;
3413 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3414 document.getElementById('focusFolder').value = focusFolder;
3415 document.getElementById('ieId').value = ieId;
3417 if(sortBy == previousSort) {
3418 document.getElementById('reverse').value = '1';
3421 var formObject = document.getElementById('emailUIForm');
3422 YAHOO.util.Connect.setForm(formObject);
3424 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3429 * Enables click/arrow select of grid items which then populate the preview pane.
3431 selectFirstRow : function() {
3432 SE.grid.selModel.selectFirstRow();
3435 selectLastRow : function() {
3436 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3439 setEmailListStyles : function() {
3440 SE.listView.boldUnreadRows();
3442 var ds = SE.grid.getStore();
3443 if (SE.grid.getSelections().length == 0) {
3444 document.getElementById('_blank').innerHTML = '';
3448 if(typeof(ds.baseParams.mbox) != 'undefined') {
3449 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3450 var cm = SE.grid.getColumnModel();
3451 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3452 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3454 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3455 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3459 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3460 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3462 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3463 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3464 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3465 if (node) node.data.unseen = unread;
3467 SE.accounts.renderTree();
3470 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3471 if(forcePreview && ds.totalCount > 0) {
3472 SE.detailView.getEmailPreview();
3473 forcePreview = false;
3478 * Removes a row if found via its UID
3480 removeRowByUid : function(uid) {
3481 uid = new String(uid);
3482 uids = uid.split(',');
3483 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3485 for(j=0; j<uids.length; j++) {
3486 var theUid = uids[j];
3487 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3488 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3489 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3495 displaySelectedEmails : function(rows) {
3496 var dm = SE.grid.getDataModel();
3499 for(i=0; i<rows.length; i++) {
3500 var rowIndex = rows[i].rowIndex;
3501 var metadata = dm.data[rowIndex];
3506 uids += metadata[5];
3508 // unbold unseen email
3509 this.unboldRow(rowIndex);
3512 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3516 * exception handler for data load failures
3518 loadException : function(dataModel, ex, response) {
3523 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3524 * @param string sourceIeId Email's source I-E id
3525 * @param string sourceFolder Email's current folder
3526 * @param destinationIeId Destination I-E id
3527 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3529 * @param array emailUids Array of email's UIDs
3531 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3532 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3533 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3535 SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3536 // remove rows from visibility
3537 for(row in selectedRows) {
3538 //SE.grid.getStore().remove(row);
3541 var baseUrl = '&sourceIeId=' + sourceIeId +
3542 '&sourceFolder=' + sourceFolder +
3543 '&destinationIeId=' + destinationIeId +
3544 '&destinationFolder=' + destinationFolder;
3547 for(i=0; i<emailUids.length; i++) {
3549 uids += app_strings.LBL_EMAIL_DELIMITER;
3551 uids += emailUids[i];
3553 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3554 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3556 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3562 * Unbolds text in the grid view to denote read status
3564 markRead : function(index, record) {
3565 // unbold unseen email
3566 var row = SE.grid.getRecord(record);
3567 row.getData().seen = 1;
3568 SE.grid.getTrEl(record).style.fontWeight = "normal";
3572 * grid row output, bolding unread emails
3574 boldUnreadRows : function() {
3575 // bold unread emails
3576 var trEl = SE.grid.getFirstTrEl();
3577 while(trEl != null) {
3578 if(SE.grid.getRecord(trEl).getData().seen == "0")
3579 trEl.style.fontWeight = "bold";
3581 trEl.style.fontWeight = "";
3582 trEl = SE.grid.getNextTrEl(trEl);
3587 * Show preview for an email if 1 and only 1 is selected
3588 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3590 handleRowSelect : function(e) {
3591 if(e.selectedRows.length == 1) {
3592 SE.detailView.getEmailPreview();
3596 handleDrop : function(e, dd, targetId, e2) {
3598 case 'htmleditordiv':
3599 var rows = SE.grid.getSelectedRows();
3600 if(rows.length > 0) {
3601 SE.listView.displaySelectedEmails(rows);
3606 var targetElId = new String(targetId);
3607 var targetIndex = targetElId.replace('ygtvlabelel',"");
3608 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3609 var dm = SE.grid.getDataModel();
3610 var emailUids = new Array();
3611 var destinationIeId = targetNode.data.ieId;
3612 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3615 var rows = SE.grid.getSelectedRows();
3616 // iterate through dragged rows
3617 for(i=0; i<rows.length; i++) {
3618 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3619 var rowIndex = rows[i].rowIndex;
3620 var dataModelRow = dm.data[rowIndex];
3621 var sourceIeId = dataModelRow[7];
3622 var sourceFolder = dataModelRow[6];
3623 emailUids[i] = dataModelRow[5];
3626 // event wrapped call - need FQ
3627 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3628 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3634 * Hack-around to get double-click and single clicks to work on the grid
3635 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3637 handleClick : function(o) {
3638 SUGAR.email2.grid.clearTextSelection();
3640 var el = SUGAR.email2.grid.getSelectedRows();
3642 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3643 if ( el.length == 1)
3646 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3647 SUGAR.email2.listView.currentRowIndex = rowId;
3648 clearTimeout(SUGAR.email2.detailView.previewTimer);
3649 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3654 * Custom handler for double-click/enter
3655 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3657 getEmail : function(e) {
3658 var rows = SE.grid.getSelectedRows();
3659 var row = SE.grid.getRecord(rows[0]).getData();
3661 clearTimeout(SE.detailView.previewTimer);
3662 document.getElementById("_blank").innerHTML = "";
3664 if(row.type != "draft") {
3665 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3667 // circumventing yui-ext tab generation, let callback handler build new view
3668 SE.util.clearHiddenFieldValues('emailUIForm');
3669 //function(uid, mbox, ieId, setRead, destination) {
3670 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3671 document.getElementById('uid').value = row.uid; // uid;
3672 document.getElementById('mbox').value = row.mbox; // mbox;
3673 document.getElementById('ieId').value = row.ieId; // ieId;
3675 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3676 AjaxObject.target = '_blank';
3677 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3682 * Retrieves a row if found via its UID
3686 getRowIndexByUid : function(uid) {
3687 uid = new String(uid);
3688 uids = uid.split(',');
3690 for(j=0; j<uids.length; j++) {
3691 var theUid = uids[j];
3693 for(i=0; i<SE.grid.getStore().data.length; i++) {
3694 if(SE.grid.getStore().data[i].id == theUid) {
3702 * Returns the UID's of the seleted rows
3705 getUidsFromSelection : function() {
3706 var rows = SE.grid.getSelectedRows();
3708 /* iterate through available rows JIC a row is deleted - use first available */
3709 for(var i=0; i<rows.length; i++) {
3710 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3715 refreshGrid : function() {
3716 SE.grid.getDataSource().sendRequest(
3717 SUGAR.util.paramsToUrl(SE.grid.params),
3718 SE.grid.onDataReturnInitializeTable,
3724 //// END SE.listView
3725 ///////////////////////////////////////////////////////////////////////////////
3727 ///////////////////////////////////////////////////////////////////////////////
3731 * sends search criteria
3732 * @param reference element search field
3734 search : function(el) {
3735 var searchCriteria = new String(el.value);
3737 if(searchCriteria == '') {
3738 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3742 var safeCriteria = escape(searchCriteria);
3744 var accountListSearch = document.getElementById('accountListSearch');
3746 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3747 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3748 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3749 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3750 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3755 * sends advanced search criteria
3757 searchAdvanced : function() {
3758 var formObject = document.getElementById('advancedSearchForm');
3761 //Set assigned user id to blank if name is not present.
3762 if (formObject.elements['assigned_user_name'].value == "")
3763 formObject.elements['assigned_user_id'].value = "";
3765 for(i=0; i<formObject.elements.length; i++) {
3766 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3769 if(formObject.elements[i].type == 'text') {
3770 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3772 if(formObject.elements[i].type == 'hidden') {
3773 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3775 if(formObject.elements[i].type == 'select-one') {
3776 var el = formObject.elements[i];
3777 var v = el.options[el.selectedIndex].value;
3780 SE.grid.params[el.name] = v;
3783 //Clear previous search results if necessary
3784 if(typeof( SE.grid.params[el.name]) != 'undefined')
3785 delete SE.grid.params[el.name]
3792 if(! this.validateSearchFormInput() )
3795 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3796 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3797 var accountListSearch = document.getElementById('accountListSearch');
3798 SE.listView.refreshGrid();
3800 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3805 * Validates the search form inputs to ensure all parameters are valid
3808 validateSearchFormInput: function()
3810 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3811 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3812 var dateCheck = check_form('advancedSearchForm');
3814 //If the parent type is selected ensure the user selected a parent_id.
3815 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3821 * Toggles the advanced options, either hidding or showing the selection.
3823 toggleAdvancedOptions: function()
3825 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3827 for(var i=0;i<el.length;i++)
3829 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3830 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3832 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3836 * clears adv search form fields
3838 searchClearAdvanced : function() {
3839 var form = document.getElementById('advancedSearchForm');
3841 for(i=0; i<form.elements.length; i++) {
3842 if(form.elements[i].type != 'button') {
3843 form.elements[i].value = '';
3849 //////////////////////////////////////////////////////////////////////////////
3852 //////////////////////////////////////////////////////////////////////////////
3855 /******************************************************************************
3856 * USER SIGNATURES calls stolen from Users module
3857 *****************************************************************************/
3858 createSignature : function(record, the_user_id) {
3859 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3861 URL += "&record="+record;
3863 if(the_user_id != "") {
3864 URL += "&the_user_id="+the_user_id;
3866 var windowName = 'email_signature';
3867 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3869 var win = window.open(URL, windowName, windowFeatures);
3870 if(win && win.focus) {
3871 // put the focus on the popup if the browser supports the focus() method
3876 deleteSignature : function() {
3877 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3878 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3879 var singature_id = document.getElementById('signature_id').value;
3880 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3884 saveOptionsGeneral : function(displayMessage) {
3885 var formObject = document.getElementById('formEmailSettingsGeneral');
3886 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3887 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3890 YAHOO.util.Connect.setForm(formObject);
3891 SE.composeLayout.emailTemplates = null;
3893 AjaxObject.target = 'frameFlex';
3894 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3897 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3899 SE.settings.settingsDialog.hide();
3903 * Shows settings container screen
3905 showSettings : function() {
3906 if(!SE.settings.settingsDialog) {
3907 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3913 constraintoviewport: true
3915 dlg.showEvent.subscribe( function (){
3916 var el = this.element;
3917 var viewH = YAHOO.util.Dom.getViewportHeight();
3918 if (this.header && el && viewH - 50 < el.clientHeight) {
3919 var body = this.header.nextElementSibling;
3920 body.style.overflow = "auto";
3921 body.style.height = (viewH - 50) + "px";
3924 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3925 dlg.setBody('<div id="settingsTabDiv"/>');
3926 dlg.beforeRenderEvent.subscribe(function() {
3927 var dd = new YAHOO.util.DDProxy(dlg.element);
3928 dd.setHandleElId(dlg.header);
3929 dd.on('endDragEvent', function() {
3935 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3936 var tabContent = Dom.get("tab_general");
3937 tp.addTab(new YAHOO.widget.Tab({
3938 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3940 content : tabContent.innerHTML,
3941 id : "generalSettings",
3944 tabContent.parentNode.removeChild(tabContent);
3945 tabContent = Dom.get("tab_accounts");
3946 var accountTab = new YAHOO.widget.Tab({
3947 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3949 content : tabContent.innerHTML,
3950 id : "accountSettings"
3952 tp.addTab(accountTab);
3953 tabContent.parentNode.removeChild(tabContent);
3955 tp.appendTo(dlg.body);
3958 SE.settings.settingsDialog.show();
3959 SE.folders.lazyLoadSettings();
3960 SE.accounts.lazyLoad();
3964 lazyLoadRules : function() {
3965 if(false/*!SE.settings.rules*/) {
3966 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3971 //// END SE.settings
3972 ///////////////////////////////////////////////////////////////////////////////
3975 /******************************************************************************
3977 *****************************************************************************/
3978 function removeHiddenNodes(nodes, grid) {
3980 for(var i = nodes.length - 1; i > -1; i--) {
3981 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3982 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3988 function strpad(val) {
3989 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3992 function refreshTodos() {
3993 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3994 AjaxObject.target = 'todo';
3995 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3998 /******************************************************************************
3999 * MUST STAY IN GLOBAL NAMESPACE
4000 *****************************************************************************/
4001 function refresh_signature_list(signature_id, signature_name) {
4002 var field=document.getElementById('signature_id');
4004 for (var i=0; i < field.options.length; i++) {
4005 if (field.options[i].value == signature_id) {
4006 if (field.options[i].selected==false) {
4007 field.options[i].selected=true;
4012 //add item to selection list.
4014 var newElement=document.createElement('option');
4015 newElement.text=signature_name;
4016 newElement.value=signature_id;
4017 field.options.add(newElement);
4018 newElement.selected=true;
4021 //enable the edit button.
4022 var field1=document.getElementById('edit_sig');
4023 field1.style.visibility="inherit";
4024 var deleteButt = document.getElementById('delete_sig');
4025 deleteButt.style.visibility="inherit";
4028 function setDefaultSigId(id) {
4029 var checkbox = document.getElementById("signature_default");
4030 var default_sig = document.getElementById("signatureDefault");
4032 if(checkbox.checked) {
4033 default_sig.value = id;
4035 default_sig.value = "";
4039 function setSigEditButtonVisibility() {
4040 var field = document.getElementById('signature_id');
4041 var editButt = document.getElementById('edit_sig');
4042 var deleteButt = document.getElementById('delete_sig');
4043 if(field.value != '') {
4044 editButt.style.visibility = "inherit";
4045 deleteButt.style.visibility = "inherit";
4047 editButt.style.visibility = "hidden";
4048 deleteButt.style.visibility = "hidden";
4050 }// End of File modules/Emails/javascript/EmailUI.js
4052 /*********************************************************************************
4053 * SugarCRM Community Edition is a customer relationship management program developed by
4054 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4056 * This program is free software; you can redistribute it and/or modify it under
4057 * the terms of the GNU Affero General Public License version 3 as published by the
4058 * Free Software Foundation with the addition of the following permission added
4059 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4060 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4061 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4063 * This program is distributed in the hope that it will be useful, but WITHOUT
4064 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4065 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4068 * You should have received a copy of the GNU Affero General Public License along with
4069 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4070 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4073 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4074 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4076 * The interactive user interfaces in modified source and object code versions
4077 * of this program must display Appropriate Legal Notices, as required under
4078 * Section 5 of the GNU Affero General Public License version 3.
4080 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4081 * these Appropriate Legal Notices must retain the display of the "Powered by
4082 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4083 * technical reasons, the Appropriate Legal Notices must display the words
4084 * "Powered by SugarCRM".
4085 ********************************************************************************/
4088 var sw = YAHOO.SUGAR,
4089 Event = YAHOO.util.Event,
4090 Connect = YAHOO.util.Connect,
4091 Dom = YAHOO.util.Dom
4094 ///////////////////////////////////////////////////////////////////////////////
4097 _contactCache : new Array(), // cache of contacts
4098 _dd : new Array(), // filtered list, same format as _contactCache
4099 _ddLists : new Array(), // list of Lists
4100 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4101 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4102 clickBubble : true, // hack to get around onclick event bubbling
4104 relatedBeanType : '',
4107 itemSpacing : 'white-space:nowrap; padding:2px;',
4113 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4115 initFixForDatatableSort: function () {
4116 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4117 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4118 var oColumn = this._oColumnSet.getColumn(column);
4121 // Validate TD element
4122 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4124 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4126 // Validate TH element
4128 elCell = this.getThEl(column);
4131 var allColumns = this._oColumnSet.flat;
4132 for(var i=0, len=allColumns.length; i<len; i++) {
4133 if(allColumns[i].getThEl().id === elCell.id) {
4134 oColumn = allColumns[i];
4145 cancelEdit : function() {
4146 if(this.editContactDialog)
4147 this.editContactDialog.hide();
4148 if(this.editMailingListDialog)
4149 this.editMailingListDialog.hide();
4153 * Clears filter form
4155 clear : function() {
4156 var t = document.getElementById('contactsFilter');
4162 * handle context-menu Compose-to call
4163 * @param string type 'contacts' or 'lists'
4165 composeTo : function(type, waited) {
4166 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4167 if (activePanel.substring(0, 10) != "composeTab") {
4168 SE.composeLayout.c0_composeNewEmail();
4169 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4170 SE.contextMenus.contactsContextMenu.hide();
4173 var idx = activePanel.substring(10);
4176 // determine if we have a selection to work with
4177 if(type == 'contacts') {
4178 var ids = SE.contactView.getSelectedRows();
4179 for (var i in ids) {
4180 rows[i] = SE.contactView.getRecord(ids[i]);
4182 removeHiddenNodes(rows, SE.contactView);
4186 if(rows.length > 0) {
4187 SE.composeLayout.handleDrop(
4188 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4189 null, rows, 'addressTO' + idx );
4191 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4195 editContact : function() {
4196 SE.contextMenus.contactsContextMenu.hide();
4197 var element = SE.contactView.getSelectedNodes()[0];
4199 if (element.className.indexOf('address-contact') > -1) {
4200 elementId = element.id;
4201 } else if (element.className.indexOf('address-exp-contact') > -1) {
4202 elementId = element.id.substring(2);
4208 * Filters contact entries based on user input
4210 filter : function(inputEl) {
4211 var ret = new Object();
4212 var re = new RegExp(inputEl.value, "gi");
4214 for(var i in this._contactCache) {
4215 if(this._contactCache[i].name.match(re)) {
4216 ret[i] = this._contactCache[i];
4220 this.buildContactList(ret);
4223 fullForm : function(id, module) {
4224 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4228 * returns a formatted email address from the addressBook cache
4230 getFormattedAddress : function(id) {
4231 var o = this._contactCache[id];
4232 var primaryEmail = '';
4234 for(var i=0; i<o.email.length; i++) {
4235 var currentEmail = o.email[i].email_address;
4237 if(o.email[i].primary_address == 1) {
4238 primaryEmail = o.email[i].email_address;
4242 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4243 var name = new String(o.name);
4244 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4245 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4251 * Sets up async call to query for matching contacts, users, etc.
4253 searchContacts : function() {
4254 var fn = document.getElementById('input_searchField').value;
4255 var pe = document.getElementById('input_searchPerson').value;
4257 var rb = document.getElementById('hasRelatedBean').checked;
4260 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4261 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4262 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4263 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4265 this.addressBookDataModel.params['related_bean_id'] = '';
4268 this.addressBookDataModel.params['search_field'] = fn;
4269 this.addressBookDataModel.params['person'] = pe;
4270 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4271 this.grid._oDataSource = this.addressBookDataModel;
4272 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4276 * Clear Search Crieteria For Addressbook
4278 clearAddressBookSearch : function() {
4279 document.getElementById('input_searchField').value = "";
4280 document.getElementById('input_searchPerson').selectedIndex = 0;
4284 * Opens modal select window to add contacts to addressbook
4286 selectContactsDialogue : function(destId) {
4287 if(!this.contactsDialogue) {
4288 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4292 constraintoviewport: true,
4294 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4295 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4297 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4299 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4300 dlg.setBody(body.innerHTML);
4301 dlg.renderEvent.subscribe(function() {
4302 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4303 if (iev && !SUGAR.isIE) {
4304 this.body.style.width = "950px";
4309 dlg.beforeRenderEvent.subscribe(function() {
4310 var dd = new YAHOO.util.DDProxy(dlg.element);
4311 dd.setHandleElId(dlg.header);
4312 dd.on('endDragEvent', function() {
4318 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4320 var tabContent = SUGAR.util.getAndRemove("searchForm");
4321 tp.addTab(new YAHOO.widget.Tab({
4322 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4324 content : tabContent.innerHTML,
4325 id : "addressSearchTab",
4329 var addListenerFields = ['input_searchPerson','input_searchField' ]
4330 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4331 if (e.keyCode == 13) {
4332 YAHOO.util.Event.stopEvent(e);
4333 SUGAR.email2.addressBook.searchContacts();
4337 this.contactsDialogue.render();
4340 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4341 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4345 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4346 var idx = activePanel.substring(10);
4348 SE.addressBook.idx = idx;
4351 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4352 document.getElementById('relatedBeanColumn').style.display = '';
4353 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4354 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4355 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4356 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4357 SE.addressBook.relatedBeanType = relatedBeanType;
4359 document.getElementById('relatedBeanColumn').style.display = 'none';
4360 document.getElementById('hasRelatedBean').checked = false;
4363 if (!SE.addressBook.grid)
4365 if (hasRelatedBeanId) {
4366 document.getElementById('hasRelatedBean').checked = true;
4368 AddressSearchGridInit();
4369 SE.addressBook.relatedBeanId = relatedBeanId;
4373 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4375 SE.addressBook.relatedBeanId = relatedBeanId;
4376 document.getElementById('hasRelatedBean').checked = true;
4378 if (document.getElementById('hasRelatedBean').checked == true)
4380 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4381 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4383 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4384 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4386 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4387 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4388 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4391 //Remove any lingering rows in the result set table if the module was closed.
4392 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4394 SE.addressBook.populateResulstTableEmailAddresses();
4396 this.contactsDialogue.show();
4399 * Clear all email addresses from result table.
4402 clearAllEmailAddressFieldsFromResultTable: function () {
4403 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4404 //Unhighlight any rows currently selected if the emails were cleared.
4405 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4406 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4409 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4410 * results table. This function is called when the address book is displayed.
4412 populateResulstTableEmailAddresses: function () {
4414 var idx = SE.addressBook.idx;
4415 var emailFields = ['to','cc','bcc'];
4417 for(var k=0;k<emailFields.length;k++)
4419 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4420 var allEmails = document.getElementById(elKey).value;
4424 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4426 for (var i=0; i<formatedEmails.length; i++)
4428 var t_name = formatedEmails[i].name;
4429 var t_emailAddr = formatedEmails[i].email_address;
4430 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4432 t_name = displayEmail = t_emailAddr;
4434 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4435 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4436 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4442 * Checks all entries in the result table against a particular email address, returning true
4443 * if the email address is found, false otherwise.
4445 doesEmailAdddressExistInResultTable: function(emailAddress)
4447 if(trim(emailAddress) == '')
4450 var emailAddressFound = false;
4451 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4452 for (var i=0; i < contacts.length; i++)
4454 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4455 //If we are adding to cc or bcc fields, make them visible.
4456 if(data.email_address == emailAddress)
4458 emailAddressFound = true;
4463 return emailAddressFound;
4466 * Takes all email addresses that the users wishes to add from the address book and populates the To
4467 * fields on the compose tab.
4469 populateEmailAddressFieldsFromResultTable: function()
4471 //Clear the fields first, all email addresses are stored in the address book
4472 var idx = SE.addressBook.idx;
4473 var emailFields = ['to','cc','bcc'];
4474 for(var k=0;k<emailFields.length;k++)
4476 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4477 document.getElementById(elKey).value = "";
4480 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4481 for (var i=0; i < contacts.length; i++)
4483 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4485 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4486 //If we are adding to cc or bcc fields, make them visible.
4487 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4488 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4489 //Construct the target id
4490 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4492 var target = document.getElementById(target_id);
4493 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4496 //Delete all rows from the result set table
4497 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4500 SE.addressBook.contactsDialogue.hide()
4503 * Insert contacts into the result table.
4505 insertContactToResultTable : function(event,address_type) {
4507 var contactsDialogue = SE.addressBook.contactsDialogue;
4508 var contacts = SE.addressBook.grid.getSelectedRows();
4510 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4511 for (var i = 0; i < rows.length; i++)
4513 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4515 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4516 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4517 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4518 rows[i].setData("selected",true);
4521 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4522 for (var i = 0; i < checkBoxes.length; i++) {
4523 checkBoxes[i].checked = false;
4529 insertContactRowToResultTable : function(rowId, addressType) {
4530 var data = SE.addressBook.grid.getRecord(rowId).getData();
4531 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4533 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4534 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4535 if(addressType == null)
4536 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4537 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});
4540 * Remove a row from the gridsResult table.
4542 removeRowFromGridResults : function(rowId,emailAddress)
4544 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4545 for (var i=0; i < contacts.length; i++)
4547 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4548 var data = rec.getData();
4549 if(data.email_address == emailAddress)
4551 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4556 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4559 * Translates between the addressType To|Cc|Bcc labels/keys.
4561 translateAddresType: function(addressType,fromKey)
4563 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4564 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4565 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4566 var mappingObject = {};
4569 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4572 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4573 mappingObject[displayCc] = 'cc';
4574 mappingObject[displayBcc] = 'bcc';
4577 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4583 toggleSearchRowIcon : function(rowId,show)
4587 var idToShow = rowId + '_add_img';
4588 var idToHide = rowId + '_rm_img';
4592 var idToShow = rowId + '_rm_img';
4593 var idToHide = rowId + '_add_img';
4597 Dom.addClass(idToHide, "yui-hidden");
4598 Dom.removeClass(idToShow, "yui-hidden");
4601 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4603 doesGridResultsEntryExist: function(emailAddrs)
4606 var contactExists = false;
4607 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4608 for (var i=0; i < contacts.length; i++)
4610 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4611 if(data.email_address == emailAddrs)
4613 contactExists = true;
4617 return contactExists;
4621 * adds an email address to a string, but first checks if it exists
4622 * @param string concat The string we are appending email addresses to
4623 * @param string addr Email address to add
4626 smartAddEmailAddressToComposeField : function(concat, addr) {
4627 var re = new RegExp(addr);
4629 if(!concat.match(re)) {
4631 concat += "; " + addr;
4640 //// END ADDRESS BOOK
4641 ///////////////////////////////////////////////////////////////////////////////
4645 ///////////////////////////////////////////////////////////////////////////////
4648 * Auto-complete object
4652 delimChar : [";", ","],
4656 prehighlightClassName : "yui-ac-prehighlight",
4659 instances : new Array(),
4662 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4663 * @param object Contact from AddressBook
4666 getPrimaryAddress : function(contact) {
4667 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4669 for(var eIndex in contact.email) {
4670 address = contact.email[eIndex].email_address;
4671 if(contact.email[eIndex].primary_address == 1) {
4672 return contact.email[eIndex].email_address;
4680 * initializes autocomplete widgets for a given compose view
4683 init : function(idx) {
4684 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4685 "queryMatchContains" : false,
4686 "queryMatchSubset" : true
4689 this.instances[idx] = {
4696 // instantiate the autoComplete widgets
4697 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4698 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4699 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4701 // enable hiding of interfering textareas
4702 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4703 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4704 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4706 // enable reshowing of hidden textareas
4707 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4708 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4709 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4711 // enable refreshes of contact lists
4712 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4713 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4714 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4717 refreshDataSource : function(sType, aArgs) {
4718 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4720 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4722 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4723 idx = textBoxId.substr(9);
4725 idx = textBoxId.substr(10);
4728 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4729 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4730 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4734 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4736 returnDataSource : function(contacts) {
4737 var ret = new Array();
4738 for(var id in contacts) {
4739 if (contacts[id].name) {
4740 var primary = this.getPrimaryAddress(contacts[id]);
4742 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4743 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4745 for(var emailIndex in contacts[id].email) {
4746 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4755 * Hides address textareas to prevent autocomplete dropdown from being obscured
4757 toggleTextareaHide : function(sType, aArgs) {
4758 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4762 if(textBoxId.indexOf("addressTO") > -1) {
4764 } else if(textBoxId.indexOf("addressCC") > -1) {
4767 idx = textBoxId.substr(9);
4769 // follow through if not BCC
4771 var cc = document.getElementById("addressCC" + idx);
4772 var bcc = document.getElementById("addressBCC" + idx);
4776 cc.style.visibility = 'hidden';
4778 bcc.style.visibility = 'hidden';
4785 * Redisplays the textareas after an address is commited
4787 toggleTextareaShow : function(sType, aArgs) {
4788 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4792 if(textBoxId.indexOf("addressTO") > -1) {
4794 } else if(textBoxId.indexOf("addressCC") > -1) {
4797 idx = textBoxId.substr(9);
4799 // follow through if not BCC
4801 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4802 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4807 //// END AUTOCOMPLETE
4808 ///////////////////////////////////////////////////////////////////////////////
4810 ///////////////////////////////////////////////////////////////////////////////
4813 * expands the options sidebar
4815 SE.composeLayout = {
4816 currentInstanceId : 0,
4819 outboundAccountErrors : null,
4820 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4822 showAddressDetails : function(e) {
4823 var linkElement = document.getElementById("More"+e.id);
4824 var spanElement = document.getElementById("Detail"+e.id);
4825 var emailAddressList = e.value;
4826 if(e.value.length > 96)
4828 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4829 var displayArray = [];
4830 for (var i=0; i<resultArray.length; i++)
4832 var t_name = resultArray[i].name;
4833 var t_emailAddr = resultArray[i].email_address;
4835 displayArray.push('<br/><' + t_emailAddr + '>');
4837 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4840 var result = displayArray.join('<br/>');
4842 linkElement.style.display = "inline";
4843 linkElement.style.height="10px";
4844 linkElement.style.overflow="visible";
4845 spanElement.innerHTML = result;
4848 linkElement.style.display = "none";
4853 * Given a string of email address, return an array containing the name portion (if available)
4854 * and email portion.
4856 _getEmailArrayFromString : function (emailAddressList){
4859 while ((results = reg.exec(emailAddressList)) != null)
4861 orignial = results[0];
4862 parsedResult = results[0].replace(';', ':::::');
4863 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4867 while ((results = reg.exec(emailAddressList)) != null)
4869 orignial = results[0];
4870 parsedResult = results[0].replace(',', ':::::');
4871 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4873 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4874 var emailArr = emailAddressList.split(":::::");
4875 var resultsArray = [];
4877 for (var i=0; i<emailArr.length; i++)
4879 var rposition = emailArr[i].indexOf('<');
4880 var lposition = emailArr[i].indexOf('>');
4882 if(trim(emailArr[i]) != '')
4884 if(rposition != -1 && lposition != -1)
4886 var t_name = emailArr[i].substr(0, rposition-1);
4887 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4888 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4892 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4896 return resultsArray;
4898 ///////////////////////////////////////////////////////////////////////////
4901 * Prepare bucket DIV and yui-ext tab panels
4903 _0_yui : function() {
4904 var idx = this.currentInstanceId;
4906 var composeTab = new YAHOO.SUGAR.ClosableTab({
4907 label: mod_strings.LNK_NEW_SEND_EMAIL,
4909 content : "<div id='htmleditordiv" + idx + "'/>",
4910 id : "composeTab" + idx,
4911 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4914 SE.innerLayout.addTab(composeTab);
4916 // get template engine with template
4917 if (!SE.composeLayout.composeTemplate) {
4918 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4921 // create Tab inner layout
4922 var composePanel = this.getComposeLayout();
4923 composePanel.getUnitByPosition("right").collapse();
4924 composePanel.autoSize();
4928 * Generate the quick compose layout
4929 * @method getQuickComposeLayout
4930 * @param {Pannel} parentPanel Parent pannel
4931 * @param {Object} o Options
4934 getQuickComposeLayout : function (parentPanel,o) {
4935 var idx = SE.composeLayout.currentInstanceId;
4937 //Before rendering the parent pannel we need to initalize the grid layout
4938 parentPanel.beforeRenderEvent.subscribe(function() {
4940 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4941 SE.composeLayout._createComposeLayout(idx);
4942 SE.composeLayout[idx].set('height', 350);
4943 SE.composeLayout[idx].render();
4947 //Wait until the Compose Layout has rendered, then add the
4948 //options tab and perform the tiny initialization.
4949 parentPanel.renderEvent.subscribe(function() {
4951 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4952 SE.composeLayout._initComposeOptionTabs(idx);
4953 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4954 //Initialize tinyMCE
4955 SE.composeLayout._1_tiny(false);
4957 //Init templates and address book
4958 SE.composeLayout._2_final();
4960 SE.composeLayout.quickCreateComposePackage(o);
4965 //Check if we have the div override for the shortcut bar
4966 if(typeof o.menu_id != 'undefined') {
4967 parentPanel.render(o.menu_id);
4969 parentPanel.render(document.body);
4972 return SE.composeLayout[idx];
4975 * Fill in all fields into the quick compose layout.
4976 * @method quickCreateComposePackage
4977 * @param {Object} o Options
4980 quickCreateComposePackage: function(o)
4982 //If we have a compose package fill in defaults.
4983 if (typeof(o.composePackage) != 'undefined')
4985 composePackage = o.composePackage; //Set the compose data object
4986 //Hijack this method called by composePackage as it's not need for quick creates.
4987 SE.composeLayout.c0_composeNewEmail = function(){};
4988 SE.composeLayout.composePackage(); //Fill in defaults.
4991 getComposeLayout : function() {
4992 var idx = SE.composeLayout.currentInstanceId;
4994 this._createComposeLayout(idx);
4995 SE.composeLayout[idx].render();
4996 this._initComposeOptionTabs(idx);
4998 return SE.composeLayout[idx];
5002 * Create the layout manager for the compose window.
5004 _createComposeLayout : function(idx)
5006 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
5007 parent: SE.complexLayout,
5017 SE.composeLayout.composeTemplate.exec({
5018 'app_strings':app_strings,
5019 'mod_strings':mod_strings,
5020 'linkbeans_options' : linkBeans,
5021 'idx' : SE.composeLayout.currentInstanceId
5032 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5035 header: app_strings.LBL_EMAIL_OPTIONS
5041 * Create compose tab which will populate the 'right' container in the compose window.
5043 _initComposeOptionTabs : function(idx)
5045 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5046 var tab = new YAHOO.widget.Tab({
5047 label: app_strings.LBL_EMAIL_ATTACHMENT,
5049 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5050 id : "divAttachments" + idx,
5054 tab.layout = SE.composeLayout[idx];
5056 tab.on("activeChange", function(o){
5058 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5064 tab = new YAHOO.widget.Tab({
5065 label: app_strings.LBL_EMAIL_OPTIONS,
5067 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5068 id : "divOptions" + idx,
5072 tab.layout = SE.composeLayout[idx];
5073 tab.on("activeChange", function(o){
5075 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5080 SE.composeLayout[idx].autoSize = function() {
5081 var pEl = this.get("element").parentNode.parentNode.parentNode;
5082 this.set("height", pEl.clientHeight-30);
5086 SE.composeLayout[idx].rightTabs = cTabs;
5088 isParentTypeValid : function(idx) {
5089 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5090 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5091 if (trim(parentTypeValue) == ""){
5092 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5098 isParentTypeAndNameValid : function(idx) {
5099 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5100 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5101 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5102 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5103 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5104 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5110 callopenpopupForEmail2 : function(idx,options) {
5112 var formName = 'emailCompose' + idx;
5114 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5115 formName = options.form_name;
5117 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5118 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5119 if (!SE.composeLayout.isParentTypeValid(idx)) {
5122 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5124 call_back_function:"SE.composeLayout.popupAddEmail",
5126 field_to_name_array:{
5127 id:'data_parent_id' + idx,
5128 name:'data_parent_name' + idx,
5133 popupAddEmail : function(o)
5135 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5136 var data = o.name_to_value_array;
5137 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5138 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5140 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5141 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5148 _1_tiny : function(isReplyForward) {
5149 var idx = SE.composeLayout.currentInstanceId;
5150 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5151 SE.tinyInstances[elId] = { };
5152 SE.tinyInstances[elId].ready = false;
5154 if (!SUGAR.util.isTouchScreen()) {
5155 var t = tinyMCE.getInstanceById(elId);
5157 if(typeof(t) == 'undefined') {
5158 if (!SUGAR.util.isTouchScreen()) {
5159 tinyMCE.execCommand('mceAddControl', false, elId);
5161 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5162 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
5167 resizeEditorSetSignature : function(idx,setSignature)
5169 var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5171 if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
5172 setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+setSignature+"');",500);
5176 SE.composeLayout.resizeEditor(idx);
5178 setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
5183 resizeEditor : function(idx)
5185 var cof = Dom.get('composeOverFrame' + idx);
5186 var head = Dom.get('composeHeaderTable' + idx);
5187 var targetHeight = cof.clientHeight - head.clientHeight;
5188 var instance = SE.util.getTiny('htmleditor' + idx);
5191 var parentEl = Dom.get(instance.editorId + '_parent');
5192 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5193 var contentEl = instance.contentAreaContainer;
5194 var iFrame = contentEl.firstChild;
5195 var tinMceToolbarOffset = 18;
5196 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5199 setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
5204 * Initializes d&d, auto-complete, email templates
5206 _2_final : function() {
5207 var idx = SE.composeLayout.currentInstanceId;
5209 if(this.emailTemplates) {
5210 this.setComposeOptions(idx);
5212 //populate email template cache
5213 AjaxObject.target = '';
5214 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5217 // handle drop targets for addressBook
5218 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5219 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5220 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5221 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5223 // auto-complete setup
5224 SE.autoComplete.init(idx);
5227 document.getElementById("addressTO" + idx).focus();
5231 * hide tinyMCE tool bar if send email as plaintext is checked
5233 renderTinyMCEToolBar : function (idx, hide) {
5235 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5237 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5241 c1_composeEmail : function(isReplyForward, retry) {
5245 if (!SUGAR.util.isTouchScreen() && (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined')){
5246 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5248 this._1_tiny(isReplyForward);
5251 if(isReplyForward) {
5252 this.replyForwardEmailStage2();
5258 * takes draft info and prepopulates
5260 c0_composeDraft : function() {
5261 this.getNewInstanceId();
5263 document.getElementById('_blank').innerHTML = '';
5264 var idx = SE.composeLayout.currentInstanceId;
5265 SE.composeLayout.draftObject = new Object();
5266 SE.composeLayout.draftObject.id = idx;
5267 SE.composeLayout.draftObject.isDraft = true;
5268 SE.composeLayout.currentInstanceId = idx;
5269 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5270 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5271 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5273 SE.composeLayout._0_yui();
5274 SE.composeLayout._1_tiny(true);
5277 SE.composeLayout._2_final();
5279 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5280 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5284 * Strip & Prep editor hidden fields
5286 c0_composeNewEmail : function() {
5287 this.getNewInstanceId();
5288 this.c1_composeEmail(false);
5292 * Sends async request to get the compose view.
5293 * Requests come from "reply" or "forwards"
5295 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5296 SE.composeLayout.replyForwardObj = new Object();
5297 SE.composeLayout.replyForwardObj.ieId = ieId;
5298 SE.composeLayout.replyForwardObj.uid = uid;
5299 SE.composeLayout.replyForwardObj.mbox = mbox;
5300 SE.composeLayout.replyForwardObj.type = type;
5302 if(mbox == 'sugar::Emails') {
5303 SE.composeLayout.replyForwardObj.sugarEmail = true;
5306 SE.composeLayout.getNewInstanceId();
5307 SE.composeLayout.c1_composeEmail(true);
5309 //// END COMPOSE FLOW
5310 ///////////////////////////////////////////////////////////////////////////
5313 * Called when a contact, email, or mailinglist is dropped
5314 * into one of the compose fields.
5316 handleDrop : function (source, event, data, target) {
5319 target = event.getTarget();
5321 data.nodes = [data.nodes];
5325 target = document.getElementById(target);
5329 if (target.id.indexOf('address') > -1) {
5330 // dropped onto email to/cc/bcc field
5331 for(var i in nodes) {
5332 var node = nodes[i].getData();
5334 if (node[1].indexOf('contact') > -1) {
5335 email = SE.addressBook.getFormattedAddress(node[0]);
5336 } else if (node[1].indexOf('address-email') > -1){
5337 email = node[3].replace(/ /gi, '');
5338 email = email.replace('<', '<').replace('>', '>');
5339 var tr = source.getTrEl(nodes[i]);
5340 while (tr && !Dom.hasClass(tr, "address-contact")) {
5341 tr = source.getPreviousTrEl(tr);
5343 var CID = source.getRecord(tr).getData()[0];
5344 var o = SE.addressBook._contactCache[CID];
5345 var name = new String(o.name);
5346 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5347 email = finalName + email;
5349 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5355 /*/////////////////////////////////////////////////////////////////////////////
5356 /// EMAIL TEMPLATE CODE
5358 applyEmailTemplate : function (idx, id) {
5361 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5362 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5363 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5366 var to_addr = document.getElementById('addressTO'+idx);
5367 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
5369 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5370 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5373 // id is selected index of email template drop-down
5374 if(id == '' || id == "0") {
5375 YAHOO.SUGAR.MessageBox.show({
5380 if(btn=='no'){return;};
5381 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5388 YAHOO.SUGAR.MessageBox.show({
5393 if(btn=='no'){return;};
5394 SUGAR.email2.composeLayout.processResult(idx, id);},
5400 processNoneResult : function(idx, id) {
5401 var tiny = SE.util.getTiny('htmleditor' + idx);
5402 var tinyHTML = tiny.getContent();
5403 var openTag = '<div><span><span>';
5404 var htmllow = tinyHTML.toLowerCase();
5405 var start = htmllow.indexOf(openTag);
5407 tinyHTML = tinyHTML.substr(start);
5408 tiny.setContent(tinyHTML);
5410 tiny.setContent('');
5414 processResult : function(idx , id){
5415 var post_data = {"module":"EmailTemplates","record":id};
5416 var global_rpcClient = new SugarRPCClient();
5418 result = global_rpcClient.call_method('retrieve', post_data, true);
5419 if(!result['record']) return;
5420 json_objects['email_template_object'] = result['record'];
5421 this.appendEmailTemplateJSON();
5423 // get attachments if any
5424 AjaxObject.target = '';
5425 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5428 appendEmailTemplateJSON : function() {
5429 var idx = SE.composeLayout.currentInstanceId; // post increment
5431 // query based on template, contact_id0,related_to
5432 //jchi 09/10/2008 refix #7743
5433 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5434 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5437 var 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,'"');
5439 // cn: bug 14361 - text-only templates don't fill compose screen
5441 text = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body'])).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"').replace(/\r\n/gi,"<br/>");
5444 var tiny = SE.util.getTiny('htmleditor' + idx);
5445 var tinyHTML = tiny.getContent();
5446 var openTag = '<div><span><span>';
5447 var closeTag = '</span></span></div>';
5448 var htmllow = tinyHTML.toLowerCase();
5449 var start = htmllow.indexOf(openTag);
5451 var htmlPart2 = tinyHTML.substr(start);
5452 tinyHTML = text + htmlPart2;
5453 tiny.setContent(tinyHTML);
5455 tiny.setContent(text);
5460 * Writes out the signature in the email editor
5462 setSignature : function(idx) {
5465 var hide = document.getElementById('setEditor' + idx).checked;
5466 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5467 //wait for signatures to load before trying to set them
5468 if (!SE.composeLayout.signatures) {
5469 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5474 var sel = document.getElementById('signatures' + idx);
5476 var sel = document.getElementById('signature_id');
5477 idx = SE.tinyInstances.currentHtmleditor;
5480 //Ensure that the tinyMCE html has been rendered.
5481 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5482 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5489 signature = sel.options[sel.selectedIndex].value;
5494 var openTag = '<div><span><span>';
5495 var closeTag = '</span></span></div>';
5496 var t = tinyMCE.getInstanceById('htmleditor' + idx);
5498 if(typeof(t) != 'undefined')
5500 t.contentDocument = t.contentWindow.document;
5501 var html = t.getContent();
5508 var htmllow = html.toLowerCase();
5509 var start = htmllow.indexOf(openTag);
5510 var end = htmllow.indexOf(closeTag) + closeTag.length;
5512 // selected "none" - remove signature from email
5513 if(signature == '') {
5515 var htmlPart1 = html.substr(0, start);
5516 var htmlPart2 = html.substr(end, html.length);
5518 html = htmlPart1 + htmlPart2;
5521 SE.signatures.lastAttemptedLoad = '';
5525 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5526 SE.signatures.lastAttemptedLoad = '';
5528 SE.signatures.lastAttemptedLoad = signature;
5530 if(typeof(SE.signatures[signature]) == 'undefined') {
5532 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5533 SE.signatures.targetInstance = (idx) ? idx : "";
5534 AjaxObject.target = '';
5535 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5537 var newSignature = this.prepareSignature(SE.signatures[signature]);
5539 // clear out old signature
5540 if(SE.signatures.lastAttemptedLoad && start > -1) {
5541 var htmlPart1 = html.substr(0, start);
5542 var htmlPart2 = html.substr(end, html.length);
5544 html = htmlPart1 + htmlPart2;
5548 start = html.indexOf('<div><hr></div>');
5549 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5550 var htmlPart1 = html.substr(0, start);
5551 var htmlPart2 = html.substr(start, html.length);
5552 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5553 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5554 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5556 var newHtml = html + openTag + newSignature + closeTag;
5558 //tinyMCE.setContent(newHtml);
5559 t.setContent(newHtml);
5563 prepareSignature : function(str) {
5564 var signature = new String(str);
5566 signature = signature.replace(/</gi, '<');
5567 signature = signature.replace(/>/gi, '>');
5573 showAttachmentPanel : function(idx) {
5574 var east = SE.composeLayout[idx].getUnitByPosition("right");
5575 var tabs = SE.composeLayout[idx].rightTabs;
5577 tabs.set("activeTab", tabs.getTab(0));
5581 * expands sidebar and displays options panel
5583 showOptionsPanel : function(idx) {
5584 var east = SE.composeLayout[idx].getUnitByPosition("right");
5585 var tabs = SE.composeLayout[idx].rightTabs;
5587 tabs.set("activeTab", tabs.getTab(1));
5591 * Selects the Contacts tab
5593 showContactsPanel : function() {
5594 SE.complexLayout.regions.west.showPanel("contactsTab");
5598 * Generates fields for Select Document
5600 addDocumentField : function(idx) {
5601 var basket = document.getElementById('addedDocuments' + idx);
5603 var index = (basket.childNodes.length / 7) - 1;
5610 var test = document.getElementById('documentId' + idx + index);
5612 while(test != null) {
5614 test = document.getElementById('documentId' + idx + index);
5617 var documentCup = document.createElement("div");
5618 documentCup.id = 'documentCup' + idx + index;
5619 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5620 // document id field
5621 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5622 // document name field
5623 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5625 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5626 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5627 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5629 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5630 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5631 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5634 basket.appendChild(documentCup);
5635 //basket.innerHTML += out;
5640 * Makes async call to save a draft of the email
5641 * @param int Instance index
5643 saveDraft : function(tinyInstance) {
5644 this.sendEmail(tinyInstance, true);
5647 selectDocument : function(target) {
5648 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5649 windowName = 'selectDocument';
5650 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5652 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5654 // put the focus on the popup if the browser supports the focus() method
5660 * Modal popup for file attachment dialogue
5662 addFileField : function() {
5663 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5664 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5668 constraintoviewport: true,
5670 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5671 fn:function(){SE.addFileDialog.hide();}
5674 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5675 SE.addFileDialog.render();
5676 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5678 Dom.removeClass("addFileDialog", "yui-hidden");
5680 SE.addFileDialog.show();
5684 * Async upload of file to temp dir
5686 uploadAttachment : function() {
5687 if(document.getElementById('email_attachment').value != "") {
5688 var formObject = document.getElementById('uploadAttachment');
5689 YAHOO.util.Connect.setForm(formObject, true, true);
5690 AjaxObject.target = '';
5691 AjaxObject.startRequest(callbackUploadAttachment, null);
5693 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5698 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5699 * @param string target in focus compose layout
5701 setDocument : function(idx, target, documentId, documentName, docRevId) {
5702 // fields are named/id'd [fieldName][instanceId][index]
5703 var addedDocs = document.getElementById("addedDocuments" + idx);
5704 var docId = document.getElementById('documentId' + idx + target);
5705 var docName = document.getElementById('documentName' + idx + target);
5706 var docRevisionId = document.getElementById('document' + idx + target);
5707 docId.value = documentId;
5708 docName.value = documentName;
5709 docRevisionId.value = docRevId;
5713 * Removes the bucket div containing the document input fields
5715 deleteDocumentField : function(documentCup) {
5716 var f0 = document.getElementById(documentCup);
5717 f0.parentNode.removeChild(f0);
5721 * Removes a Template Attachment field
5725 deleteTemplateAttachmentField : function(idx, index) {
5726 // create not-in-array values for removal filtering
5727 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5733 r += document.getElementById('templateAttachmentId' + idx + index).value;
5734 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5736 var target = 'templateAttachmentCup' + idx + index;
5737 d = document.getElementById(target);
5738 d.parentNode.removeChild(d);
5742 * Async removal of uploaded temp file
5743 * @param string index Should be a concatenation of idx and index
5746 deleteUploadAttachment : function(index, file) {
5747 var d = document.getElementById('email_attachment_bucket' + index);
5748 d.parentNode.removeChild(d);
5750 // make async call to delete cached file
5751 AjaxObject.target = '';
5752 AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5756 * Attaches files coming from Email Templates
5758 addTemplateAttachmentField : function(idx) {
5760 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5762 var basket = document.getElementById('addedTemplateAttachments' + idx);
5765 var index = basket.childNodes.length;
5772 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5774 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5775 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5776 idx + "\",\"" + index + "\");'/>" +
5778 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5779 // templateAttachment field
5780 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5782 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5784 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5785 "<br id='br" + index + "></br>" +
5786 "<br id='brdoc" + index + "></br>" +
5788 basket.innerHTML = basket.innerHTML + out;
5794 * Sends one email via async call
5795 * @param int idx Editor instance ID
5796 * @param bool isDraft
5798 sendEmail : function(idx, isDraft) {
5800 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5801 var obAccountID = document.getElementById('addressFrom' + idx).value;
5803 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5805 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5810 var form = document.getElementById('emailCompose' + idx);
5811 var composeOptionsFormName = "composeOptionsForm" + idx;
5814 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5815 if (t != null || typeof(t) != "undefined") {
5816 var html = t.getContent();
5818 var html = "<p>" + document.getElementById('htmleditor' + idx).value + "</p>";
5821 var subj = document.getElementById('emailSubject' + idx).value;
5822 var to = trim(document.getElementById('addressTO' + idx).value);
5823 var cc = trim(document.getElementById('addressCC' + idx).value);
5824 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5825 var email_id = document.getElementById('email_id' + idx).value;
5826 var composeType = document.getElementById('composeType').value;
5827 var parent_type = document.getElementById("parent_type").value;
5828 var parent_id = document.getElementById("parent_id").value;
5830 var el_uid = document.getElementById("uid");
5831 var uid = (el_uid == null) ? '' : el_uid.value;
5833 var el_ieId = document.getElementById("ieId");
5834 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5836 var el_mbox = document.getElementById("mbox");
5837 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5839 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5840 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5844 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5847 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5848 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5849 parent_id = parentIdValue;
5850 parent_type = parentTypeValue;
5852 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5853 // baseline viability check
5855 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5856 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5858 } else if(subj == '' && !isDraft) {
5859 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5862 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5864 } else if(html == '' && !isDraft) {
5865 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5870 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5871 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5872 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5873 SUGAR.showMessageBox(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5874 html = html.replace(/</ig, "sugarLessThan");
5875 html = html.replace(/>/ig, "sugarGreaterThan");
5877 form.sendDescription.value = html;
5878 form.sendSubject.value = subj;
5879 form.sendTo.value = to;
5880 form.sendCc.value = cc;
5881 form.sendBcc.value = bcc;
5882 form.email_id.value = email_id;
5883 form.composeType.value = composeType;
5884 form.composeLayoutId.value = 'composeLayout' + idx;
5885 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5886 form.saveToSugar.value = 1;
5887 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5888 form.parent_type.value = parent_type;
5889 form.parent_id.value = parent_id;
5890 form.uid.value = uid;
5891 form.ieId.value = ieId;
5892 form.mbox.value = mbox;
5894 // email attachments
5895 var addedFiles = document.getElementById('addedFiles' + idx);
5897 for(i=0; i<addedFiles.childNodes.length; i++) {
5898 var bucket = addedFiles.childNodes[i];
5900 for(j=0; j<bucket.childNodes.length; j++) {
5901 var node = bucket.childNodes[j];
5902 var nName = new String(node.name);
5904 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5905 if(form.attachments.value != '') {
5906 form.attachments.value += "::";
5908 form.attachments.value += node.value;
5915 var addedDocs = document.getElementById('addedDocuments' + idx);
5917 for(i=0; i<addedDocs.childNodes.length; i++) {
5918 var cNode = addedDocs.childNodes[i];
5919 for(j=0; j<cNode.childNodes.length; j++) {
5920 var node = cNode.childNodes[j];
5921 var nName = new String(node.name);
5922 if(node.type == 'hidden' && nName.match(/documentId/)) {
5923 if(form.documents.value != '') {
5924 form.documents.value += "::";
5926 form.documents.value += node.value;
5932 // template attachments
5933 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5934 if(addedTemplateAttachments) {
5935 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5936 var cNode = addedTemplateAttachments.childNodes[i];
5937 for(j=0; j<cNode.childNodes.length; j++) {
5938 var node = cNode.childNodes[j];
5939 var nName = new String(node.name);
5940 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5941 if(form.templateAttachments.value != "") {
5942 form.templateAttachments.value += "::";
5944 form.templateAttachments.value += node.value;
5950 // remove attachments
5951 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5953 YAHOO.util.Connect.setForm(form);
5955 AjaxObject.target = 'frameFlex';
5957 // sending a draft email
5958 if(!isDraft && in_draft) {
5960 SE.listView.removeRowByUid(email_id);
5963 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5964 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5966 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5970 * Handles clicking the email address link from a given view
5972 composePackage : function() {
5973 if(composePackage != null) {
5974 SE.composeLayout.c0_composeNewEmail();
5977 if(composePackage.to_email_addrs) {
5978 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5980 if (composePackage.subject != null && composePackage.subject.length > 0) {
5981 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5984 //If no parent fields are set in the composePackage, ensure they are cleared.
5985 var parentFields = ['parent_type','parent_name','parent_id'];
5986 for(var i=0;i<parentFields.length;i++)
5988 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5989 composePackage[parentFields[i]] = "";
5992 document.getElementById("parent_type").value = composePackage.parent_type;
5993 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5994 document.getElementById("parent_id").value = composePackage.parent_id;
5995 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5996 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5998 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5999 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
6001 if (composePackage.body != null && composePackage.body.length > 0) {
6002 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6003 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
6004 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
6006 if (composePackage.attachments != null) {
6007 SE.composeLayout.loadAttachments(composePackage.attachments);
6010 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
6011 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
6012 SE.util.emptySelectOptions(addressFrom);
6013 var fromAccountOpts = composePackage.fromAccounts.data;
6014 for(i=0; i<fromAccountOpts.length; i++) {
6015 var key = fromAccountOpts[i].value;
6016 var display = fromAccountOpts[i].text;
6017 var opt = new Option(display, key);
6018 if (fromAccountOpts[i].selected) {
6019 opt.selected = true;
6021 addressFrom.options.add(opt);
6028 setContentOnThisTiny : function() {
6029 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6030 var tinyHTML = tiny.getContent();
6031 composePackage.body = decodeURI(encodeURI(composePackage.body));
6032 // cn: bug 14361 - text-only templates don't fill compose screen
6033 if(composePackage.body == '') {
6034 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
6036 //Flag determines if we should clear the tiny contents or just append
6037 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
6038 SE.composeLayout.tinyHTML = '';
6040 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
6042 tiny.setContent(SE.composeLayout.tinyHTML);
6043 //Indicate that the contents has been loaded successfully.
6044 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
6047 * Confirms closure of a compose screen if "x" is clicked
6049 confirmClose : function(panel) {
6050 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6051 SE.composeLayout.closeCompose(panel.id);
6059 * forces close of a compose screen
6061 forceCloseCompose : function(id) {
6062 SE.composeLayout.closeCompose(id);
6064 // handle flow back to originating view
6065 if(composePackage) {
6066 // check if it's a module we need to return to
6067 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6068 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6069 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6070 window.location = url;
6077 * closes the editor that just sent email
6078 * @param string id ID of composeLayout tab
6080 closeCompose : function(id) {
6081 // destroy tinyMCE instance
6082 var idx = id.substr(13, id.length);
6083 var instanceId = "htmleditor" + idx;
6084 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6086 // nullify DOM and namespace values.
6088 SE.composeLayout[idx] = null;
6089 SE.tinyInstances[instanceId] = null;
6090 var tabsArray = SE.innerLayout.get("tabs");
6091 for (i = 0 ; i < tabsArray.length ; i++) {
6092 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6093 tabsArray[i].close();
6097 //SE.innerLayout.getTab(idx).close();
6101 * Enable the quick search for the compose relate field or search tab
6103 enableQuickSearchRelate: function(idx,overides){
6105 if(typeof overides != 'undefined')
6107 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6108 var newModule = document.getElementById(newModuleID).value;
6109 var formName = overides['formName'];
6110 var fieldName = overides['fieldName'];
6111 var fieldId = overides['fieldId'];
6112 var fullName = formName + "_" + fieldName;
6113 var postBlurFunction = null;
6117 var newModule = document.getElementById('data_parent_type'+idx).value;
6118 var formName = 'emailCompose'+idx;
6119 var fieldName = 'data_parent_name'+idx;
6120 var fieldId = 'data_parent_id'+idx;
6121 var fullName = formName + "_" + fieldName;
6122 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6125 if(typeof sqs_objects == 'undefined')
6126 window['sqs_objects'] = new Array;
6128 window['sqs_objects'][fullName] = {
6131 modules:[newModule],
6133 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6134 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6135 post_onblur_function: postBlurFunction,
6136 order:"name","limit":"30","no_match_text":"No Match"};
6139 if(typeof QSProcessedFieldsArray != 'undefined')
6140 QSProcessedFieldsArray[fullName] = false;
6141 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6142 QSFieldsArray[fullName].destroy();
6143 delete QSFieldsArray[fullName];
6145 if (Dom.get(fullName + "_results")) {
6146 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6152 qsAddAddress : function(o) {
6153 if (o.name != "" && o.email1 != "")
6155 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6156 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6160 * Returns a new instance ID, 0-index
6162 getNewInstanceId : function() {
6163 this.currentInstanceId = this.currentInstanceId + 1;
6164 return this.currentInstanceId;
6168 * 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.
6170 loadAttachments : function(result) {
6171 var idx = SE.composeLayout.currentInstanceId;
6173 if(typeof(result) == 'object') {
6174 //jchi #20680. Clean the former template attachments;
6175 var basket = document.getElementById('addedTemplateAttachments' + idx);
6176 if(basket.innerHTML != ''){
6177 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6179 basket.innerHTML = '';
6184 if(typeof result[i] == 'object') {
6185 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6186 var bean = result[i];
6187 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6188 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6195 * fills drop-down values for email templates and signatures
6197 setComposeOptions : function(idx) {
6198 // send from accounts
6199 var addressFrom = document.getElementById('addressFrom' + idx);
6201 if (addressFrom.options.length <= 0) {
6202 SE.util.emptySelectOptions(addressFrom);
6203 var fromAccountOpts = SE.composeLayout.fromAccounts;
6204 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6205 var key = fromAccountOpts[id].value;
6206 var display = fromAccountOpts[id].text;
6207 var is_default = false;
6208 if(key == SUGAR.default_inbound_accnt_id)
6210 var opt = new Option(display, key);
6211 addressFrom.options.add(opt);
6212 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6217 var et = document.getElementById('email_template' + idx);
6218 SE.util.emptySelectOptions(et);
6220 for(var key in this.emailTemplates) { // iterate through assoc array
6221 var display = this.emailTemplates[key];
6222 var opt = new Option(display, key);
6223 et.options.add(opt);
6227 var sigs = document.getElementById('signatures' + idx);
6228 SE.util.emptySelectOptions(sigs);
6230 for(var key in this.signatures) { // iterate through assoc array
6231 var display = this.signatures[key];
6232 var opt = new Option(display, key);
6234 if(key == SE.userPrefs.signatures.signature_default) {
6235 opt.selected = true;
6238 sigs.options.add(opt);
6241 // html/plain email?
6242 var htmlEmail = document.getElementById('setEditor' + idx);
6243 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6244 htmlEmail.checked = true;
6246 htmlEmail.checked = false;
6249 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6253 * After compose screen is rendered, async call to get email body from Sugar
6255 replyForwardEmailStage2 : function() {
6256 SE.util.clearHiddenFieldValues('emailUIForm');
6257 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6259 var ieId = SE.composeLayout.replyForwardObj.ieId;
6260 var uid = SE.composeLayout.replyForwardObj.uid;
6261 var mbox = SE.composeLayout.replyForwardObj.mbox;
6262 var type = SE.composeLayout.replyForwardObj.type;
6263 var idx = SE.composeLayout.currentInstanceId;
6265 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6267 document.getElementById('emailSubject' + idx).value = type;
6268 document.getElementById('emailUIAction').value = 'composeEmail';
6269 document.getElementById('composeType').value = type;
6270 document.getElementById('ieId').value = ieId;
6271 document.getElementById('uid').value = uid;
6272 document.getElementById('mbox').value = mbox;
6273 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6274 var formObject = document.getElementById('emailUIForm');
6275 YAHOO.util.Connect.setForm(formObject);
6277 var sendType = type;
6278 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6282 * Show the hidden cc or bcc fields
6284 showHiddenAddress: function(addrType,idx){
6286 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6287 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6288 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6289 this[addrType+'Hidden'+idx] = false;
6291 //After bcc or cc is added, move options below last addr field
6292 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6294 //If both cc and bcc hidden, remove the empty row containing text.
6295 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6296 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6297 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6299 // SE.composeLayout.resizeEditor(idx);
6302 * Hide the cc and bcc fields if they were shown.
6304 hideHiddenAddresses: function(idx){
6306 var addrTypes = ['cc','bcc'];
6307 for(var i = 0;i<addrTypes.length;i++)
6309 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6310 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6311 this[addrTypes[i] + 'Hidden'+idx] = true
6314 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6315 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6316 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6320 //// END SE.composeLayout
6321 ///////////////////////////////////////////////////////////////////////////////
6322 ///////////////////////////////////////////////////////////////////////////////
6326 * Cleans serialized UID lists of duplicates
6330 cleanUids : function(str) {
6331 var seen = new Object();
6333 var arr = new String(str).split(",");
6335 for(var i=0; i<arr.length; i++) {
6340 clean += (clean != "") ? "," : "";
6342 seen[arr[i]] = true;
6349 * Clears hidden field values
6350 * @param string id ID of form element to clear
6352 clearHiddenFieldValues : function(id) {
6353 var form = document.getElementById(id);
6355 for(i=0; i<form.elements.length; i++) {
6356 if(form.elements[i].type == 'hidden') {
6357 var e = form.elements[i];
6358 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6366 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6368 emptySelectOptions : function(el) {
6370 for(i=el.childNodes.length - 1; i >= 0; i--) {
6371 if(el.childNodes[i]) {
6372 el.removeChild(el.childNodes[i]);
6379 * Returns the MBOX path in the manner php_imap expects:
6380 * ie: INBOX.DEBUG.test
6381 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6383 generateMboxPath : function(str) {
6384 var ex = str.split("::");
6386 /* we have a serialized MBOX path */
6390 for(var i=0; i<ex.length; i++) {
6391 if(ex[i] == 'INBOX') {
6403 /* we have a Sugar folder GUID - do nothing */
6411 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6412 * @param HTMLElement el
6413 * @return string GUID of found element or empty on failure
6415 getGuidFromElement : function(el) {
6421 for(var i=0; i<iterations; i++) {
6423 if(el.id.match(SE.reGUID)) {
6435 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6438 getPanelId : function() {
6439 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6443 * wrapper to handle weirdness with IE
6444 * @param string instanceId
6445 * @return tinyMCE Controller object
6447 getTiny : function(instanceId) {
6448 if(instanceId == '') {
6452 var t = tinyMCE.getInstanceById(instanceId);
6456 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6462 * Simple check for MSIE browser
6466 var nav = new String(navigator.appVersion);
6467 if(nav.match(/MSIE/)) {
6474 * Recursively removes an element from the DOM
6475 * @param HTMLElement
6477 removeElementRecursive : function(el) {
6478 this.emptySelectOptions(el);
6485 sleep : function(secs) {
6486 setTimeout("void(0);", secs);
6490 * Converts a <select> element to an Ext.form.combobox
6492 convertSelect : function(select) {
6493 alert('in convertSelect');
6494 if (typeof(select) == "string") {
6495 select = document.getElementById(select);
6499 findChildNode : function (parent, property, value) {
6500 for (i in parent.children) {
6501 var child = parent.children[i];
6502 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6504 var searchChild = SE.util.findChildNode(child, property, value);
6511 cascadeNodes : function (parent, fn, scope, args) {
6512 for (i in parent.children) {
6513 var child = parent.children[i];
6514 var s = scope ? scope : child;
6515 var a = args ? args : child;
6517 SE.util.cascadeNodes(child, fn, scope, args);
6524 ///////////////////////////////////////////////////////////////////////////////
6527 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6529 /*********************************************************************************
6530 * SugarCRM Community Edition is a customer relationship management program developed by
6531 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6533 * This program is free software; you can redistribute it and/or modify it under
6534 * the terms of the GNU Affero General Public License version 3 as published by the
6535 * Free Software Foundation with the addition of the following permission added
6536 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6537 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6538 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6540 * This program is distributed in the hope that it will be useful, but WITHOUT
6541 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6542 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6545 * You should have received a copy of the GNU Affero General Public License along with
6546 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6547 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6550 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6551 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6553 * The interactive user interfaces in modified source and object code versions
6554 * of this program must display Appropriate Legal Notices, as required under
6555 * Section 5 of the GNU Affero General Public License version 3.
6557 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6558 * these Appropriate Legal Notices must retain the display of the "Powered by
6559 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6560 * technical reasons, the Appropriate Legal Notices must display the words
6561 * "Powered by SugarCRM".
6562 ********************************************************************************/
6565 if (typeof console == "undefined")
6566 console = { log: function(o) {alert(o)} };
6570 currentRequestObject : null,
6571 //timeout : 30000, // 30 second timeout default
6572 timeout : 9999999999, // 30 second timeout default
6574 trail : new Array(),
6578 _reset : function() {
6579 this.timeout = 30000;
6580 this.forceAbort = false;
6583 folderRenameCleanup : function() {
6584 SUGAR.email2.folders.setSugarFolders();
6587 fullSyncCleanup : function(o) {
6588 this.folders.checkMailCleanup(o);
6589 SUGAR.email2.settings.settingsDialog.hide();
6594 composeCache : function(o) {
6595 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6596 // get email templates and user signatures
6597 var ret = YAHOO.lang.JSON.parse(o.responseText);
6599 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6600 SUGAR.email2.composeLayout.signatures = ret.signatures;
6601 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6603 SUGAR.email2.composeLayout.setComposeOptions(idx);
6605 //Set the error array so we can notify the user when they try to hit send if any errors
6606 //are present. We will also notify them now (after hitting compose button).
6607 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6610 //if error element is returning an array, then check the length to make sure we have error messages
6611 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6612 //add error messages for display
6613 for(i in ret.errorArray)
6614 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6615 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6616 //if error element is returning an object, and the object value is not empty or null, then display error message
6617 for(i in ret.errorArray)
6618 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6621 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6623 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6625 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6631 handleDeleteSignature : function(o) {
6632 SUGAR.hideMessageBox();
6633 var ret = YAHOO.lang.JSON.parse(o.responseText);
6634 SUGAR.email2.composeLayout.signatures = ret.signatures;
6635 var field = document.getElementById('signature_id');
6636 SUGAR.email2.util.emptySelectOptions(field);
6638 for(var i in ret.signatures) { // iterate through assoc array
6639 var opt = new Option(ret.signatures[i], i);
6640 field.options.add(opt);
6642 setSigEditButtonVisibility();
6647 handleDeleteReturn : function(o) {
6648 // force refresh ListView
6649 SUGAR.hideMessageBox();
6650 if(document.getElementById('focusEmailMbox')) {
6651 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6654 // need to display success message before calling next async call?
6655 document.getElementById(this.target).innerHTML = o.responseText;
6660 handleFailure : function(o) {
6662 SUGAR.showMessageBox('Exception occurred...', o.statusText, 'alert');
6663 if(document.getElementById('saveButton')) {
6664 document.getElementById('saveButton').disabled = false;
6668 handleReplyForward : function(o) {
6669 var a = YAHOO.lang.JSON.parse(o.responseText);
6671 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6673 document.getElementById('email_id' + idx).value = a.uid;
6674 document.getElementById('emailSubject' + idx).value = a.name;
6675 document.getElementById('addressTO' + idx).value = a.from;
6676 document.getElementById('uid' + idx).value = a.uid;
6678 document.getElementById('addressCC' + idx).value = a.cc;
6679 SE.composeLayout.showHiddenAddress('cc', idx);
6683 document.getElementById('type' + idx).value = a.type;
6686 // apply attachment values
6687 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6689 setTimeout("callbackReplyForward.finish(globalA);", 500);
6692 handleReplyForwardForDraft : function(o) {
6693 var a = YAHOO.lang.JSON.parse(o.responseText);
6695 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6697 document.getElementById('email_id' + idx).value = a.uid;
6698 document.getElementById('emailSubject' + idx).value = a.name;
6699 document.getElementById('addressTO' + idx).value = a.to;
6702 document.getElementById('addressCC' + idx).value = a.cc;
6703 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6707 document.getElementById('addressBCC' + idx).value = a.bcc;
6708 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6713 document.getElementById('type' + idx).value = a.type;
6717 // apply attachment values
6718 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6720 setTimeout("callbackReplyForward.finish(globalA);", 500);
6725 handleSuccess : function(o) {
6726 document.getElementById(this.target).innerHTML = o.responseText;
6727 SUGAR.hideMessageBox();
6732 ieDeleteSuccess : function(o) {
6733 SUGAR.hideMessageBox();
6734 SUGAR.email2.accounts.refreshInboundAccountTable();
6735 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6736 SUGAR.email2.accounts.rebuildFolderList();
6741 ieSaveSuccess : function(o) {
6742 document.getElementById('saveButton').disabled = false;
6743 var a = YAHOO.lang.JSON.parse(o.responseText);
6746 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6747 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6749 resp = YAHOO.lang.JSON.parse(o.responseText);
6750 SUGAR.email2.accounts.refreshInboundAccountTable();
6751 SUGAR.email2.accounts.refreshOuboundAccountTable();
6752 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6753 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6756 SUGAR.hideMessageBox();
6757 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6764 loadAttachments : function(o) {
6765 var result = YAHOO.lang.JSON.parse(o.responseText);
6767 SUGAR.email2.composeLayout.loadAttachments(result);
6772 loadSignature : function(o) {
6773 var ret = YAHOO.lang.JSON.parse(o.responseText);
6774 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6775 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6779 * Follow up to mark email read|unread|flagged
6781 markEmailCleanup : function(o) {
6782 var ret = YAHOO.lang.JSON.parse(o.responseText);
6783 if (!ret['status']) {
6784 SUGAR.hideMessageBox();
6785 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6787 SUGAR.email2.contextMenus.markEmailCleanup();
6793 rebuildShowFolders : function(o) {
6794 var t = YAHOO.lang.JSON.parse(o.responseText);
6795 var show = document.getElementById('ieAccountListShow');
6797 SUGAR.email2.util.emptySelectOptions(show);
6799 for(i=0; i<t.length; i++) { // iterate through assoc array
6800 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6801 opt.selected = t[i].selected;
6802 show.options.add(opt);
6805 SUGAR.email2.accounts.renderTree();
6809 saveListViewSortOrderPart2 : function() {
6810 // create the JSON string the func expects
6811 focusFolderPath = '[ "Home", "' + ieName + '"';
6813 var f = new String(focusFolder);
6814 var fEx = f.split('.');
6816 for(i=0; i<fEx.length; i++) {
6817 focusFolderPath += ', "' + fEx[i] +'"'
6820 focusFolderPath += ']';
6822 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6823 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6829 sendEmailCleanUp : function(o) {
6831 SUGAR.hideMessageBox();
6834 ret = YAHOO.lang.JSON.parse(o.responseText);
6835 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6836 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6838 if (o.responseText) {
6839 SUGAR.showMessageBox(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6841 // Else we have an error here.
6844 if (typeof(SE.grid) != 'undefined')
6845 SE.listView.refreshGrid();
6846 //Disabled while address book is disabled
6848 //If this call back was initiated by quick compose from a Detail View page, refresh the
6849 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6850 //close the shortcut bar menu
6851 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6852 if(action_sugar_grp1 == 'DetailView') {
6853 showSubPanel('history',null,true);
6854 } else if(action_sugar_grp1 == 'quickcreate') {
6855 closeEmailOverlay();
6861 ieSendSuccess : function(o) {
6862 SUGAR.hideMessageBox();
6863 SUGAR.showMessageBox(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6868 settingsFolderRefresh : function(o) {
6869 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6870 var ret = YAHOO.lang.JSON.parse(o.responseText);
6871 var user = document.getElementById('userFolders');
6873 SUGAR.email2.util.emptySelectOptions(user);
6875 for(i=0; i<ret.userFolders.length; i++) {
6876 var display = ret.userFolders[i].name;
6877 var value = ret.userFolders[i].id;
6878 var selected = (ret.userFolders[i].selected != "") ? true : false;
6879 var opt = new Option(display, value, selected);
6880 opt.selected = selected;
6881 user.options.add(opt);
6887 startRequest : function(callback, args, forceAbort) {
6888 if(this.currentRequestObject != null) {
6889 if(this.forceAbort == true) {
6890 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6893 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6897 requestInProgress : function() {
6898 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6903 updateFolderSubscriptions : function() {
6904 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6905 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6906 SUGAR.hideMessageBox();
6911 updateFrameFolder : function() {
6912 SUGAR.email2.folders.checkEmailAccounts();
6917 updateUserPrefs : function(o) {
6918 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
6919 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6924 uploadAttachmentSuccessful : function(o) {
6926 document.getElementById('email_attachment').value = '';
6928 var ret = YAHOO.lang.JSON.parse(o.responseText);
6929 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6930 var overall = document.getElementById('addedFiles' + idx);
6931 var index = overall.childNodes.length;
6933 "<div id='email_attachment_bucket" + idx + index + "'>" +
6935 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6936 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6937 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6939 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6940 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6942 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6944 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6947 overall.innerHTML += out;
6948 if(SUGAR.email2.util.isIe()) {
6949 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6953 SUGAR.email2.addFileDialog.hide();
6954 // focus attachments
6955 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6960 ///////////////////////////////////////////////////////////////////////////
6961 //// PER MODULE CALLBACK OBJECTS
6962 AjaxObject.accounts = {
6963 saveOutboundCleanup : function(o) {
6964 SUGAR.email2.accounts.refreshOuboundAccountTable();
6965 SUGAR.email2.accounts.outboundDialog.hide();
6966 var id = o.responseText;
6967 SUGAR.email2.accounts.newAddedOutboundId = id;
6969 saveDefaultOutboundCleanup: function(o){
6972 callbackEditOutbound : {
6973 success : function(o)
6975 var ret = YAHOO.lang.JSON.parse(o.responseText);
6977 SUGAR.email2.accounts.showAddSmtp();
6980 document.getElementById("mail_id").value = ret.id;
6981 document.getElementById("type").value = ret.type;
6982 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6983 document.getElementById("mail_name").value = ret.name;
6984 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6985 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6986 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6987 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6988 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6989 SUGAR.email2.accounts.smtp_authenticate_field_display();
6990 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6992 if(ret.type == 'system-override') {
6993 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6994 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6997 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6998 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
7000 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
7003 failure : AjaxObject.handleFailure,
7004 timeout : AjaxObject.timeout,
7007 callbackDeleteOutbound : {
7008 success : function(o) {
7009 var ret = YAHOO.lang.JSON.parse(o.responseText);
7012 if(confirm(ret.error_message))
7014 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
7015 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
7018 SUGAR.hideMessageBox();
7022 SUGAR.hideMessageBox();
7023 SUGAR.email2.accounts.refreshOuboundAccountTable();
7027 failure : AjaxObject.handleFailure,
7028 timeout : AjaxObject.timeout,
7032 callbackCheckMailProgress : {
7033 success : function(o) {
7034 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
7035 SUGAR.email2.accounts.totalMsgCount = -1;
7038 //Check for server timeout / errors
7039 var ret = YAHOO.lang.JSON.parse(o.responseText);
7042 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
7043 SUGAR.hideMessageBox();
7044 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7045 SUGAR.email2.accounts.totalMsgCount = -1;
7046 //SUGAR.email2.folders.rebuildFolders();
7050 var currIeId = ret['ieid'];
7053 var serverCount = ret.count;
7055 if (ret['status'] == 'done') {
7056 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7057 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7061 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7062 //Go to next account
7063 currIeId = SUGAR.email2.accounts.ieIds[i+1];
7065 SUGAR.email2.accounts.totalMsgCount = -1;
7070 else if (ret.mbox && ret.totalcount && ret.count) {
7071 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7072 if (ret.count >= ret.totalcount) {
7075 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7076 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7078 SUGAR.hideMessageBox();
7079 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7080 SUGAR.email2.accounts.totalMsgCount = -1;
7085 SUGAR.email2.accounts.totalMsgCount = -1;
7086 SUGAR.hideMessageBox();
7087 SUGAR.email2.folders.rebuildFolders();
7088 SE.listView.refreshGrid();
7089 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7090 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7091 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7092 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7094 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7095 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7096 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7097 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7098 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7101 failure : AjaxObject.handleFailure,
7102 timeout : AjaxObject.timeout,
7107 ///////////////////////////////////////////////////////////////////////////////
7109 AjaxObject.composeLayout = {
7111 * Populates the record id
7113 saveDraftCleanup : function(o) {
7115 SUGAR.hideMessageBox();
7118 ret = YAHOO.lang.JSON.parse(o.responseText);
7119 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7121 if (o.responseText) {
7122 SUGAR.showMessageBox(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7128 AjaxObject.composeLayout.callback = {
7130 success : AjaxObject.composeLayout.saveDraftCleanup,
7131 failure : AjaxObject.handleFailure,
7132 timeout : AjaxObject.timeout,
7137 AjaxObject.detailView = {
7139 * Pops-up a printable view of an email
7141 displayPrintable : function(o) {
7142 var ret = YAHOO.lang.JSON.parse(o.responseText);
7143 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7144 // 2 below must be in global context
7146 meta['panelId'] = SUGAR.email2.util.getPanelId();
7147 email = ret.meta.email;
7148 if (typeof(email.cc) == 'undefined') {
7152 var out = displayTemplate.exec({
7153 'app_strings' : app_strings,
7157 'email' : meta.email
7160 // open popup window
7161 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7162 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7164 popup.document.write(out);
7165 popup.document.close();
7169 * Takes formatted response and creates a modal pop-over containing a title and content
7171 displayView : function(o) {
7172 var SED = SUGAR.email2.detailView;
7173 var ret = YAHOO.lang.JSON.parse(o.responseText);
7175 if(!SED.viewDialog) {
7176 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7180 constraintoviewport: true,
7183 SED.viewDialog.renderEvent.subscribe(function() {
7184 var content = this.body.firstChild;
7185 var viewH = YAHOO.util.Dom.getViewportHeight();
7187 this.body.style.overflow = "auto";
7188 this.body.style.width = "800px";
7189 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7193 SED.viewDialog.setHeader(ret.title);
7194 SED.viewDialog.setBody(ret.html);
7195 SED.viewDialog.render();
7196 SED.viewDialog.show();
7200 * Generates a modal popup to populate with the contents of bean's full EditView
7202 showQuickCreateForm : function(o) {
7203 var SED = SUGAR.email2.detailView;
7204 var ret = YAHOO.lang.JSON.parse(o.responseText);
7206 if(!SED.quickCreateDialog) {
7207 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7211 constraintoviewport: true,
7215 SED.quickCreateDialog.renderEvent.subscribe(function() {
7216 var viewH = YAHOO.util.Dom.getViewportHeight();
7218 for (var i in this.body.childNodes) {
7219 if (this.body.childNodes[i].clientHeight) {
7220 contH += this.body.childNodes[i].clientHeight;
7221 } else if (this.body.childNodes[i].offsetHeight) {
7222 contH += this.body.childNodes[i].offsetHeight;
7225 this.body.style.width = "800px";
7226 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7227 this.body.style.overflow = "auto";
7228 }, SED.quickCreateDialog);
7230 SED.quickCreateDialog.hideEvent.subscribe(function(){
7231 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7232 /*for(var qsField in qsFields){
7233 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7234 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7237 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7240 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7242 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7243 SED.quickCreateDialog.render();
7244 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7246 SED.quickCreateDialog.ieId = ret.ieId;
7247 SED.quickCreateDialog.uid = ret.uid;
7248 SED.quickCreateDialog.mbox = ret.mbox;
7249 SED.quickCreateDialog.qcmodule = ret.module;
7251 SED.quickCreateDialog.show();
7253 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7255 editForm.module.value = 'Emails';
7256 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7257 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7258 var instId = ret.module + count;
7259 SED.quickCreateEmailsToAdd = ret.emailAddress;
7260 SED.quickCreateEmailCallback = function(instId, tableId) {
7261 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7262 if (typeof(eaw) == "undefined")
7263 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7264 + instId + "','" + tableId + "');", 100);
7265 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7267 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7268 + instId + "','" + tableId + "');", 100);
7272 saveQuickCreateForm : function(o) {
7273 SUGAR.hideMessageBox();
7274 SUGAR.email2.detailView.quickCreateDialog.hide();
7275 validate['EditView'] = [ ];
7278 saveQuickCreateFormAndReply : function(o) {
7279 SUGAR.hideMessageBox();
7280 var ret = YAHOO.lang.JSON.parse(o.responseText);
7281 SUGAR.email2.detailView.quickCreateDialog.hide();
7282 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7283 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7285 var emailID = ret.id;
7286 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7288 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7290 //Cean the validate cache to prevent errors on the next call
7291 validate['EditView'] = [ ];
7294 saveQuickCreateFormAndAddToAddressBook : function(o) {
7295 SUGAR.hideMessageBox();
7296 SUGAR.email2.detailView.quickCreateDialog.hide();
7297 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7298 validate['EditView'] = [ ];
7301 handleAssignmentDialogAssignAction : function() {
7304 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7306 var dist = 'direct';
7310 var found_teams = false;
7311 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7312 if(!found_teams && assign_user_id == '' )
7314 alert(warning_message);
7318 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7320 for(i=0; i<emailUids.length; i++) {
7322 uids += app_strings.LBL_EMAIL_DELIMITER;
7324 uids += emailUids[i];
7327 var row = SUGAR.email2.grid.getSelectedRows()[0];
7328 var data = SUGAR.email2.grid.getRecord(row).getData();
7329 var ieid = data.ieId;
7330 var mbox = data.mbox;
7331 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7332 SUGAR.email2.contextMenus.assignToDialogue.hide();
7333 SUGAR.showMessageBox('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7337 handleAssignmentDialogDeleteAction : function() {
7338 // TO pass list of UIDS/emailIds
7339 var uids = SUGAR.email2.listView.getUidsFromSelection();
7340 var row = SUGAR.email2.grid.getSelections()[0];
7341 var ieid = row.data.ieId;
7342 var mbox = row.data.mbox;
7343 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7344 SUGAR.email2.contextMenus.assignmentDialog.hide();
7345 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7351 showEmailDetailView : function(o) {
7352 SUGAR.hideMessageBox();
7353 var SED = SUGAR.email2.detailView;
7354 var ret = YAHOO.lang.JSON.parse(o.responseText);
7356 if(!SED.quickCreateDialog) {
7357 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7361 constraintoviewport: true,
7363 autofillheight: "body",
7366 SED.quickCreateDialog.renderEvent.subscribe(function() {
7367 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7369 for (var i in this.body.childNodes) {
7370 if (this.body.childNodes[i].offsetHeight)
7371 contH += this.body.childNodes[i].offsetHeight;
7373 this.body.style.overflow = "auto";
7374 this.body.style.width = "800px";
7375 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7377 }, SED.quickCreateDialog);
7379 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7380 SED.quickCreateDialog.setBody(ret.html);
7381 SED.quickCreateDialog.render();
7382 SUGAR.util.evalScript(ret.html);
7383 SED.quickCreateDialog.show();
7386 showAssignmentDialogWithData : function(o) {
7387 var SEC = SUGAR.email2.contextMenus;
7388 SUGAR.hideMessageBox();
7389 var ret = YAHOO.lang.JSON.parse(o.responseText);
7390 if (!SEC.assignmentDialog) {
7391 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7394 constraintoviewport: true,
7397 SEC.assignmentDialog.setBody("");
7398 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7399 SEC.assignmentDialog.renderEvent.subscribe(function() {
7400 var iev = YAHOO.util.Dom.get("Distribute");
7402 this.body.style.width = "700px";
7404 }, SEC.assignmentDialog);
7405 SEC.assignmentDialog.render();
7407 SEC.assignmentDialog.setBody(ret);
7408 SEC.assignmentDialog.render();
7410 SEC.assignmentDialog.show();
7411 SUGAR.util.evalScript(ret);
7414 showImportForm : function(o) {
7415 var SED = SUGAR.email2.detailView;
7416 var ret = YAHOO.lang.JSON.parse(o.responseText);
7418 document.getElementById('quickCreateContent').innerHTML = "";
7419 SUGAR.hideMessageBox();
7424 if(!SED.importDialog) {
7425 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7429 constraintoviewport: true,
7431 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7432 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7436 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7437 SED.importDialog.setBody("");
7438 SED.importDialog.hideEvent.subscribe(function(){
7439 for(var i in QSFieldsArray) {
7440 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7441 QSFieldsArray[i].destroy();
7442 delete QSFieldsArray[i];
7444 if (QSProcessedFieldsArray[i]) {
7445 QSProcessedFieldsArray[i] = false;
7449 SED.importDialog.renderEvent.subscribe(function() {
7450 var iev = YAHOO.util.Dom.get("ImportEditView");
7452 //this.body.style.height = (iev.clientHeight + 10) + "px";
7453 this.body.style.width = "600px";
7455 }, SED.importDialog);
7456 SED.importDialog.render();
7458 SED.importDialog.setBody(ret.html);
7459 SED.importDialog.ret = ret;
7460 SUGAR.util.evalScript(ret.html);
7461 SED.importDialog.render();
7463 SED.importDialog.show();
7464 SED.importDialog.focusFirstButton();
7466 getImportAction : function(ret) {
7467 if (!check_form('ImportEditView')) return false;
7468 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7469 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7473 var editView = document.getElementById('ImportEditView');
7474 if (editView.assigned_user_id != null) {
7475 get = get + "&user_id=" + editView.assigned_user_id.value
7476 //var user_id = editView.assigned_user_id.value;
7478 var parent_id = editView.parent_id.value;
7479 var parent_type = editView.parent_type.value;
7480 var row = SUGAR.email2.grid.getSelectedRows()[0];
7481 row = SUGAR.email2.grid.getRecord(row);
7482 var data = row.getData();
7483 var ieId = data.ieId;
7484 var mbox = data.mbox;
7485 var serverDelete = editView.serverDelete.checked;
7486 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7488 for(i=0; i<emailUids.length; i++) {
7490 uids += app_strings.LBL_EMAIL_DELIMITER;
7492 uids += emailUids[i];
7495 var action = 'importEmail&uid=';
7497 action = 'moveEmails';
7498 action = action + '&sourceFolder=' + ret['srcFolder'];
7499 action = action + '&sourceIeId=' + ret['srcIeId'];
7500 action = action + '&destinationFolder=' + ret['dstFolder'];
7501 action = action + '&destinationIeId=' + ret['dstIeId'];
7502 action = action + '&emailUids=';
7504 if (action.search(/importEmail/) != -1) {
7505 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7507 SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7510 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7511 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7512 SUGAR.email2.detailView.importDialog.hide();
7513 document.getElementById('importDialogContent').innerHTML = "";
7516 showRelateForm : function(o) {
7517 var SED = SUGAR.email2.detailView;
7518 var ret = YAHOO.lang.JSON.parse(o.responseText);
7519 document.getElementById('quickCreateContent').innerHTML = "";
7520 SUGAR.hideMessageBox();
7524 dialog_loaded = true;
7526 if(!SED.relateDialog) {
7527 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7532 constraintoviewport: true,
7534 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7535 if (!check_form('RelateEditView')) return false;
7537 var editView = document.getElementById('RelateEditView');
7538 var parent_id = editView.parent_id.value;
7539 var parent_type = editView.parent_type.value;
7540 var row = SUGAR.email2.grid.getSelectedRows()[0];
7541 row = SUGAR.email2.grid.getRecord(row);
7542 var ieId = row.getData().ieId;
7543 var mbox = row.getData().mbox;
7544 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7546 for(i=0; i<emailUids.length; i++) {
7548 uids += app_strings.LBL_EMAIL_DELIMITER;
7550 uids += emailUids[i];
7552 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7553 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7554 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7555 SED.relateDialog.hide();
7556 document.getElementById('relateDialogContent').innerHTML = "";
7561 SED.relateDialog.hideEvent.subscribe(function(){
7562 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7563 QSFieldsArray['ImportEditView_parent_name'].destroy();
7564 delete QSFieldsArray['ImportEditView_parent_name'];
7566 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7567 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7571 SED.relateDialog.renderEvent.subscribe(function() {
7572 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7574 for (var i in this.body.childNodes) {
7575 if (this.body.childNodes[i].clientHeight)
7576 contH += this.body.childNodes[i].clientHeight;
7578 }, SED.relateDialog);
7579 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7582 SED.relateDialog.setBody(ret.html);
7583 SED.relateDialog.render();
7584 SUGAR.util.evalScript(ret.html);
7585 SED.relateDialog.show();
7589 * DetailView callbacks
7591 AjaxObject.detailView.callback = {
7593 success : function(o) {
7595 var ret = YAHOO.lang.JSON.parse(o.responseText);
7596 SUGAR.email2.detailView.consumeMetaDetail(ret);
7598 argument: [targetDiv],
7599 failure : AjaxObject.handleFailure,
7604 success : function(o) {
7606 var ret = YAHOO.lang.JSON.parse(o.responseText);
7607 SUGAR.email2.detailView.consumeMetaPreview(ret);
7609 failure : AjaxObject.handleFailure,
7614 success : AjaxObject.detailView.displayPrintable,
7615 failure : AjaxObject.handleFailure,
7616 timeout : AjaxObject.timeout,
7620 success : AjaxObject.detailView.displayView,
7621 failure : AjaxObject.handleFailure,
7622 timeout : AjaxObject.timeout,
7631 AjaxObject.folders = {
7633 * check-mail post actions
7635 checkMailCleanup : function(o) {
7636 SUGAR.hideMessageBox();
7637 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7639 // refresh focus ListView
7640 SE.listView.refreshGrid();
7641 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7646 rebuildFolders : function(o) {
7647 SUGAR.hideMessageBox();
7649 var data = YAHOO.lang.JSON.parse(o.responseText);
7651 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7652 SUGAR.email2.folders.setSugarFolders();
7655 AjaxObject.folders.callback = {
7657 success : AjaxObject.folders.checkMailCleanup,
7658 failure : AjaxObject.handleFailure,
7659 timeout : 600000, // 5 mins
7664 AjaxObject.rules = {
7665 loadRulesForSettings : function(o) {
7666 document.getElementById("rulesListCell").innerHTML = o.responseText;
7667 // assume we have the class we need
7668 SUGAR.routing.getStrings();
7669 SUGAR.routing.getDependentDropdowns();
7672 //// END PER MODULE CALLBACK OBJECTS
7673 ///////////////////////////////////////////////////////////////////////////
7677 success : AjaxObject.handleSuccess,
7678 failure : AjaxObject.handleFailure,
7679 timeout : AjaxObject.timeout,
7682 var callbackAccount = {
7683 success : AjaxObject.ieSaveSuccess,
7684 failure : AjaxObject.handleFailure,
7685 timeout : AjaxObject.timeout,
7688 var callbackAccountDelete = {
7689 success : AjaxObject.ieDeleteSuccess,
7690 failure : AjaxObject.handleFailure,
7691 timeout : AjaxObject.timeout,
7694 var callbackOutboundTest = {
7695 success : AjaxObject.ieSendSuccess,
7696 failure : AjaxObject.handleFailure,
7697 timeout : AjaxObject.timeout,
7703 var callbackTeamInfoForSettings = {
7704 success : function (o) {
7705 var data = YAHOO.lang.JSON.parse(o.responseText);
7706 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7708 failure : AjaxObject.handleFailure,
7709 timeout : AjaxObject.timeout,
7714 var callbackStatusForImport = {
7715 success : function (o) {
7716 SUGAR.hideMessageBox();
7717 if (o.responseText != "") {
7718 var statusString = "";
7719 var data = YAHOO.lang.JSON.parse(o.responseText);
7720 for(i=0; i<data.length; i++) {
7721 statusString = statusString + data[i] + '<br/>';
7723 SUGAR.showMessageBox(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7725 SE.listView.refreshGrid();
7728 failure : AjaxObject.handleFailure,
7729 timeout : AjaxObject.timeout,
7733 var callbackComposeCache = {
7734 success : AjaxObject.composeCache,
7735 failure : AjaxObject.handleFailure,
7736 timeout : AjaxObject.timeout,
7739 var callbackDelete = {
7740 success : AjaxObject.handleDeleteReturn,
7741 failure : AjaxObject.handleFailure,
7742 timeout : AjaxObject.timeout,
7745 var callbackEmailDetailMultiple = {
7746 success : function(o) {
7747 SUGAR.hideMessageBox();
7748 var retMulti = YAHOO.lang.JSON.parse(o.responseText);
7749 var ret = new Object();
7751 for(var i=0; i<retMulti.length; i++) {
7754 SUGAR.email2._setDetailCache(ret);
7755 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7758 failure : AjaxObject.handleFailure,
7762 var callbackListViewSortOrderChange = {
7763 success : AjaxObject.saveListViewSortOrderPart2,
7764 failure : AjaxObject.handleFailure,
7765 timeout : AjaxObject.timeout,
7767 argument : [ieId, ieName, focusFolder]
7769 var callbackEmptyTrash = {
7770 success : function(o) {
7771 SUGAR.hideMessageBox();
7772 AjaxObject.folderRenameCleanup;
7774 failure : AjaxObject.handleFailure,
7775 timeout : AjaxObject.timeout,
7778 var callbackClearCacheFiles = {
7779 success : function(o) {
7780 SUGAR.hideMessageBox();
7782 failure : AjaxObject.handleFailure,
7783 timeout : AjaxObject.timeout,
7786 var callbackFolderRename = {
7787 success : function(o) {SUGAR.hideMessageBox();SUGAR.email2.folders.rebuildFolders();},
7788 failure : AjaxObject.handleFailure,
7789 timeout : AjaxObject.timeout,
7792 var callbackFolderDelete = {
7793 success : function(o) {
7794 var ret = YAHOO.lang.JSON.parse(o.responseText);
7796 if (ret.folder_id) {
7797 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7799 SUGAR.email2.tree.removeNode(node, true);
7800 } else if (ret.ieId && ret.mbox) {
7801 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7803 SUGAR.email2.tree.removeNode(node, true);
7805 SUGAR.hideMessageBox();
7806 //SUGAR.email2.folders.loadSettingFolder();
7808 SUGAR.hideMessageBox();
7809 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7812 failure : AjaxObject.handleFailure,
7813 timeout : AjaxObject.timeout,
7816 var callbackFolderSave = {
7817 success : function(o) {
7818 var ret = YAHOO.lang.JSON.parse(o.responseText);
7820 switch(ret.action) {
7821 case 'newFolderSave':
7822 SUGAR.email2.folders.rebuildFolders();
7826 failure : AjaxObject.handleFailure,
7827 timeout : AjaxObject.timeout,
7830 var callbackFolderSubscriptions = {
7831 success : AjaxObject.updateFolderSubscriptions,
7832 failure : AjaxObject.handleFailure,
7833 timeout : AjaxObject.timeout,
7836 var callbackFolderUpdate = {
7837 success : AjaxObject.updateFrameFolder,
7838 failure : AjaxObject.handleFailure,
7839 timeout : AjaxObject.timeout,
7842 var callbackFolders = {
7843 success : AjaxObject.folders.rebuildFolders,
7844 //success : void(true),
7845 failure : AjaxObject.handleFailure,
7846 timeout : AjaxObject.timeout,
7849 var callbackFullSync = {
7850 success : AjaxObject.fullSyncCleanup,
7851 failure : AjaxObject.handleFailure,
7852 timeout : 9999999999999,
7855 var callbackGeneric = {
7856 success : function() {
7857 SUGAR.hideMessageBox();
7859 failure : AjaxObject.handleFailure,
7860 timeout : AjaxObject.timeout,
7863 var callbackIeAccountRetrieve = {
7864 success : function(o) {
7865 // return JSON encoding
7866 SUGAR.hideMessageBox();
7867 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7868 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7870 failure : AjaxObject.handleFailure,
7871 timeout : AjaxObject.timeout,
7874 var callbackImportOneEmail = {
7875 success : AjaxObject.detailView.showImportForm,
7876 failure : AjaxObject.handleFailure,
7877 timeout : AjaxObject.timeout,
7880 var callbackRelateEmail = {
7881 success : AjaxObject.detailView.showRelateForm,
7882 failure : AjaxObject.handleFailure,
7883 timeout : AjaxObject.timeout,
7886 var callbackEmailDetailView = {
7887 success : AjaxObject.detailView.showEmailDetailView,
7888 failure : AjaxObject.handleFailure,
7889 timeout : AjaxObject.timeout,
7892 var callbackAssignmentDialog = {
7893 success : AjaxObject.detailView.showAssignmentDialogWithData,
7894 failure : AjaxObject.handleFailure,
7895 timeout : AjaxObject.timeout,
7898 var callbackAssignmentAction = {
7899 success : function(o) {
7900 SE.listView.refreshGrid();
7901 SUGAR.hideMessageBox();
7902 if(o.responseText != '') {
7903 SUGAR.showMessageBox('Assignment action result', o.responseText, 'alert');
7906 failure : AjaxObject.handleFailure,
7907 timeout : AjaxObject.timeout,
7910 var callbackMoveEmails = {
7911 success : function(o) {
7912 SE.listView.refreshGrid();
7913 SUGAR.hideMessageBox();
7914 if(o.responseText != '') {
7915 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7918 failure : AjaxObject.handleFailure,
7919 timeout : AjaxObject.timeout,
7922 var callbackLoadAttachments = {
7923 success : AjaxObject.loadAttachments,
7924 failure : AjaxObject.handleFailure,
7925 timeout : AjaxObject.timeout,
7928 var callbackLoadRules = {
7929 success : AjaxObject.rules.loadRulesForSettings,
7930 failure : AjaxObject.handleFailure,
7931 timeout : AjaxObject.timeout,
7934 var callbackLoadSignature = {
7935 success : AjaxObject.loadSignature,
7936 failure : AjaxObject.handleFailure,
7937 timeout : AjaxObject.timeout,
7940 var callbackDeleteSignature = {
7941 success : AjaxObject.handleDeleteSignature,
7942 failure : AjaxObject.handleFailure,
7943 timeout : AjaxObject.timeout,
7946 /*var callbackMoveEmails = {
7947 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7948 failure : AjaxObject.handleFailure,
7949 timeout : AjaxObject.timeout,
7952 var callbackOutboundSave = {
7953 success : AjaxObject.accounts.saveOutboundCleanup,
7954 failure : AjaxObject.handleFailure,
7955 timeout : AjaxObject.timeout,
7958 var callbackDefaultOutboundSave = {
7959 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7960 failure : AjaxObject.handleFailure,
7961 timeout : AjaxObject.timeout,
7964 var callbackQuickCreate = {
7965 success : AjaxObject.detailView.showQuickCreateForm,
7966 failure : AjaxObject.handleFailure,
7967 timeout : AjaxObject.timeout,
7970 var callbackQuickCreateSave = {
7971 success : AjaxObject.detailView.saveQuickCreateForm,
7972 failure : AjaxObject.handleFailure,
7973 timeout : AjaxObject.timeout,
7976 var callbackQuickCreateSaveAndAddToAddressBook = {
7977 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7978 failure : AjaxObject.handleFailure,
7979 timeout : AjaxObject.timeout,
7982 var callbackQuickCreateSaveAndReply = {
7983 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7984 failure : AjaxObject.handleFailure,
7985 timeout : AjaxObject.timeout,
7988 var callbackQuickCreateSaveAndReplyCase = {
7989 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7990 failure : AjaxObject.handleFailure,
7991 timeout : AjaxObject.timeout,
7994 var callbackRebuildShowAccountList = {
7995 success : AjaxObject.rebuildShowFolders,
7996 failure : AjaxObject.handleFailure,
7997 timeout : AjaxObject.timeout,
8001 var callbackRefreshSugarFolders = {
8002 success : function(o) {
8003 var t = YAHOO.lang.JSON.parse(o.responseText);
8004 SUGAR.email2.folders.setSugarFoldersEnd(t);
8006 failure : AjaxObject.handleFailure,
8007 timeout : AjaxObject.timeout,
8010 var callbackReplyForward = {
8011 success : AjaxObject.handleReplyForward,
8012 finish : function(a, retryCount) {
8013 if (typeof(retryCount) == 'undefined') {
8018 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8019 var t = tinyMCE.getInstanceById('htmleditor' + idx);
8021 var html = t.getContent();
8023 html = " <div><hr></div>" + a.description;
8025 t.setContent(html);//
8027 if (a.type != 'draft') {
8028 // Next step, attach signature
8029 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
8033 if (retryCount < 5) {
8034 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
8038 var tabArray = SUGAR.email2.innerLayout.get("tabs");
8039 if (tabArray != null && tabArray.length > 0) {
8040 for (i = 0 ; i < tabArray.length ; i++) {
8041 var tabObject = tabArray[i];
8042 if (tabObject.get("id") == ("composeTab" + idx)) {
8043 var tabLabel = a.name;
8044 if (tabLabel != null && tabLabel.length > 25) {
8045 tabLabel = tabLabel.substring(0, 25) + "...";
8047 tabObject.get("labelEl").firstChild.data = tabLabel;
8053 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8054 if (a.parent_name != null && a.parent_name != "") {
8055 document.getElementById('data_parent_name' + idx).value = a.parent_name;
8057 if (a.parent_type != null && a.parent_type != "") {
8058 document.getElementById('data_parent_type' + idx).value = a.parent_type;
8060 if (a.parent_id != null && a.parent_id != "") {
8061 document.getElementById('data_parent_id' + idx).value = a.parent_id;
8063 if (a.fromAccounts.status) {
8064 var addressFrom = document.getElementById('addressFrom' + idx);
8065 SUGAR.email2.util.emptySelectOptions(addressFrom);
8066 var fromAccountOpts = a.fromAccounts.data;
8067 for(i=0; i<fromAccountOpts.length; i++) {
8068 var key = fromAccountOpts[i].value;
8069 var display = fromAccountOpts[i].text;
8070 var opt = new Option(display, key);
8071 if (fromAccountOpts[i].selected) {
8072 opt.selected = true;
8074 addressFrom.options.add(opt);
8077 SUGAR.hideMessageBox();
8080 failure : AjaxObject.handleFailure,
8081 timeout : AjaxObject.timeout,
8083 argument : [sendType]
8085 var callbackSendEmail = {
8086 success : AjaxObject.sendEmailCleanUp,
8087 failure : AjaxObject.handleFailure,
8088 timeout : AjaxObject.timeout,
8091 var callbackSettings = {
8092 success : AjaxObject.updateUserPrefs,
8093 failure : AjaxObject.handleFailure,
8094 timeout : AjaxObject.timeout,
8097 var callbackSettingsFolderRefresh = {
8098 success : AjaxObject.settingsFolderRefresh,
8099 failure : AjaxObject.handleFailure,
8100 timeout : AjaxObject.timeout,
8103 var callbackLoadSettingFolder = {
8104 success : function(o) {
8105 AjaxObject.settingsFolderRefresh(o);
8106 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8108 failure : AjaxObject.handleFailure,
8109 timeout : AjaxObject.timeout,
8113 var callbackUploadAttachment = {
8114 success : AjaxObject.uploadAttachmentSuccessful,
8115 upload : AjaxObject.uploadAttachmentSuccessful,
8116 failure : AjaxObject.handleFailure,
8117 timeout : AjaxObject.timeout,
8120 var callbackUserPrefs = {
8121 success : function(o) {
8122 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
8124 failure : AjaxObject.handleFailure,
8125 timeout : AjaxObject.timeout,
8129 var callbackContextmenus = {
8131 success : AjaxObject.markEmailCleanup,
8132 failure : AjaxObject.handleFailure,
8133 timeout : AjaxObject.timeout,
8138 var callbackCheckEmail2 = {
8139 success : function(o) {
8140 var ret = YAHOO.lang.JSON.parse(o.responseText);
8141 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8145 failure : AjaxObject.handleFailure,
8146 timeout : AjaxObject.timeout,
8148 }// End of File modules/Emails/javascript/ajax.js
8150 /*********************************************************************************
8151 * SugarCRM Community Edition is a customer relationship management program developed by
8152 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8154 * This program is free software; you can redistribute it and/or modify it under
8155 * the terms of the GNU Affero General Public License version 3 as published by the
8156 * Free Software Foundation with the addition of the following permission added
8157 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8158 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8159 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8161 * This program is distributed in the hope that it will be useful, but WITHOUT
8162 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8163 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8166 * You should have received a copy of the GNU Affero General Public License along with
8167 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8168 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8171 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8172 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8174 * The interactive user interfaces in modified source and object code versions
8175 * of this program must display Appropriate Legal Notices, as required under
8176 * Section 5 of the GNU Affero General Public License version 3.
8178 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8179 * these Appropriate Legal Notices must retain the display of the "Powered by
8180 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8181 * technical reasons, the Appropriate Legal Notices must display the words
8182 * "Powered by SugarCRM".
8183 ********************************************************************************/
8185 function gridInit() {
8186 if(SUGAR.email2.grid) {
8187 SUGAR.email2.grid.destroy();
8193 var Ck = YAHOO.util.Cookie;
8194 var widths = [ 10, 10, 150, 250, 175, 125 ];
8196 if (Ck.get("EmailGridWidths")) {
8197 for (var i=0; i < widths.length; i++) {
8198 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8201 for (var i=0; i < widths.length; i++) {
8202 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8206 // changes "F" to an icon
8207 function flaggedIcon(cell, record, column, value) {
8209 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8212 // changes "A" to replied icon
8213 function repliedIcon(cell, record, column, value) {
8215 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8218 function attachIcon(cell, record, column, value) {
8220 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8227 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8232 formatter: attachIcon,
8236 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8241 formatter: flaggedIcon,
8245 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8250 formatter: repliedIcon,
8254 label: app_strings.LBL_EMAIL_FROM,
8261 label: app_strings.LBL_EMAIL_SUBJECT,
8268 label: mod_strings.LBL_LIST_DATE,
8275 label: app_strings.LBL_EMAIL_TO,
8311 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8312 responseType: YAHOO.util.DataSource.TYPE_JSON,
8314 resultsList: 'Email',
8315 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8316 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8322 action : "EmailUIAjax",
8323 emailUIAction : "getMessageList",
8326 forceRefresh : "false"
8328 if(lazyLoadFolder != null) {
8329 params['mbox'] = lazyLoadFolder.folder;
8330 params['ieId'] = lazyLoadFolder.ieId;
8331 //Check if the folder is a Sugar Folder
8332 var test = new String(lazyLoadFolder.folder);
8333 if(test.match(/SUGAR\./)) {
8334 params['emailUIAction'] = 'getMessageListSugarFolders';
8335 params['mbox'] = test.substr(6);
8338 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8341 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8342 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8344 paginator: new YAHOO.widget.Paginator({
8345 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8346 containers : ["dt-pag-nav"],
8347 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8348 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8349 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8350 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8351 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8353 initialRequest:SUGAR.util.paramsToUrl(params),
8360 //Override Paging request construction
8361 grid.set("generateRequest", function(oState, oSelf) {
8362 oState = oState || {pagination:null, sortedBy:null};
8363 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8364 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8365 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8366 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8367 // Build the request
8369 SUGAR.util.paramsToUrl(oSelf.params) +
8372 "&start=" + startIndex +
8373 ((results !== null) ? "&limit=" + results : "");
8378 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8379 oPayload = oPayload || { };
8381 oPayload.totalRecords = oResponse.meta.total;
8382 oPayload.unreadRecords = oResponse.meta.unread;
8384 var tabObject = SE.innerLayout.get("tabs")[0];
8386 if (this.params.mbox != null) {
8387 mboxTitle = this.params.mbox;
8389 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8390 tabObject.get("labelEl").firstChild.data = tabtext;
8393 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8395 node.data.unseen = oResponse.meta.unread;
8396 SE.accounts.renderTree();
8402 var resize = grid.resizeGrid = function () {
8403 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8404 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8406 grid.convertDDRows = function() {
8407 var rowEl = this.getFirstTrEl();
8408 while (rowEl != null) {
8409 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8410 rowEl = this.getNextTrEl(rowEl);
8415 grid.on("columnResizeEvent", function(o) {
8416 //Find the index of the column
8417 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8418 for (var i=0; i < colSet.length; i++) {
8419 if (o.column == colSet[i]) {
8420 //Store it in the cookie
8421 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8424 //this.resizeGrid();
8427 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8428 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8429 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8431 SUGAR.email2.listViewLayout.on("render", resize);
8434 //Setup the default load parameters
8435 SUGAR.email2.grid.params = params;
8437 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8438 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8439 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8446 function initRowDD() {
8447 var sg = SUGAR.email2.grid,
8448 Dom = YAHOO.util.Dom;
8449 sg.DDRow = function(oDataTable, oRecord, elTr) {
8450 if(oDataTable && oRecord && elTr) {
8451 this.ddtable = oDataTable;
8452 this.table = oDataTable.getTableEl();
8455 this.newIndex = null;
8457 this.initFrame(); // Needed for DDProxy
8458 this.invalidHandleTypes = {};
8462 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8463 _resizeProxy: function() {
8464 this.constructor.superclass._resizeProxy.apply(this, arguments);
8465 var dragEl = this.getDragEl(),
8467 var xy = Dom.getXY(el);
8469 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8470 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8471 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8472 Dom.setStyle(dragEl, 'display', "");
8475 startDrag: function(x, y) {
8476 //Check if we should be dragging a set of rows rather than just the one.
8477 var selectedRows = this.ddtable.getSelectedRows();
8478 var iSelected = false;
8479 for (var i in selectedRows) {
8480 if (this.rowEl.id == selectedRows[i]) {
8487 for (var i in selectedRows) {
8488 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8491 this.rows = [this.row];
8492 this.ddtable.unselectAllRows();
8493 this.ddtable.selectRow(this.row);
8496 //Initialize the dragable proxy
8497 var dragEl = this.getDragEl();
8498 var clickEl = this.getEl();
8499 Dom.setStyle(clickEl, "opacity", "0.25");
8500 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8501 Dom.addClass(dragEl, "yui-dt-liner");
8502 Dom.setStyle(dragEl, "opacity", "0.5");
8503 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8504 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8505 Dom.setStyle(dragEl, "border", "2px solid gray");
8508 clickValidator: function(e) {
8509 if (this.row.getData()[0] == " ")
8511 var target = YAHOO.util.Event.getTarget(e);
8512 return ( this.isValidHandleChild(target) &&
8513 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8516 * This funciton checks that the target of the drag is a table row in this
8517 * DDGroup and simply moves the sourceEL to that location as a preview.
8519 onDragOver: function(ev, id) {
8520 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8521 if (node && node != this.targetNode) {
8522 this.targetNode = node;
8523 SUGAR.email2.folders.unhighliteAll();
8528 onDragOut: function(e, id) {
8529 if (this.targetNode) {
8530 SUGAR.email2.folders.unhighliteAll();
8531 this.targetNode = false;
8534 endDrag: function() {
8535 Dom.setStyle(this.getEl(), "opacity", "");
8536 Dom.setStyle(this.getDragEl(), "display", "none");
8537 if (this.targetNode) {
8538 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8540 SUGAR.email2.folders.unhighliteAll();
8546 function AddressSearchGridInit() {
8547 function moduleIcon(elCell, oRecord, oColumn, oData) {
8548 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8550 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8551 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8553 var checkHeader = '<input type="checkbox" ';
8554 if (SUGAR.email2.util.isIe()) {
8555 checkHeader += 'style="top:-5px" ';
8557 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8562 formatter: selectionCheckBox,
8566 label: mod_strings.LBL_LIST_TYPE,
8568 formatter: moduleIcon,
8572 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8578 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8584 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8585 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8587 resultsList: 'Person',
8588 fields: ['name', 'email', 'bean_id', 'bean_module'],
8589 metaFields: {total: 'TotalCount'}
8591 //enable sorting on the server accross all data
8594 dataModel.params = {
8597 action : "EmailUIAjax",
8598 emailUIAction:"getAddressSearchResults"
8600 var rb = document.getElementById('hasRelatedBean').checked;
8602 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8603 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8604 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8605 dataModel.params['related_bean_id'] = relatedBeanId;
8606 dataModel.params['related_bean_type'] = relatedBeanType;
8607 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8609 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8611 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8612 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8614 paginator: new YAHOO.widget.Paginator({
8616 containers : ["dt-pag-nav-addressbook"],
8617 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8618 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8619 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8620 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8621 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8623 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8627 //Override Paging request construction
8628 grid.set("generateRequest", function(oState, oSelf) {
8629 oState = oState || {pagination:null, sortedBy:null};
8630 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8631 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8632 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8633 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8634 // Build the request
8636 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8637 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8638 ((results !== null) ? "&limit=" + results : "");
8642 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8643 oPayload = oPayload || { };
8644 oPayload.totalRecords = oResponse.meta.total;
8648 grid.clickToggleSelect= function(args) {
8649 var isIE = (args.event.target == null);
8650 var targetElement = isIE ? args.event.srcElement : args.event.target;
8651 if(targetElement.type == null || targetElement.type != 'checkbox') {
8652 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8656 grid.reSelectRowsOnRender = function (){
8657 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8658 for (var i = 0; i < rows.length; i++)
8660 var emailAddress = rows[i].getData("email");
8661 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8664 rows[i].setData("selected", true);
8665 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8669 rows[i].setData("selected", false);
8670 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8674 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8675 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8676 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8677 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8680 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8681 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8683 grid.toggleSelectCheckbox = function(id,checked){
8684 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8685 row.setData("checked",checked);
8687 grid.toggleSelect = function(id, checked) {
8688 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8689 checked = row.getData("selected");
8692 SUGAR.email2.addressBook.grid.selectRow(row);
8693 SE.addressBook.insertContactRowToResultTable(id,null)
8696 SUGAR.email2.addressBook.grid.unselectRow(row);
8697 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8699 row.setData("selected", !checked);
8702 grid.toggleSelectAll = function(checked) {
8703 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8704 for (var i = 0; i < rows.length; i++) {
8705 if (typeof(rows[i]) != "undefined")
8706 rows[i].setData("checked", checked);
8708 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8709 for (var i = 0; i < checkBoxes.length; i++) {
8710 checkBoxes[i].checked = checked;
8714 //Initialize the grid result table.
8715 AddressSearchResultsGridInit();
8721 * Initalize the results table for the address book selection.
8724 function AddressSearchResultsGridInit()
8727 /* Full name sort funciton to compare by last name if available */
8728 var fullNameSort = function(a, b, desc) {
8729 // Deal with empty values
8730 if(!YAHOO.lang.isValue(a))
8731 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8732 else if(!YAHOO.lang.isValue(b))
8735 var aNames = a.getData("name").split(' ');
8736 var bNames = b.getData("name").split(' ');
8738 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8739 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8741 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8745 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8746 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8747 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8749 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})},
8750 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8752 var myDataSource = new YAHOO.util.DataSource([]);
8753 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8754 myDataSource.responseSchema = {
8755 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8758 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8759 width: "350px",height: "250px", MSG_EMPTY: " "});
8761 var highlightEditableCell = function(oArgs) {
8762 var elCell = oArgs.target;
8763 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8764 this.highlightCell(elCell);
8768 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8769 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8770 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8771 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8772 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8774 //Setup the context menus
8775 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8776 var task = p_aArgs[1];
8779 var elRow = this.contextEventTarget;
8780 elRow = p_myDataTable.getTrEl(elRow);
8787 var oRecord = p_myDataTable.getRecord(elRow);
8788 p_myDataTable.deleteRow(elRow);
8789 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8794 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8795 {trigger:gridResults.getTbodyEl()});
8796 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8797 contextMenu.render("addrSearchResultGrid");
8798 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8800 // End of File modules/Emails/javascript/grid.js
8802 /*********************************************************************************
8803 * SugarCRM Community Edition is a customer relationship management program developed by
8804 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8806 * This program is free software; you can redistribute it and/or modify it under
8807 * the terms of the GNU Affero General Public License version 3 as published by the
8808 * Free Software Foundation with the addition of the following permission added
8809 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8810 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8811 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8813 * This program is distributed in the hope that it will be useful, but WITHOUT
8814 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8815 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8818 * You should have received a copy of the GNU Affero General Public License along with
8819 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8820 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8823 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8824 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8826 * The interactive user interfaces in modified source and object code versions
8827 * of this program must display Appropriate Legal Notices, as required under
8828 * Section 5 of the GNU Affero General Public License version 3.
8830 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8831 * these Appropriate Legal Notices must retain the display of the "Powered by
8832 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8833 * technical reasons, the Appropriate Legal Notices must display the words
8834 * "Powered by SugarCRM".
8835 ********************************************************************************/
8838 /******************************************************************************
8839 * Initialize Email 2.0 Application
8842 //Override Sugar Languge so quick creates work properly
8845 function email2init() {
8848 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
8849 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
8850 if (!SUGAR.util.isTouchScreen()) {
8852 convert_urls : false,
8853 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
8854 width: tinyConfig.width,
8855 theme: tinyConfig.theme,
8856 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
8857 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
8858 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
8859 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
8860 plugins : tinyConfig.plugins,
8861 elements : tinyConfig.elements,
8862 language : tinyConfig.language,
8863 extended_valid_elements : tinyConfig.extended_valid_elements,
8864 mode: tinyConfig.mode,
8865 strict_loading_mode : true,
8866 force_br_newlines : true,
8867 forced_root_block : '',
8868 directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
8872 // initialze message overlay
8873 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
8883 if (SUGAR.themes.tempHideLeftCol)
8884 SUGAR.themes.tempHideLeftCol();
8886 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
8887 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
8889 // set defaults for YAHOO.util.DragDropManager
8890 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
8892 SUGAR.email2.nextYear = new Date();
8893 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
8896 // initialize and display UI framework (complexLayout.js)
8897 complexLayoutInit();
8899 // initialize and display grid (grid.js)
8902 // initialize treeview for folders
8904 SUGAR.email2.folders.rebuildFolders(true);
8907 //Setup the Message Box overlay
8908 /*Ext.MessageBox.maxWidth = 350;
8909 Ext.MessageBox.minProgressWidth = 350;
8911 ///////////////////////////////////////////////////////////////////////////
8914 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
8916 var SEC = SUGAR.email2.contextMenus;
8919 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
8920 trigger: SUGAR.email2.grid.get("element"),
8923 emailMenu.subscribe("beforeShow", function() {
8924 var oTarget = this.contextEventTarget;
8925 if (typeof(oTarget) == "undefined")
8927 var grid = SUGAR.email2.grid;
8928 var selectedRows = grid.getSelectedRows();
8929 var multipleSelected = (selectedRows.length > 1) ? true: false;
8930 if (!multipleSelected)
8932 grid.unselectAllRows();
8933 grid.selectRow(oTarget);
8934 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8936 else if(multipleSelected)
8938 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8942 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
8943 //us to access individual elements easier by name rather than by index
8944 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
8945 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
8946 emailMenu.addItems([
8948 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
8949 id: 'showDetailView',
8950 onclick: { fn: SEC.showDetailView }
8953 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
8954 onclick: { fn: SEC.openMultiple }
8957 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
8958 onclick: { fn: SEC.archiveToSugar }
8961 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
8963 onclick: { fn: SEC.replyForwardEmailContext }
8966 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
8968 onclick: { fn: SEC.replyForwardEmailContext }
8971 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
8973 onclick: { fn: SEC.replyForwardEmailContext }
8976 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
8978 onclick: { fn: SEC.markDeleted }
8981 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
8983 onclick: { fn: SEC.viewPrintable }
8987 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
8989 id: "markEmailMenu",
8992 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
8993 onclick: { fn: SEC.markUnread }
8996 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
8997 onclick: { fn: SEC.markRead }
9000 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9001 onclick: { fn: SEC.markFlagged }
9004 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9005 onclick: { fn: SEC.markUnflagged }
9011 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9013 onclick: { fn: SEC.assignEmailsTo }
9016 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9018 onclick: { fn: SEC.relateTo }
9021 SEC.emailListContextMenu.render();
9023 //Handle the Tree folder menu trigger ourselves
9024 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9028 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9032 SEC.frameFoldersContextMenu.addItems([
9033 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9034 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9035 onclick: { fn: function() {
9036 var node = SUGAR.email2.clickedFolderNode;
9037 if (node.data.ieId) {
9038 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9041 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9042 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9043 onclick: { fn: function() {
9044 var node = SUGAR.email2.clickedFolderNode;
9045 if (node.data.ieId) {
9046 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9050 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9051 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9052 onclick: { fn: SUGAR.email2.folders.folderAdd }
9055 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9056 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9057 onclick: { fn: SUGAR.email2.folders.folderDelete }
9060 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9061 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9062 onclick: { fn: SUGAR.email2.folders.folderRename }
9065 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9066 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9067 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9070 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9071 onclick: { fn: function() {
9072 var node = SUGAR.email2.clickedFolderNode;
9073 if (node.data.ieId) {
9074 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9078 SEC.frameFoldersContextMenu.render();
9080 SEC.initContactsMenu = function() {
9082 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9083 trigger: "contacts",
9086 SEC.contactsContextMenu.addItems([
9088 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9089 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9092 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9093 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9096 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9097 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9098 if (oTarget && !grid.isSelected(oTarget)) {
9099 grid.unselectAllRows();
9100 grid.selectRow(oTarget);
9103 SEC.contactsContextMenu.render();
9107 // set auto-check timer
9108 SUGAR.email2.folders.startCheckTimer();
9109 // check if we're coming from an email-link click
9110 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9112 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9114 //Init fix for YUI 2.7.0 datatable sort.
9115 SUGAR.email2.addressBook.initFixForDatatableSort();
9118 function createTreePanel(treeData, params) {
9119 var tree = new YAHOO.widget.TreeView(params.id);
9120 var root = tree.getRoot();
9122 //if (treeData.nodes && treeData[0].id == "Home")
9123 // treeData = treeData[0];
9127 function addChildNodes(parentNode, parentData) {
9128 var Ck = YAHOO.util.Cookie;
9129 var nextyear = SUGAR.email2.nextYear;
9130 var nodes = parentData.nodes || parentData.children;
9132 if (typeof(nodes[i]) == 'object') {
9133 if (nodes[i].data) {
9134 // See comment about href below.
9135 // nodes[i].data.href = '#';
9136 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode);
9137 node.action = nodes[i].data.action;
9139 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9140 addChildNodes(parentNode, nodes[i]);
9143 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9144 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9146 nodes[i].className = nodes[i].cls;
9148 // Previously, span was added in the label so it was rendering in the tree.
9149 // Default behavior is to wrap in span if no href property, and since this href
9150 // doesn't do anything, remove it so that it will be wrapped in spans.
9151 // nodes[i].href = "#";
9152 if (nodes[i].text) nodes[i].label = nodes[i].text;
9153 //Override YUI child node creation
9154 if (nodes[i].children) {
9155 nodes[i].nodes = nodes[i].children;
9156 nodes[i].children = [ ];
9158 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9161 if (typeof(nodes[i].nodes) == 'object') {
9162 addChildNodes(node, nodes[i]);
9169 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9171 function email2treeinit(tree, treedata, treediv, params) {
9172 //ensure the tree data is not corrupt
9176 if (SUGAR.email2.tree) {
9177 SUGAR.email2.tree.destroy();
9178 SUGAR.email2.tree = null;
9181 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9185 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9186 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9187 tree.subscribe("expandComplete", function(node){
9188 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9189 for (var i in node.children) {
9190 SE.accounts.setupDDTarget(node.children[i]);
9193 tree.setCollapseAnim("TVSlideOut");
9194 tree.setExpandAnim("TVSlideIn");
9195 var root = tree.root;
9196 while (root.hasChildren()) {
9197 var node = root.children[0];
9199 tree.removeNode(root.children[0], false);
9201 addChildNodes(root, treedata);
9203 SUGAR.email2.accounts.renderTree();
9206 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9207 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9211 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9212 startDrag: function(x, y) {
9213 var Dom = YAHOO.util.Dom;
9214 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9217 var dragEl = this.getDragEl();
9218 var clickEl = this.getEl();
9219 Dom.setStyle(clickEl, "color", "#AAA");
9220 Dom.setStyle(clickEl, "opacity", "0.25");
9221 dragEl.innerHTML = clickEl.innerHTML;
9223 Dom.addClass(dragEl, "ygtvcell");
9224 Dom.addClass(dragEl, "ygtvcontent");
9225 Dom.addClass(dragEl, "folderDragProxy");
9226 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9227 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9228 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9229 Dom.setStyle(dragEl, "opacity", "0.5");
9230 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9233 onDragOver: function(ev, id) {
9234 var Dom = YAHOO.util.Dom;
9235 if (id != this.dragId)
9237 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9238 if(node.data.cls != "sugarFolder") {
9239 SUGAR.email2.folders.unhighliteAll();
9243 this.targetNode = node;
9244 SUGAR.email2.folders.unhighliteAll();
9249 onDragOut: function(e, id) {
9250 if (this.targetNode) {
9251 SUGAR.email2.folders.unhighliteAll();
9252 this.targetNode = false;
9253 this.dragId = false;
9257 endDrag: function() {
9258 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9259 if (this.targetNode) {
9260 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9263 });// End of File modules/Emails/javascript/init.js
9265 /*********************************************************************************
9266 * SugarCRM Community Edition is a customer relationship management program developed by
9267 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9269 * This program is free software; you can redistribute it and/or modify it under
9270 * the terms of the GNU Affero General Public License version 3 as published by the
9271 * Free Software Foundation with the addition of the following permission added
9272 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9273 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9274 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9276 * This program is distributed in the hope that it will be useful, but WITHOUT
9277 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9278 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9281 * You should have received a copy of the GNU Affero General Public License along with
9282 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9283 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9286 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9287 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9289 * The interactive user interfaces in modified source and object code versions
9290 * of this program must display Appropriate Legal Notices, as required under
9291 * Section 5 of the GNU Affero General Public License version 3.
9293 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9294 * these Appropriate Legal Notices must retain the display of the "Powered by
9295 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9296 * technical reasons, the Appropriate Legal Notices must display the words
9297 * "Powered by SugarCRM".
9298 ********************************************************************************/
9303 function complexLayoutInit() {
9304 var se = SUGAR.email2;
9305 var Dom = YAHOO.util.Dom;
9307 getInnerLayout : function(rows) {
9308 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
9309 parent: se.complexLayout,
9315 scroll:false, // grid should autoScroll itself
9317 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
9325 body: "<div id='listBottom' />"
9333 body: "<div id='listRight' />",
9334 titlebar: false //,header: "right"
9337 se.complexLayout.on("render", function(){
9338 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
9339 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9340 SUGAR.email2.listViewLayout.set("height", height);
9341 SUGAR.email2.listViewLayout.render();
9343 se.listViewLayout.render();
9345 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
9346 var rp = se.listViewLayout.resizePreview = function() {
9347 var pre = Dom.get("displayEmailFramePreview");
9349 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
9350 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
9353 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
9354 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
9355 se.e2Layout.setPreviewPanel(rows);
9356 se.previewLayout = se.listViewLayout;
9357 return se.listViewLayout;
9360 getInnerLayout2Rows : function() {
9361 return this.getInnerLayout(true);
9363 getInnerLayout2Columns : function() {
9364 return this.getInnerLayout(false);
9368 // initialize state manager, we will use cookies
9369 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
9370 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
9371 se.complexLayout = new YAHOO.widget.Layout("container", {
9374 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
9375 width: Dom.getViewportWidth() - 40,
9379 body: "<div id='emailtabs'></div>"
9384 body: "<div id='lefttabs'></div>",
9394 header: Dom.get('footerLinks').innerHTML,
9401 se.complexLayout.render();
9402 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
9403 tp.addTab(new YAHOO.widget.Tab({
9406 content : "<div id='listViewDiv'/>",
9410 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
9411 tp.appendTo(centerEl);
9413 tp.get("element").style.borderRight = "1px solid #666"
9415 var listV = this.getInnerLayout2Rows();
9416 listV.set("height", tp.get("element").clientHeight - 25);
9419 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
9420 var folderTab = new YAHOO.widget.Tab({
9421 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
9423 content : "<div id='emailtree'/>",
9427 folderTab.on("activeChange", function(o){
9429 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
9432 se.leftTabs.addTab(folderTab);
9434 var tabContent = SUGAR.util.getAndRemove("searchTab");
9435 var searchTab = new YAHOO.widget.Tab({
9436 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
9438 content : tabContent.innerHTML,
9441 searchTab.on("activeChange", function(o){
9444 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
9445 //Setup the calendars if needed
9446 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
9447 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
9449 //Initalize sqs object for assigned user name
9450 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
9452 //Attach event handler for when the relate module option is selected for the correct sqs object
9453 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
9454 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
9455 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
9456 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
9458 //If enter key is pressed, perform search
9459 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
9460 for(var i=0; i < addKeyPressFields.length;i++)
9462 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
9463 if (e.keyCode == 13) {
9464 YAHOO.util.Event.stopEvent(e);
9465 SUGAR.email2.search.searchAdvanced();
9469 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
9471 //Clear parent values if selecting another parent type.
9472 YAHOO.util.Event.addListener('data_parent_type_search','change',
9474 document.getElementById('data_parent_id_search').value ='';
9475 document.getElementById('data_parent_name_search').value ='';
9480 se.leftTabs.addTab(searchTab);
9482 var resizeTabBody = function() {
9483 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
9484 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9487 se.complexLayout.on("render", resizeTabBody);
9488 se.leftTabs.on("activeTabChange", resizeTabBody);
9489 //hack to allow left pane scroll bar to fully show
9490 var lefttabsDiv = document.getElementById('lefttabs');
9491 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
9492 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
9493 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
9496 initSQSObject: function(formName,fieldName)
9498 var fullFieldName = formName + '_' + fieldName; //SQS Convention
9499 var resultName = fullFieldName + '_' + 'results';
9501 if (QSFieldsArray[fullFieldName] != null)
9503 QSFieldsArray[fullFieldName].destroy();
9504 delete QSFieldsArray[fullFieldName];
9506 if (QSProcessedFieldsArray[fullFieldName])
9507 QSProcessedFieldsArray[fullFieldName] = false;
9509 if( Dom.get(resultName) )
9511 var obj = document.getElementById(resultName);
9512 obj.parentNode.removeChild(obj);
9515 setPreviewPanel: function(rows) {
9517 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9518 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9519 Dom.get("listRight").innerHTML = "";
9520 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9522 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9523 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9524 Dom.get("listBottom").innerHTML = "";
9525 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9532 var myBufferedListenerObject = new Object();
9533 myBufferedListenerObject.refit = function() {
9534 if(SUGAR.email2.grid) {
9535 SUGAR.email2.grid.autoSize();
9538 // End of File modules/Emails/javascript/complexLayout.js
9540 /*********************************************************************************
9541 * SugarCRM Community Edition is a customer relationship management program developed by
9542 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9544 * This program is free software; you can redistribute it and/or modify it under
9545 * the terms of the GNU Affero General Public License version 3 as published by the
9546 * Free Software Foundation with the addition of the following permission added
9547 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9548 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9549 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9551 * This program is distributed in the hope that it will be useful, but WITHOUT
9552 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9553 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9556 * You should have received a copy of the GNU Affero General Public License along with
9557 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9558 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9561 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9562 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9564 * The interactive user interfaces in modified source and object code versions
9565 * of this program must display Appropriate Legal Notices, as required under
9566 * Section 5 of the GNU Affero General Public License version 3.
9568 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9569 * these Appropriate Legal Notices must retain the display of the "Powered by
9570 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9571 * technical reasons, the Appropriate Legal Notices must display the words
9572 * "Powered by SugarCRM".
9573 ********************************************************************************/
9575 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9576 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9577 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9578 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9579 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9580 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9581 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9582 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9583 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9584 ' <input type="hidden" id="composeType" name="composeType">' +
9585 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9586 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9587 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9588 ' <input type="hidden" id="sendTo" name="sendTo">' +
9589 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9590 ' <input type="hidden" id="sendCc" name="sendCc">' +
9591 ' <input type="hidden" id="setEditor" name="setEditor">' +
9592 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9593 ' <input type="hidden" id="parent_id" name="parent_id">' +
9594 ' <input type="hidden" id="parent_type" name="parent_type">' +
9595 ' <input type="hidden" id="attachments" name="attachments">' +
9596 ' <input type="hidden" id="documents" name="documents">' +
9597 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9598 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9599 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9600 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9602 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9603 ' <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>' +
9604 ' <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>' +
9605 ' <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>' +
9606 ' <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>' +
9607 '</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>' +
9608 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9609 '<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>' +
9610 ' </td></tr></tbody></table></th>' +
9614 ' <div style="margin:5px;">' +
9615 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9617 ' <td class="emailUILabel" NOWRAP >' +
9618 ' {app_strings.LBL_EMAIL_FROM}:' +
9620 ' <td class="emailUIField" NOWRAP>' +
9622 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9627 ' <td class="emailUILabel" NOWRAP>' +
9628 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9629 ' {app_strings.LBL_EMAIL_TO}:' +
9632 ' <td class="emailUIField" NOWRAP>' +
9633 ' <div class="ac_autocomplete">' +
9634 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9635 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9636 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9640 ' <tr id="add_addr_options_tr{idx}">' +
9641 ' <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>'+
9643 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9644 ' <td class="emailUILabel" NOWRAP>' +
9645 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9646 ' {app_strings.LBL_EMAIL_CC}:' +
9649 ' <td class="emailUIField" NOWRAP>' +
9650 ' <div class="ac_autocomplete">' +
9651 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9652 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9653 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9657 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9658 ' <td class="emailUILabel" NOWRAP>' +
9659 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9660 ' {app_strings.LBL_EMAIL_BCC}:' +
9663 ' <td class="emailUIField" NOWRAP>' +
9664 ' <div class="ac_autocomplete">' +
9665 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9666 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9667 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9672 ' <td class="emailUILabel" NOWRAP width="1%">' +
9673 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9675 ' <td class="emailUIField" NOWRAP width="99%">' +
9676 ' <div class="ac_autocomplete">' +
9677 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9686 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9687 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9688 ' <div style="padding:5px;">' +
9689 ' <table cellpadding="2" cellspacing="0" border="0">' +
9692 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9699 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9700 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9712 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9719 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9720 ' <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>' +
9732 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9739 ' <div id="addedTemplateAttachments{idx}"></div>' +
9746 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9747 ' <div style="padding:5px;">' +
9748 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9749 ' <table border="0" width="100%">' +
9751 ' <td NOWRAP style="padding:2px;">' +
9752 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9756 ' <td NOWRAP style="padding:2px;">' +
9757 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9762 ' <table border="0" width="100%">' +
9764 ' <td NOWRAP style="padding:2px;">' +
9765 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9769 ' <td NOWRAP style="padding:2px;">' +
9770 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9774 ' <table border="0" width="100%">' +
9776 ' <td NOWRAP style="padding:2px;">' +
9777 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9778 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9786 // End of File modules/Emails/javascript/composeEmailTemplate.js
9788 /*********************************************************************************
9789 * SugarCRM Community Edition is a customer relationship management program developed by
9790 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9792 * This program is free software; you can redistribute it and/or modify it under
9793 * the terms of the GNU Affero General Public License version 3 as published by the
9794 * Free Software Foundation with the addition of the following permission added
9795 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9796 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9797 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9799 * This program is distributed in the hope that it will be useful, but WITHOUT
9800 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9801 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9804 * You should have received a copy of the GNU Affero General Public License along with
9805 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9806 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9809 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9810 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9812 * The interactive user interfaces in modified source and object code versions
9813 * of this program must display Appropriate Legal Notices, as required under
9814 * Section 5 of the GNU Affero General Public License version 3.
9816 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9817 * these Appropriate Legal Notices must retain the display of the "Powered by
9818 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9819 * technical reasons, the Appropriate Legal Notices must display the words
9820 * "Powered by SugarCRM".
9821 ********************************************************************************/
9823 SUGAR.email2.templates['displayOneEmail'] =
9824 '<div class="emailDetailTable" style="height:100%">' +
9825 '<div id="viewMenuDiv{idx}"></div>' +
9826 '<div width="100%" class="displayEmailValue">' +
9827 ' <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>' +
9828 ' <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>' +
9829 ' <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>' +
9830 ' <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>' +
9831 ' <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>' +
9832 ' <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>' +
9833 ' <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>' +
9834 ' <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>' +
9835 ' <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>' +
9837 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9839 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9840 ' {app_strings.LBL_EMAIL_FROM}:' +
9842 ' <td width="99%" class="displayEmailValue">' +
9843 ' {email.from_addr}' +
9847 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9848 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9850 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9851 ' <b>{email.name}</b>' +
9855 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9856 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9858 ' <td class="displayEmailValue">' +
9859 ' {email.date_start} {email.time_start}' +
9863 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9864 ' {app_strings.LBL_EMAIL_TO}:' +
9866 ' <td class="displayEmailValue">' +
9867 ' {email.toaddrs}' +
9870 ' <tr>{meta.cc}</tr>' +
9871 ' <tr>{email.attachments}</tr>' +
9873 ' <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>' +
9874 //' {email.description}' +
9876 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9878 /*********************************************************************************
9879 * SugarCRM Community Edition is a customer relationship management program developed by
9880 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9882 * This program is free software; you can redistribute it and/or modify it under
9883 * the terms of the GNU Affero General Public License version 3 as published by the
9884 * Free Software Foundation with the addition of the following permission added
9885 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9886 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9887 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9889 * This program is distributed in the hope that it will be useful, but WITHOUT
9890 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9891 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9894 * You should have received a copy of the GNU Affero General Public License along with
9895 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9896 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9899 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9900 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9902 * The interactive user interfaces in modified source and object code versions
9903 * of this program must display Appropriate Legal Notices, as required under
9904 * Section 5 of the GNU Affero General Public License version 3.
9906 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9907 * these Appropriate Legal Notices must retain the display of the "Powered by
9908 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9909 * technical reasons, the Appropriate Legal Notices must display the words
9910 * "Powered by SugarCRM".
9911 ********************************************************************************/
9913 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9914 '<body onload="javascript:window.print();">' +
9918 ' font-family: helvetica, impact, sans-serif;' +
9919 ' font-size : 12pt;' +
9926 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9929 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9931 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9932 ' {app_strings.LBL_EMAIL_FROM}:' +
9934 ' <td width="99%" class="displayEmailValue">' +
9935 ' {email.from_name} <{email.from_addr}>' +
9939 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9940 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9942 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9943 ' <b>{email.name}</b>' +
9947 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9948 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9950 ' <td class="displayEmailValue">' +
9951 ' {email.date_start} {email.time_start}' +
9955 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9956 ' {app_strings.LBL_EMAIL_TO}:' +
9958 ' <td class="displayEmailValue">' +
9959 ' {email.toaddrs}' +
9963 ' {email.attachments}' +
9969 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9971 ' <td style="border-top: 1px solid #333;">' +
9972 ' <div style="padding:5px;">' +
9973 '{email.description}' +
9983 // End of File modules/Emails/javascript/viewPrintable.js
9985 /*********************************************************************************
9986 * SugarCRM Community Edition is a customer relationship management program developed by
9987 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9989 * This program is free software; you can redistribute it and/or modify it under
9990 * the terms of the GNU Affero General Public License version 3 as published by the
9991 * Free Software Foundation with the addition of the following permission added
9992 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9993 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9994 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9996 * This program is distributed in the hope that it will be useful, but WITHOUT
9997 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9998 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
10001 * You should have received a copy of the GNU Affero General Public License along with
10002 * this program; if not, see http://www.gnu.org/licenses or write to the Free
10003 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
10006 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
10007 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
10009 * The interactive user interfaces in modified source and object code versions
10010 * of this program must display Appropriate Legal Notices, as required under
10011 * Section 5 of the GNU Affero General Public License version 3.
10013 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
10014 * these Appropriate Legal Notices must retain the display of the "Powered by
10015 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
10016 * technical reasons, the Appropriate Legal Notices must display the words
10017 * "Powered by SugarCRM".
10018 ********************************************************************************/
10019 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
10020 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;}
10021 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');}
10022 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;}}
10023 if(QSProcessedFieldsArray[qs_index_id]){skipSTR='collection_0';if(qs_index_id.lastIndexOf(skipSTR)!=(qs_index_id.length-skipSTR.length)){continue;}}
10024 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
10025 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}
10026 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]]);}}}
10027 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]]);}}
10028 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
10029 {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]])
10030 {document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";}}}};search.setFields=function(data,filter)
10031 {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])
10032 {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';}}}}
10033 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))
10034 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
10035 {if(this.inputElement.id=='shipping_account_name')
10036 {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)/;}
10037 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
10038 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
10039 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];}}}
10040 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]];}
10041 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;}}}}});}
10042 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
10043 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}
10044 // End of File include/javascript/quicksearch.js