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 if(typeof(ie_id)=='undefined'||ie_id=='')
359 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id.value:'';URL='index.php?'
360 +'module='+module_name
363 +'&target='+pageTarget
364 +'&target1='+pageTarget
365 +'&server_url='+mail_server
366 +'&email_user='+words[0]
367 +'&protocol='+protocol
369 +'&email_password='+words[1]
370 +'&mailbox='+words[2]
373 +'&personal='+isPersonal;var SI=SUGAR.inboundEmail;if(!SI.testDlg){SI.testDlg=new YAHOO.widget.SimpleDialog("testSettingsDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.testDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);if(this.evalJS)
374 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
375 this.body.style.width=w}}
376 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
377 title=SUGAR.language.get('InboundEmail','LBL_TEST_SETTINGS');SI.testDlg.setHeader(title);SI.testDlg.setBody(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.testDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.testDlg._updateContent,failure:SI.testDlg.hide,scope:SI.testDlg});SI.testDlg.show();}
378 function isDataValid(formName,validateMonitoredFolder){var formObject=document.getElementById(formName);var errors=new Array();var out=new String();if(trim(formObject.server_url.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_SERVER'));}
379 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
380 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
381 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
382 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
383 if(errors.length>0){out=SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_DESC');for(i=0;i<errors.length;i++){if(out!=""){out+="\n";}
385 alert(out);return false;}else{return true;}}
386 function getFoldersListForInboundAccount(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,searchFieldValue,formName){if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';URL='index.php?'
387 +'module='+module_name
390 +'&target='+pageTarget
391 +'&target1='+pageTarget
392 +'&server_url='+mail_server
393 +'&email_user='+words[0]
394 +'&protocol='+protocol
396 +'&email_password='+words[1]
397 +'&mailbox='+words[2]
399 +'&personal='+isPersonal
400 +'&searchField='+searchFieldValue;var SI=SUGAR.inboundEmail;if(!SI.listDlg){SI.listDlg=new YAHOO.widget.SimpleDialog("selectFoldersDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.listDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
401 this.body.style.width=w}}
402 SI.listDlg.setHeader(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.listDlg.setBody('');SI.listDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.listDlg._updateContent,failure:SI.listDlg.hide,scope:SI.listDlg});SI.listDlg.show();}
403 function setPortDefault(){var prot=document.getElementById('protocol');var ssl=document.getElementById('ssl');var port=document.getElementById('port');var stdPorts=new Array("110","143","993","995");var stdBool=new Boolean(false);if(port.value==''){stdBool.value=true;}else{for(i=0;i<stdPorts.length;i++){if(stdPorts[i]==port.value){stdBool.value=true;}}}
404 if(stdBool.value==true){if(prot.value=='imap'&&ssl.checked==false){port.value="143";}else if(prot.value=='imap'&&ssl.checked==true){port.value='993';}else if(prot.value=='pop3'&&ssl.checked==false){port.value='110';}else if(prot.value=='pop3'&&ssl.checked==true){port.value='995';}}}
405 function toggle_monitored_folder(field){var field1=document.getElementById('protocol');var mailbox=document.getElementById('mailbox');var label_inbox=document.getElementById('label_inbox');var subscribeFolderButton=document.getElementById('subscribeFolderButton');var trashFolderRow=document.getElementById('trashFolderRow');var trashFolderRow1=document.getElementById('trashFolderRow1');var sentFolderRow=document.getElementById('sentFolderRow');if(field1.value=='imap'){mailbox.disabled=false;try{mailbox.style.display='';trashFolderRow.style.display='';sentFolderRow.style.display='';trashFolderRow1.style.display='';subscribeFolderButton.style.display='';}catch(e){};label_inbox.style.display='';}
406 else{mailbox.value="INBOX";mailbox.disabled=false;try{mailbox.style.display="none";trashFolderRow.style.display="none";sentFolderRow.style.display="none";trashFolderRow1.style.display="none";subscribeFolderButton.style.display="none";}catch(e){};label_inbox.style.display="none";}}
407 // End of File modules/InboundEmail/InboundEmail.js
409 /*********************************************************************************
410 * SugarCRM Community Edition is a customer relationship management program developed by
411 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
413 * This program is free software; you can redistribute it and/or modify it under
414 * the terms of the GNU Affero General Public License version 3 as published by the
415 * Free Software Foundation with the addition of the following permission added
416 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
417 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
418 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
420 * This program is distributed in the hope that it will be useful, but WITHOUT
421 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
422 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
425 * You should have received a copy of the GNU Affero General Public License along with
426 * this program; if not, see http://www.gnu.org/licenses or write to the Free
427 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
430 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
431 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
433 * The interactive user interfaces in modified source and object code versions
434 * of this program must display Appropriate Legal Notices, as required under
435 * Section 5 of the GNU Affero General Public License version 3.
437 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
438 * these Appropriate Legal Notices must retain the display of the "Powered by
439 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
440 * technical reasons, the Appropriate Legal Notices must display the words
441 * "Powered by SugarCRM".
442 ********************************************************************************/
445 cache : new Object(),
446 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
447 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
450 currentHtmleditor : ''
454 * preserves hits from email server
456 _setDetailCache : function(ret) {
458 var compKey = ret.meta.mbox + ret.meta.uid;
460 if(!SUGAR.email2.cache[compKey]) {
461 SUGAR.email2.cache[compKey] = ret;
466 autoSetLayout : function() {
467 var c = document.getElementById('container');
468 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
469 //Ensure a minimum height.
470 tHeight = Math.max(tHeight, 550);
471 c.style.height = tHeight + "px";
472 SUGAR.email2.complexLayout.set('height', tHeight);
473 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
474 SUGAR.email2.complexLayout.render();
475 SUGAR.email2.listViewLayout.resizePreview();
481 * Shows overlay progress message
485 SUGAR.showMessageBoxModal = function(title, body) {
486 SUGAR.showMessageBox(title, body);
490 SUGAR.showMessageBox = function(reqtitle, body, type, additconfig) {
492 if (typeof(additconfig) == "object") {
493 var config = additconfig;
496 config.title = reqtitle;
498 YAHOO.SUGAR.MessageBox.show(config);
502 SUGAR.hideMessageBox = function() {
503 YAHOO.SUGAR.MessageBox.hide();
505 // End of File modules/Emails/javascript/EmailUIShared.js
507 /*********************************************************************************
508 * SugarCRM Community Edition is a customer relationship management program developed by
509 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
511 * This program is free software; you can redistribute it and/or modify it under
512 * the terms of the GNU Affero General Public License version 3 as published by the
513 * Free Software Foundation with the addition of the following permission added
514 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
515 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
516 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
518 * This program is distributed in the hope that it will be useful, but WITHOUT
519 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
520 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
523 * You should have received a copy of the GNU Affero General Public License along with
524 * this program; if not, see http://www.gnu.org/licenses or write to the Free
525 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
528 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
529 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
531 * The interactive user interfaces in modified source and object code versions
532 * of this program must display Appropriate Legal Notices, as required under
533 * Section 5 of the GNU Affero General Public License version 3.
535 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
536 * these Appropriate Legal Notices must retain the display of the "Powered by
537 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
538 * technical reasons, the Appropriate Legal Notices must display the words
539 * "Powered by SugarCRM".
540 ********************************************************************************/
544 var sw = YAHOO.SUGAR,
545 Event = YAHOO.util.Event,
546 Connect = YAHOO.util.Connect,
550 ///////////////////////////////////////////////////////////////////////////////
553 outboundDialog : null,
554 inboundAccountEditDialog : null,
555 inboundAccountsSettingsTable : null,
556 outboundAccountsSettingsTable : null,
557 testOutboundDialog : null,
558 errorStyle : 'input-error',
560 newAddedOutboundId : '',
563 * makes async call to retrieve an outbound instance for editting
566 editOutbound : function(obi) {
568 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
571 deleteOutbound : function(obi) {
573 if(obi.match(/^(add|line|sendmail)+/)) {
574 alert('Invalid Operation');
576 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
577 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
581 getReplyAddress : function() {
584 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
585 var addy = SE.userPrefs.current_user.emailAddresses[i];
587 if(addy.primary_address == "1") {
588 primary = addy.email_address;
591 if(addy.reply_to == "1") {
592 return addy.email_address;
600 * Called on "Accounts" tab activation event
602 lazyLoad : function() {
604 this._setupInboundAccountTable();
605 this._setupOutboundAccountTable();
609 _setupInboundAccountTable: function()
611 //Setup the inbound mail settings
612 if(!this.inboundAccountsSettingsTable)
614 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
615 var clckEvent = oColumn.key;
617 var is_group = oRecord.getData("is_group");
620 if(oColumn.key == 'edit')
622 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
623 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
625 else if(oColumn.key == 'delete')
627 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
628 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
630 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
634 this.showBoolean = function(el, oRecord, oColumn, oData)
636 var is_group = oRecord.getData("is_group");
637 var bChecked = oData;
638 bChecked = (bChecked) ? " checked" : "";
641 el.innerHTML = "<input type=\"radio\"" + bChecked +
642 " name=\"col" + oColumn.getId() + "-radio\"" +
643 " class=\"yui-dt-radio\">";
648 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
649 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
651 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
652 '<img border="0" src="themes/default/images/helpInline.gif">' +
653 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
656 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
657 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
658 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
659 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
660 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
661 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
662 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
663 this.ieDataSource = new YAHOO.util.DataSource(query);
664 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
665 this.ieDataSource.responseSchema = {
666 resultsList: "account_list",
667 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
669 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
670 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
672 var elCheckbox = oArgs.target;
673 var oColumn = this.getColumn(elCheckbox);
674 if(oColumn.key == 'is_active')
676 var oRecord = this.getRecord(elCheckbox);
677 oRecord.setData("is_active",elCheckbox.checked);
678 var t_id = oRecord.getData('id');
679 var isGroupFolder = oRecord.getData('has_groupfolder');
682 SUGAR.email2.folders.updateSubscriptions();
684 SUGAR.email2.folders.setFolderSelection();
688 var lastDefaultSelectedId = "";
689 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
691 var elRadio = oArgs.target;
692 var oColumn = this.getColumn(elRadio);
693 if(oColumn.key == 'is_default')
695 var oRecord = this.getRecord(elRadio);
696 var t_id = oRecord.getData('id');
697 var t_isGroup = oRecord.getData('is_group');
698 if(t_id != lastDefaultSelectedId && !t_isGroup)
700 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
701 lastDefaultSelectedId = t_id;
702 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
705 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
710 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
711 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
714 _setupOutboundAccountTable: function()
716 if(!this.outboundAccountsSettingsTable)
718 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
719 var clckEvent = oColumn.key;
721 var isEditable = oRecord.getData("is_editable");
722 var type = oRecord.getData("type");
725 if(oColumn.key == 'edit')
727 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
728 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
730 else if(oColumn.key == 'delete' && type == 'user')
732 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
733 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
736 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
740 //Custom formatter to display any error messages.
741 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
743 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
744 SUGAR.email2.composeLayout.outboundAccountErrors = {};
746 var id = oRecord.getData('id');
747 var message = oRecord.getData("errors");
750 elLiner.innerHTML = '<span class="required">' + message + '</span>';
751 //Add the id and message for all outbound accounts.
752 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
756 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
757 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
760 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
761 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
763 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
764 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
765 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
766 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
768 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
769 this.obDataSource = new YAHOO.util.DataSource(query);
770 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
771 this.obDataSource.responseSchema = {
773 resultsList: "outbound_account_list",
774 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
777 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
780 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
781 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
782 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
786 * Displays a modal diaglogue to edit outbound account settings
788 showEditInboundAccountDialogue : function(clear) {
790 if(!this.inboundAccountEditDialog) {
791 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
795 constraintoviewport: true,
799 EAD.showEvent.subscribe(function() {
800 var el = this.element;
801 var viewH = YAHOO.util.Dom.getViewportHeight();
802 if (this.header && el && viewH - 50 < el.clientHeight) {
803 var body = this.header.nextElementSibling;
804 body.style.overflow = "hidden";
805 body.style.height = "100%";
808 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
809 Dom.removeClass("editAccountDialogue", "yui-hidden");
813 if(clear == undefined || clear == true)
815 SE.accounts.clearInboundAccountEditScreen();
816 //Set default protocol to IMAP when creating new records
817 document.forms['ieAccount'].elements['protocol'].value = "imap";
818 SE.accounts.setPortDefault();
821 //Check if we should display username/password fields for outbound account if errors were detected.
822 this.checkOutBoundSelection();
824 this.inboundAccountEditDialog.render();
825 this.inboundAccountEditDialog.show();
826 SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
830 * Set all fields on the outbound edit form to either enabled/disabled
831 * except for the username/password.
834 toggleOutboundAccountDisabledFields: function(disable)
836 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
837 for(var i=0;i<fields.length;i++)
839 document.getElementById(fields[i]).disabled = disable;
842 Dom.addClass("mail_smtpssl_row", "yui-hidden");
844 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
848 * Refresh the inbound accounts table.
850 refreshInboundAccountTable : function()
852 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
854 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
855 scope: this.inboundAccountsSettingsTable }
859 * Refresh the outbound accounts table.
861 refreshOuboundAccountTable : function()
863 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
865 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
866 scope: this.outboundAccountsSettingsTable }
870 * Displays a modal diaglogue to add a SMTP server
872 showAddSmtp : function() {
873 // lazy load dialogue
874 if(!this.outboundDialog) {
875 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
879 constraintoviewport: true,
883 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
884 this.outboundDialog.hideEvent.subscribe(function(){
885 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
886 var out = Dom.get("outbound_email");
887 if (out && out.value == "SYSTEM_ADD")
889 out.value = out.options[0].value;
891 //Check if we should display username/password for system account.
892 SE.accounts.checkOutBoundSelection();
896 Dom.removeClass("outboundDialog", "yui-hidden");
900 var form = document.getElementById('outboundEmailForm');
901 for(i=0; i<form.elements.length; i++) {
902 if(form.elements[i].name == 'mail_smtpport') {
903 form.elements[i].value = 25;
904 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
905 form.elements[i].value = '';
906 } else if(form.elements[i].type == 'checkbox') {
907 form.elements[i].checked = false;
910 //Render the SMTP buttons
911 if ( !SUGAR.smtpButtonGroup ) {
912 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
913 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
915 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
916 document.getElementById('smtp_settings').style.display = '';
917 form.mail_smtptype.value = e.newValue.get('value');
919 YAHOO.widget.Button.addHiddenFieldsToForm(form);
921 //Hide Username/Password
922 SUGAR.email2.accounts.smtp_authenticate_field_display();
923 //Unset readonly fields
924 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
925 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
926 this.outboundDialog.render();
927 this.outboundDialog.show();
931 * Accounts' Advanced Settings view toggle
933 toggleAdv : function() {
934 var adv = document.getElementById("ie_adv");
935 if(adv.style.display == 'none') {
936 adv.style.display = "";
938 adv.style.display = 'none';
942 smtp_authenticate_field_display : function() {
943 var smtpauth_req = document.getElementById("mail_smtpauth_req");
944 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
945 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
948 smtp_setDefaultSMTPPort : function() {
949 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
951 if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
952 document.getElementById("mail_smtpport").value = '465';
954 if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
955 document.getElementById("mail_smtpport").value = '25';
960 * Changes the display used in the outbound email SMTP dialog to match the
962 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
964 document.getElementById("smtpButtonGroupTD").style.display = '';
965 document.getElementById("chooseEmailProviderTD").style.display = '';
966 document.getElementById("mailsettings1").style.display = '';
967 document.getElementById("mailsettings2").style.display = '';
968 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
969 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
970 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
971 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
975 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
976 document.getElementById("mail_smtpport").value = '465';
977 document.getElementById("mail_smtpauth_req").checked = true;
978 var ssl = document.getElementById("mail_smtpssl");
979 for(var j=0;j<ssl.options.length;j++) {
980 if(ssl.options[j].text == 'SSL') {
981 ssl.options[j].selected = true;
985 document.getElementById("mailsettings1").style.display = 'none';
986 document.getElementById("mailsettings2").style.display = 'none';
987 document.getElementById("mail_smtppass_label").innerHTML =
988 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
989 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
992 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
993 document.getElementById("mail_smtpport").value = '587';
994 document.getElementById("mail_smtpauth_req").checked = true;
995 var ssl = document.getElementById("mail_smtpssl");
996 for(var j=0;j<ssl.options.length;j++) {
997 if(ssl.options[j].text == 'TLS') {
998 ssl.options[j].selected = true;
1002 document.getElementById("mailsettings1").style.display = 'none';
1003 document.getElementById("mailsettings2").style.display = 'none';
1004 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
1005 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
1008 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
1009 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
1010 document.getElementById("mail_smtpserver").value = '';
1012 document.getElementById("mail_smtpport").value = '25';
1013 document.getElementById("mail_smtpauth_req").checked = true;
1014 document.getElementById("mailsettings1").style.display = '';
1015 document.getElementById("mailsettings2").style.display = '';
1016 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1017 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1018 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1019 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1022 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1024 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1025 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1026 document.getElementById("mailsettings2").style.display = 'none';
1029 SUGAR.email2.accounts.smtp_authenticate_field_display();
1030 SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1034 * Fill the gmail default values for inbound accounts.
1036 fillInboundGmailDefaults: function () {
1038 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1039 document.forms['ieAccount'].elements['ssl'].checked = true;
1040 document.forms['ieAccount'].elements['protocol'].value = "imap";
1041 SUGAR.email2.accounts.setPortDefault();
1042 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1045 * Sets Port field to selected protocol and SSL settings defaults
1047 setPortDefault : function() {
1048 var prot = document.getElementById('protocol');
1049 var ssl = document.getElementById('ssl');
1050 var port = document.getElementById('port');
1051 var stdPorts= new Array("110", "143", "993", "995");
1052 var stdBool = new Boolean(false);
1053 var mailboxdiv = document.getElementById("mailboxdiv");
1054 var trashFolderdiv = document.getElementById("trashFolderdiv");
1055 var sentFolderdiv = document.getElementById("sentFolderdiv");
1056 var monitoredFolder = document.getElementById("subscribeFolderButton");
1057 if(port.value == '') {
1058 stdBool.value = true;
1060 for(i=0; i<stdPorts.length; i++) {
1061 if(stdPorts[i] == port.value) {
1062 stdBool.value = true;
1067 if(stdBool.value == true) {
1068 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1070 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1072 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1074 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1079 if (prot.value == 'imap') {
1080 mailboxdiv.style.display = "";
1081 trashFolderdiv.style.display = "";
1082 sentFolderdiv.style.display = "";
1083 monitoredFolder.style.display = "";
1084 if (document.getElementById('mailbox').value == "") {
1085 document.getElementById('mailbox').value = "INBOX";
1088 mailboxdiv.style.display = "none";
1089 trashFolderdiv.style.display = "none";
1090 sentFolderdiv.style.display = "none";
1091 monitoredFolder.style.display = "none";
1092 document.getElementById('mailbox').value = "";
1097 * Draws/removes red boxes around required fields.
1099 ieAccountError : function(style) {
1100 document.getElementById('server_url').className = style;
1101 document.getElementById('email_user').className = style;
1102 document.getElementById('email_password').className = style;
1103 document.getElementById('protocol').className = style;
1104 document.getElementById('port').className = style;
1107 checkOutBoundSelection: function() {
1108 var select = Dom.get('outbound_email');
1109 if (!select || select.selectedIndex == -1) { return; }
1111 var v = select.options[select.selectedIndex].value;
1115 select.options[select.selectedIndex].selected = false;
1116 v = select.options[0].value;
1118 else if (v == 'SYSTEM_ADD')
1119 SUGAR.email2.accounts.showAddSmtp();
1121 var foundError = false;
1122 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1123 for(i in errorAccounts)
1132 //Should username/password fields for outbound account.
1134 this.toggleInboundOutboundFields(true);
1136 this.toggleInboundOutboundFields(false);
1141 toggleInboundOutboundFields : function (display)
1145 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1146 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1150 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1151 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1155 * rebuilds the select options for mailer options
1157 rebuildMailerOptions : function() {
1158 var select = document.forms['ieAccount'].elements['outbound_email'];
1159 SE.util.emptySelectOptions(select);
1161 //Get the available sugar mailers
1162 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1164 for(i=0;i<a_outbound.length;i++)
1166 var t_record = a_outbound[i];
1167 var key = t_record.getData('id');
1168 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1170 var opt = new Option(display, key);
1171 select.options.add(opt);
1172 if (key == SE.accounts.newAddedOutboundId) {
1173 select.options.selectedIndex = i;
1177 select.options.add(new Option('',''));
1178 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1179 //Hide/Show username password fields if necessary.
1180 SE.accounts.checkOutBoundSelection();
1183 * Empties all the fields in the accounts edit view
1185 clearInboundAccountEditScreen:function() {
1187 document.getElementById('ie_id').value = '';
1188 document.getElementById('ie_name').value = '';
1189 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1190 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1191 document.getElementById('reply_to_addr').value = '';
1192 document.getElementById('server_url').value = '';
1193 document.getElementById('email_user').value = '';
1194 document.getElementById('email_password').value = '';
1195 document.getElementById('port').value = '';
1196 document.getElementById('inbound_mail_smtpuser').value = '';
1197 document.getElementById('inbound_mail_smtppass').value = '';
1198 document.ieAccount.protocol.options[0].selected = true;
1200 document.getElementById('ssl').checked = false;
1201 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1205 * Populates an account's fields in Settings->Accounts
1207 fillIeAccount:function(jsonstr) {
1208 var o = YAHOO.lang.JSON.parse(jsonstr);
1210 document.getElementById('ie_id').value = o.id;
1211 document.getElementById('ie_name').value = o.name;
1212 if (o.stored_options != null) {
1213 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1214 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1215 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1216 if (o.stored_options.trashFolder != null) {
1217 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1219 if (o.stored_options.sentFolder != null) {
1220 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1223 document.getElementById('server_url').value = o.server_url;
1224 document.getElementById('email_user').value = o.email_user;
1225 document.getElementById('port').value = o.port;
1226 document.getElementById('group_id').value = o.group_id;
1227 document.getElementById('mailbox').value = o.mailbox;
1233 if(typeof(o.service[2]) != 'undefined') {
1234 document.getElementById('ssl').checked = true;
1238 if(document.getElementById('protocol').value != o.protocol) {
1239 var prot = document.getElementById('protocol');
1240 for(i=0; i<prot.options.length; i++) {
1241 if(prot.options[i].value == o.service[3]) {
1242 prot.options[i].selected = true;
1243 this.setPortDefault();
1247 // handle SMTP selection
1248 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1249 var opts = document.getElementById('outbound_email').options;
1250 for(i=0; i<opts.length; i++) {
1251 if(opts[i].value == o.stored_options.outbound_email) {
1252 opts[i].selected = true;
1258 deleteIeAccount : function(IeAccountID,IeGroupID) {
1259 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1261 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1263 AjaxObject.target = 'frameFlex';
1264 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1265 SUGAR.email2.accounts.refreshInboundAccountTable();
1269 // Null check for Outbound Settings.
1270 checkOutboundSettings: function() {
1271 var errorMessage = '';
1272 var isError = false;
1273 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1274 var mailName = document.getElementById('mail_name').value;
1275 var smtpServer = document.getElementById('mail_smtpserver').value;
1276 var smtpPort = document.getElementById('mail_smtpport').value;
1278 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1279 if(trim(mailName) == '') {
1281 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1283 if(trim(smtpServer) == '') {
1285 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1287 if(trim(smtpPort) == '') {
1289 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1291 if(mailsmtpauthreq.checked) {
1292 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1294 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1299 SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1306 testOutboundSettings: function() {
1307 var errorMessage = '';
1308 var isError = false;
1309 var fromAddress = document.getElementById("outboundtest_from_address").value;
1310 if (trim(fromAddress) == "") {
1311 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1312 SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1316 else if (!isValidEmail(fromAddress)) {
1317 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1318 SUGAR.showMessageBox(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1322 //Hide the dialogue and show an in progress indicator.
1323 SE.accounts.testOutboundDialog.hide();
1324 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1326 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1327 //nothing is sent in the request.
1328 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1329 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1331 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1332 if(outboundType == 'system-override')
1333 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1335 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1336 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1340 testOutboundSettingsDialog: function() {
1341 //Ensure that all settings are correct before proceeding to send test email.
1342 if(!SE.accounts.checkOutboundSettings())
1345 // lazy load dialogue
1346 if(!SE.accounts.testOutboundDialog) {
1347 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1351 constraintoviewport: true,
1355 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1356 Dom.removeClass("testOutboundDialog", "yui-hidden");
1358 SE.accounts.testOutboundDialog.render();
1359 SE.accounts.testOutboundDialog.show();
1363 * Saves Outbound email settings
1365 saveOutboundSettings : function() {
1366 if(SE.accounts.checkOutboundSettings()) {
1367 //Enable the form fields for the post.
1368 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1369 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1370 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1376 saveIeAccount : function() {
1378 //Before saving check if there are any error messages associated with the outbound account.
1379 var outboundID = document.getElementById('outbound_email').value;
1381 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1382 'validateSMTPCreds':true}) )
1384 document.getElementById('saveButton').disabled = true;
1386 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1388 var formObject = document.getElementById('ieAccount');
1389 YAHOO.util.Connect.setForm(formObject);
1391 AjaxObject._reset();
1392 AjaxObject.target = 'frameFlex';
1393 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1397 testSettings : function() {
1398 form = document.getElementById('ieAccount');
1400 if(SE.accounts.checkIeCreds()) {
1401 ie_test_open_popup_with_submit("InboundEmail", "Popup", "Popup", 400, 300, trim(form.server_url.value), form.protocol.value, trim(form.port.value), trim(form.email_user.value), Rot13.write(form.email_password.value), trim(form.mailbox.value), form.ssl.checked, true, "ieAccount", form.ie_id.value);
1405 getFoldersListForInboundAccountForEmail2 : function() {
1406 form = document.getElementById('ieAccount');
1407 if(SE.accounts.checkIeCreds()) {
1408 var mailBoxValue = form.mailbox.value;
1409 if (form.searchField.value.length > 0) {
1412 getFoldersListForInboundAccount("InboundEmail", "ShowInboundFoldersList", "Popup", 400, 300, form.server_url.value, form.protocol.value, form.port.value, form.email_user.value, Rot13.write(form.email_password.value), mailBoxValue, form.ssl.checked, true, form.searchField.value );
1417 checkIeCreds : function(validateRules) {
1418 if(typeof(validateRules) == 'undefined')
1421 var errors = new Array();
1422 var out = new String();
1424 var ie_name = Dom.get('ie_name').value;
1425 var fromAddress = Dom.get('ie_from_addr').value;
1426 var server_url = Dom.get('server_url').value;
1427 var email_user = Dom.get('email_user').value;
1428 var email_password = Dom.get('email_password').value;
1429 var protocol = Dom.get('protocol').value;
1430 var port = Dom.get('port').value;
1431 var oe = Dom.get('outbound_email');
1433 // Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
1434 // other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
1435 // return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
1436 var oe_value = (typeof(oe.options[oe.selectedIndex]) === 'undefined' || typeof(oe.options[oe.selectedIndex]) === 'unknown' || typeof(oe.options[oe.selectedIndex]) === null) ? "" : oe.options[oe.selectedIndex].value;
1438 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1439 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1441 //If the username and password were provided then ignore the error messge
1443 var outboundCredentialsFound = false;
1445 if(outboundUserName != "" && outboundPass != "")
1446 outboundCredentialsFound = true;
1448 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1450 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1451 && validateSMTPCreds)
1453 if(trim(outboundUserName) == "") {
1454 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1456 if(trim(outboundPass) == "") {
1457 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1461 if(trim(ie_name) == "") {
1462 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1465 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1467 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1468 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1473 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1474 || trim(oe_value) == "SYSTEM_ADD") ) {
1475 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1477 if(trim(server_url) == "") {
1478 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1480 if(trim(email_user) == "") {
1481 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1483 if(protocol == "") {
1484 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1486 if (protocol == 'imap') {
1487 var mailbox = document.getElementById('mailbox').value;
1488 if (trim(mailbox) == "") {
1489 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1491 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1492 var trashFolder = document.getElementById('trashFolder').value;
1493 if (trim(trashFolder) == "") {
1494 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1499 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1502 if(errors.length > 0) {
1503 out = app_strings.LBL_EMAIL_ERROR_DESC;
1504 for(i=0; i<errors.length; i++) {
1519 getIeAccount : function(ieId) {
1523 SUGAR.showMessageBox(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1524 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1526 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1530 * Iterates through TreeView nodes to apply styles dependent nature of node
1532 renderTree:function() {
1533 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1537 //Sets the style for any nodes that need it.
1538 setNodeStyle : function(node) {
1539 if (!node.data.origText) {
1540 node.data.origText = node.data.text;
1543 if (typeof(node.data.unseen) != 'undefined') {
1544 if (node.data.unseen > 0) {
1545 node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
1546 // Add bold style to label, kinda hacky
1547 node.labelStyle += " ygtvlabelbold";
1550 node.setUpLabel(node.data.origText);
1553 node.setUpLabel(node.data.origText);
1555 SE.accounts.setupDDTarget(node);
1558 setupDDTarget : function(node) {
1559 if (node.ddTarget) {
1560 node.ddTarget.removeFromGroup();
1561 delete node.ddTarget;
1563 var id = node.getElId();
1564 var num = id.substring(4);
1565 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1566 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1567 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1569 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1571 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1572 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1577 * Async call to rebuild the folder list. After a folder delete or account delete
1579 rebuildFolderList : function() {
1580 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1581 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1585 * Returns the number of remote accounts the user has active.
1587 getAccountCount : function() {
1590 for(i=0; i<tree._nodes.length; i++) {
1591 var node = tree._nodes[i];
1593 if(typeof(node) != 'undefined' && node.data.ieId) {
1601 ///////////////////////////////////////////////////////////////////////////////
1606 ///////////////////////////////////////////////////////////////////////////////
1607 //// CONTEXT MENU CALLS
1610 assignToDialogue : null,
1612 * Archives from context menu
1614 * @param string ieId
1615 * @param string folder
1617 _archiveToSugar : function(uids, ieId, folder) {
1620 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1621 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1624 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1628 * Archives from context menu
1630 archiveToSugar : function(menuItem) {
1631 SE.contextMenus.emailListContextMenu.hide();
1633 var rows = SE.grid.getSelectedRows();
1635 /* iterate through available rows JIC a row is deleted - use first available */
1636 for(var i=0; i<rows.length; i++) {
1637 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1639 var data = SE.grid.getRecord(rows[0]).getData();
1640 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1644 * Popup the printable version and start system's print function.
1646 viewPrintable : function(menuItem) {
1647 var rows = SE.grid.getSelectedRows();
1648 var data = SE.grid.getRecord(rows[0]).getData();
1649 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1653 * Marks email flagged on mail server
1655 markRead : function(type, contextMenuId) {
1656 SE.contextMenus.markEmail('read');
1660 * Assign this emails to people based on assignment rules
1662 assignEmailsTo : function(type, contextMenuId) {
1663 if(!SE.contextMenus.assignToDialogue)
1665 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1669 constraintoviewport: true,
1673 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1677 Dom.removeClass("assignToDiv", "yui-hidden");
1678 SE.contextMenus.assignToDialogue.render();
1679 SE.contextMenus.assignToDialogue.show();
1683 * Marks email flagged on mail server
1685 markFlagged : function(contextMenuId) {
1686 SE.contextMenus.markEmail('flagged');
1690 * Marks email unflagged on mail server
1692 markUnflagged : function(contextMenuId) {
1693 SE.contextMenus.markEmail('unflagged');
1697 * Marks email unread on mail server
1699 markUnread : function() {
1700 SE.contextMenus.markEmail('unread');
1704 * Deletes an email from context menu
1706 markDeleted : function() {
1707 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1708 document.getElementById('_blank').innerHTML = "";
1709 SE.contextMenus.markEmail('deleted');
1714 * generic call API to apply a flag to emails on the server and on sugar
1715 * @param string type "read" | "unread" | "flagged" | "deleted"
1717 markEmail : function(type) {
1718 SE.contextMenus.emailListContextMenu.hide();
1720 //var dm = SE.grid.getStore();
1721 //var uids = SE.grid.getSelectedRowIds();
1722 //var indexes = SE.grid.getSelectedRowIndexes();
1723 var rows = SE.grid.getSelectedRows();
1724 if (rows.length == 0)
1725 rows = [SE.contextMenus.currentRow];
1728 for(var i=0; i<rows.length; i++) {
1729 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1732 ser = YAHOO.lang.JSON.stringify(ser);
1734 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1735 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1741 if(type == 'read' || type == 'deleted') {
1743 for(var j=0; j<rows.length; j++) {
1744 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1746 SE.grid.getRecord(rows[j]).setData("seen", "1");
1749 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1751 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1752 var unseenCount = node.data.unseen;
1753 if (isNaN(unseenCount)) {
1756 var finalCount = parseInt(unseenCount) - count;
1757 node.data.unseen = finalCount;
1759 SE.accounts.renderTree();
1761 } else if(type == 'unread') {
1763 for(var j=0; j<rows.length; j++) {
1764 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1769 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1770 var unseenCount = node.data.unseen;
1771 if (isNaN(unseenCount)) {
1774 var finalCount = parseInt(unseenCount) + count;
1775 node.data.unseen = finalCount;
1776 SE.accounts.renderTree();
1779 if (type == 'unread') {
1780 for(var i=0; i<rows.length; i++) {
1781 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1785 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1786 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1790 * refreshes the ListView to show changes to cache
1792 markEmailCleanup : function() {
1793 SE.accounts.renderTree();
1794 SUGAR.hideMessageBox();
1795 SE.listView.refreshGrid();
1798 showAssignmentDialog : function() {
1799 if (SE.contextMenus.assignmentDialog == null) {
1800 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1802 SE.contextMenus.assignmentDialog.show();
1807 * shows the import dialog with only relate visible.
1809 relateTo : function() {
1810 SE.contextMenus.emailListContextMenu.hide();
1812 var rows = SE.grid.getSelectedRows();
1813 var data = SE.grid.getRecord(rows[0]).getData();
1814 var ieId = data.ieId;
1815 var folder = data.mbox;
1817 /* iterate through available rows JIC a row is deleted - use first available */
1818 for(var i=0; i<rows.length; i++) {
1819 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1821 var ser = YAHOO.lang.JSON.stringify(uids);
1823 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1827 * shows the import dialog with only relate visible.
1829 showDetailView : function() {
1830 SE.contextMenus.emailListContextMenu.hide();
1831 var rows = SE.grid.getSelectedRows();
1832 if (rows.length > 1) {
1833 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1836 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1837 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1838 /* iterate through available rows JIC a row is deleted - use first available */
1839 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1840 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1846 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1847 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1848 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1852 * Opens multiple messages from ListView context click
1854 openMultiple : function() {
1855 SE.contextMenus.emailListContextMenu.hide();
1857 var rows = SE.grid.getSelectedRows();
1858 var uids = SE.listView.getUidsFromSelection();
1860 if(uids.length > 0) {
1861 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1862 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1863 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1868 * Replies/forwards email
1870 replyForwardEmailContext : function() {
1871 SE.contextMenus.emailListContextMenu.hide();
1873 var indexes = SE.grid.getSelectedRows();
1874 //var dm = SE.grid.getDataModel();
1877 for(var i=0; i<indexes.length; i++) {
1878 var row = SE.grid.getRecord(indexes[i]).getData();
1879 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1883 //show menu functions
1884 showEmailsListMenu : function(grid, row) {
1886 var data = row.getData();
1887 var draft = (data.type == "draft");
1888 var menu = SE.contextMenus.emailListContextMenu;
1893 if (data.mbox == 'sugar::Emails')
1894 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1896 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1898 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1899 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1900 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1901 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1903 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1906 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1908 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1909 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1910 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1911 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1912 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1915 if (data.mbox == "sugar::Emails")
1917 //Allow users to reassign imported emails
1918 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1919 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1920 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1921 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1925 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1926 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1930 showFolderMenu : function(grid, rowIndex, event) {
1932 var coords = event.getXY();
1933 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1937 SE.contextMenus.dv = {
1938 archiveToSugar : function(contextMenuId) {
1940 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1943 replyForwardEmailContext : function(all) {
1944 SE.contextMenus.detailViewContextMenu.hide();
1953 //// END SE.contextMenus
1954 ///////////////////////////////////////////////////////////////////////////////
1958 ///////////////////////////////////////////////////////////////////////////////
1961 consumeMetaDetail : function(ret) {
1962 // handling if the Email drafts
1963 if(ret.type == 'draft') {
1964 SE.composeLayout.c0_composeDraft();
1969 // cache contents browser-side
1970 SE._setDetailCache(ret);
1972 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1973 // 2 below must be in global context
1975 meta['panelId'] = SE.util.getPanelId();
1977 email = ret.meta.email;
1978 var out = displayTemplate.exec({
1979 'app_strings' : app_strings,
1981 'idx' : targetDiv.id,
1983 'email' : meta.email,
1984 'linkBeans' : linkBeans
1986 var tabLabel = meta.email.name;
1987 if (tabLabel != null && tabLabel.length > 25) {
1988 tabLabel = tabLabel.substring(0, 25) + "...";
1990 targetDiv.set("label", tabLabel);
1991 targetDiv.set("content", out);
1993 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1994 if (SUGAR.email2.util.isIe()) {
1995 displayEmailFrameDiv.style.height = "390px";
1997 displayEmailFrameDiv.style.height = "410px";
2000 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
2001 displayFrame.contentWindow.document.write(email.description);
2002 displayFrame.contentWindow.document.close();
2004 // hide archive links
2005 if(ret.meta.is_sugarEmail) {
2006 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
2007 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
2009 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
2010 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
2015 consumeMetaPreview : function(ret) {
2016 // cache contents browser-side
2017 SE._setDetailCache(ret);
2021 var currrow = SE.grid.getLastSelectedRecord();
2022 currrow = SE.grid.getRecord(currrow);
2024 document.getElementById('_blank').innerHTML = '';
2027 // handling if the Email drafts
2028 if(ret.type == 'draft'){
2029 if (currrow.getData().uid == ret.uid) {
2030 SE.composeLayout.c0_composeDraft();
2035 if (currrow.getData().uid != ret.meta.uid) {
2039 // remove loading sprite
2040 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2041 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2043 meta['panelId'] = SE.util.getPanelId();
2044 email = ret.meta.email;
2046 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2047 'app_strings' : app_strings,
2051 'email' :meta.email,
2052 'linkBeans' : linkBeans
2054 // document.getElementById('_blank').innerHTML = meta.email;
2055 /* displayTemplate.append('_blank', {
2056 'app_strings' : app_strings,
2060 'email' :meta.email,
2061 'linkBeans' : linkBeans
2064 var displayFrame = document.getElementById('displayEmailFramePreview');
2065 displayFrame.contentWindow.document.write(email.description);
2066 displayFrame.contentWindow.document.close();
2068 SE.listViewLayout.resizePreview();
2070 // hide archive links
2071 if(ret.meta.is_sugarEmail) {
2072 document.getElementById("archiveEmailPreview").innerHTML = " ";
2073 document.getElementById("btnEmailViewPreview").style.display = "none";
2074 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2076 //hide view relationship link
2077 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2082 * wraps emailDelete() for single messages, comes from preview or tab
2084 emailDeleteSingle : function(ieId, uid, mbox) {
2085 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2086 // find active panel and close if the user double clicked the email to view.
2087 var activeTabId = SE.util.getPanelId();
2088 if(activeTabId != 'Preview')
2089 SE.innerLayout.get("activeTab").close();
2091 document.getElementById('_blank').innerHTML = "";
2094 uid = YAHOO.lang.JSON.stringify(ser);
2095 this.emailDelete(ieId, uid, mbox);
2100 * Sends async call to delete a given message
2103 emailDelete : function(ieId, uid, mbox) {
2104 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2105 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2106 uid + "&ieId=" + ieId + "&folder=" + mbox);
2110 * retrieves one email to display in the preview pane.
2112 getEmailPreview : function() {
2113 var row = SUGAR.email2.listView.currentRow;
2114 var data = row.getData();
2115 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2116 var setRead = (data['seen'] == 0) ? true : false;
2117 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2118 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2123 * Imports one email into Sugar
2125 importEmail : function(ieId, uid, mbox) {
2126 SE.util.clearHiddenFieldValues('emailUIForm');
2128 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2130 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2131 AjaxObject.target = '';
2132 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2136 * Populates the frameFlex div with the contents of an email
2138 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2139 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2141 var mboxStr = new String(mbox);
2142 var compKey = mbox + uid;
2144 if(setRead == true) {
2145 SE.listView.boldUnreadRows()
2146 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2149 if(destination == SE.innerLayout) {
2151 * loading email into a tab, peer with ListView
2152 * targetDiv must remain in the global namespace as it is used by AjaxObject
2154 //Check if we already have a tab of the email open
2155 var tabs = SE.innerLayout.get("tabs");
2156 for (var t in tabs) {
2157 if (tabs[t].id && tabs[t].id == uid) {
2158 SE.innerLayout.set("activeTab", tabs[t]);
2163 targetDiv = new YAHOO.SUGAR.ClosableTab({
2164 label: loadingSprite,
2170 SE.innerLayout.addTab(targetDiv);
2172 // use cache if available
2173 if(SE.cache[compKey]) {
2174 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2176 // open email as peer-tab to listView
2177 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2178 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2181 // loading email into preview pane
2182 document.getElementById('_blank').innerHTML = loadingSprite;
2184 // use cache if available
2185 if(SE.cache[compKey]) {
2186 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2188 AjaxObject.forceAbort = true;
2189 // open in preview window
2190 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2191 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2196 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2198 if(mboxStr.substring(0,7) == 'sugar::') {
2199 // display an email from Sugar
2200 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2202 // display an email from an email server
2203 document.getElementById('emailUIAction').value = 'getSingleMessage';
2205 document.getElementById('mbox').value = mbox;
2206 document.getElementById('ieId').value = ieId;
2207 document.getElementById('uid').value = uid;
2209 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2211 AjaxObject.forceAbort = true;
2212 AjaxObject.target = '_blank';
2213 AjaxObject.startRequest(callback, null);
2217 * Retrieves multiple emails for DetailView
2219 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2220 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2221 SE.util.clearHiddenFieldValues('emailUIForm');
2223 var mboxStr = new String(mbox);
2225 uids = SE.util.cleanUids(uids);
2227 if(mboxStr.substring(0,7) == 'sugar::') {
2228 // display an email from Sugar
2229 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2230 document.getElementById('uid').value = uids;
2232 // display an email from an email server
2233 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2234 document.getElementById('mbox').value = mbox;
2235 document.getElementById('ieId').value = ieId;
2236 document.getElementById('uid').value = uids;
2239 var formObject = document.getElementById('emailUIForm');
2240 YAHOO.util.Connect.setForm(formObject);
2242 AjaxObject.target = 'frameFlex';
2243 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2245 if(setRead == true) {
2246 var c = uids.split(",");
2247 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2252 * Makes async call to get QuickCreate form
2253 * Renders a modal edit view for a given module
2255 quickCreate : function(module, ieId, uid, mailbox) {
2256 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2258 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2259 get += "&sugarEmail=true";
2262 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2266 * Makes async call to save a quick create
2269 saveQuickCreate : function(action) {
2270 var qcd = SE.detailView.quickCreateDialog;
2271 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2272 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2273 var theCallback = callbackQuickCreateSave;
2274 var accountType = '&sugarEmail=true';
2275 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2276 accountType = '&ieId=' + qcd.ieId;
2279 if (action == 'reply') {
2280 theCallback = callbackQuickCreateSaveAndReply;
2281 } else if (action == true) {
2282 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2284 formObject.action.value = 'EmailUIAjax';
2285 YAHOO.util.Connect.setForm(formObject);
2286 SUGAR.showMessageBox('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2287 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2288 accountType + '&mbox=' + qcd.mbox);
2293 * Code to show/hide long list of email address in DetailView
2295 showCroppedEmailList : function(el) {
2296 el.style.display = 'none';
2297 el.previousSibling.style.display = 'inline'
2299 showFullEmailList : function(el) {
2300 el.style.display = 'none';
2301 el.nextSibling.style.display = 'inline';
2305 * Shows the QuickCreate overlay
2306 * @param string ieId
2308 * @param string mailbox
2310 showQuickCreate : function(ieId, uid, mailbox) {
2311 var panelId = SE.util.getPanelId();
2312 var context = document.getElementById("quickCreateSpan" + panelId);
2314 if (!SE.detailView.cqMenus)
2315 SE.detailView.cqMenus = {};
2317 if (SE.detailView.cqMenus[context])
2318 SE.detailView.cqMenus[context].destroy();
2320 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2322 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2325 for (var i=0; i < this.qcmodules.length; i++) {
2326 var module = this.qcmodules[i];
2328 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2331 onclick: { fn: function() {
2332 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2338 menu.render(document.body);
2343 * Displays the "View" submenu in the detailView
2344 * @param string ieId
2346 * @param string mailbox
2348 showViewMenu : function(ieId, uid, mailbox) {
2349 var panelId = SE.util.getPanelId();
2350 var context = "btnEmailView" + panelId;
2351 if (!SE.detailView.viewMenus)
2352 SE.detailView.viewMenus = {};
2354 if (SE.detailView.viewMenus[context])
2355 SE.detailView.viewMenus[context].destroy();
2357 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2359 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2363 (ieId == 'null' || ieId == null) ?
2364 //No ieId - Sugar Email
2366 text: app_strings.LBL_EMAIL_VIEW_RAW,
2367 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2370 //IeID exists, on a remote server
2372 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2373 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2375 text: app_strings.LBL_EMAIL_VIEW_RAW,
2376 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2379 menu.render(document.body);
2384 //#23108 jchi@07/17/2008
2385 menu.render('quickCreateSpan'+ panelId);*/
2386 //this.viewMenu = menu;
2387 //this.viewMenu.show(context);
2390 * Makes async call to get an email's headers
2392 viewHeaders : function(ieId, uid, mailbox) {
2393 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2394 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2398 * Makes async call to get a printable version
2400 viewPrintable : function(ieId, uid, mailbox) {
2401 if(mailbox == 'sugar::Emails') {
2402 // display an email from Sugar
2403 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2405 // display an email from an email server
2406 var emailUIAction = '&emailUIAction=getSingleMessage';
2409 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2410 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2414 * Makes async call to get an email's raw source
2416 viewRaw : function(ieId, uid, mailbox) {
2417 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2418 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2422 * Display all email addresses in detailview.
2424 displayAllAddrs : function(el) {
2425 el.style.display = 'none';
2426 Dom.getNextSibling(el).style.display = 'inline';
2429 //// END SE.detailView
2430 ///////////////////////////////////////////////////////////////////////////////
2434 ///////////////////////////////////////////////////////////////////////////////
2437 contextMenuFocus : new Object(),
2440 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2441 * SugarFolder ID - folder strings
2443 _createFolderId : function(node) {
2449 if(node.data.ieId) {
2450 /* we have a local Sugar folder */
2451 if(node.data.ieId == 'folder') {
2452 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2453 } else if(node.data.ieId.match(SE.reGUID)) {
2454 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2463 addChildNode : function(parentNode, childNode) {
2464 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2465 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2466 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2468 if(childNode.nodes) {
2469 if(childNode.nodes.length > 0) {
2470 for(j=0; j<childNode.nodes.length; j++) {
2471 var newChildNode = childNode.nodes[j];
2472 this.addChildNode(node, newChildNode);
2479 * Builds and returns a new TreeView Node
2480 * @param string name
2482 * @param int is_group
2485 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2486 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2488 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2489 node.expanded = expanded;
2490 node.data = new Object;
2491 node.data['id'] = id;
2492 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2493 node.data['label'] = name;
2494 node.data['ieId'] = 'folder';
2495 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2496 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2497 node.data['unseen'] = unseen;
2502 * ensures that a new folder has a valid name
2504 checkFolderName : function(name) {
2508 this.folderAdd(name);
2512 * Pings email servers for new email - forces refresh of folder pane
2514 checkEmailAccounts : function() {
2515 this.checkEmailAccountsSilent(true);
2518 checkEmailAccountsSilent : function(showOverlay) {
2519 if(typeof(SE.folders.checkingMail)) {
2520 clearTimeout(SE.folders.checkingMail);
2523 // don't stomp an on-going request
2524 if(AjaxObject.currentRequestObject.conn == null) {
2526 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW,
2527 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2529 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2531 // wait 5 secs before trying again.
2532 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2537 * Starts check of all email Accounts using a loading bar for large POP accounts
2539 startEmailAccountCheck : function() {
2540 // don't do two checks at the same time
2541 if(!AjaxObject.requestInProgress()) {
2542 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2543 SE.accounts.ieIds = SE.folders.getIeIds();
2544 if (SE.accounts.ieIds.length > 0) {
2545 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2546 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2548 SUGAR.hideMessageBox();
2551 // wait 5 secs before trying again.
2552 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2557 * Checks a single Account check based on passed ieId
2559 startEmailCheckOneAccount : function(ieId, synch) {
2566 var node = SE.clickedFolderNode;
2567 if (node && !synch) {
2568 mbox = node.data.mbox;
2570 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2571 SE.accounts.ieIds = [ieId];
2572 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2573 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2578 * Empties trash for subscribed accounts
2580 emptyTrash : function() {
2581 SE.contextMenus.frameFoldersContextMenu.hide();
2582 SUGAR.showMessageBox(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2583 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2587 * Clears Cache files of the inboundemail account
2589 clearCacheFiles : function(ieId) {
2590 SE.contextMenus.frameFoldersContextMenu.hide();
2591 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2592 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2597 * Returns an array of all the active accounts in the folder view
2599 getIeIds : function() {
2601 var root = SE.tree.getRoot();
2602 for(i=0; i < root.children.length; i++) {
2603 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2604 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2605 ieIds.push(root.children[i].children[0].data.ieId);
2612 * loads folder lists in Settings->Folders
2614 lazyLoadSettings : function() {
2615 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2616 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2620 * After the add new folder is done via folders tab on seetings, this function should get called
2621 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2623 loadSettingFolder : function() {
2624 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2625 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2629 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2631 removeSugarFolders : function() {
2633 var root = tree.getRoot();
2634 var folder = SE.util.findChildNode(root, "ieId", "folder");
2636 tree.removeNode(folder);
2637 folder = SE.util.findChildNode(root, "ieId", "folder");
2639 if (!root.childrenRendered) {
2640 root.childrenRendered = true;
2644 rebuildFolders : function(silent) {
2645 if (!silent) SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2646 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2652 * Updates TreeView with Sugar Folders
2654 setSugarFolders : function(delay) {
2655 this.removeSugarFolders();
2656 //AjaxObject.forceAbort = true;
2657 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2661 * Takes async data object and creates the sugar folders in TreeView
2663 setSugarFoldersEnd : function(o) {
2664 var root = SE.tree.getRoot();
2665 addChildNodes(root, {nodes: o});
2666 SE.accounts.renderTree();
2667 //If nothing is loaded in the grid, load "My Inbox"
2668 if (SE.grid.params.ieId == "undefined") {
2669 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2673 startCheckTimer : function() {
2674 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2675 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2677 if(typeof(SE.folders.checkTimer) != 'undefined') {
2678 clearTimeout(SE.folders.checkTimer);
2681 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2682 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2684 SE.userPrefs.emailSettings.firstAutoCheck = true;
2685 SE.folders.checkEmailAccountsSilent(false);
2691 * makes an async call to save user preference and refresh folder view
2692 * @param object SELECT list object
2694 setFolderSelection : function() {
2695 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2697 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2698 var a_active_accnts = "";
2699 for(i=0;i<a_rs.length;i++)
2701 var t_record = a_rs[i];
2702 var is_active = t_record.getData('is_active');
2704 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2707 if(a_active_accnts == "")
2708 a_active_accnts = "&ieIdShow[]=";
2710 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2712 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2716 * makes async call to save user preference for a given node's open state
2717 * @param object node YUI TextNode object
2719 setOpenState : function(node) {
2720 SE.util.clearHiddenFieldValues('emailUIForm');
2721 var nodePath = node.data.id;
2722 var nodeParent = node.parent;
2724 while(nodeParent != null) {
2725 // root node has no ID param
2726 if(nodeParent.data != null) {
2727 nodePath = nodeParent.data.id + "::" + nodePath;
2730 var nodeParent = nodeParent.parent;
2733 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2734 document.getElementById('focusFolder').value = nodePath;
2736 if(node.expanded == true) {
2737 document.getElementById('focusFolderOpen').value = 'open';
2739 document.getElementById('focusFolderOpen').value = 'closed';
2742 var formObject = document.getElementById('emailUIForm');
2743 YAHOO.util.Connect.setForm(formObject);
2745 AjaxObject.startRequest(null, null);
2748 getNodeFromMboxPath : function(path) {
2749 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2750 var a = YAHOO.lang.JSON.parse(path);
2752 var node = tree.getRoot();
2755 while(i < a.length) {
2756 node = this.getChildNodeFromLabel(node, a[i]);
2763 getChildNodeFromLabel : function(node, nodeLabel) {
2764 for(i=0; i<node.children.length; i++) {
2765 if(node.children[i].data.id == nodeLabel) {
2766 return node.children[i];
2772 * returns the node that presumably under the user's right-click
2774 getNodeFromContextMenuFocus : function() {
2775 //// get the target(parent) node
2776 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2778 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2780 // filter local folders
2781 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2782 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2783 if(target.id == '') {
2784 target = target.parentNode;
2791 var targetNode = document.getElementById(target.id);
2792 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2795 var matches = re.exec(targetNode.id);
2797 return document.getElementById(ygtvlabelel1);
2803 // usually parent node
2804 matches = re.exec(targetNode.parentNode.id);
2811 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2812 parentNode.expand();
2818 * Decrements the Unread Email count in folder text
2819 * @param string ieId ID to look for
2820 * @param string mailbox name
2821 * @param count how many to decrement
2823 decrementUnreadCount : function(ieId, mbox, count) {
2828 if(mbox.indexOf("sugar::") === 0) {
2829 var node = this.getNodeFromId(ieId);
2831 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2834 var unseen = node.data.unseen;
2836 var check = unseen - count;
2837 var finalCount = (check >= 0) ? check : 0;
2838 node.data.unseen = finalCount;
2840 SE.accounts.renderTree();
2845 * gets the TreeView node with a given ID/ieId
2846 * @param string id ID to look for
2847 * @return object Node
2849 getNodeFromId : function(id) {
2850 SE.folders.focusNode = null;
2851 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2852 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2853 SE.folders.focusNode = this;
2857 return SE.folders.focusNode;
2861 * Uses ieId and mailbox to try to find a node in the tree
2863 getNodeFromIeIdAndMailbox : function(id, mbox) {
2864 SE.folders.focusNode = null;
2865 if (mbox == "sugar::Emails") {
2869 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2870 if (varsarray instanceof Array) {
2871 if (this.data.ieId && this.data.ieId == varsarray[0]
2872 && this.data.mbox == varsarray[1]) {
2873 SE.folders.focusNode = this;
2877 if (this.data.ieId && this.data.ieId == varsarray) {
2878 SE.folders.focusNode = this;
2882 }, null, [id, mbox]);
2883 return SE.folders.focusNode;
2886 unhighliteAll : function() {
2887 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2891 * Displays a short form
2893 folderAdd : function() {
2894 SE.contextMenus.frameFoldersContextMenu.hide();
2896 var node = SE.clickedFolderNode;
2898 if(node != null && node.data) {
2899 SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2900 app_strings.LBL_EMAIL_SETTINGS_NAME,
2901 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2903 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2907 folderAddRegisterEnter : function() {
2908 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2909 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2910 this.buttons[1].handler);
2912 this.enterKeyListener.enable();
2915 folderRemoveRegisterEnter : function() {
2916 this.enterKeyListener.disable();
2919 folderAddXmlCall : function(name) {
2920 if (trim(name) == "") {
2921 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2924 name = escape(name);
2928 var parentNode = SE.clickedFolderNode;
2930 this.contextMenuFocus = parentNode;
2932 if(parentNode.data.ieId) {
2933 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2937 if(type == 'imap') {
2938 // make an IMAP folder
2939 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2940 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2941 } else if(type == 'sugar') {
2942 // make a Sugar folder
2943 if(SE.folders.isUniqueFolderName(name)) {
2944 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2945 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2947 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2948 SE.folders.folderAdd();
2952 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2955 // hide add-folder diaglogue
2956 SE.e2overlay.hide();
2960 * Removes either an IMAP folder or a Sugar Folder
2962 folderDelete : function() {
2963 SE.contextMenus.frameFoldersContextMenu.hide();
2965 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2967 var parentNode = SE.clickedFolderNode;
2969 if(parentNode != null && parentNode.data) {
2970 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2971 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2975 AjaxObject.target = 'frameFlex';
2977 if(parentNode.data.ieId != 'folder') {
2978 // delete an IMAP folder
2979 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2981 // delete a sugar folder
2982 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2984 SUGAR.showMessageBox("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2985 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2987 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2993 * Rename folder form
2996 folderRename : function() {
2997 SE.contextMenus.frameFoldersContextMenu.hide();
2998 var node = SE.clickedFolderNode;
3001 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
3002 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
3006 SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
3007 app_strings.LBL_EMAIL_SETTINGS_NAME,
3009 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
3011 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
3016 * fills an Object with key-value pairs of available folders
3018 getAvailableFoldersObject : function() {
3019 var ret = new Object();
3020 var tree = SE.tree.root;
3023 for(var i=0; i<tree.children.length; i++) {
3024 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3027 ret['none'] = app_strings.LBL_NONE;
3034 * Fills in key-value pairs for dependent dropdowns
3035 * @param object ret Associative array
3036 * @param object node TreeView node in focus
3037 * @param string currentPath Built up path thus far
3038 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3040 getFolderFromChild : function(ret, node, currentPath, spacer) {
3041 if(node.data != null && node.depth > 0) {
3042 /* handle visual separtors differentiating b/t mailserver and local */
3043 if(node.data.ieId && node.data.ieId == 'folder') {
3044 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3048 ret['spacer0'] = spacer;
3049 } else if(ret.spacer0 != spacer) {
3050 ret['spacer1'] = spacer
3053 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3054 var depthMarker = currentPath;
3055 var retIndex = SE.folders._createFolderId(node);
3056 ret[retIndex] = depthMarker + theLabel;
3059 if(node.children != null) {
3061 currentPath += theLabel + "/";
3064 for(var i=0; i<node.children.length; i++) {
3065 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3073 * Wrapper to refresh folders tree
3075 getFolders : function() {
3076 SE.accounts.rebuildFolderList();
3080 * handles events around folder-rename input field changes
3081 * @param object YUI event object
3083 handleEnter : function(e) {
3084 switch(e.browserEvent.type) {
3086 e.preventDefault(); // click in text field
3090 SE.folders.submitFolderRename(e);
3094 var kc = e.browserEvent.keyCode;
3098 SE.folders.submitFolderRename(e);
3102 e.preventDefault(e);
3103 SE.folders.cancelFolderRename(e);
3110 * Called when a node is clicked on in the folder tree
3111 * @param node, The node clicked on
3112 * @param e, The click event
3114 handleClick : function(o) {
3116 //If the click was on a sugar folder
3117 if (node.data.ieId == "folder") {
3118 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3121 SE.listView.populateListFrame(node, node.data.ieId, false);
3123 //eval(node.data.click);
3128 * Called when a node is right-clicked on in the folder tree
3130 handleRightClick : function(e) {
3131 YAHOO.util.Event.preventDefault(e);
3133 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3134 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3136 //If the click was on a sugar folder
3137 SE.clickedFolderNode = node;
3138 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3139 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3140 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3141 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3142 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3143 menu.getItem(3).cfg.setProperty("disabled", false);
3144 menu.getItem(4).cfg.setProperty("disabled", false);
3145 menu.getItem(5).cfg.setProperty("disabled", false);
3146 menu.getItem(6).cfg.setProperty("disabled", true);
3148 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3149 menu.getItem(0).cfg.setProperty("disabled", true);
3150 menu.getItem(1).cfg.setProperty("disabled", true);
3151 menu.getItem(2).cfg.setProperty("disabled", true);
3152 menu.getItem(3).cfg.setProperty("disabled", true);
3153 menu.getItem(4).cfg.setProperty("disabled", true);
3155 if (node.data.protocol != null) {
3156 menu.getItem(6).cfg.setProperty("disabled", false);
3158 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3159 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3160 //Sent or Draft folders
3161 menu.getItem(3).cfg.setProperty("disabled", true);
3162 menu.getItem(4).cfg.setProperty("disabled", true);
3163 menu.getItem(5).cfg.setProperty("disabled", true);
3166 //For group with auto inbound, disable everything.
3167 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3169 menu.getItem(0).cfg.setProperty("disabled", true);
3170 menu.getItem(1).cfg.setProperty("disabled", true);
3171 menu.getItem(2).cfg.setProperty("disabled", true);
3172 menu.getItem(3).cfg.setProperty("disabled", true);
3173 menu.getItem(4).cfg.setProperty("disabled", true);
3174 menu.getItem(5).cfg.setProperty("disabled", true);
3175 menu.getItem(6).cfg.setProperty("disabled", true);
3178 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3183 * Called when a row is dropped on a node
3185 handleDrop : function(rows, targetFolder) {
3186 var rowData = rows[0].getData();
3187 if (rowData.mbox != targetFolder.data.mbox) {
3188 var srcIeId = rowData.ieId;
3189 var srcFolder = rowData.mbox;
3190 var destIeId = targetFolder.data.ieId;
3191 var destFolder = targetFolder.data.mbox;
3193 for(var i=0; i<rows.length; i++) {
3194 uids[i] = rows[i].getData().uid;
3196 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3201 * Called when something is dragged over a Folder Node
3203 dragOver : function(dragObject) {
3208 * Determines if a folder name is unique to the folder tree
3209 * @param string name
3211 isUniqueFolderName : function(name) {
3212 uniqueFolder = true;
3213 var root = SE.tree.getRoot();
3214 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3215 if (this.attributes && this.attributes.ieId == "folder") {
3216 if (this.attributes.text == name) {
3217 uniqueFolder = false;
3222 return uniqueFolder;
3226 * Makes async call to rename folder in focus
3227 * @param object e Event Object
3229 submitFolderRename : function(newName) {
3230 if (trim(newName) == "") {
3231 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3234 newName = escape(newName);
3235 var node = SE.clickedFolderNode;
3236 var origName = node.data.text
3238 if (newName == origName) {
3241 if(SE.folders.isUniqueFolderName(newName)) {
3242 SUGAR.showMessageBox(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3243 if (node.data.ieId == "folder") {
3245 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3248 //IMAP folder or POP mailbox
3249 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3250 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3251 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3255 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3260 moveFolder : function(folderId, parentFolderId) {
3261 if (folderId != parentFolderId)
3263 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3264 + folderId + "&newParentId=" + parentFolderId);
3269 * makes async call to do a full synchronization of all accounts
3271 synchronizeAccounts : function() {
3272 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3273 SUGAR.showMessageBoxModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3274 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3279 * Updates user's folder subscriptsion (Sugar only)
3280 * @param object SELECT DOM object in focus
3281 * @param string type of Folder selection
3283 updateSubscriptions : function() {
3284 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3288 select = document.getElementById('userFolders');
3290 for(i=0; i<select.options.length; i++) {
3291 var opt = select.options[i];
3292 if(opt.selected && opt.value != "") {
3296 active += opt.value;
3300 //Add the group folder ids.
3301 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3302 for(i=0; i<group_folders.length; i++)
3304 active += ("::" + group_folders[i]);
3307 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3310 * Updates user's group folder subscriptsion (Sugar only)
3311 * @param ieID The group folder to add to the tree view
3313 retrieveGroupFolderSubscriptions : function() {
3315 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3316 var activeGroupFolders = "";
3317 var activeGroupIds = [];
3318 for(i=0;i<a_rs.length;i++)
3320 var t_record = a_rs[i];
3321 var is_active = t_record.getData('is_active');
3322 var isGroupFolder = t_record.getData('has_groupfolder');
3323 var ieID = t_record.getData('id');
3327 activeGroupIds.push(ieID);
3331 return activeGroupIds;
3336 SE.folders.checkEmail2 = function() {
3337 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3339 //// END FOLDERS OBJECT
3340 ///////////////////////////////////////////////////////////////////////////////
3343 ///////////////////////////////////////////////////////////////////////////////
3346 * Keypress Event capture and processing
3349 overall : function(e) {
3350 switch(e.charCode) {
3352 if(e.ctrlKey || e.altKey) {
3353 var focusRegion = SE.innerLayout.regions.center;
3354 if(focusRegion.activePanel.closable == true) {
3355 focusRegion.remove(focusRegion.activePanel);
3363 ///////////////////////////////////////////////////////////////////////////////
3366 ///////////////////////////////////////////////////////////////////////////////
3369 * ListView object methods and attributes
3375 * Fills the ListView pane with detected messages.
3377 populateListFrame : function(node, ieId, forceRefresh) {
3378 SE.innerLayout.selectTab(0);
3379 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3381 Dom.get('_blank').innerHTML = "";
3382 SE.grid.params['emailUIAction'] = 'getMessageList';
3383 SE.grid.params['mbox'] = node.data.mbox;
3384 SE.grid.params['ieId'] = ieId;
3385 forcePreview = true; // loads the preview pane with first item in grid
3386 SE.listView.refreshGrid();
3390 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3392 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3393 SE.innerLayout.selectTab(0);
3394 Dom.get('_blank').innerHTML = "";
3395 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3396 SE.grid.params['ieId'] = node.data.id;
3397 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3398 SE.listView.refreshGrid();
3402 * Sets sort order as user preference
3405 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3407 ieName = ieNamePassed;
3408 focusFolder = focusFolderPassed;
3410 SE.util.clearHiddenFieldValues('emailUIForm');
3411 var previousSort = document.getElementById('sortBy').value;
3413 document.getElementById('sortBy').value = sortBy;
3414 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3415 document.getElementById('focusFolder').value = focusFolder;
3416 document.getElementById('ieId').value = ieId;
3418 if(sortBy == previousSort) {
3419 document.getElementById('reverse').value = '1';
3422 var formObject = document.getElementById('emailUIForm');
3423 YAHOO.util.Connect.setForm(formObject);
3425 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3430 * Enables click/arrow select of grid items which then populate the preview pane.
3432 selectFirstRow : function() {
3433 SE.grid.selModel.selectFirstRow();
3436 selectLastRow : function() {
3437 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3440 setEmailListStyles : function() {
3441 SE.listView.boldUnreadRows();
3443 var ds = SE.grid.getStore();
3444 if (SE.grid.getSelections().length == 0) {
3445 document.getElementById('_blank').innerHTML = '';
3449 if(typeof(ds.baseParams.mbox) != 'undefined') {
3450 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3451 var cm = SE.grid.getColumnModel();
3452 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3453 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3455 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3456 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3460 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3461 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3463 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3464 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3465 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3466 if (node) node.data.unseen = unread;
3468 SE.accounts.renderTree();
3471 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3472 if(forcePreview && ds.totalCount > 0) {
3473 SE.detailView.getEmailPreview();
3474 forcePreview = false;
3479 * Removes a row if found via its UID
3481 removeRowByUid : function(uid) {
3482 uid = new String(uid);
3483 uids = uid.split(',');
3484 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3486 for(j=0; j<uids.length; j++) {
3487 var theUid = uids[j];
3488 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3489 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3490 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3496 displaySelectedEmails : function(rows) {
3497 var dm = SE.grid.getDataModel();
3500 for(i=0; i<rows.length; i++) {
3501 var rowIndex = rows[i].rowIndex;
3502 var metadata = dm.data[rowIndex];
3507 uids += metadata[5];
3509 // unbold unseen email
3510 this.unboldRow(rowIndex);
3513 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3517 * exception handler for data load failures
3519 loadException : function(dataModel, ex, response) {
3524 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3525 * @param string sourceIeId Email's source I-E id
3526 * @param string sourceFolder Email's current folder
3527 * @param destinationIeId Destination I-E id
3528 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3530 * @param array emailUids Array of email's UIDs
3532 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3533 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3534 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3536 SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3537 // remove rows from visibility
3538 for(row in selectedRows) {
3539 //SE.grid.getStore().remove(row);
3542 var baseUrl = '&sourceIeId=' + sourceIeId +
3543 '&sourceFolder=' + sourceFolder +
3544 '&destinationIeId=' + destinationIeId +
3545 '&destinationFolder=' + destinationFolder;
3548 for(i=0; i<emailUids.length; i++) {
3550 uids += app_strings.LBL_EMAIL_DELIMITER;
3552 uids += emailUids[i];
3554 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3555 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3557 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3563 * Unbolds text in the grid view to denote read status
3565 markRead : function(index, record) {
3566 // unbold unseen email
3567 var row = SE.grid.getRecord(record);
3568 row.getData().seen = 1;
3569 SE.grid.getTrEl(record).style.fontWeight = "normal";
3573 * grid row output, bolding unread emails
3575 boldUnreadRows : function() {
3576 // bold unread emails
3577 var trEl = SE.grid.getFirstTrEl();
3578 while(trEl != null) {
3579 if(SE.grid.getRecord(trEl).getData().seen == "0")
3580 trEl.style.fontWeight = "bold";
3582 trEl.style.fontWeight = "";
3583 trEl = SE.grid.getNextTrEl(trEl);
3588 * Show preview for an email if 1 and only 1 is selected
3589 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3591 handleRowSelect : function(e) {
3592 if(e.selectedRows.length == 1) {
3593 SE.detailView.getEmailPreview();
3597 handleDrop : function(e, dd, targetId, e2) {
3599 case 'htmleditordiv':
3600 var rows = SE.grid.getSelectedRows();
3601 if(rows.length > 0) {
3602 SE.listView.displaySelectedEmails(rows);
3607 var targetElId = new String(targetId);
3608 var targetIndex = targetElId.replace('ygtvlabelel',"");
3609 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3610 var dm = SE.grid.getDataModel();
3611 var emailUids = new Array();
3612 var destinationIeId = targetNode.data.ieId;
3613 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3616 var rows = SE.grid.getSelectedRows();
3617 // iterate through dragged rows
3618 for(i=0; i<rows.length; i++) {
3619 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3620 var rowIndex = rows[i].rowIndex;
3621 var dataModelRow = dm.data[rowIndex];
3622 var sourceIeId = dataModelRow[7];
3623 var sourceFolder = dataModelRow[6];
3624 emailUids[i] = dataModelRow[5];
3627 // event wrapped call - need FQ
3628 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3629 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3635 * Hack-around to get double-click and single clicks to work on the grid
3636 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3638 handleClick : function(o) {
3639 SUGAR.email2.grid.clearTextSelection();
3641 var el = SUGAR.email2.grid.getSelectedRows();
3643 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3644 if ( el.length == 1)
3647 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3648 SUGAR.email2.listView.currentRowIndex = rowId;
3649 clearTimeout(SUGAR.email2.detailView.previewTimer);
3650 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3655 * Custom handler for double-click/enter
3656 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3658 getEmail : function(e) {
3659 var rows = SE.grid.getSelectedRows();
3660 var row = SE.grid.getRecord(rows[0]).getData();
3662 clearTimeout(SE.detailView.previewTimer);
3663 document.getElementById("_blank").innerHTML = "";
3665 if(row.type != "draft") {
3666 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3668 // circumventing yui-ext tab generation, let callback handler build new view
3669 SE.util.clearHiddenFieldValues('emailUIForm');
3670 //function(uid, mbox, ieId, setRead, destination) {
3671 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3672 document.getElementById('uid').value = row.uid; // uid;
3673 document.getElementById('mbox').value = row.mbox; // mbox;
3674 document.getElementById('ieId').value = row.ieId; // ieId;
3676 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3677 AjaxObject.target = '_blank';
3678 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3683 * Retrieves a row if found via its UID
3687 getRowIndexByUid : function(uid) {
3688 uid = new String(uid);
3689 uids = uid.split(',');
3691 for(j=0; j<uids.length; j++) {
3692 var theUid = uids[j];
3694 for(i=0; i<SE.grid.getStore().data.length; i++) {
3695 if(SE.grid.getStore().data[i].id == theUid) {
3703 * Returns the UID's of the seleted rows
3706 getUidsFromSelection : function() {
3707 var rows = SE.grid.getSelectedRows();
3709 /* iterate through available rows JIC a row is deleted - use first available */
3710 for(var i=0; i<rows.length; i++) {
3711 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3716 refreshGrid : function() {
3717 SE.grid.getDataSource().sendRequest(
3718 SUGAR.util.paramsToUrl(SE.grid.params),
3719 SE.grid.onDataReturnInitializeTable,
3725 //// END SE.listView
3726 ///////////////////////////////////////////////////////////////////////////////
3728 ///////////////////////////////////////////////////////////////////////////////
3732 * sends search criteria
3733 * @param reference element search field
3735 search : function(el) {
3736 var searchCriteria = new String(el.value);
3738 if(searchCriteria == '') {
3739 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3743 var safeCriteria = escape(searchCriteria);
3745 var accountListSearch = document.getElementById('accountListSearch');
3747 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3748 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3749 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3750 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3751 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3756 * sends advanced search criteria
3758 searchAdvanced : function() {
3759 var formObject = document.getElementById('advancedSearchForm');
3762 //Set assigned user id to blank if name is not present.
3763 if (formObject.elements['assigned_user_name'].value == "")
3764 formObject.elements['assigned_user_id'].value = "";
3766 for(i=0; i<formObject.elements.length; i++) {
3767 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3770 if(formObject.elements[i].type == 'text') {
3771 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3773 if(formObject.elements[i].type == 'hidden') {
3774 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3776 if(formObject.elements[i].type == 'select-one') {
3777 var el = formObject.elements[i];
3778 var v = el.options[el.selectedIndex].value;
3781 SE.grid.params[el.name] = v;
3784 //Clear previous search results if necessary
3785 if(typeof( SE.grid.params[el.name]) != 'undefined')
3786 delete SE.grid.params[el.name]
3793 if(! this.validateSearchFormInput() )
3796 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3797 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3798 var accountListSearch = document.getElementById('accountListSearch');
3799 SE.listView.refreshGrid();
3801 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3806 * Validates the search form inputs to ensure all parameters are valid
3809 validateSearchFormInput: function()
3811 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3812 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3813 var dateCheck = check_form('advancedSearchForm');
3815 //If the parent type is selected ensure the user selected a parent_id.
3816 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3822 * Toggles the advanced options, either hidding or showing the selection.
3824 toggleAdvancedOptions: function()
3826 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3828 for(var i=0;i<el.length;i++)
3830 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3831 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3833 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3837 * clears adv search form fields
3839 searchClearAdvanced : function() {
3840 var form = document.getElementById('advancedSearchForm');
3842 for(i=0; i<form.elements.length; i++) {
3843 if(form.elements[i].type != 'button') {
3844 form.elements[i].value = '';
3850 //////////////////////////////////////////////////////////////////////////////
3853 //////////////////////////////////////////////////////////////////////////////
3856 /******************************************************************************
3857 * USER SIGNATURES calls stolen from Users module
3858 *****************************************************************************/
3859 createSignature : function(record, the_user_id) {
3860 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3862 URL += "&record="+record;
3864 if(the_user_id != "") {
3865 URL += "&the_user_id="+the_user_id;
3867 var windowName = 'email_signature';
3868 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3870 var win = window.open(URL, windowName, windowFeatures);
3871 if(win && win.focus) {
3872 // put the focus on the popup if the browser supports the focus() method
3877 deleteSignature : function() {
3878 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3879 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3880 var singature_id = document.getElementById('signature_id').value;
3881 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3885 saveOptionsGeneral : function(displayMessage) {
3886 var formObject = document.getElementById('formEmailSettingsGeneral');
3887 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3888 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3891 YAHOO.util.Connect.setForm(formObject);
3892 SE.composeLayout.emailTemplates = null;
3894 AjaxObject.target = 'frameFlex';
3895 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3898 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3900 SE.settings.settingsDialog.hide();
3904 * Shows settings container screen
3906 showSettings : function() {
3907 if(!SE.settings.settingsDialog) {
3908 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3914 constraintoviewport: true
3916 dlg.showEvent.subscribe( function (){
3917 var el = this.element;
3918 var viewH = YAHOO.util.Dom.getViewportHeight();
3919 if (this.header && el && viewH - 50 < el.clientHeight) {
3920 var body = this.header.nextElementSibling;
3921 body.style.overflow = "auto";
3922 body.style.height = (viewH - 50) + "px";
3925 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3926 dlg.setBody('<div id="settingsTabDiv"/>');
3927 dlg.beforeRenderEvent.subscribe(function() {
3928 var dd = new YAHOO.util.DDProxy(dlg.element);
3929 dd.setHandleElId(dlg.header);
3930 dd.on('endDragEvent', function() {
3936 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3937 var tabContent = Dom.get("tab_general");
3938 tp.addTab(new YAHOO.widget.Tab({
3939 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3941 content : tabContent.innerHTML,
3942 id : "generalSettings",
3945 tabContent.parentNode.removeChild(tabContent);
3946 tabContent = Dom.get("tab_accounts");
3947 var accountTab = new YAHOO.widget.Tab({
3948 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3950 content : tabContent.innerHTML,
3951 id : "accountSettings"
3953 tp.addTab(accountTab);
3954 tabContent.parentNode.removeChild(tabContent);
3956 tp.appendTo(dlg.body);
3959 SE.settings.settingsDialog.show();
3960 SE.folders.lazyLoadSettings();
3961 SE.accounts.lazyLoad();
3965 lazyLoadRules : function() {
3966 if(false/*!SE.settings.rules*/) {
3967 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3972 //// END SE.settings
3973 ///////////////////////////////////////////////////////////////////////////////
3976 /******************************************************************************
3978 *****************************************************************************/
3979 function removeHiddenNodes(nodes, grid) {
3981 for(var i = nodes.length - 1; i > -1; i--) {
3982 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3983 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3989 function strpad(val) {
3990 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3993 function refreshTodos() {
3994 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3995 AjaxObject.target = 'todo';
3996 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3999 /******************************************************************************
4000 * MUST STAY IN GLOBAL NAMESPACE
4001 *****************************************************************************/
4002 function refresh_signature_list(signature_id, signature_name) {
4003 var field=document.getElementById('signature_id');
4005 for (var i=0; i < field.options.length; i++) {
4006 if (field.options[i].value == signature_id) {
4007 if (field.options[i].selected==false) {
4008 field.options[i].selected=true;
4013 //add item to selection list.
4015 var newElement=document.createElement('option');
4016 newElement.text=signature_name;
4017 newElement.value=signature_id;
4018 field.options.add(newElement);
4019 newElement.selected=true;
4022 //enable the edit button.
4023 var field1=document.getElementById('edit_sig');
4024 field1.style.visibility="inherit";
4025 var deleteButt = document.getElementById('delete_sig');
4026 deleteButt.style.visibility="inherit";
4029 function setDefaultSigId(id) {
4030 var checkbox = document.getElementById("signature_default");
4031 var default_sig = document.getElementById("signatureDefault");
4033 if(checkbox.checked) {
4034 default_sig.value = id;
4036 default_sig.value = "";
4040 function setSigEditButtonVisibility() {
4041 var field = document.getElementById('signature_id');
4042 var editButt = document.getElementById('edit_sig');
4043 var deleteButt = document.getElementById('delete_sig');
4044 if(field.value != '') {
4045 editButt.style.visibility = "inherit";
4046 deleteButt.style.visibility = "inherit";
4048 editButt.style.visibility = "hidden";
4049 deleteButt.style.visibility = "hidden";
4051 }// End of File modules/Emails/javascript/EmailUI.js
4053 /*********************************************************************************
4054 * SugarCRM Community Edition is a customer relationship management program developed by
4055 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4057 * This program is free software; you can redistribute it and/or modify it under
4058 * the terms of the GNU Affero General Public License version 3 as published by the
4059 * Free Software Foundation with the addition of the following permission added
4060 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4061 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4062 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4064 * This program is distributed in the hope that it will be useful, but WITHOUT
4065 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4066 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4069 * You should have received a copy of the GNU Affero General Public License along with
4070 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4071 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4074 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4075 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4077 * The interactive user interfaces in modified source and object code versions
4078 * of this program must display Appropriate Legal Notices, as required under
4079 * Section 5 of the GNU Affero General Public License version 3.
4081 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4082 * these Appropriate Legal Notices must retain the display of the "Powered by
4083 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4084 * technical reasons, the Appropriate Legal Notices must display the words
4085 * "Powered by SugarCRM".
4086 ********************************************************************************/
4089 var sw = YAHOO.SUGAR,
4090 Event = YAHOO.util.Event,
4091 Connect = YAHOO.util.Connect,
4092 Dom = YAHOO.util.Dom
4095 ///////////////////////////////////////////////////////////////////////////////
4098 _contactCache : new Array(), // cache of contacts
4099 _dd : new Array(), // filtered list, same format as _contactCache
4100 _ddLists : new Array(), // list of Lists
4101 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4102 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4103 clickBubble : true, // hack to get around onclick event bubbling
4105 relatedBeanType : '',
4108 itemSpacing : 'white-space:nowrap; padding:2px;',
4114 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4116 initFixForDatatableSort: function () {
4117 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4118 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4119 var oColumn = this._oColumnSet.getColumn(column);
4122 // Validate TD element
4123 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4125 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4127 // Validate TH element
4129 elCell = this.getThEl(column);
4132 var allColumns = this._oColumnSet.flat;
4133 for(var i=0, len=allColumns.length; i<len; i++) {
4134 if(allColumns[i].getThEl().id === elCell.id) {
4135 oColumn = allColumns[i];
4146 cancelEdit : function() {
4147 if(this.editContactDialog)
4148 this.editContactDialog.hide();
4149 if(this.editMailingListDialog)
4150 this.editMailingListDialog.hide();
4154 * Clears filter form
4156 clear : function() {
4157 var t = document.getElementById('contactsFilter');
4163 * handle context-menu Compose-to call
4164 * @param string type 'contacts' or 'lists'
4166 composeTo : function(type, waited) {
4167 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4168 if (activePanel.substring(0, 10) != "composeTab") {
4169 SE.composeLayout.c0_composeNewEmail();
4170 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4171 SE.contextMenus.contactsContextMenu.hide();
4174 var idx = activePanel.substring(10);
4177 // determine if we have a selection to work with
4178 if(type == 'contacts') {
4179 var ids = SE.contactView.getSelectedRows();
4180 for (var i in ids) {
4181 rows[i] = SE.contactView.getRecord(ids[i]);
4183 removeHiddenNodes(rows, SE.contactView);
4187 if(rows.length > 0) {
4188 SE.composeLayout.handleDrop(
4189 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4190 null, rows, 'addressTO' + idx );
4192 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4196 editContact : function() {
4197 SE.contextMenus.contactsContextMenu.hide();
4198 var element = SE.contactView.getSelectedNodes()[0];
4200 if (element.className.indexOf('address-contact') > -1) {
4201 elementId = element.id;
4202 } else if (element.className.indexOf('address-exp-contact') > -1) {
4203 elementId = element.id.substring(2);
4209 * Filters contact entries based on user input
4211 filter : function(inputEl) {
4212 var ret = new Object();
4213 var re = new RegExp(inputEl.value, "gi");
4215 for(var i in this._contactCache) {
4216 if(this._contactCache[i].name.match(re)) {
4217 ret[i] = this._contactCache[i];
4221 this.buildContactList(ret);
4224 fullForm : function(id, module) {
4225 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4229 * returns a formatted email address from the addressBook cache
4231 getFormattedAddress : function(id) {
4232 var o = this._contactCache[id];
4233 var primaryEmail = '';
4235 for(var i=0; i<o.email.length; i++) {
4236 var currentEmail = o.email[i].email_address;
4238 if(o.email[i].primary_address == 1) {
4239 primaryEmail = o.email[i].email_address;
4243 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4244 var name = new String(o.name);
4245 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4246 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4252 * Sets up async call to query for matching contacts, users, etc.
4254 searchContacts : function() {
4255 var fn = document.getElementById('input_searchField').value;
4256 var pe = document.getElementById('input_searchPerson').value;
4258 var rb = document.getElementById('hasRelatedBean').checked;
4261 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4262 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4263 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4264 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4266 this.addressBookDataModel.params['related_bean_id'] = '';
4269 this.addressBookDataModel.params['search_field'] = fn;
4270 this.addressBookDataModel.params['person'] = pe;
4271 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4272 this.grid._oDataSource = this.addressBookDataModel;
4273 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4277 * Clear Search Crieteria For Addressbook
4279 clearAddressBookSearch : function() {
4280 document.getElementById('input_searchField').value = "";
4281 document.getElementById('input_searchPerson').selectedIndex = 0;
4285 * Opens modal select window to add contacts to addressbook
4287 selectContactsDialogue : function(destId) {
4288 if(!this.contactsDialogue) {
4289 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4293 constraintoviewport: true,
4295 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4296 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4298 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4300 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4301 dlg.setBody(body.innerHTML);
4302 dlg.renderEvent.subscribe(function() {
4303 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4304 if (iev && !SUGAR.isIE) {
4305 this.body.style.width = "950px";
4310 dlg.beforeRenderEvent.subscribe(function() {
4311 var dd = new YAHOO.util.DDProxy(dlg.element);
4312 dd.setHandleElId(dlg.header);
4313 dd.on('endDragEvent', function() {
4319 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4321 var tabContent = SUGAR.util.getAndRemove("searchForm");
4322 tp.addTab(new YAHOO.widget.Tab({
4323 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4325 content : tabContent.innerHTML,
4326 id : "addressSearchTab",
4330 var addListenerFields = ['input_searchPerson','input_searchField' ]
4331 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4332 if (e.keyCode == 13) {
4333 YAHOO.util.Event.stopEvent(e);
4334 SUGAR.email2.addressBook.searchContacts();
4338 this.contactsDialogue.render();
4341 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4342 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4346 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4347 var idx = activePanel.substring(10);
4349 SE.addressBook.idx = idx;
4352 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4353 document.getElementById('relatedBeanColumn').style.display = '';
4354 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4355 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4356 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4357 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4358 SE.addressBook.relatedBeanType = relatedBeanType;
4360 document.getElementById('relatedBeanColumn').style.display = 'none';
4361 document.getElementById('hasRelatedBean').checked = false;
4364 if (!SE.addressBook.grid)
4366 if (hasRelatedBeanId) {
4367 document.getElementById('hasRelatedBean').checked = true;
4369 AddressSearchGridInit();
4370 SE.addressBook.relatedBeanId = relatedBeanId;
4374 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4376 SE.addressBook.relatedBeanId = relatedBeanId;
4377 document.getElementById('hasRelatedBean').checked = true;
4379 if (document.getElementById('hasRelatedBean').checked == true)
4381 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4382 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4384 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4385 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4387 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4388 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4389 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4392 //Remove any lingering rows in the result set table if the module was closed.
4393 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4395 SE.addressBook.populateResulstTableEmailAddresses();
4397 this.contactsDialogue.show();
4400 * Clear all email addresses from result table.
4403 clearAllEmailAddressFieldsFromResultTable: function () {
4404 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4405 //Unhighlight any rows currently selected if the emails were cleared.
4406 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4407 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4410 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4411 * results table. This function is called when the address book is displayed.
4413 populateResulstTableEmailAddresses: function () {
4415 var idx = SE.addressBook.idx;
4416 var emailFields = ['to','cc','bcc'];
4418 for(var k=0;k<emailFields.length;k++)
4420 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4421 var allEmails = document.getElementById(elKey).value;
4425 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4427 for (var i=0; i<formatedEmails.length; i++)
4429 var t_name = formatedEmails[i].name;
4430 var t_emailAddr = formatedEmails[i].email_address;
4431 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4433 t_name = displayEmail = t_emailAddr;
4435 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4436 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4437 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4443 * Checks all entries in the result table against a particular email address, returning true
4444 * if the email address is found, false otherwise.
4446 doesEmailAdddressExistInResultTable: function(emailAddress)
4448 if(trim(emailAddress) == '')
4451 var emailAddressFound = false;
4452 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4453 for (var i=0; i < contacts.length; i++)
4455 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4456 //If we are adding to cc or bcc fields, make them visible.
4457 if(data.email_address == emailAddress)
4459 emailAddressFound = true;
4464 return emailAddressFound;
4467 * Takes all email addresses that the users wishes to add from the address book and populates the To
4468 * fields on the compose tab.
4470 populateEmailAddressFieldsFromResultTable: function()
4472 //Clear the fields first, all email addresses are stored in the address book
4473 var idx = SE.addressBook.idx;
4474 var emailFields = ['to','cc','bcc'];
4475 for(var k=0;k<emailFields.length;k++)
4477 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4478 document.getElementById(elKey).value = "";
4481 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4482 for (var i=0; i < contacts.length; i++)
4484 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4486 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4487 //If we are adding to cc or bcc fields, make them visible.
4488 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4489 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4490 //Construct the target id
4491 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4493 var target = document.getElementById(target_id);
4494 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4497 //Delete all rows from the result set table
4498 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4501 SE.addressBook.contactsDialogue.hide()
4504 * Insert contacts into the result table.
4506 insertContactToResultTable : function(event,address_type) {
4508 var contactsDialogue = SE.addressBook.contactsDialogue;
4509 var contacts = SE.addressBook.grid.getSelectedRows();
4511 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4512 for (var i = 0; i < rows.length; i++)
4514 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4516 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4517 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4518 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4519 rows[i].setData("selected",true);
4522 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4523 for (var i = 0; i < checkBoxes.length; i++) {
4524 checkBoxes[i].checked = false;
4530 insertContactRowToResultTable : function(rowId, addressType) {
4531 var data = SE.addressBook.grid.getRecord(rowId).getData();
4532 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4534 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4535 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4536 if(addressType == null)
4537 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4538 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':name,'email_address': data.email,'display_email_address': ea,'bean_id': data.bean_id,'idx' : SE.addressBook.idx});
4541 * Remove a row from the gridsResult table.
4543 removeRowFromGridResults : function(rowId,emailAddress)
4545 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4546 for (var i=0; i < contacts.length; i++)
4548 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4549 var data = rec.getData();
4550 if(data.email_address == emailAddress)
4552 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4557 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4560 * Translates between the addressType To|Cc|Bcc labels/keys.
4562 translateAddresType: function(addressType,fromKey)
4564 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4565 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4566 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4567 var mappingObject = {};
4570 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4573 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4574 mappingObject[displayCc] = 'cc';
4575 mappingObject[displayBcc] = 'bcc';
4578 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4584 toggleSearchRowIcon : function(rowId,show)
4588 var idToShow = rowId + '_add_img';
4589 var idToHide = rowId + '_rm_img';
4593 var idToShow = rowId + '_rm_img';
4594 var idToHide = rowId + '_add_img';
4598 Dom.addClass(idToHide, "yui-hidden");
4599 Dom.removeClass(idToShow, "yui-hidden");
4602 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4604 doesGridResultsEntryExist: function(emailAddrs)
4607 var contactExists = false;
4608 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4609 for (var i=0; i < contacts.length; i++)
4611 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4612 if(data.email_address == emailAddrs)
4614 contactExists = true;
4618 return contactExists;
4622 * adds an email address to a string, but first checks if it exists
4623 * @param string concat The string we are appending email addresses to
4624 * @param string addr Email address to add
4627 smartAddEmailAddressToComposeField : function(concat, addr) {
4628 var re = new RegExp(addr);
4630 if(!concat.match(re)) {
4632 concat += "; " + addr;
4641 //// END ADDRESS BOOK
4642 ///////////////////////////////////////////////////////////////////////////////
4646 ///////////////////////////////////////////////////////////////////////////////
4649 * Auto-complete object
4653 delimChar : [";", ","],
4657 prehighlightClassName : "yui-ac-prehighlight",
4660 instances : new Array(),
4663 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4664 * @param object Contact from AddressBook
4667 getPrimaryAddress : function(contact) {
4668 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4670 for(var eIndex in contact.email) {
4671 address = contact.email[eIndex].email_address;
4672 if(contact.email[eIndex].primary_address == 1) {
4673 return contact.email[eIndex].email_address;
4681 * initializes autocomplete widgets for a given compose view
4684 init : function(idx) {
4685 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4686 "queryMatchContains" : false,
4687 "queryMatchSubset" : true
4690 this.instances[idx] = {
4697 // instantiate the autoComplete widgets
4698 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4699 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4700 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4702 // enable hiding of interfering textareas
4703 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4704 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4705 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4707 // enable reshowing of hidden textareas
4708 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4709 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4710 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4712 // enable refreshes of contact lists
4713 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4714 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4715 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4718 refreshDataSource : function(sType, aArgs) {
4719 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4721 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4723 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4724 idx = textBoxId.substr(9);
4726 idx = textBoxId.substr(10);
4729 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4730 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4731 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4735 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4737 returnDataSource : function(contacts) {
4738 var ret = new Array();
4739 for(var id in contacts) {
4740 if (contacts[id].name) {
4741 var primary = this.getPrimaryAddress(contacts[id]);
4743 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4744 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4746 for(var emailIndex in contacts[id].email) {
4747 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4756 * Hides address textareas to prevent autocomplete dropdown from being obscured
4758 toggleTextareaHide : function(sType, aArgs) {
4759 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4763 if(textBoxId.indexOf("addressTO") > -1) {
4765 } else if(textBoxId.indexOf("addressCC") > -1) {
4768 idx = textBoxId.substr(9);
4770 // follow through if not BCC
4772 var cc = document.getElementById("addressCC" + idx);
4773 var bcc = document.getElementById("addressBCC" + idx);
4777 cc.style.visibility = 'hidden';
4779 bcc.style.visibility = 'hidden';
4786 * Redisplays the textareas after an address is commited
4788 toggleTextareaShow : function(sType, aArgs) {
4789 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4793 if(textBoxId.indexOf("addressTO") > -1) {
4795 } else if(textBoxId.indexOf("addressCC") > -1) {
4798 idx = textBoxId.substr(9);
4800 // follow through if not BCC
4802 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4803 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4808 //// END AUTOCOMPLETE
4809 ///////////////////////////////////////////////////////////////////////////////
4811 ///////////////////////////////////////////////////////////////////////////////
4814 * expands the options sidebar
4816 SE.composeLayout = {
4817 currentInstanceId : 0,
4820 outboundAccountErrors : null,
4821 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4823 showAddressDetails : function(e) {
4824 var linkElement = document.getElementById("More"+e.id);
4825 var spanElement = document.getElementById("Detail"+e.id);
4826 var emailAddressList = e.value;
4827 if(e.value.length > 96)
4829 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4830 var displayArray = [];
4831 for (var i=0; i<resultArray.length; i++)
4833 var t_name = resultArray[i].name;
4834 var t_emailAddr = resultArray[i].email_address;
4836 displayArray.push('<br/><' + t_emailAddr + '>');
4838 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4841 var result = displayArray.join('<br/>');
4843 linkElement.style.display = "inline";
4844 linkElement.style.height="10px";
4845 linkElement.style.overflow="visible";
4846 spanElement.innerHTML = result;
4849 linkElement.style.display = "none";
4854 * Given a string of email address, return an array containing the name portion (if available)
4855 * and email portion.
4857 _getEmailArrayFromString : function (emailAddressList){
4860 while ((results = reg.exec(emailAddressList)) != null)
4862 orignial = results[0];
4863 parsedResult = results[0].replace(';', ':::::');
4864 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4868 while ((results = reg.exec(emailAddressList)) != null)
4870 orignial = results[0];
4871 parsedResult = results[0].replace(',', ':::::');
4872 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4874 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4875 var emailArr = emailAddressList.split(":::::");
4876 var resultsArray = [];
4878 for (var i=0; i<emailArr.length; i++)
4880 var rposition = emailArr[i].indexOf('<');
4881 var lposition = emailArr[i].indexOf('>');
4883 if(trim(emailArr[i]) != '')
4885 if(rposition != -1 && lposition != -1)
4887 var t_name = emailArr[i].substr(0, rposition-1);
4888 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4889 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4893 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4897 return resultsArray;
4899 ///////////////////////////////////////////////////////////////////////////
4902 * Prepare bucket DIV and yui-ext tab panels
4904 _0_yui : function() {
4905 var idx = this.currentInstanceId;
4907 var composeTab = new YAHOO.SUGAR.ClosableTab({
4908 label: mod_strings.LNK_NEW_SEND_EMAIL,
4910 content : "<div id='htmleditordiv" + idx + "'/>",
4911 id : "composeTab" + idx,
4912 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4915 SE.innerLayout.addTab(composeTab);
4917 // get template engine with template
4918 if (!SE.composeLayout.composeTemplate) {
4919 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4922 // create Tab inner layout
4923 var composePanel = this.getComposeLayout();
4924 composePanel.getUnitByPosition("right").collapse();
4925 composePanel.autoSize();
4929 * Generate the quick compose layout
4930 * @method getQuickComposeLayout
4931 * @param {Pannel} parentPanel Parent pannel
4932 * @param {Object} o Options
4935 getQuickComposeLayout : function (parentPanel,o) {
4936 var idx = SE.composeLayout.currentInstanceId;
4938 //Before rendering the parent pannel we need to initalize the grid layout
4939 parentPanel.beforeRenderEvent.subscribe(function() {
4941 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4942 SE.composeLayout._createComposeLayout(idx);
4943 SE.composeLayout[idx].set('height', 350);
4944 SE.composeLayout[idx].render();
4948 //Wait until the Compose Layout has rendered, then add the
4949 //options tab and perform the tiny initialization.
4950 parentPanel.renderEvent.subscribe(function() {
4952 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4953 SE.composeLayout._initComposeOptionTabs(idx);
4954 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4955 //Initialize tinyMCE
4956 SE.composeLayout._1_tiny(false);
4958 //Init templates and address book
4959 SE.composeLayout._2_final();
4961 SE.composeLayout.quickCreateComposePackage(o);
4966 //Check if we have the div override for the shortcut bar
4967 if(typeof o.menu_id != 'undefined') {
4968 parentPanel.render(o.menu_id);
4970 parentPanel.render(document.body);
4973 return SE.composeLayout[idx];
4976 * Fill in all fields into the quick compose layout.
4977 * @method quickCreateComposePackage
4978 * @param {Object} o Options
4981 quickCreateComposePackage: function(o)
4983 //If we have a compose package fill in defaults.
4984 if (typeof(o.composePackage) != 'undefined')
4986 composePackage = o.composePackage; //Set the compose data object
4987 //Hijack this method called by composePackage as it's not need for quick creates.
4988 SE.composeLayout.c0_composeNewEmail = function(){};
4989 SE.composeLayout.composePackage(); //Fill in defaults.
4992 getComposeLayout : function() {
4993 var idx = SE.composeLayout.currentInstanceId;
4995 this._createComposeLayout(idx);
4996 SE.composeLayout[idx].render();
4997 this._initComposeOptionTabs(idx);
4999 return SE.composeLayout[idx];
5003 * Create the layout manager for the compose window.
5005 _createComposeLayout : function(idx)
5007 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
5008 parent: SE.complexLayout,
5018 SE.composeLayout.composeTemplate.exec({
5019 'app_strings':app_strings,
5020 'mod_strings':mod_strings,
5021 'linkbeans_options' : linkBeans,
5022 'idx' : SE.composeLayout.currentInstanceId
5033 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5036 header: app_strings.LBL_EMAIL_OPTIONS
5042 * Create compose tab which will populate the 'right' container in the compose window.
5044 _initComposeOptionTabs : function(idx)
5046 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5047 var tab = new YAHOO.widget.Tab({
5048 label: app_strings.LBL_EMAIL_ATTACHMENT,
5050 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5051 id : "divAttachments" + idx,
5055 tab.layout = SE.composeLayout[idx];
5057 tab.on("activeChange", function(o){
5059 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5065 tab = new YAHOO.widget.Tab({
5066 label: app_strings.LBL_EMAIL_OPTIONS,
5068 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5069 id : "divOptions" + idx,
5073 tab.layout = SE.composeLayout[idx];
5074 tab.on("activeChange", function(o){
5076 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5081 SE.composeLayout[idx].autoSize = function() {
5082 var pEl = this.get("element").parentNode.parentNode.parentNode;
5083 this.set("height", pEl.clientHeight-30);
5087 SE.composeLayout[idx].rightTabs = cTabs;
5089 isParentTypeValid : function(idx) {
5090 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5091 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5092 if (trim(parentTypeValue) == ""){
5093 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5099 isParentTypeAndNameValid : function(idx) {
5100 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5101 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5102 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5103 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5104 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5105 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5111 callopenpopupForEmail2 : function(idx,options) {
5113 var formName = 'emailCompose' + idx;
5115 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5116 formName = options.form_name;
5118 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5119 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5120 if (!SE.composeLayout.isParentTypeValid(idx)) {
5123 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5125 call_back_function:"SE.composeLayout.popupAddEmail",
5127 field_to_name_array:{
5128 id:'data_parent_id' + idx,
5129 name:'data_parent_name' + idx,
5134 popupAddEmail : function(o)
5136 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5137 var data = o.name_to_value_array;
5138 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5139 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5141 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5142 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5149 _1_tiny : function(isReplyForward) {
5150 var idx = SE.composeLayout.currentInstanceId;
5151 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5152 SE.tinyInstances[elId] = { };
5153 SE.tinyInstances[elId].ready = false;
5155 if (!SUGAR.util.isTouchScreen()) {
5156 var t = tinyMCE.getInstanceById(elId);
5158 if(typeof(t) == 'undefined') {
5159 if (!SUGAR.util.isTouchScreen()) {
5160 tinyMCE.execCommand('mceAddControl', false, elId);
5162 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5163 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
5168 resizeEditorSetSignature : function(idx,setSignature)
5170 var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5172 if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
5173 setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+setSignature+"');",500);
5177 SE.composeLayout.resizeEditor(idx);
5179 setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
5184 resizeEditor : function(idx)
5186 var cof = Dom.get('composeOverFrame' + idx);
5187 var head = Dom.get('composeHeaderTable' + idx);
5188 var targetHeight = cof.clientHeight - head.clientHeight;
5189 var instance = SE.util.getTiny('htmleditor' + idx);
5192 var parentEl = Dom.get(instance.editorId + '_parent');
5193 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5194 var contentEl = instance.contentAreaContainer;
5195 var iFrame = contentEl.firstChild;
5196 var tinMceToolbarOffset = 18;
5197 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5200 setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
5205 * Initializes d&d, auto-complete, email templates
5207 _2_final : function() {
5208 var idx = SE.composeLayout.currentInstanceId;
5210 if(this.emailTemplates) {
5211 this.setComposeOptions(idx);
5213 //populate email template cache
5214 AjaxObject.target = '';
5215 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5218 // handle drop targets for addressBook
5219 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5220 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5221 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5222 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5224 // auto-complete setup
5225 SE.autoComplete.init(idx);
5228 document.getElementById("addressTO" + idx).focus();
5232 * hide tinyMCE tool bar if send email as plaintext is checked
5234 renderTinyMCEToolBar : function (idx, hide) {
5236 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5238 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5242 c1_composeEmail : function(isReplyForward, retry) {
5246 if (!SUGAR.util.isTouchScreen() && (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined')){
5247 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5249 this._1_tiny(isReplyForward);
5252 if(isReplyForward) {
5253 this.replyForwardEmailStage2();
5259 * takes draft info and prepopulates
5261 c0_composeDraft : function() {
5262 this.getNewInstanceId();
5264 document.getElementById('_blank').innerHTML = '';
5265 var idx = SE.composeLayout.currentInstanceId;
5266 SE.composeLayout.draftObject = new Object();
5267 SE.composeLayout.draftObject.id = idx;
5268 SE.composeLayout.draftObject.isDraft = true;
5269 SE.composeLayout.currentInstanceId = idx;
5270 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5271 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5272 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5274 SE.composeLayout._0_yui();
5275 SE.composeLayout._1_tiny(true);
5278 SE.composeLayout._2_final();
5280 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5281 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5285 * Strip & Prep editor hidden fields
5287 c0_composeNewEmail : function() {
5288 this.getNewInstanceId();
5289 this.c1_composeEmail(false);
5293 * Sends async request to get the compose view.
5294 * Requests come from "reply" or "forwards"
5296 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5297 SE.composeLayout.replyForwardObj = new Object();
5298 SE.composeLayout.replyForwardObj.ieId = ieId;
5299 SE.composeLayout.replyForwardObj.uid = uid;
5300 SE.composeLayout.replyForwardObj.mbox = mbox;
5301 SE.composeLayout.replyForwardObj.type = type;
5303 if(mbox == 'sugar::Emails') {
5304 SE.composeLayout.replyForwardObj.sugarEmail = true;
5307 SE.composeLayout.getNewInstanceId();
5308 SE.composeLayout.c1_composeEmail(true);
5310 //// END COMPOSE FLOW
5311 ///////////////////////////////////////////////////////////////////////////
5314 * Called when a contact, email, or mailinglist is dropped
5315 * into one of the compose fields.
5317 handleDrop : function (source, event, data, target) {
5320 target = event.getTarget();
5322 data.nodes = [data.nodes];
5326 target = document.getElementById(target);
5330 if (target.id.indexOf('address') > -1) {
5331 // dropped onto email to/cc/bcc field
5332 for(var i in nodes) {
5333 var node = nodes[i].getData();
5335 if (node[1].indexOf('contact') > -1) {
5336 email = SE.addressBook.getFormattedAddress(node[0]);
5337 } else if (node[1].indexOf('address-email') > -1){
5338 email = node[3].replace(/ /gi, '');
5339 email = email.replace('<', '<').replace('>', '>');
5340 var tr = source.getTrEl(nodes[i]);
5341 while (tr && !Dom.hasClass(tr, "address-contact")) {
5342 tr = source.getPreviousTrEl(tr);
5344 var CID = source.getRecord(tr).getData()[0];
5345 var o = SE.addressBook._contactCache[CID];
5346 var name = new String(o.name);
5347 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5348 email = finalName + email;
5350 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5356 /*/////////////////////////////////////////////////////////////////////////////
5357 /// EMAIL TEMPLATE CODE
5359 applyEmailTemplate : function (idx, id) {
5362 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5363 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5364 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5367 var to_addr = document.getElementById('addressTO'+idx);
5368 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
5370 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5371 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5374 // id is selected index of email template drop-down
5375 if(id == '' || id == "0") {
5376 YAHOO.SUGAR.MessageBox.show({
5381 if(btn=='no'){return;};
5382 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5389 YAHOO.SUGAR.MessageBox.show({
5394 if(btn=='no'){return;};
5395 SUGAR.email2.composeLayout.processResult(idx, id);},
5401 processNoneResult : function(idx, id) {
5402 var tiny = SE.util.getTiny('htmleditor' + idx);
5403 var tinyHTML = tiny.getContent();
5404 var openTag = '<div><span><span>';
5405 var htmllow = tinyHTML.toLowerCase();
5406 var start = htmllow.indexOf(openTag);
5408 tinyHTML = tinyHTML.substr(start);
5409 tiny.setContent(tinyHTML);
5411 tiny.setContent('');
5415 processResult : function(idx , id){
5416 var post_data = {"module":"EmailTemplates","record":id};
5417 var global_rpcClient = new SugarRPCClient();
5419 result = global_rpcClient.call_method('retrieve', post_data, true);
5420 if(!result['record']) return;
5421 json_objects['email_template_object'] = result['record'];
5422 this.appendEmailTemplateJSON();
5424 // get attachments if any
5425 AjaxObject.target = '';
5426 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5429 appendEmailTemplateJSON : function() {
5430 var idx = SE.composeLayout.currentInstanceId; // post increment
5432 // query based on template, contact_id0,related_to
5433 //jchi 09/10/2008 refix #7743
5434 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5435 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5438 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,'"');
5440 // cn: bug 14361 - text-only templates don't fill compose screen
5442 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/>");
5445 var tiny = SE.util.getTiny('htmleditor' + idx);
5446 var tinyHTML = tiny.getContent();
5447 var openTag = '<div><span><span>';
5448 var closeTag = '</span></span></div>';
5449 var htmllow = tinyHTML.toLowerCase();
5450 var start = htmllow.indexOf(openTag);
5452 var htmlPart2 = tinyHTML.substr(start);
5453 tinyHTML = text + htmlPart2;
5454 tiny.setContent(tinyHTML);
5456 tiny.setContent(text);
5461 * Writes out the signature in the email editor
5463 setSignature : function(idx) {
5466 var hide = document.getElementById('setEditor' + idx).checked;
5467 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5468 //wait for signatures to load before trying to set them
5469 if (!SE.composeLayout.signatures) {
5470 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5475 var sel = document.getElementById('signatures' + idx);
5477 var sel = document.getElementById('signature_id');
5478 idx = SE.tinyInstances.currentHtmleditor;
5481 //Ensure that the tinyMCE html has been rendered.
5482 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5483 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5490 signature = sel.options[sel.selectedIndex].value;
5495 var openTag = '<div><span> </span>';
5496 var closeTag = '<span> </span></div>';
5497 var t = tinyMCE.getInstanceById('htmleditor' + idx);
5499 if(typeof(t) != 'undefined')
5501 t.contentDocument = t.contentWindow.document;
5502 var html = t.getContent();
5509 var htmllow = html.toLowerCase();
5510 var start = htmllow.indexOf(openTag);
5511 var end = htmllow.indexOf(closeTag) + closeTag.length;
5513 // selected "none" - remove signature from email
5514 if(signature == '') {
5516 var htmlPart1 = html.substr(0, start);
5517 var htmlPart2 = html.substr(end, html.length);
5519 html = htmlPart1 + htmlPart2;
5522 SE.signatures.lastAttemptedLoad = '';
5526 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5527 SE.signatures.lastAttemptedLoad = '';
5529 SE.signatures.lastAttemptedLoad = signature;
5531 if(typeof(SE.signatures[signature]) == 'undefined') {
5533 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5534 SE.signatures.targetInstance = (idx) ? idx : "";
5535 AjaxObject.target = '';
5536 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5538 var newSignature = this.prepareSignature(SE.signatures[signature]);
5540 // clear out old signature
5541 if(SE.signatures.lastAttemptedLoad && start > -1) {
5542 var htmlPart1 = html.substr(0, start);
5543 var htmlPart2 = html.substr(end, html.length);
5545 html = htmlPart1 + htmlPart2;
5549 start = html.indexOf('<div><hr></div>');
5550 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5551 var htmlPart1 = html.substr(0, start);
5552 var htmlPart2 = html.substr(start, html.length);
5553 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5554 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5555 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5557 var body = html.indexOf('</body>');
5559 var part1 = html.substr(0, body);
5560 var part2 = html.substr(body, html.length);
5561 var newHtml = part1 + openTag + newSignature + closeTag + part2;
5563 var newHtml = html + openTag + newSignature + closeTag;
5566 //tinyMCE.setContent(newHtml);
5567 t.setContent(newHtml);
5571 prepareSignature : function(str) {
5572 var signature = new String(str);
5574 signature = signature.replace(/</gi, '<');
5575 signature = signature.replace(/>/gi, '>');
5581 showAttachmentPanel : function(idx) {
5582 var east = SE.composeLayout[idx].getUnitByPosition("right");
5583 var tabs = SE.composeLayout[idx].rightTabs;
5585 tabs.set("activeTab", tabs.getTab(0));
5589 * expands sidebar and displays options panel
5591 showOptionsPanel : function(idx) {
5592 var east = SE.composeLayout[idx].getUnitByPosition("right");
5593 var tabs = SE.composeLayout[idx].rightTabs;
5595 tabs.set("activeTab", tabs.getTab(1));
5599 * Selects the Contacts tab
5601 showContactsPanel : function() {
5602 SE.complexLayout.regions.west.showPanel("contactsTab");
5606 * Generates fields for Select Document
5608 addDocumentField : function(idx) {
5609 var basket = document.getElementById('addedDocuments' + idx);
5611 var index = (basket.childNodes.length / 7) - 1;
5618 var test = document.getElementById('documentId' + idx + index);
5620 while(test != null) {
5622 test = document.getElementById('documentId' + idx + index);
5625 var documentCup = document.createElement("div");
5626 documentCup.id = 'documentCup' + idx + index;
5627 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5628 // document id field
5629 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5630 // document name field
5631 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5633 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5634 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5635 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5637 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5638 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5639 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5642 basket.appendChild(documentCup);
5643 //basket.innerHTML += out;
5648 * Makes async call to save a draft of the email
5649 * @param int Instance index
5651 saveDraft : function(tinyInstance) {
5652 this.sendEmail(tinyInstance, true);
5655 selectDocument : function(target) {
5656 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5657 windowName = 'selectDocument';
5658 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5660 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5662 // put the focus on the popup if the browser supports the focus() method
5668 * Modal popup for file attachment dialogue
5670 addFileField : function() {
5671 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5672 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5676 constraintoviewport: true,
5678 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5679 fn:function(){SE.addFileDialog.hide();}
5682 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5683 SE.addFileDialog.render();
5684 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5686 Dom.removeClass("addFileDialog", "yui-hidden");
5688 SE.addFileDialog.show();
5692 * Async upload of file to temp dir
5694 uploadAttachment : function() {
5695 if(document.getElementById('email_attachment').value != "") {
5696 var formObject = document.getElementById('uploadAttachment');
5697 YAHOO.util.Connect.setForm(formObject, true, true);
5698 AjaxObject.target = '';
5699 AjaxObject.startRequest(callbackUploadAttachment, null);
5701 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5706 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5707 * @param string target in focus compose layout
5709 setDocument : function(idx, target, documentId, documentName, docRevId) {
5710 // fields are named/id'd [fieldName][instanceId][index]
5711 var addedDocs = document.getElementById("addedDocuments" + idx);
5712 var docId = document.getElementById('documentId' + idx + target);
5713 var docName = document.getElementById('documentName' + idx + target);
5714 var docRevisionId = document.getElementById('document' + idx + target);
5715 docId.value = documentId;
5716 docName.value = documentName;
5717 docRevisionId.value = docRevId;
5721 * Removes the bucket div containing the document input fields
5723 deleteDocumentField : function(documentCup) {
5724 var f0 = document.getElementById(documentCup);
5725 f0.parentNode.removeChild(f0);
5729 * Removes a Template Attachment field
5733 deleteTemplateAttachmentField : function(idx, index) {
5734 // create not-in-array values for removal filtering
5735 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5741 r += document.getElementById('templateAttachmentId' + idx + index).value;
5742 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5744 var target = 'templateAttachmentCup' + idx + index;
5745 d = document.getElementById(target);
5746 d.parentNode.removeChild(d);
5750 * Async removal of uploaded temp file
5751 * @param string index Should be a concatenation of idx and index
5754 deleteUploadAttachment : function(index, file) {
5755 var d = document.getElementById('email_attachment_bucket' + index);
5756 d.parentNode.removeChild(d);
5758 // make async call to delete cached file
5759 AjaxObject.target = '';
5760 AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5764 * Attaches files coming from Email Templates
5766 addTemplateAttachmentField : function(idx) {
5768 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5770 var basket = document.getElementById('addedTemplateAttachments' + idx);
5773 var index = basket.childNodes.length;
5780 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5782 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5783 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5784 idx + "\",\"" + index + "\");'/>" +
5786 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5787 // templateAttachment field
5788 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5790 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5792 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5793 "<br id='br" + index + "></br>" +
5794 "<br id='brdoc" + index + "></br>" +
5796 basket.innerHTML = basket.innerHTML + out;
5802 * Sends one email via async call
5803 * @param int idx Editor instance ID
5804 * @param bool isDraft
5806 sendEmail : function(idx, isDraft) {
5808 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5809 var obAccountID = document.getElementById('addressFrom' + idx).value;
5811 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5813 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5818 var form = document.getElementById('emailCompose' + idx);
5819 var composeOptionsFormName = "composeOptionsForm" + idx;
5822 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5823 if (t != null || typeof(t) != "undefined") {
5824 var html = t.getContent();
5826 var html = "<p>" + document.getElementById('htmleditor' + idx).value + "</p>";
5829 var subj = document.getElementById('emailSubject' + idx).value;
5830 var to = trim(document.getElementById('addressTO' + idx).value);
5831 var cc = trim(document.getElementById('addressCC' + idx).value);
5832 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5833 var email_id = document.getElementById('email_id' + idx).value;
5834 var composeType = document.getElementById('composeType').value;
5835 var parent_type = document.getElementById("parent_type").value;
5836 var parent_id = document.getElementById("parent_id").value;
5838 var el_uid = document.getElementById("uid");
5839 var uid = (el_uid == null) ? '' : el_uid.value;
5841 var el_ieId = document.getElementById("ieId");
5842 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5844 var el_mbox = document.getElementById("mbox");
5845 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5847 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5848 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5852 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5855 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5856 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5857 parent_id = parentIdValue;
5858 parent_type = parentTypeValue;
5860 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5861 // baseline viability check
5863 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5864 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5866 } else if(subj == '' && !isDraft) {
5867 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5870 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5872 } else if(html == '' && !isDraft) {
5873 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5878 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5879 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5880 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5881 SUGAR.showMessageBox(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5882 html = html.replace(/</ig, "sugarLessThan");
5883 html = html.replace(/>/ig, "sugarGreaterThan");
5885 form.sendDescription.value = html;
5886 form.sendSubject.value = subj;
5887 form.sendTo.value = to;
5888 form.sendCc.value = cc;
5889 form.sendBcc.value = bcc;
5890 form.email_id.value = email_id;
5891 form.composeType.value = composeType;
5892 form.composeLayoutId.value = 'composeLayout' + idx;
5893 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5894 form.saveToSugar.value = 1;
5895 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5896 form.parent_type.value = parent_type;
5897 form.parent_id.value = parent_id;
5898 form.uid.value = uid;
5899 form.ieId.value = ieId;
5900 form.mbox.value = mbox;
5902 // email attachments
5903 var addedFiles = document.getElementById('addedFiles' + idx);
5905 for(i=0; i<addedFiles.childNodes.length; i++) {
5906 var bucket = addedFiles.childNodes[i];
5908 for(j=0; j<bucket.childNodes.length; j++) {
5909 var node = bucket.childNodes[j];
5910 var nName = new String(node.name);
5912 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5913 if(form.attachments.value != '') {
5914 form.attachments.value += "::";
5916 form.attachments.value += node.value;
5923 var addedDocs = document.getElementById('addedDocuments' + idx);
5925 for(i=0; i<addedDocs.childNodes.length; i++) {
5926 var cNode = addedDocs.childNodes[i];
5927 for(j=0; j<cNode.childNodes.length; j++) {
5928 var node = cNode.childNodes[j];
5929 var nName = new String(node.name);
5930 if(node.type == 'hidden' && nName.match(/documentId/)) {
5931 if(form.documents.value != '') {
5932 form.documents.value += "::";
5934 form.documents.value += node.value;
5940 // template attachments
5941 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5942 if(addedTemplateAttachments) {
5943 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5944 var cNode = addedTemplateAttachments.childNodes[i];
5945 for(j=0; j<cNode.childNodes.length; j++) {
5946 var node = cNode.childNodes[j];
5947 var nName = new String(node.name);
5948 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5949 if(form.templateAttachments.value != "") {
5950 form.templateAttachments.value += "::";
5952 form.templateAttachments.value += node.value;
5958 // remove attachments
5959 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5961 YAHOO.util.Connect.setForm(form);
5963 AjaxObject.target = 'frameFlex';
5965 // sending a draft email
5966 if(!isDraft && in_draft) {
5968 SE.listView.removeRowByUid(email_id);
5971 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5972 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5974 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5978 * Handles clicking the email address link from a given view
5980 composePackage : function() {
5981 if(composePackage != null) {
5982 SE.composeLayout.c0_composeNewEmail();
5985 if(composePackage.to_email_addrs) {
5986 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5988 if (composePackage.subject != null && composePackage.subject.length > 0) {
5989 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5992 //If no parent fields are set in the composePackage, ensure they are cleared.
5993 var parentFields = ['parent_type','parent_name','parent_id'];
5994 for(var i=0;i<parentFields.length;i++)
5996 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5997 composePackage[parentFields[i]] = "";
6000 document.getElementById("parent_type").value = composePackage.parent_type;
6001 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
6002 document.getElementById("parent_id").value = composePackage.parent_id;
6003 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
6004 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
6006 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
6007 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
6009 if (composePackage.body != null && composePackage.body.length > 0) {
6010 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6011 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
6012 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
6014 if (composePackage.attachments != null) {
6015 SE.composeLayout.loadAttachments(composePackage.attachments);
6018 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
6019 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
6020 SE.util.emptySelectOptions(addressFrom);
6021 var fromAccountOpts = composePackage.fromAccounts.data;
6022 for(i=0; i<fromAccountOpts.length; i++) {
6023 var key = fromAccountOpts[i].value;
6024 var display = fromAccountOpts[i].text;
6025 var opt = new Option(display, key);
6026 if (fromAccountOpts[i].selected) {
6027 opt.selected = true;
6029 addressFrom.options.add(opt);
6036 setContentOnThisTiny : function() {
6037 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6038 var tinyHTML = tiny.getContent();
6039 composePackage.body = decodeURI(encodeURI(composePackage.body));
6040 // cn: bug 14361 - text-only templates don't fill compose screen
6041 if(composePackage.body == '') {
6042 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
6044 //Flag determines if we should clear the tiny contents or just append
6045 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
6046 SE.composeLayout.tinyHTML = '';
6048 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
6050 tiny.setContent(SE.composeLayout.tinyHTML);
6051 //Indicate that the contents has been loaded successfully.
6052 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
6055 * Confirms closure of a compose screen if "x" is clicked
6057 confirmClose : function(panel) {
6058 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6059 SE.composeLayout.closeCompose(panel.id);
6067 * forces close of a compose screen
6069 forceCloseCompose : function(id) {
6070 SE.composeLayout.closeCompose(id);
6072 // handle flow back to originating view
6073 if(composePackage) {
6074 // check if it's a module we need to return to
6075 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6076 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6077 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6078 window.location = url;
6085 * closes the editor that just sent email
6086 * @param string id ID of composeLayout tab
6088 closeCompose : function(id) {
6089 // destroy tinyMCE instance
6090 var idx = id.substr(13, id.length);
6091 var instanceId = "htmleditor" + idx;
6092 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6094 // nullify DOM and namespace values.
6096 SE.composeLayout[idx] = null;
6097 SE.tinyInstances[instanceId] = null;
6098 var tabsArray = SE.innerLayout.get("tabs");
6099 for (i = 0 ; i < tabsArray.length ; i++) {
6100 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6101 tabsArray[i].close();
6105 //SE.innerLayout.getTab(idx).close();
6109 * Enable the quick search for the compose relate field or search tab
6111 enableQuickSearchRelate: function(idx,overides){
6113 if(typeof overides != 'undefined')
6115 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6116 var newModule = document.getElementById(newModuleID).value;
6117 var formName = overides['formName'];
6118 var fieldName = overides['fieldName'];
6119 var fieldId = overides['fieldId'];
6120 var fullName = formName + "_" + fieldName;
6121 var postBlurFunction = null;
6125 var newModule = document.getElementById('data_parent_type'+idx).value;
6126 var formName = 'emailCompose'+idx;
6127 var fieldName = 'data_parent_name'+idx;
6128 var fieldId = 'data_parent_id'+idx;
6129 var fullName = formName + "_" + fieldName;
6130 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6133 if(typeof sqs_objects == 'undefined')
6134 window['sqs_objects'] = new Array;
6136 window['sqs_objects'][fullName] = {
6139 modules:[newModule],
6141 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6142 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6143 post_onblur_function: postBlurFunction,
6144 order:"name","limit":"30","no_match_text":"No Match"};
6147 if(typeof QSProcessedFieldsArray != 'undefined')
6148 QSProcessedFieldsArray[fullName] = false;
6149 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6150 QSFieldsArray[fullName].destroy();
6151 delete QSFieldsArray[fullName];
6153 if (Dom.get(fullName + "_results")) {
6154 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6160 qsAddAddress : function(o) {
6161 if (o.name != "" && o.email1 != "")
6163 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6164 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6168 * Returns a new instance ID, 0-index
6170 getNewInstanceId : function() {
6171 this.currentInstanceId = this.currentInstanceId + 1;
6172 return this.currentInstanceId;
6176 * 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.
6178 loadAttachments : function(result) {
6179 var idx = SE.composeLayout.currentInstanceId;
6181 if(typeof(result) == 'object') {
6182 //jchi #20680. Clean the former template attachments;
6183 var basket = document.getElementById('addedTemplateAttachments' + idx);
6184 if(basket.innerHTML != ''){
6185 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6187 basket.innerHTML = '';
6192 if(typeof result[i] == 'object') {
6193 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6194 var bean = result[i];
6195 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6196 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6203 * fills drop-down values for email templates and signatures
6205 setComposeOptions : function(idx) {
6206 // send from accounts
6207 var addressFrom = document.getElementById('addressFrom' + idx);
6209 if (addressFrom.options.length <= 0) {
6210 SE.util.emptySelectOptions(addressFrom);
6211 var fromAccountOpts = SE.composeLayout.fromAccounts;
6212 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6213 var key = fromAccountOpts[id].value;
6214 var display = fromAccountOpts[id].text;
6215 var is_default = false;
6216 if(key == SUGAR.default_inbound_accnt_id)
6218 var opt = new Option(display, key);
6219 addressFrom.options.add(opt);
6220 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6225 var et = document.getElementById('email_template' + idx);
6226 SE.util.emptySelectOptions(et);
6228 for(var key in this.emailTemplates) { // iterate through assoc array
6229 var display = this.emailTemplates[key];
6230 var opt = new Option(display, key);
6231 et.options.add(opt);
6235 var sigs = document.getElementById('signatures' + idx);
6236 SE.util.emptySelectOptions(sigs);
6238 for(var key in this.signatures) { // iterate through assoc array
6239 var display = this.signatures[key];
6240 var opt = new Option(display, key);
6242 if(key == SE.userPrefs.signatures.signature_default) {
6243 opt.selected = true;
6246 sigs.options.add(opt);
6249 // html/plain email?
6250 var htmlEmail = document.getElementById('setEditor' + idx);
6251 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6252 htmlEmail.checked = true;
6254 htmlEmail.checked = false;
6257 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6261 * After compose screen is rendered, async call to get email body from Sugar
6263 replyForwardEmailStage2 : function() {
6264 SE.util.clearHiddenFieldValues('emailUIForm');
6265 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6267 var ieId = SE.composeLayout.replyForwardObj.ieId;
6268 var uid = SE.composeLayout.replyForwardObj.uid;
6269 var mbox = SE.composeLayout.replyForwardObj.mbox;
6270 var type = SE.composeLayout.replyForwardObj.type;
6271 var idx = SE.composeLayout.currentInstanceId;
6273 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6275 document.getElementById('emailSubject' + idx).value = type;
6276 document.getElementById('emailUIAction').value = 'composeEmail';
6277 document.getElementById('composeType').value = type;
6278 document.getElementById('ieId').value = ieId;
6279 document.getElementById('uid').value = uid;
6280 document.getElementById('mbox').value = mbox;
6281 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6282 var formObject = document.getElementById('emailUIForm');
6283 YAHOO.util.Connect.setForm(formObject);
6285 var sendType = type;
6286 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6290 * Show the hidden cc or bcc fields
6292 showHiddenAddress: function(addrType,idx){
6294 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6295 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6296 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6297 this[addrType+'Hidden'+idx] = false;
6299 //After bcc or cc is added, move options below last addr field
6300 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6302 //If both cc and bcc hidden, remove the empty row containing text.
6303 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6304 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6305 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6307 // SE.composeLayout.resizeEditor(idx);
6310 * Hide the cc and bcc fields if they were shown.
6312 hideHiddenAddresses: function(idx){
6314 var addrTypes = ['cc','bcc'];
6315 for(var i = 0;i<addrTypes.length;i++)
6317 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6318 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6319 this[addrTypes[i] + 'Hidden'+idx] = true
6322 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6323 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6324 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6328 //// END SE.composeLayout
6329 ///////////////////////////////////////////////////////////////////////////////
6330 ///////////////////////////////////////////////////////////////////////////////
6334 * Cleans serialized UID lists of duplicates
6338 cleanUids : function(str) {
6339 var seen = new Object();
6341 var arr = new String(str).split(",");
6343 for(var i=0; i<arr.length; i++) {
6348 clean += (clean != "") ? "," : "";
6350 seen[arr[i]] = true;
6357 * Clears hidden field values
6358 * @param string id ID of form element to clear
6360 clearHiddenFieldValues : function(id) {
6361 var form = document.getElementById(id);
6363 for(i=0; i<form.elements.length; i++) {
6364 if(form.elements[i].type == 'hidden') {
6365 var e = form.elements[i];
6366 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6374 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6376 emptySelectOptions : function(el) {
6378 for(i=el.childNodes.length - 1; i >= 0; i--) {
6379 if(el.childNodes[i]) {
6380 el.removeChild(el.childNodes[i]);
6387 * Returns the MBOX path in the manner php_imap expects:
6388 * ie: INBOX.DEBUG.test
6389 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6391 generateMboxPath : function(str) {
6392 var ex = str.split("::");
6394 /* we have a serialized MBOX path */
6398 for(var i=0; i<ex.length; i++) {
6399 if(ex[i] == 'INBOX') {
6411 /* we have a Sugar folder GUID - do nothing */
6419 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6420 * @param HTMLElement el
6421 * @return string GUID of found element or empty on failure
6423 getGuidFromElement : function(el) {
6429 for(var i=0; i<iterations; i++) {
6431 if(el.id.match(SE.reGUID)) {
6443 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6446 getPanelId : function() {
6447 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6451 * wrapper to handle weirdness with IE
6452 * @param string instanceId
6453 * @return tinyMCE Controller object
6455 getTiny : function(instanceId) {
6456 if(instanceId == '') {
6460 var t = tinyMCE.getInstanceById(instanceId);
6464 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6470 * Simple check for MSIE browser
6474 var nav = new String(navigator.appVersion);
6475 if(nav.match(/MSIE/)) {
6482 * Recursively removes an element from the DOM
6483 * @param HTMLElement
6485 removeElementRecursive : function(el) {
6486 this.emptySelectOptions(el);
6493 sleep : function(secs) {
6494 setTimeout("void(0);", secs);
6498 * Converts a <select> element to an Ext.form.combobox
6500 convertSelect : function(select) {
6501 alert('in convertSelect');
6502 if (typeof(select) == "string") {
6503 select = document.getElementById(select);
6507 findChildNode : function (parent, property, value) {
6508 for (i in parent.children) {
6509 var child = parent.children[i];
6510 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6512 var searchChild = SE.util.findChildNode(child, property, value);
6519 cascadeNodes : function (parent, fn, scope, args) {
6520 for (i in parent.children) {
6521 var child = parent.children[i];
6522 var s = scope ? scope : child;
6523 var a = args ? args : child;
6525 SE.util.cascadeNodes(child, fn, scope, args);
6532 ///////////////////////////////////////////////////////////////////////////////
6535 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6537 /*********************************************************************************
6538 * SugarCRM Community Edition is a customer relationship management program developed by
6539 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6541 * This program is free software; you can redistribute it and/or modify it under
6542 * the terms of the GNU Affero General Public License version 3 as published by the
6543 * Free Software Foundation with the addition of the following permission added
6544 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6545 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6546 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6548 * This program is distributed in the hope that it will be useful, but WITHOUT
6549 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6550 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6553 * You should have received a copy of the GNU Affero General Public License along with
6554 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6555 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6558 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6559 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6561 * The interactive user interfaces in modified source and object code versions
6562 * of this program must display Appropriate Legal Notices, as required under
6563 * Section 5 of the GNU Affero General Public License version 3.
6565 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6566 * these Appropriate Legal Notices must retain the display of the "Powered by
6567 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6568 * technical reasons, the Appropriate Legal Notices must display the words
6569 * "Powered by SugarCRM".
6570 ********************************************************************************/
6573 if (typeof console == "undefined")
6574 console = { log: function(o) {alert(o)} };
6578 currentRequestObject : null,
6579 //timeout : 30000, // 30 second timeout default
6580 timeout : 9999999999, // 30 second timeout default
6582 trail : new Array(),
6586 _reset : function() {
6587 this.timeout = 30000;
6588 this.forceAbort = false;
6591 folderRenameCleanup : function() {
6592 SUGAR.email2.folders.setSugarFolders();
6595 fullSyncCleanup : function(o) {
6596 this.folders.checkMailCleanup(o);
6597 SUGAR.email2.settings.settingsDialog.hide();
6602 composeCache : function(o) {
6603 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6604 // get email templates and user signatures
6605 var ret = YAHOO.lang.JSON.parse(o.responseText);
6607 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6608 SUGAR.email2.composeLayout.signatures = ret.signatures;
6609 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6611 SUGAR.email2.composeLayout.setComposeOptions(idx);
6613 //Set the error array so we can notify the user when they try to hit send if any errors
6614 //are present. We will also notify them now (after hitting compose button).
6615 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6618 //if error element is returning an array, then check the length to make sure we have error messages
6619 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6620 //add error messages for display
6621 for(i in ret.errorArray)
6622 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6623 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6624 //if error element is returning an object, and the object value is not empty or null, then display error message
6625 for(i in ret.errorArray)
6626 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6629 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6631 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6633 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6639 handleDeleteSignature : function(o) {
6640 SUGAR.hideMessageBox();
6641 var ret = YAHOO.lang.JSON.parse(o.responseText);
6642 SUGAR.email2.composeLayout.signatures = ret.signatures;
6643 var field = document.getElementById('signature_id');
6644 SUGAR.email2.util.emptySelectOptions(field);
6646 for(var i in ret.signatures) { // iterate through assoc array
6647 var opt = new Option(ret.signatures[i], i);
6648 field.options.add(opt);
6650 setSigEditButtonVisibility();
6655 handleDeleteReturn : function(o) {
6656 // force refresh ListView
6657 SUGAR.hideMessageBox();
6658 if(document.getElementById('focusEmailMbox')) {
6659 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6662 // need to display success message before calling next async call?
6663 document.getElementById(this.target).innerHTML = o.responseText;
6668 handleFailure : function(o) {
6670 SUGAR.showMessageBox('Exception occurred...', o.statusText, 'alert');
6671 if(document.getElementById('saveButton')) {
6672 document.getElementById('saveButton').disabled = false;
6676 handleReplyForward : function(o) {
6677 var a = YAHOO.lang.JSON.parse(o.responseText);
6679 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6681 document.getElementById('email_id' + idx).value = a.uid;
6682 document.getElementById('emailSubject' + idx).value = a.name;
6683 document.getElementById('addressTO' + idx).value = a.from;
6684 document.getElementById('uid' + idx).value = a.uid;
6686 document.getElementById('addressCC' + idx).value = a.cc;
6687 SE.composeLayout.showHiddenAddress('cc', idx);
6691 document.getElementById('type' + idx).value = a.type;
6694 // apply attachment values
6695 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6697 setTimeout("callbackReplyForward.finish(globalA);", 500);
6700 handleReplyForwardForDraft : function(o) {
6701 var a = YAHOO.lang.JSON.parse(o.responseText);
6703 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6705 document.getElementById('email_id' + idx).value = a.uid;
6706 document.getElementById('emailSubject' + idx).value = a.name;
6707 document.getElementById('addressTO' + idx).value = a.to;
6710 document.getElementById('addressCC' + idx).value = a.cc;
6711 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6715 document.getElementById('addressBCC' + idx).value = a.bcc;
6716 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6721 document.getElementById('type' + idx).value = a.type;
6725 // apply attachment values
6726 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6728 setTimeout("callbackReplyForward.finish(globalA);", 500);
6733 handleSuccess : function(o) {
6734 document.getElementById(this.target).innerHTML = o.responseText;
6735 SUGAR.hideMessageBox();
6740 ieDeleteSuccess : function(o) {
6741 SUGAR.hideMessageBox();
6742 SUGAR.email2.accounts.refreshInboundAccountTable();
6743 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6744 SUGAR.email2.accounts.rebuildFolderList();
6749 ieSaveSuccess : function(o) {
6750 document.getElementById('saveButton').disabled = false;
6751 var a = YAHOO.lang.JSON.parse(o.responseText);
6754 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6755 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6757 resp = YAHOO.lang.JSON.parse(o.responseText);
6758 SUGAR.email2.accounts.refreshInboundAccountTable();
6759 SUGAR.email2.accounts.refreshOuboundAccountTable();
6760 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6761 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6764 SUGAR.hideMessageBox();
6765 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6772 loadAttachments : function(o) {
6773 var result = YAHOO.lang.JSON.parse(o.responseText);
6775 SUGAR.email2.composeLayout.loadAttachments(result);
6780 loadSignature : function(o) {
6781 var ret = YAHOO.lang.JSON.parse(o.responseText);
6782 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6783 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6787 * Follow up to mark email read|unread|flagged
6789 markEmailCleanup : function(o) {
6790 var ret = YAHOO.lang.JSON.parse(o.responseText);
6791 if (!ret['status']) {
6792 SUGAR.hideMessageBox();
6793 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6795 SUGAR.email2.contextMenus.markEmailCleanup();
6801 rebuildShowFolders : function(o) {
6802 var t = YAHOO.lang.JSON.parse(o.responseText);
6803 var show = document.getElementById('ieAccountListShow');
6805 SUGAR.email2.util.emptySelectOptions(show);
6807 for(i=0; i<t.length; i++) { // iterate through assoc array
6808 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6809 opt.selected = t[i].selected;
6810 show.options.add(opt);
6813 SUGAR.email2.accounts.renderTree();
6817 saveListViewSortOrderPart2 : function() {
6818 // create the JSON string the func expects
6819 focusFolderPath = '[ "Home", "' + ieName + '"';
6821 var f = new String(focusFolder);
6822 var fEx = f.split('.');
6824 for(i=0; i<fEx.length; i++) {
6825 focusFolderPath += ', "' + fEx[i] +'"'
6828 focusFolderPath += ']';
6830 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6831 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6837 sendEmailCleanUp : function(o) {
6839 SUGAR.hideMessageBox();
6842 ret = YAHOO.lang.JSON.parse(o.responseText);
6843 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6844 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6846 if (o.responseText) {
6847 SUGAR.showMessageBox(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6849 // Else we have an error here.
6852 if (typeof(SE.grid) != 'undefined')
6853 SE.listView.refreshGrid();
6854 //Disabled while address book is disabled
6856 //If this call back was initiated by quick compose from a Detail View page, refresh the
6857 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6858 //close the shortcut bar menu
6859 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6860 if(action_sugar_grp1 == 'DetailView') {
6861 showSubPanel('history',null,true);
6862 } else if(action_sugar_grp1 == 'quickcreate') {
6863 closeEmailOverlay();
6869 ieSendSuccess : function(o) {
6870 SUGAR.hideMessageBox();
6871 SUGAR.showMessageBox(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6876 settingsFolderRefresh : function(o) {
6877 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6878 var ret = YAHOO.lang.JSON.parse(o.responseText);
6879 var user = document.getElementById('userFolders');
6881 SUGAR.email2.util.emptySelectOptions(user);
6883 for(i=0; i<ret.userFolders.length; i++) {
6884 var display = ret.userFolders[i].name;
6885 var value = ret.userFolders[i].id;
6886 var selected = (ret.userFolders[i].selected != "") ? true : false;
6887 var opt = new Option(display, value, selected);
6888 opt.selected = selected;
6889 user.options.add(opt);
6895 startRequest : function(callback, args, forceAbort) {
6896 if(this.currentRequestObject != null) {
6897 if(this.forceAbort == true) {
6898 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6901 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6905 requestInProgress : function() {
6906 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6911 updateFolderSubscriptions : function() {
6912 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6913 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6914 SUGAR.hideMessageBox();
6919 updateFrameFolder : function() {
6920 SUGAR.email2.folders.checkEmailAccounts();
6925 updateUserPrefs : function(o) {
6926 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
6927 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6932 uploadAttachmentSuccessful : function(o) {
6934 document.getElementById('email_attachment').value = '';
6936 var ret = YAHOO.lang.JSON.parse(o.responseText);
6937 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6938 var overall = document.getElementById('addedFiles' + idx);
6939 var index = overall.childNodes.length;
6941 "<div id='email_attachment_bucket" + idx + index + "'>" +
6943 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6944 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6945 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6947 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6948 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6950 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6952 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6955 overall.innerHTML += out;
6956 if(SUGAR.email2.util.isIe()) {
6957 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6961 SUGAR.email2.addFileDialog.hide();
6962 // focus attachments
6963 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6968 ///////////////////////////////////////////////////////////////////////////
6969 //// PER MODULE CALLBACK OBJECTS
6970 AjaxObject.accounts = {
6971 saveOutboundCleanup : function(o) {
6972 SUGAR.email2.accounts.refreshOuboundAccountTable();
6973 SUGAR.email2.accounts.outboundDialog.hide();
6974 var id = o.responseText;
6975 SUGAR.email2.accounts.newAddedOutboundId = id;
6977 saveDefaultOutboundCleanup: function(o){
6980 callbackEditOutbound : {
6981 success : function(o)
6983 var ret = YAHOO.lang.JSON.parse(o.responseText);
6985 SUGAR.email2.accounts.showAddSmtp();
6988 document.getElementById("mail_id").value = ret.id;
6989 document.getElementById("type").value = ret.type;
6990 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6991 document.getElementById("mail_name").value = ret.name;
6992 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6993 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6994 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6995 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6996 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6997 SUGAR.email2.accounts.smtp_authenticate_field_display();
6998 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
7000 if(ret.type == 'system-override') {
7001 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
7002 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
7005 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
7006 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
7008 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
7011 failure : AjaxObject.handleFailure,
7012 timeout : AjaxObject.timeout,
7015 callbackDeleteOutbound : {
7016 success : function(o) {
7017 var ret = YAHOO.lang.JSON.parse(o.responseText);
7020 if(confirm(ret.error_message))
7022 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
7023 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
7026 SUGAR.hideMessageBox();
7030 SUGAR.hideMessageBox();
7031 SUGAR.email2.accounts.refreshOuboundAccountTable();
7035 failure : AjaxObject.handleFailure,
7036 timeout : AjaxObject.timeout,
7040 callbackCheckMailProgress : {
7041 success : function(o) {
7042 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
7043 SUGAR.email2.accounts.totalMsgCount = -1;
7046 //Check for server timeout / errors
7047 var ret = YAHOO.lang.JSON.parse(o.responseText);
7050 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
7051 SUGAR.hideMessageBox();
7052 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7053 SUGAR.email2.accounts.totalMsgCount = -1;
7054 //SUGAR.email2.folders.rebuildFolders();
7058 var currIeId = ret['ieid'];
7061 var serverCount = ret.count;
7063 if (ret['status'] == 'done') {
7064 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7065 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7069 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7070 //Go to next account
7071 currIeId = SUGAR.email2.accounts.ieIds[i+1];
7073 SUGAR.email2.accounts.totalMsgCount = -1;
7078 else if (ret.mbox && ret.totalcount && ret.count) {
7079 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7080 if (ret.count >= ret.totalcount) {
7083 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7084 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7086 SUGAR.hideMessageBox();
7087 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7088 SUGAR.email2.accounts.totalMsgCount = -1;
7093 SUGAR.email2.accounts.totalMsgCount = -1;
7094 SUGAR.hideMessageBox();
7095 SUGAR.email2.folders.rebuildFolders();
7096 SE.listView.refreshGrid();
7097 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7098 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7099 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7100 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7102 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7103 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7104 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7105 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7106 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7109 failure : AjaxObject.handleFailure,
7110 timeout : AjaxObject.timeout,
7115 ///////////////////////////////////////////////////////////////////////////////
7117 AjaxObject.composeLayout = {
7119 * Populates the record id
7121 saveDraftCleanup : function(o) {
7123 SUGAR.hideMessageBox();
7126 ret = YAHOO.lang.JSON.parse(o.responseText);
7127 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7129 if (o.responseText) {
7130 SUGAR.showMessageBox(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7136 AjaxObject.composeLayout.callback = {
7138 success : AjaxObject.composeLayout.saveDraftCleanup,
7139 failure : AjaxObject.handleFailure,
7140 timeout : AjaxObject.timeout,
7145 AjaxObject.detailView = {
7147 * Pops-up a printable view of an email
7149 displayPrintable : function(o) {
7150 var ret = YAHOO.lang.JSON.parse(o.responseText);
7151 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7152 // 2 below must be in global context
7154 meta['panelId'] = SUGAR.email2.util.getPanelId();
7155 email = ret.meta.email;
7156 if (typeof(email.cc) == 'undefined') {
7160 var out = displayTemplate.exec({
7161 'app_strings' : app_strings,
7165 'email' : meta.email
7168 // open popup window
7169 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7170 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7172 popup.document.write(out);
7173 popup.document.close();
7177 * Takes formatted response and creates a modal pop-over containing a title and content
7179 displayView : function(o) {
7180 var SED = SUGAR.email2.detailView;
7181 var ret = YAHOO.lang.JSON.parse(o.responseText);
7183 if(!SED.viewDialog) {
7184 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7188 constraintoviewport: true,
7191 SED.viewDialog.renderEvent.subscribe(function() {
7192 var content = this.body.firstChild;
7193 var viewH = YAHOO.util.Dom.getViewportHeight();
7195 this.body.style.overflow = "auto";
7196 this.body.style.width = "800px";
7197 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7201 SED.viewDialog.setHeader(ret.title);
7202 SED.viewDialog.setBody(ret.html);
7203 SED.viewDialog.render();
7204 SED.viewDialog.show();
7208 * Generates a modal popup to populate with the contents of bean's full EditView
7210 showQuickCreateForm : function(o) {
7211 var SED = SUGAR.email2.detailView;
7212 var ret = YAHOO.lang.JSON.parse(o.responseText);
7214 if(!SED.quickCreateDialog) {
7215 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7219 constraintoviewport: true,
7223 SED.quickCreateDialog.renderEvent.subscribe(function() {
7224 var viewH = YAHOO.util.Dom.getViewportHeight();
7226 for (var i in this.body.childNodes) {
7227 if (this.body.childNodes[i].clientHeight) {
7228 contH += this.body.childNodes[i].clientHeight;
7229 } else if (this.body.childNodes[i].offsetHeight) {
7230 contH += this.body.childNodes[i].offsetHeight;
7233 this.body.style.width = "800px";
7234 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7235 this.body.style.overflow = "auto";
7236 }, SED.quickCreateDialog);
7238 SED.quickCreateDialog.hideEvent.subscribe(function(){
7239 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7240 /*for(var qsField in qsFields){
7241 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7242 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7245 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7248 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7250 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7251 SED.quickCreateDialog.render();
7252 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7254 SED.quickCreateDialog.ieId = ret.ieId;
7255 SED.quickCreateDialog.uid = ret.uid;
7256 SED.quickCreateDialog.mbox = ret.mbox;
7257 SED.quickCreateDialog.qcmodule = ret.module;
7259 SED.quickCreateDialog.show();
7261 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7263 editForm.module.value = 'Emails';
7264 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7265 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7266 var instId = ret.module + count;
7267 SED.quickCreateEmailsToAdd = ret.emailAddress;
7268 SED.quickCreateEmailCallback = function(instId, tableId) {
7269 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7270 if (typeof(eaw) == "undefined")
7271 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7272 + instId + "','" + tableId + "');", 100);
7273 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7275 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7276 + instId + "','" + tableId + "');", 100);
7280 saveQuickCreateForm : function(o) {
7281 SUGAR.hideMessageBox();
7282 SUGAR.email2.detailView.quickCreateDialog.hide();
7283 validate['EditView'] = [ ];
7286 saveQuickCreateFormAndReply : function(o) {
7287 SUGAR.hideMessageBox();
7288 var ret = YAHOO.lang.JSON.parse(o.responseText);
7289 SUGAR.email2.detailView.quickCreateDialog.hide();
7290 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7291 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7293 var emailID = ret.id;
7294 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7296 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7298 //Cean the validate cache to prevent errors on the next call
7299 validate['EditView'] = [ ];
7302 saveQuickCreateFormAndAddToAddressBook : function(o) {
7303 SUGAR.hideMessageBox();
7304 SUGAR.email2.detailView.quickCreateDialog.hide();
7305 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7306 validate['EditView'] = [ ];
7309 handleAssignmentDialogAssignAction : function() {
7312 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7314 var dist = 'direct';
7318 var found_teams = false;
7319 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7320 if(!found_teams && assign_user_id == '' )
7322 alert(warning_message);
7326 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7328 for(i=0; i<emailUids.length; i++) {
7330 uids += app_strings.LBL_EMAIL_DELIMITER;
7332 uids += emailUids[i];
7335 var row = SUGAR.email2.grid.getSelectedRows()[0];
7336 var data = SUGAR.email2.grid.getRecord(row).getData();
7337 var ieid = data.ieId;
7338 var mbox = data.mbox;
7339 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7340 SUGAR.email2.contextMenus.assignToDialogue.hide();
7341 SUGAR.showMessageBox('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7345 handleAssignmentDialogDeleteAction : function() {
7346 // TO pass list of UIDS/emailIds
7347 var uids = SUGAR.email2.listView.getUidsFromSelection();
7348 var row = SUGAR.email2.grid.getSelections()[0];
7349 var ieid = row.data.ieId;
7350 var mbox = row.data.mbox;
7351 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7352 SUGAR.email2.contextMenus.assignmentDialog.hide();
7353 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7359 showEmailDetailView : function(o) {
7360 SUGAR.hideMessageBox();
7361 var SED = SUGAR.email2.detailView;
7362 var ret = YAHOO.lang.JSON.parse(o.responseText);
7364 if(!SED.quickCreateDialog) {
7365 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7369 constraintoviewport: true,
7371 autofillheight: "body",
7374 SED.quickCreateDialog.renderEvent.subscribe(function() {
7375 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7377 for (var i in this.body.childNodes) {
7378 if (this.body.childNodes[i].offsetHeight)
7379 contH += this.body.childNodes[i].offsetHeight;
7381 this.body.style.overflow = "auto";
7382 this.body.style.width = "800px";
7383 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7385 }, SED.quickCreateDialog);
7387 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7388 SED.quickCreateDialog.setBody(ret.html);
7389 SED.quickCreateDialog.render();
7390 SUGAR.util.evalScript(ret.html);
7391 SED.quickCreateDialog.show();
7394 showAssignmentDialogWithData : function(o) {
7395 var SEC = SUGAR.email2.contextMenus;
7396 SUGAR.hideMessageBox();
7397 var ret = YAHOO.lang.JSON.parse(o.responseText);
7398 if (!SEC.assignmentDialog) {
7399 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7402 constraintoviewport: true,
7405 SEC.assignmentDialog.setBody("");
7406 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7407 SEC.assignmentDialog.renderEvent.subscribe(function() {
7408 var iev = YAHOO.util.Dom.get("Distribute");
7410 this.body.style.width = "700px";
7412 }, SEC.assignmentDialog);
7413 SEC.assignmentDialog.render();
7415 SEC.assignmentDialog.setBody(ret);
7416 SEC.assignmentDialog.render();
7418 SEC.assignmentDialog.show();
7419 SUGAR.util.evalScript(ret);
7422 showImportForm : function(o) {
7423 var SED = SUGAR.email2.detailView;
7424 var ret = YAHOO.lang.JSON.parse(o.responseText);
7426 document.getElementById('quickCreateContent').innerHTML = "";
7427 SUGAR.hideMessageBox();
7432 if(!SED.importDialog) {
7433 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7437 constraintoviewport: true,
7439 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7440 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7444 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7445 SED.importDialog.setBody("");
7446 SED.importDialog.hideEvent.subscribe(function(){
7447 for(var i in QSFieldsArray) {
7448 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7449 QSFieldsArray[i].destroy();
7450 delete QSFieldsArray[i];
7452 if (QSProcessedFieldsArray[i]) {
7453 QSProcessedFieldsArray[i] = false;
7457 SED.importDialog.renderEvent.subscribe(function() {
7458 var iev = YAHOO.util.Dom.get("ImportEditView");
7460 //this.body.style.height = (iev.clientHeight + 10) + "px";
7461 this.body.style.width = "600px";
7463 }, SED.importDialog);
7464 SED.importDialog.render();
7466 SED.importDialog.setBody(ret.html);
7467 SED.importDialog.ret = ret;
7468 SUGAR.util.evalScript(ret.html);
7469 SED.importDialog.render();
7471 SED.importDialog.show();
7472 SED.importDialog.focusFirstButton();
7474 getImportAction : function(ret) {
7475 if (!check_form('ImportEditView')) return false;
7476 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7477 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7481 var editView = document.getElementById('ImportEditView');
7482 if (editView.assigned_user_id != null) {
7483 get = get + "&user_id=" + editView.assigned_user_id.value
7484 //var user_id = editView.assigned_user_id.value;
7486 var parent_id = editView.parent_id.value;
7487 var parent_type = editView.parent_type.value;
7488 var row = SUGAR.email2.grid.getSelectedRows()[0];
7489 row = SUGAR.email2.grid.getRecord(row);
7490 var data = row.getData();
7491 var ieId = data.ieId;
7492 var mbox = data.mbox;
7493 var serverDelete = editView.serverDelete.checked;
7494 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7496 for(i=0; i<emailUids.length; i++) {
7498 uids += app_strings.LBL_EMAIL_DELIMITER;
7500 uids += emailUids[i];
7503 var action = 'importEmail&uid=';
7505 action = 'moveEmails';
7506 action = action + '&sourceFolder=' + ret['srcFolder'];
7507 action = action + '&sourceIeId=' + ret['srcIeId'];
7508 action = action + '&destinationFolder=' + ret['dstFolder'];
7509 action = action + '&destinationIeId=' + ret['dstIeId'];
7510 action = action + '&emailUids=';
7512 if (action.search(/importEmail/) != -1) {
7513 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7515 SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7518 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7519 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7520 SUGAR.email2.detailView.importDialog.hide();
7521 document.getElementById('importDialogContent').innerHTML = "";
7524 showRelateForm : function(o) {
7525 var SED = SUGAR.email2.detailView;
7526 var ret = YAHOO.lang.JSON.parse(o.responseText);
7527 document.getElementById('quickCreateContent').innerHTML = "";
7528 SUGAR.hideMessageBox();
7532 dialog_loaded = true;
7534 if(!SED.relateDialog) {
7535 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7540 constraintoviewport: true,
7542 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7543 if (!check_form('RelateEditView')) return false;
7545 var editView = document.getElementById('RelateEditView');
7546 var parent_id = editView.parent_id.value;
7547 var parent_type = editView.parent_type.value;
7548 var row = SUGAR.email2.grid.getSelectedRows()[0];
7549 row = SUGAR.email2.grid.getRecord(row);
7550 var ieId = row.getData().ieId;
7551 var mbox = row.getData().mbox;
7552 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7554 for(i=0; i<emailUids.length; i++) {
7556 uids += app_strings.LBL_EMAIL_DELIMITER;
7558 uids += emailUids[i];
7560 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7561 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7562 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7563 SED.relateDialog.hide();
7564 document.getElementById('relateDialogContent').innerHTML = "";
7569 SED.relateDialog.hideEvent.subscribe(function(){
7570 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7571 QSFieldsArray['ImportEditView_parent_name'].destroy();
7572 delete QSFieldsArray['ImportEditView_parent_name'];
7574 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7575 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7579 SED.relateDialog.renderEvent.subscribe(function() {
7580 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7582 for (var i in this.body.childNodes) {
7583 if (this.body.childNodes[i].clientHeight)
7584 contH += this.body.childNodes[i].clientHeight;
7586 }, SED.relateDialog);
7587 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7590 SED.relateDialog.setBody(ret.html);
7591 SED.relateDialog.render();
7592 SUGAR.util.evalScript(ret.html);
7593 SED.relateDialog.show();
7597 * DetailView callbacks
7599 AjaxObject.detailView.callback = {
7601 success : function(o) {
7603 var ret = YAHOO.lang.JSON.parse(o.responseText);
7604 SUGAR.email2.detailView.consumeMetaDetail(ret);
7606 argument: [targetDiv],
7607 failure : AjaxObject.handleFailure,
7612 success : function(o) {
7614 var ret = YAHOO.lang.JSON.parse(o.responseText);
7615 SUGAR.email2.detailView.consumeMetaPreview(ret);
7617 failure : AjaxObject.handleFailure,
7622 success : AjaxObject.detailView.displayPrintable,
7623 failure : AjaxObject.handleFailure,
7624 timeout : AjaxObject.timeout,
7628 success : AjaxObject.detailView.displayView,
7629 failure : AjaxObject.handleFailure,
7630 timeout : AjaxObject.timeout,
7639 AjaxObject.folders = {
7641 * check-mail post actions
7643 checkMailCleanup : function(o) {
7644 SUGAR.hideMessageBox();
7645 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7647 // refresh focus ListView
7648 SE.listView.refreshGrid();
7649 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7654 rebuildFolders : function(o) {
7655 SUGAR.hideMessageBox();
7657 var data = YAHOO.lang.JSON.parse(o.responseText);
7659 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7660 SUGAR.email2.folders.setSugarFolders();
7663 AjaxObject.folders.callback = {
7665 success : AjaxObject.folders.checkMailCleanup,
7666 failure : AjaxObject.handleFailure,
7667 timeout : 600000, // 5 mins
7672 AjaxObject.rules = {
7673 loadRulesForSettings : function(o) {
7674 document.getElementById("rulesListCell").innerHTML = o.responseText;
7675 // assume we have the class we need
7676 SUGAR.routing.getStrings();
7677 SUGAR.routing.getDependentDropdowns();
7680 //// END PER MODULE CALLBACK OBJECTS
7681 ///////////////////////////////////////////////////////////////////////////
7685 success : AjaxObject.handleSuccess,
7686 failure : AjaxObject.handleFailure,
7687 timeout : AjaxObject.timeout,
7690 var callbackAccount = {
7691 success : AjaxObject.ieSaveSuccess,
7692 failure : AjaxObject.handleFailure,
7693 timeout : AjaxObject.timeout,
7696 var callbackAccountDelete = {
7697 success : AjaxObject.ieDeleteSuccess,
7698 failure : AjaxObject.handleFailure,
7699 timeout : AjaxObject.timeout,
7702 var callbackOutboundTest = {
7703 success : AjaxObject.ieSendSuccess,
7704 failure : AjaxObject.handleFailure,
7705 timeout : AjaxObject.timeout,
7711 var callbackTeamInfoForSettings = {
7712 success : function (o) {
7713 var data = YAHOO.lang.JSON.parse(o.responseText);
7714 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7716 failure : AjaxObject.handleFailure,
7717 timeout : AjaxObject.timeout,
7722 var callbackStatusForImport = {
7723 success : function (o) {
7724 SUGAR.hideMessageBox();
7725 if (o.responseText != "") {
7726 var statusString = "";
7727 var data = YAHOO.lang.JSON.parse(o.responseText);
7728 for(i=0; i<data.length; i++) {
7729 statusString = statusString + data[i] + '<br/>';
7731 SUGAR.showMessageBox(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7733 SE.listView.refreshGrid();
7736 failure : AjaxObject.handleFailure,
7737 timeout : AjaxObject.timeout,
7741 var callbackComposeCache = {
7742 success : AjaxObject.composeCache,
7743 failure : AjaxObject.handleFailure,
7744 timeout : AjaxObject.timeout,
7747 var callbackDelete = {
7748 success : AjaxObject.handleDeleteReturn,
7749 failure : AjaxObject.handleFailure,
7750 timeout : AjaxObject.timeout,
7753 var callbackEmailDetailMultiple = {
7754 success : function(o) {
7755 SUGAR.hideMessageBox();
7756 var retMulti = YAHOO.lang.JSON.parse(o.responseText);
7757 var ret = new Object();
7759 for(var i=0; i<retMulti.length; i++) {
7762 SUGAR.email2._setDetailCache(ret);
7763 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7766 failure : AjaxObject.handleFailure,
7770 var callbackListViewSortOrderChange = {
7771 success : AjaxObject.saveListViewSortOrderPart2,
7772 failure : AjaxObject.handleFailure,
7773 timeout : AjaxObject.timeout,
7775 argument : [ieId, ieName, focusFolder]
7777 var callbackEmptyTrash = {
7778 success : function(o) {
7779 SUGAR.hideMessageBox();
7780 AjaxObject.folderRenameCleanup;
7782 failure : AjaxObject.handleFailure,
7783 timeout : AjaxObject.timeout,
7786 var callbackClearCacheFiles = {
7787 success : function(o) {
7788 SUGAR.hideMessageBox();
7790 failure : AjaxObject.handleFailure,
7791 timeout : AjaxObject.timeout,
7794 var callbackFolderRename = {
7795 success : function(o) {SUGAR.hideMessageBox();SUGAR.email2.folders.rebuildFolders();},
7796 failure : AjaxObject.handleFailure,
7797 timeout : AjaxObject.timeout,
7800 var callbackFolderDelete = {
7801 success : function(o) {
7802 var ret = YAHOO.lang.JSON.parse(o.responseText);
7804 if (ret.folder_id) {
7805 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7807 SUGAR.email2.tree.removeNode(node, true);
7808 } else if (ret.ieId && ret.mbox) {
7809 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7811 SUGAR.email2.tree.removeNode(node, true);
7813 SUGAR.hideMessageBox();
7814 //SUGAR.email2.folders.loadSettingFolder();
7816 SUGAR.hideMessageBox();
7817 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7820 failure : AjaxObject.handleFailure,
7821 timeout : AjaxObject.timeout,
7824 var callbackFolderSave = {
7825 success : function(o) {
7826 var ret = YAHOO.lang.JSON.parse(o.responseText);
7828 switch(ret.action) {
7829 case 'newFolderSave':
7830 SUGAR.email2.folders.rebuildFolders();
7834 failure : AjaxObject.handleFailure,
7835 timeout : AjaxObject.timeout,
7838 var callbackFolderSubscriptions = {
7839 success : AjaxObject.updateFolderSubscriptions,
7840 failure : AjaxObject.handleFailure,
7841 timeout : AjaxObject.timeout,
7844 var callbackFolderUpdate = {
7845 success : AjaxObject.updateFrameFolder,
7846 failure : AjaxObject.handleFailure,
7847 timeout : AjaxObject.timeout,
7850 var callbackFolders = {
7851 success : AjaxObject.folders.rebuildFolders,
7852 //success : void(true),
7853 failure : AjaxObject.handleFailure,
7854 timeout : AjaxObject.timeout,
7857 var callbackFullSync = {
7858 success : AjaxObject.fullSyncCleanup,
7859 failure : AjaxObject.handleFailure,
7860 timeout : 9999999999999,
7863 var callbackGeneric = {
7864 success : function() {
7865 SUGAR.hideMessageBox();
7867 failure : AjaxObject.handleFailure,
7868 timeout : AjaxObject.timeout,
7871 var callbackIeAccountRetrieve = {
7872 success : function(o) {
7873 // return JSON encoding
7874 SUGAR.hideMessageBox();
7875 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7876 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7878 failure : AjaxObject.handleFailure,
7879 timeout : AjaxObject.timeout,
7882 var callbackImportOneEmail = {
7883 success : AjaxObject.detailView.showImportForm,
7884 failure : AjaxObject.handleFailure,
7885 timeout : AjaxObject.timeout,
7888 var callbackRelateEmail = {
7889 success : AjaxObject.detailView.showRelateForm,
7890 failure : AjaxObject.handleFailure,
7891 timeout : AjaxObject.timeout,
7894 var callbackEmailDetailView = {
7895 success : AjaxObject.detailView.showEmailDetailView,
7896 failure : AjaxObject.handleFailure,
7897 timeout : AjaxObject.timeout,
7900 var callbackAssignmentDialog = {
7901 success : AjaxObject.detailView.showAssignmentDialogWithData,
7902 failure : AjaxObject.handleFailure,
7903 timeout : AjaxObject.timeout,
7906 var callbackAssignmentAction = {
7907 success : function(o) {
7908 SE.listView.refreshGrid();
7909 SUGAR.hideMessageBox();
7910 if(o.responseText != '') {
7911 SUGAR.showMessageBox('Assignment action result', o.responseText, 'alert');
7914 failure : AjaxObject.handleFailure,
7915 timeout : AjaxObject.timeout,
7918 var callbackMoveEmails = {
7919 success : function(o) {
7920 SE.listView.refreshGrid();
7921 SUGAR.hideMessageBox();
7922 if(o.responseText != '') {
7923 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7926 failure : AjaxObject.handleFailure,
7927 timeout : AjaxObject.timeout,
7930 var callbackLoadAttachments = {
7931 success : AjaxObject.loadAttachments,
7932 failure : AjaxObject.handleFailure,
7933 timeout : AjaxObject.timeout,
7936 var callbackLoadRules = {
7937 success : AjaxObject.rules.loadRulesForSettings,
7938 failure : AjaxObject.handleFailure,
7939 timeout : AjaxObject.timeout,
7942 var callbackLoadSignature = {
7943 success : AjaxObject.loadSignature,
7944 failure : AjaxObject.handleFailure,
7945 timeout : AjaxObject.timeout,
7948 var callbackDeleteSignature = {
7949 success : AjaxObject.handleDeleteSignature,
7950 failure : AjaxObject.handleFailure,
7951 timeout : AjaxObject.timeout,
7954 /*var callbackMoveEmails = {
7955 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7956 failure : AjaxObject.handleFailure,
7957 timeout : AjaxObject.timeout,
7960 var callbackOutboundSave = {
7961 success : AjaxObject.accounts.saveOutboundCleanup,
7962 failure : AjaxObject.handleFailure,
7963 timeout : AjaxObject.timeout,
7966 var callbackDefaultOutboundSave = {
7967 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7968 failure : AjaxObject.handleFailure,
7969 timeout : AjaxObject.timeout,
7972 var callbackQuickCreate = {
7973 success : AjaxObject.detailView.showQuickCreateForm,
7974 failure : AjaxObject.handleFailure,
7975 timeout : AjaxObject.timeout,
7978 var callbackQuickCreateSave = {
7979 success : AjaxObject.detailView.saveQuickCreateForm,
7980 failure : AjaxObject.handleFailure,
7981 timeout : AjaxObject.timeout,
7984 var callbackQuickCreateSaveAndAddToAddressBook = {
7985 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7986 failure : AjaxObject.handleFailure,
7987 timeout : AjaxObject.timeout,
7990 var callbackQuickCreateSaveAndReply = {
7991 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7992 failure : AjaxObject.handleFailure,
7993 timeout : AjaxObject.timeout,
7996 var callbackQuickCreateSaveAndReplyCase = {
7997 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7998 failure : AjaxObject.handleFailure,
7999 timeout : AjaxObject.timeout,
8002 var callbackRebuildShowAccountList = {
8003 success : AjaxObject.rebuildShowFolders,
8004 failure : AjaxObject.handleFailure,
8005 timeout : AjaxObject.timeout,
8009 var callbackRefreshSugarFolders = {
8010 success : function(o) {
8011 var t = YAHOO.lang.JSON.parse(o.responseText);
8012 SUGAR.email2.folders.setSugarFoldersEnd(t);
8014 failure : AjaxObject.handleFailure,
8015 timeout : AjaxObject.timeout,
8018 var callbackReplyForward = {
8019 success : AjaxObject.handleReplyForward,
8020 finish : function(a, retryCount) {
8021 if (typeof(retryCount) == 'undefined') {
8026 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8027 var t = tinyMCE.getInstanceById('htmleditor' + idx);
8029 var html = t.getContent();
8031 html = " <div><hr></div>" + a.description;
8033 t.setContent(html);//
8035 if (a.type != 'draft') {
8036 // Next step, attach signature
8037 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
8041 if (retryCount < 5) {
8042 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
8046 var tabArray = SUGAR.email2.innerLayout.get("tabs");
8047 if (tabArray != null && tabArray.length > 0) {
8048 for (i = 0 ; i < tabArray.length ; i++) {
8049 var tabObject = tabArray[i];
8050 if (tabObject.get("id") == ("composeTab" + idx)) {
8051 var tabLabel = a.name;
8052 if (tabLabel != null && tabLabel.length > 25) {
8053 tabLabel = tabLabel.substring(0, 25) + "...";
8055 tabObject.get("labelEl").firstChild.data = tabLabel;
8061 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8062 if (a.parent_name != null && a.parent_name != "") {
8063 document.getElementById('data_parent_name' + idx).value = a.parent_name;
8065 if (a.parent_type != null && a.parent_type != "") {
8066 document.getElementById('data_parent_type' + idx).value = a.parent_type;
8068 if (a.parent_id != null && a.parent_id != "") {
8069 document.getElementById('data_parent_id' + idx).value = a.parent_id;
8071 if (a.fromAccounts.status) {
8072 var addressFrom = document.getElementById('addressFrom' + idx);
8073 SUGAR.email2.util.emptySelectOptions(addressFrom);
8074 var fromAccountOpts = a.fromAccounts.data;
8075 for(i=0; i<fromAccountOpts.length; i++) {
8076 var key = fromAccountOpts[i].value;
8077 var display = fromAccountOpts[i].text;
8078 var opt = new Option(display, key);
8079 if (fromAccountOpts[i].selected) {
8080 opt.selected = true;
8082 addressFrom.options.add(opt);
8085 SUGAR.hideMessageBox();
8088 failure : AjaxObject.handleFailure,
8089 timeout : AjaxObject.timeout,
8091 argument : [sendType]
8093 var callbackSendEmail = {
8094 success : AjaxObject.sendEmailCleanUp,
8095 failure : AjaxObject.handleFailure,
8096 timeout : AjaxObject.timeout,
8099 var callbackSettings = {
8100 success : AjaxObject.updateUserPrefs,
8101 failure : AjaxObject.handleFailure,
8102 timeout : AjaxObject.timeout,
8105 var callbackSettingsFolderRefresh = {
8106 success : AjaxObject.settingsFolderRefresh,
8107 failure : AjaxObject.handleFailure,
8108 timeout : AjaxObject.timeout,
8111 var callbackLoadSettingFolder = {
8112 success : function(o) {
8113 AjaxObject.settingsFolderRefresh(o);
8114 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8116 failure : AjaxObject.handleFailure,
8117 timeout : AjaxObject.timeout,
8121 var callbackUploadAttachment = {
8122 success : AjaxObject.uploadAttachmentSuccessful,
8123 upload : AjaxObject.uploadAttachmentSuccessful,
8124 failure : AjaxObject.handleFailure,
8125 timeout : AjaxObject.timeout,
8128 var callbackUserPrefs = {
8129 success : function(o) {
8130 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
8132 failure : AjaxObject.handleFailure,
8133 timeout : AjaxObject.timeout,
8137 var callbackContextmenus = {
8139 success : AjaxObject.markEmailCleanup,
8140 failure : AjaxObject.handleFailure,
8141 timeout : AjaxObject.timeout,
8146 var callbackCheckEmail2 = {
8147 success : function(o) {
8148 var ret = YAHOO.lang.JSON.parse(o.responseText);
8149 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8153 failure : AjaxObject.handleFailure,
8154 timeout : AjaxObject.timeout,
8156 }// End of File modules/Emails/javascript/ajax.js
8158 /*********************************************************************************
8159 * SugarCRM Community Edition is a customer relationship management program developed by
8160 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8162 * This program is free software; you can redistribute it and/or modify it under
8163 * the terms of the GNU Affero General Public License version 3 as published by the
8164 * Free Software Foundation with the addition of the following permission added
8165 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8166 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8167 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8169 * This program is distributed in the hope that it will be useful, but WITHOUT
8170 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8171 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8174 * You should have received a copy of the GNU Affero General Public License along with
8175 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8176 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8179 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8180 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8182 * The interactive user interfaces in modified source and object code versions
8183 * of this program must display Appropriate Legal Notices, as required under
8184 * Section 5 of the GNU Affero General Public License version 3.
8186 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8187 * these Appropriate Legal Notices must retain the display of the "Powered by
8188 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8189 * technical reasons, the Appropriate Legal Notices must display the words
8190 * "Powered by SugarCRM".
8191 ********************************************************************************/
8193 function gridInit() {
8194 if(SUGAR.email2.grid) {
8195 SUGAR.email2.grid.destroy();
8201 var Ck = YAHOO.util.Cookie;
8202 var widths = [ 10, 10, 150, 250, 175, 125 ];
8204 if (Ck.get("EmailGridWidths")) {
8205 for (var i=0; i < widths.length; i++) {
8206 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8209 for (var i=0; i < widths.length; i++) {
8210 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8214 // changes "F" to an icon
8215 function flaggedIcon(cell, record, column, value) {
8217 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8220 // changes "A" to replied icon
8221 function repliedIcon(cell, record, column, value) {
8223 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8226 function attachIcon(cell, record, column, value) {
8228 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8235 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8240 formatter: attachIcon,
8244 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8249 formatter: flaggedIcon,
8253 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8258 formatter: repliedIcon,
8262 label: app_strings.LBL_EMAIL_FROM,
8269 label: app_strings.LBL_EMAIL_SUBJECT,
8276 label: mod_strings.LBL_LIST_DATE,
8283 label: app_strings.LBL_EMAIL_TO,
8319 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8320 responseType: YAHOO.util.DataSource.TYPE_JSON,
8322 resultsList: 'Email',
8323 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8324 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8330 action : "EmailUIAjax",
8331 emailUIAction : "getMessageList",
8334 forceRefresh : "false"
8336 if(lazyLoadFolder != null) {
8337 params['mbox'] = lazyLoadFolder.folder;
8338 params['ieId'] = lazyLoadFolder.ieId;
8339 //Check if the folder is a Sugar Folder
8340 var test = new String(lazyLoadFolder.folder);
8341 if(test.match(/SUGAR\./)) {
8342 params['emailUIAction'] = 'getMessageListSugarFolders';
8343 params['mbox'] = test.substr(6);
8346 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8349 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8350 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8352 paginator: new YAHOO.widget.Paginator({
8353 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8354 containers : ["dt-pag-nav"],
8355 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8356 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8357 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8358 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8359 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8361 initialRequest:SUGAR.util.paramsToUrl(params),
8368 //Override Paging request construction
8369 grid.set("generateRequest", function(oState, oSelf) {
8370 oState = oState || {pagination:null, sortedBy:null};
8371 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[5].getKey();
8372 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_ASC) ? "asc" : "desc";
8373 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8374 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8375 // Build the request
8377 SUGAR.util.paramsToUrl(oSelf.params) +
8380 "&start=" + startIndex +
8381 ((results !== null) ? "&limit=" + results : "");
8386 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8387 oPayload = oPayload || { };
8389 oPayload.totalRecords = oResponse.meta.total;
8390 oPayload.unreadRecords = oResponse.meta.unread;
8392 var tabObject = SE.innerLayout.get("tabs")[0];
8394 if (this.params.mbox != null) {
8395 mboxTitle = this.params.mbox;
8397 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8398 tabObject.get("labelEl").firstChild.data = tabtext;
8401 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8403 node.data.unseen = oResponse.meta.unread;
8404 SE.accounts.renderTree();
8410 var resize = grid.resizeGrid = function () {
8411 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8412 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8414 grid.convertDDRows = function() {
8415 var rowEl = this.getFirstTrEl();
8416 while (rowEl != null) {
8417 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8418 rowEl = this.getNextTrEl(rowEl);
8423 grid.on("columnResizeEvent", function(o) {
8424 //Find the index of the column
8425 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8426 for (var i=0; i < colSet.length; i++) {
8427 if (o.column == colSet[i]) {
8428 //Store it in the cookie
8429 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8432 //this.resizeGrid();
8435 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8436 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8437 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8439 SUGAR.email2.listViewLayout.on("render", resize);
8442 //Setup the default load parameters
8443 SUGAR.email2.grid.params = params;
8445 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8446 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8447 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8454 function initRowDD() {
8455 var sg = SUGAR.email2.grid,
8456 Dom = YAHOO.util.Dom;
8457 sg.DDRow = function(oDataTable, oRecord, elTr) {
8458 if(oDataTable && oRecord && elTr) {
8459 this.ddtable = oDataTable;
8460 this.table = oDataTable.getTableEl();
8463 this.newIndex = null;
8465 this.initFrame(); // Needed for DDProxy
8466 this.invalidHandleTypes = {};
8470 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8471 _resizeProxy: function() {
8472 this.constructor.superclass._resizeProxy.apply(this, arguments);
8473 var dragEl = this.getDragEl(),
8475 var xy = Dom.getXY(el);
8477 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8478 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8479 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8480 Dom.setStyle(dragEl, 'display', "");
8483 startDrag: function(x, y) {
8484 //Check if we should be dragging a set of rows rather than just the one.
8485 var selectedRows = this.ddtable.getSelectedRows();
8486 var iSelected = false;
8487 for (var i in selectedRows) {
8488 if (this.rowEl.id == selectedRows[i]) {
8495 for (var i in selectedRows) {
8496 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8499 this.rows = [this.row];
8500 this.ddtable.unselectAllRows();
8501 this.ddtable.selectRow(this.row);
8504 //Initialize the dragable proxy
8505 var dragEl = this.getDragEl();
8506 var clickEl = this.getEl();
8507 Dom.setStyle(clickEl, "opacity", "0.25");
8508 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8509 Dom.addClass(dragEl, "yui-dt-liner");
8510 Dom.setStyle(dragEl, "opacity", "0.5");
8511 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8512 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8513 Dom.setStyle(dragEl, "border", "2px solid gray");
8516 clickValidator: function(e) {
8517 if (this.row.getData()[0] == " ")
8519 var target = YAHOO.util.Event.getTarget(e);
8520 return ( this.isValidHandleChild(target) &&
8521 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8524 * This funciton checks that the target of the drag is a table row in this
8525 * DDGroup and simply moves the sourceEL to that location as a preview.
8527 onDragOver: function(ev, id) {
8528 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8529 if (node && node != this.targetNode) {
8530 this.targetNode = node;
8531 SUGAR.email2.folders.unhighliteAll();
8536 onDragOut: function(e, id) {
8537 if (this.targetNode) {
8538 SUGAR.email2.folders.unhighliteAll();
8539 this.targetNode = false;
8542 endDrag: function() {
8543 Dom.setStyle(this.getEl(), "opacity", "");
8544 Dom.setStyle(this.getDragEl(), "display", "none");
8545 if (this.targetNode) {
8546 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8548 SUGAR.email2.folders.unhighliteAll();
8554 function AddressSearchGridInit() {
8555 function moduleIcon(elCell, oRecord, oColumn, oData) {
8556 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8558 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8559 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8561 var checkHeader = '<input type="checkbox" ';
8562 if (SUGAR.email2.util.isIe()) {
8563 checkHeader += 'style="top:-5px" ';
8565 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8570 formatter: selectionCheckBox,
8574 label: mod_strings.LBL_LIST_TYPE,
8576 formatter: moduleIcon,
8580 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8586 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8592 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8593 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8595 resultsList: 'Person',
8596 fields: ['name', 'email', 'bean_id', 'bean_module'],
8597 metaFields: {total: 'TotalCount'}
8599 //enable sorting on the server accross all data
8602 dataModel.params = {
8605 action : "EmailUIAjax",
8606 emailUIAction:"getAddressSearchResults"
8608 var rb = document.getElementById('hasRelatedBean').checked;
8610 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8611 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8612 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8613 dataModel.params['related_bean_id'] = relatedBeanId;
8614 dataModel.params['related_bean_type'] = relatedBeanType;
8615 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8617 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8619 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8620 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8622 paginator: new YAHOO.widget.Paginator({
8624 containers : ["dt-pag-nav-addressbook"],
8625 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8626 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8627 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8628 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8629 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8631 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8635 //Override Paging request construction
8636 grid.set("generateRequest", function(oState, oSelf) {
8637 oState = oState || {pagination:null, sortedBy:null};
8638 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8639 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8640 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8641 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8642 // Build the request
8644 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8645 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8646 ((results !== null) ? "&limit=" + results : "");
8650 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8651 oPayload = oPayload || { };
8652 oPayload.totalRecords = oResponse.meta.total;
8656 grid.clickToggleSelect= function(args) {
8657 var isIE = (args.event.target == null);
8658 var targetElement = isIE ? args.event.srcElement : args.event.target;
8659 if(targetElement.type == null || targetElement.type != 'checkbox') {
8660 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8664 grid.reSelectRowsOnRender = function (){
8665 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8666 for (var i = 0; i < rows.length; i++)
8668 var emailAddress = rows[i].getData("email");
8669 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8672 rows[i].setData("selected", true);
8673 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8677 rows[i].setData("selected", false);
8678 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8682 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8683 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8684 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8685 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8688 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8689 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8691 grid.toggleSelectCheckbox = function(id,checked){
8692 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8693 row.setData("checked",checked);
8695 grid.toggleSelect = function(id, checked) {
8696 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8697 checked = row.getData("selected");
8700 SUGAR.email2.addressBook.grid.selectRow(row);
8701 SE.addressBook.insertContactRowToResultTable(id,null)
8704 SUGAR.email2.addressBook.grid.unselectRow(row);
8705 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8707 row.setData("selected", !checked);
8710 grid.toggleSelectAll = function(checked) {
8711 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8712 for (var i = 0; i < rows.length; i++) {
8713 if (typeof(rows[i]) != "undefined")
8714 rows[i].setData("checked", checked);
8716 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8717 for (var i = 0; i < checkBoxes.length; i++) {
8718 checkBoxes[i].checked = checked;
8722 //Initialize the grid result table.
8723 AddressSearchResultsGridInit();
8729 * Initalize the results table for the address book selection.
8732 function AddressSearchResultsGridInit()
8735 /* Full name sort funciton to compare by last name if available */
8736 var fullNameSort = function(a, b, desc) {
8737 // Deal with empty values
8738 if(!YAHOO.lang.isValue(a))
8739 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8740 else if(!YAHOO.lang.isValue(b))
8743 var aNames = a.getData("name").split(' ');
8744 var bNames = b.getData("name").split(' ');
8746 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8747 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8749 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8753 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8754 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8755 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8757 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})},
8758 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8760 var myDataSource = new YAHOO.util.DataSource([]);
8761 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8762 myDataSource.responseSchema = {
8763 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8766 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8767 width: "350px",height: "250px", MSG_EMPTY: " "});
8769 var highlightEditableCell = function(oArgs) {
8770 var elCell = oArgs.target;
8771 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8772 this.highlightCell(elCell);
8776 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8777 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8778 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8779 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8780 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8782 //Setup the context menus
8783 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8784 var task = p_aArgs[1];
8787 var elRow = this.contextEventTarget;
8788 elRow = p_myDataTable.getTrEl(elRow);
8795 var oRecord = p_myDataTable.getRecord(elRow);
8796 p_myDataTable.deleteRow(elRow);
8797 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8802 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8803 {trigger:gridResults.getTbodyEl()});
8804 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8805 contextMenu.render("addrSearchResultGrid");
8806 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8808 // End of File modules/Emails/javascript/grid.js
8810 /*********************************************************************************
8811 * SugarCRM Community Edition is a customer relationship management program developed by
8812 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8814 * This program is free software; you can redistribute it and/or modify it under
8815 * the terms of the GNU Affero General Public License version 3 as published by the
8816 * Free Software Foundation with the addition of the following permission added
8817 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8818 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8819 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8821 * This program is distributed in the hope that it will be useful, but WITHOUT
8822 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8823 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8826 * You should have received a copy of the GNU Affero General Public License along with
8827 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8828 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8831 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8832 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8834 * The interactive user interfaces in modified source and object code versions
8835 * of this program must display Appropriate Legal Notices, as required under
8836 * Section 5 of the GNU Affero General Public License version 3.
8838 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8839 * these Appropriate Legal Notices must retain the display of the "Powered by
8840 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8841 * technical reasons, the Appropriate Legal Notices must display the words
8842 * "Powered by SugarCRM".
8843 ********************************************************************************/
8846 /******************************************************************************
8847 * Initialize Email 2.0 Application
8850 //Override Sugar Languge so quick creates work properly
8853 function email2init() {
8856 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
8857 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
8858 if (!SUGAR.util.isTouchScreen()) {
8860 convert_urls : false,
8861 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
8862 width: tinyConfig.width,
8863 theme: tinyConfig.theme,
8864 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
8865 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
8866 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
8867 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
8868 plugins : tinyConfig.plugins,
8869 elements : tinyConfig.elements,
8870 language : tinyConfig.language,
8871 extended_valid_elements : tinyConfig.extended_valid_elements,
8872 mode: tinyConfig.mode,
8873 strict_loading_mode : true,
8874 force_br_newlines : true,
8875 forced_root_block : '',
8876 directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
8880 // initialze message overlay
8881 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
8891 if (SUGAR.themes.tempHideLeftCol)
8892 SUGAR.themes.tempHideLeftCol();
8894 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
8895 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
8897 // set defaults for YAHOO.util.DragDropManager
8898 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
8900 SUGAR.email2.nextYear = new Date();
8901 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
8904 // initialize and display UI framework (complexLayout.js)
8905 complexLayoutInit();
8907 // initialize and display grid (grid.js)
8910 // initialize treeview for folders
8912 SUGAR.email2.folders.rebuildFolders(true);
8915 //Setup the Message Box overlay
8916 /*Ext.MessageBox.maxWidth = 350;
8917 Ext.MessageBox.minProgressWidth = 350;
8919 ///////////////////////////////////////////////////////////////////////////
8922 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
8924 var SEC = SUGAR.email2.contextMenus;
8927 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
8928 trigger: SUGAR.email2.grid.get("element"),
8931 emailMenu.subscribe("beforeShow", function() {
8932 var oTarget = this.contextEventTarget;
8933 if (typeof(oTarget) == "undefined")
8935 var grid = SUGAR.email2.grid;
8936 var selectedRows = grid.getSelectedRows();
8937 var multipleSelected = (selectedRows.length > 1) ? true: false;
8938 if (!multipleSelected)
8940 grid.unselectAllRows();
8941 grid.selectRow(oTarget);
8942 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8944 else if(multipleSelected)
8946 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8950 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
8951 //us to access individual elements easier by name rather than by index
8952 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
8953 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
8954 emailMenu.addItems([
8956 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
8957 id: 'showDetailView',
8958 onclick: { fn: SEC.showDetailView }
8961 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
8962 onclick: { fn: SEC.openMultiple }
8965 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
8966 onclick: { fn: SEC.archiveToSugar }
8969 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
8971 onclick: { fn: SEC.replyForwardEmailContext }
8974 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
8976 onclick: { fn: SEC.replyForwardEmailContext }
8979 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
8981 onclick: { fn: SEC.replyForwardEmailContext }
8984 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
8986 onclick: { fn: SEC.markDeleted }
8989 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
8991 onclick: { fn: SEC.viewPrintable }
8995 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
8997 id: "markEmailMenu",
9000 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9001 onclick: { fn: SEC.markUnread }
9004 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9005 onclick: { fn: SEC.markRead }
9008 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9009 onclick: { fn: SEC.markFlagged }
9012 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9013 onclick: { fn: SEC.markUnflagged }
9019 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9021 onclick: { fn: SEC.assignEmailsTo }
9024 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9026 onclick: { fn: SEC.relateTo }
9029 SEC.emailListContextMenu.render();
9031 //Handle the Tree folder menu trigger ourselves
9032 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9036 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9040 SEC.frameFoldersContextMenu.addItems([
9041 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
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, false)};
9049 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9050 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9051 onclick: { fn: function() {
9052 var node = SUGAR.email2.clickedFolderNode;
9053 if (node.data.ieId) {
9054 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9058 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9059 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9060 onclick: { fn: SUGAR.email2.folders.folderAdd }
9063 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9064 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9065 onclick: { fn: SUGAR.email2.folders.folderDelete }
9068 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9069 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9070 onclick: { fn: SUGAR.email2.folders.folderRename }
9073 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9074 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9075 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9078 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9079 onclick: { fn: function() {
9080 var node = SUGAR.email2.clickedFolderNode;
9081 if (node.data.ieId) {
9082 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9086 SEC.frameFoldersContextMenu.render();
9088 SEC.initContactsMenu = function() {
9090 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9091 trigger: "contacts",
9094 SEC.contactsContextMenu.addItems([
9096 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9097 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9100 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9101 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9104 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9105 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9106 if (oTarget && !grid.isSelected(oTarget)) {
9107 grid.unselectAllRows();
9108 grid.selectRow(oTarget);
9111 SEC.contactsContextMenu.render();
9115 // set auto-check timer
9116 SUGAR.email2.folders.startCheckTimer();
9117 // check if we're coming from an email-link click
9118 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9120 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9122 //Init fix for YUI 2.7.0 datatable sort.
9123 SUGAR.email2.addressBook.initFixForDatatableSort();
9126 function createTreePanel(treeData, params) {
9127 var tree = new YAHOO.widget.TreeView(params.id);
9128 var root = tree.getRoot();
9130 //if (treeData.nodes && treeData[0].id == "Home")
9131 // treeData = treeData[0];
9135 function addChildNodes(parentNode, parentData) {
9136 var Ck = YAHOO.util.Cookie;
9137 var nextyear = SUGAR.email2.nextYear;
9138 var nodes = parentData.nodes || parentData.children;
9140 if (typeof(nodes[i]) == 'object') {
9141 if (nodes[i].data) {
9142 // See comment about href below.
9143 // nodes[i].data.href = '#';
9144 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode);
9145 node.action = nodes[i].data.action;
9147 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9148 addChildNodes(parentNode, nodes[i]);
9151 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9152 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9154 nodes[i].className = nodes[i].cls;
9156 // Previously, span was added in the label so it was rendering in the tree.
9157 // Default behavior is to wrap in span if no href property, and since this href
9158 // doesn't do anything, remove it so that it will be wrapped in spans.
9159 // nodes[i].href = "#";
9160 if (nodes[i].text) nodes[i].label = nodes[i].text;
9161 //Override YUI child node creation
9162 if (nodes[i].children) {
9163 nodes[i].nodes = nodes[i].children;
9164 nodes[i].children = [ ];
9166 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9169 if (typeof(nodes[i].nodes) == 'object') {
9170 addChildNodes(node, nodes[i]);
9177 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9179 function email2treeinit(tree, treedata, treediv, params) {
9180 //ensure the tree data is not corrupt
9184 if (SUGAR.email2.tree) {
9185 SUGAR.email2.tree.destroy();
9186 SUGAR.email2.tree = null;
9189 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9193 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9194 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9195 tree.subscribe("expandComplete", function(node){
9196 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9197 for (var i in node.children) {
9198 SE.accounts.setupDDTarget(node.children[i]);
9201 tree.setCollapseAnim("TVSlideOut");
9202 tree.setExpandAnim("TVSlideIn");
9203 var root = tree.root;
9204 while (root.hasChildren()) {
9205 var node = root.children[0];
9207 tree.removeNode(root.children[0], false);
9209 addChildNodes(root, treedata);
9211 SUGAR.email2.accounts.renderTree();
9214 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9215 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9219 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9220 startDrag: function(x, y) {
9221 var Dom = YAHOO.util.Dom;
9222 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9225 var dragEl = this.getDragEl();
9226 var clickEl = this.getEl();
9227 Dom.setStyle(clickEl, "color", "#AAA");
9228 Dom.setStyle(clickEl, "opacity", "0.25");
9229 dragEl.innerHTML = clickEl.innerHTML;
9231 Dom.addClass(dragEl, "ygtvcell");
9232 Dom.addClass(dragEl, "ygtvcontent");
9233 Dom.addClass(dragEl, "folderDragProxy");
9234 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9235 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9236 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9237 Dom.setStyle(dragEl, "opacity", "0.5");
9238 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9241 onDragOver: function(ev, id) {
9242 var Dom = YAHOO.util.Dom;
9243 if (id != this.dragId)
9245 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9246 if(node.data.cls != "sugarFolder") {
9247 SUGAR.email2.folders.unhighliteAll();
9251 this.targetNode = node;
9252 SUGAR.email2.folders.unhighliteAll();
9257 onDragOut: function(e, id) {
9258 if (this.targetNode) {
9259 SUGAR.email2.folders.unhighliteAll();
9260 this.targetNode = false;
9261 this.dragId = false;
9265 endDrag: function() {
9266 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9267 if (this.targetNode) {
9268 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9271 });// End of File modules/Emails/javascript/init.js
9273 /*********************************************************************************
9274 * SugarCRM Community Edition is a customer relationship management program developed by
9275 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9277 * This program is free software; you can redistribute it and/or modify it under
9278 * the terms of the GNU Affero General Public License version 3 as published by the
9279 * Free Software Foundation with the addition of the following permission added
9280 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9281 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9282 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9284 * This program is distributed in the hope that it will be useful, but WITHOUT
9285 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9286 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9289 * You should have received a copy of the GNU Affero General Public License along with
9290 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9291 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9294 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9295 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9297 * The interactive user interfaces in modified source and object code versions
9298 * of this program must display Appropriate Legal Notices, as required under
9299 * Section 5 of the GNU Affero General Public License version 3.
9301 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9302 * these Appropriate Legal Notices must retain the display of the "Powered by
9303 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9304 * technical reasons, the Appropriate Legal Notices must display the words
9305 * "Powered by SugarCRM".
9306 ********************************************************************************/
9311 function complexLayoutInit() {
9312 var se = SUGAR.email2;
9313 var Dom = YAHOO.util.Dom;
9315 getInnerLayout : function(rows) {
9316 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
9317 parent: se.complexLayout,
9323 scroll:false, // grid should autoScroll itself
9325 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
9333 body: "<div id='listBottom' />"
9341 body: "<div id='listRight' />",
9342 titlebar: false //,header: "right"
9345 se.complexLayout.on("render", function(){
9346 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
9347 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9348 SUGAR.email2.listViewLayout.set("height", height);
9349 SUGAR.email2.listViewLayout.render();
9351 se.listViewLayout.render();
9353 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
9354 var rp = se.listViewLayout.resizePreview = function() {
9355 var pre = Dom.get("displayEmailFramePreview");
9357 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
9358 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
9361 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
9362 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
9363 se.e2Layout.setPreviewPanel(rows);
9364 se.previewLayout = se.listViewLayout;
9365 return se.listViewLayout;
9368 getInnerLayout2Rows : function() {
9369 return this.getInnerLayout(true);
9371 getInnerLayout2Columns : function() {
9372 return this.getInnerLayout(false);
9376 // initialize state manager, we will use cookies
9377 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
9378 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
9379 se.complexLayout = new YAHOO.widget.Layout("container", {
9382 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
9383 width: Dom.getViewportWidth() - 40,
9387 body: "<div id='emailtabs'></div>"
9392 body: "<div id='lefttabs'></div>",
9402 header: Dom.get('footerLinks').innerHTML,
9409 se.complexLayout.render();
9410 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
9411 tp.addTab(new YAHOO.widget.Tab({
9414 content : "<div id='listViewDiv'/>",
9418 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
9419 tp.appendTo(centerEl);
9421 tp.get("element").style.borderRight = "1px solid #666"
9423 var listV = this.getInnerLayout2Rows();
9424 listV.set("height", tp.get("element").clientHeight - 25);
9427 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
9428 var folderTab = new YAHOO.widget.Tab({
9429 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
9431 content : "<div id='emailtree'/>",
9435 folderTab.on("activeChange", function(o){
9437 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
9440 se.leftTabs.addTab(folderTab);
9442 var tabContent = SUGAR.util.getAndRemove("searchTab");
9443 var searchTab = new YAHOO.widget.Tab({
9444 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
9446 content : tabContent.innerHTML,
9449 searchTab.on("activeChange", function(o){
9452 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
9453 //Setup the calendars if needed
9454 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
9455 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
9457 //Initalize sqs object for assigned user name
9458 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
9460 //Attach event handler for when the relate module option is selected for the correct sqs object
9461 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
9462 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
9463 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
9464 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
9466 //If enter key is pressed, perform search
9467 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
9468 for(var i=0; i < addKeyPressFields.length;i++)
9470 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
9471 if (e.keyCode == 13) {
9472 YAHOO.util.Event.stopEvent(e);
9473 SUGAR.email2.search.searchAdvanced();
9477 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
9479 //Clear parent values if selecting another parent type.
9480 YAHOO.util.Event.addListener('data_parent_type_search','change',
9482 document.getElementById('data_parent_id_search').value ='';
9483 document.getElementById('data_parent_name_search').value ='';
9488 se.leftTabs.addTab(searchTab);
9490 var resizeTabBody = function() {
9491 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
9492 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9495 se.complexLayout.on("render", resizeTabBody);
9496 se.leftTabs.on("activeTabChange", resizeTabBody);
9497 //hack to allow left pane scroll bar to fully show
9498 var lefttabsDiv = document.getElementById('lefttabs');
9499 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
9500 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
9501 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
9504 initSQSObject: function(formName,fieldName)
9506 var fullFieldName = formName + '_' + fieldName; //SQS Convention
9507 var resultName = fullFieldName + '_' + 'results';
9509 if (QSFieldsArray[fullFieldName] != null)
9511 QSFieldsArray[fullFieldName].destroy();
9512 delete QSFieldsArray[fullFieldName];
9514 if (QSProcessedFieldsArray[fullFieldName])
9515 QSProcessedFieldsArray[fullFieldName] = false;
9517 if( Dom.get(resultName) )
9519 var obj = document.getElementById(resultName);
9520 obj.parentNode.removeChild(obj);
9523 setPreviewPanel: function(rows) {
9525 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9526 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9527 Dom.get("listRight").innerHTML = "";
9528 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9530 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9531 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9532 Dom.get("listBottom").innerHTML = "";
9533 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9540 var myBufferedListenerObject = new Object();
9541 myBufferedListenerObject.refit = function() {
9542 if(SUGAR.email2.grid) {
9543 SUGAR.email2.grid.autoSize();
9546 // End of File modules/Emails/javascript/complexLayout.js
9548 /*********************************************************************************
9549 * SugarCRM Community Edition is a customer relationship management program developed by
9550 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9552 * This program is free software; you can redistribute it and/or modify it under
9553 * the terms of the GNU Affero General Public License version 3 as published by the
9554 * Free Software Foundation with the addition of the following permission added
9555 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9556 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9557 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9559 * This program is distributed in the hope that it will be useful, but WITHOUT
9560 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9561 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9564 * You should have received a copy of the GNU Affero General Public License along with
9565 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9566 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9569 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9570 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9572 * The interactive user interfaces in modified source and object code versions
9573 * of this program must display Appropriate Legal Notices, as required under
9574 * Section 5 of the GNU Affero General Public License version 3.
9576 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9577 * these Appropriate Legal Notices must retain the display of the "Powered by
9578 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9579 * technical reasons, the Appropriate Legal Notices must display the words
9580 * "Powered by SugarCRM".
9581 ********************************************************************************/
9583 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9584 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9585 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9586 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9587 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9588 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9589 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9590 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9591 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9592 ' <input type="hidden" id="composeType" name="composeType">' +
9593 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9594 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9595 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9596 ' <input type="hidden" id="sendTo" name="sendTo">' +
9597 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9598 ' <input type="hidden" id="sendCc" name="sendCc">' +
9599 ' <input type="hidden" id="setEditor" name="setEditor">' +
9600 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9601 ' <input type="hidden" id="parent_id" name="parent_id">' +
9602 ' <input type="hidden" id="parent_type" name="parent_type">' +
9603 ' <input type="hidden" id="attachments" name="attachments">' +
9604 ' <input type="hidden" id="documents" name="documents">' +
9605 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9606 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9607 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9608 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9610 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9611 ' <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>' +
9612 ' <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>' +
9613 ' <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>' +
9614 ' <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>' +
9615 '</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>' +
9616 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9617 '<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>' +
9618 ' </td></tr></tbody></table></th>' +
9622 ' <div style="margin:5px;">' +
9623 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9625 ' <td class="emailUILabel" NOWRAP >' +
9626 ' {app_strings.LBL_EMAIL_FROM}:' +
9628 ' <td class="emailUIField" NOWRAP>' +
9630 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9635 ' <td class="emailUILabel" NOWRAP>' +
9636 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9637 ' {app_strings.LBL_EMAIL_TO}:' +
9640 ' <td class="emailUIField" NOWRAP>' +
9641 ' <div class="ac_autocomplete">' +
9642 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9643 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9644 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9648 ' <tr id="add_addr_options_tr{idx}">' +
9649 ' <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>'+
9651 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9652 ' <td class="emailUILabel" NOWRAP>' +
9653 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9654 ' {app_strings.LBL_EMAIL_CC}:' +
9657 ' <td class="emailUIField" NOWRAP>' +
9658 ' <div class="ac_autocomplete">' +
9659 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9660 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9661 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9665 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9666 ' <td class="emailUILabel" NOWRAP>' +
9667 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9668 ' {app_strings.LBL_EMAIL_BCC}:' +
9671 ' <td class="emailUIField" NOWRAP>' +
9672 ' <div class="ac_autocomplete">' +
9673 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9674 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9675 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9680 ' <td class="emailUILabel" NOWRAP width="1%">' +
9681 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9683 ' <td class="emailUIField" NOWRAP width="99%">' +
9684 ' <div class="ac_autocomplete">' +
9685 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9694 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9695 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9696 ' <div style="padding:5px;">' +
9697 ' <table cellpadding="2" cellspacing="0" border="0">' +
9700 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9707 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9708 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9720 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9727 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9728 ' <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>' +
9740 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9747 ' <div id="addedTemplateAttachments{idx}"></div>' +
9754 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9755 ' <div style="padding:5px;">' +
9756 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9757 ' <table border="0" width="100%">' +
9759 ' <td NOWRAP style="padding:2px;">' +
9760 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9764 ' <td NOWRAP style="padding:2px;">' +
9765 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9770 ' <table border="0" width="100%">' +
9772 ' <td NOWRAP style="padding:2px;">' +
9773 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9777 ' <td NOWRAP style="padding:2px;">' +
9778 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9782 ' <table border="0" width="100%">' +
9784 ' <td NOWRAP style="padding:2px;">' +
9785 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9786 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9794 // End of File modules/Emails/javascript/composeEmailTemplate.js
9796 /*********************************************************************************
9797 * SugarCRM Community Edition is a customer relationship management program developed by
9798 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9800 * This program is free software; you can redistribute it and/or modify it under
9801 * the terms of the GNU Affero General Public License version 3 as published by the
9802 * Free Software Foundation with the addition of the following permission added
9803 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9804 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9805 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9807 * This program is distributed in the hope that it will be useful, but WITHOUT
9808 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9809 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9812 * You should have received a copy of the GNU Affero General Public License along with
9813 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9814 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9817 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9818 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9820 * The interactive user interfaces in modified source and object code versions
9821 * of this program must display Appropriate Legal Notices, as required under
9822 * Section 5 of the GNU Affero General Public License version 3.
9824 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9825 * these Appropriate Legal Notices must retain the display of the "Powered by
9826 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9827 * technical reasons, the Appropriate Legal Notices must display the words
9828 * "Powered by SugarCRM".
9829 ********************************************************************************/
9831 SUGAR.email2.templates['displayOneEmail'] =
9832 '<div class="emailDetailTable" style="height:100%">' +
9833 '<div id="viewMenuDiv{idx}"></div>' +
9834 '<div width="100%" class="displayEmailValue">' +
9835 ' <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>' +
9836 ' <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>' +
9837 ' <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>' +
9838 ' <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>' +
9839 ' <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>' +
9840 ' <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>' +
9841 ' <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>' +
9842 ' <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>' +
9843 ' <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>' +
9845 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9847 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9848 ' {app_strings.LBL_EMAIL_FROM}:' +
9850 ' <td width="99%" class="displayEmailValue">' +
9851 ' {email.from_addr}' +
9855 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9856 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9858 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9859 ' <b>{email.name}</b>' +
9863 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9864 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9866 ' <td class="displayEmailValue">' +
9867 ' {email.date_start} {email.time_start}' +
9871 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9872 ' {app_strings.LBL_EMAIL_TO}:' +
9874 ' <td class="displayEmailValue">' +
9875 ' {email.toaddrs}' +
9878 ' <tr>{meta.cc}</tr>' +
9879 ' <tr>{email.attachments}</tr>' +
9881 ' <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>' +
9882 //' {email.description}' +
9884 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9886 /*********************************************************************************
9887 * SugarCRM Community Edition is a customer relationship management program developed by
9888 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9890 * This program is free software; you can redistribute it and/or modify it under
9891 * the terms of the GNU Affero General Public License version 3 as published by the
9892 * Free Software Foundation with the addition of the following permission added
9893 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9894 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9895 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9897 * This program is distributed in the hope that it will be useful, but WITHOUT
9898 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9899 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9902 * You should have received a copy of the GNU Affero General Public License along with
9903 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9904 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9907 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9908 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9910 * The interactive user interfaces in modified source and object code versions
9911 * of this program must display Appropriate Legal Notices, as required under
9912 * Section 5 of the GNU Affero General Public License version 3.
9914 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9915 * these Appropriate Legal Notices must retain the display of the "Powered by
9916 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9917 * technical reasons, the Appropriate Legal Notices must display the words
9918 * "Powered by SugarCRM".
9919 ********************************************************************************/
9921 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9922 '<body onload="javascript:window.print();">' +
9926 ' font-family: helvetica, impact, sans-serif;' +
9927 ' font-size : 12pt;' +
9934 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9937 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9939 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9940 ' {app_strings.LBL_EMAIL_FROM}:' +
9942 ' <td width="99%" class="displayEmailValue">' +
9943 ' {email.from_name} <{email.from_addr}>' +
9947 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9948 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9950 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9951 ' <b>{email.name}</b>' +
9955 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9956 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9958 ' <td class="displayEmailValue">' +
9959 ' {email.date_start} {email.time_start}' +
9963 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9964 ' {app_strings.LBL_EMAIL_TO}:' +
9966 ' <td class="displayEmailValue">' +
9967 ' {email.toaddrs}' +
9971 ' {email.attachments}' +
9977 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9979 ' <td style="border-top: 1px solid #333;">' +
9980 ' <div style="padding:5px;">' +
9981 '{email.description}' +
9991 // End of File modules/Emails/javascript/viewPrintable.js
9993 /*********************************************************************************
9994 * SugarCRM Community Edition is a customer relationship management program developed by
9995 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9997 * This program is free software; you can redistribute it and/or modify it under
9998 * the terms of the GNU Affero General Public License version 3 as published by the
9999 * Free Software Foundation with the addition of the following permission added
10000 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10001 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10002 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
10004 * This program is distributed in the hope that it will be useful, but WITHOUT
10005 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10006 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
10009 * You should have received a copy of the GNU Affero General Public License along with
10010 * this program; if not, see http://www.gnu.org/licenses or write to the Free
10011 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
10014 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
10015 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
10017 * The interactive user interfaces in modified source and object code versions
10018 * of this program must display Appropriate Legal Notices, as required under
10019 * Section 5 of the GNU Affero General Public License version 3.
10021 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
10022 * these Appropriate Legal Notices must retain the display of the "Powered by
10023 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
10024 * technical reasons, the Appropriate Legal Notices must display the words
10025 * "Powered by SugarCRM".
10026 ********************************************************************************/
10027 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
10028 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;}
10029 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');}
10030 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;}}
10031 if(QSProcessedFieldsArray[qs_index_id]){skipSTR='collection_0';if(qs_index_id.lastIndexOf(skipSTR)!=(qs_index_id.length-skipSTR.length)){continue;}}
10032 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
10033 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}
10034 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]]);}}}
10035 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]]);}}
10036 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
10037 {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]])
10038 {document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";}}}};search.setFields=function(data,filter)
10039 {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])
10040 {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';}}}}
10041 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))
10042 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
10043 {if(this.inputElement.id=='shipping_account_name')
10044 {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)/;}
10045 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
10046 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
10047 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];}}}
10048 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]];}
10049 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;}}}}});}
10050 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
10051 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}
10052 // End of File include/javascript/quicksearch.js