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())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML=' ';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};addToValidate(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,'email',this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
216 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
217 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
218 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
219 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
220 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
221 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
222 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
223 if(SUGAR.isIE){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
224 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
225 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();// End of File include/SugarEmailAddress/SugarEmailAddress.js
227 /*********************************************************************************
228 * SugarCRM Community Edition is a customer relationship management program developed by
229 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
231 * This program is free software; you can redistribute it and/or modify it under
232 * the terms of the GNU Affero General Public License version 3 as published by the
233 * Free Software Foundation with the addition of the following permission added
234 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
235 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
236 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
238 * This program is distributed in the hope that it will be useful, but WITHOUT
239 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
240 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
243 * You should have received a copy of the GNU Affero General Public License along with
244 * this program; if not, see http://www.gnu.org/licenses or write to the Free
245 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
248 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
249 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
251 * The interactive user interfaces in modified source and object code versions
252 * of this program must display Appropriate Legal Notices, as required under
253 * Section 5 of the GNU Affero General Public License version 3.
255 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
256 * these Appropriate Legal Notices must retain the display of the "Powered by
257 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
258 * technical reasons, the Appropriate Legal Notices must display the words
259 * "Powered by SugarCRM".
260 ********************************************************************************/
261 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
262 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
263 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
264 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
265 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
266 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
267 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
268 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
269 this.js_more();this.js_more();}
270 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
271 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
272 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
273 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
274 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&¤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';}
275 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
276 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
277 currentNode.name=new_name;currentNode.id=new_name;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_name;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
278 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
279 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
281 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
283 if(!has_primary){return false;}
285 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
286 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
287 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
288 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
289 if(noAdd){enableQS(false);}
290 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_collection_"+i);var id_field=document.getElementById("id_"+this.field+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].id==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
292 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
293 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
295 SUGAR.collection.safe_clone=function(e,recursive)
296 {if(e.nodeName=="#text")
297 {return document.createTextNode(e.data);}
298 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;if(SUGAR.isIE7&&e.tagName.toLowerCase()=='input')
299 {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'];}
300 for(var i in properties)
301 {if(e[properties[i]])
302 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
303 newNode[properties[i]]=e[properties[i]];}}
305 {for(var i in e.childNodes)
306 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
307 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
308 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
310 /*********************************************************************************
311 * SugarCRM Community Edition is a customer relationship management program developed by
312 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
314 * This program is free software; you can redistribute it and/or modify it under
315 * the terms of the GNU Affero General Public License version 3 as published by the
316 * Free Software Foundation with the addition of the following permission added
317 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
318 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
319 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
321 * This program is distributed in the hope that it will be useful, but WITHOUT
322 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
323 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
326 * You should have received a copy of the GNU Affero General Public License along with
327 * this program; if not, see http://www.gnu.org/licenses or write to the Free
328 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
331 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
332 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
334 * The interactive user interfaces in modified source and object code versions
335 * of this program must display Appropriate Legal Notices, as required under
336 * Section 5 of the GNU Affero General Public License version 3.
338 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
339 * these Appropriate Legal Notices must retain the display of the "Powered by
340 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
341 * technical reasons, the Appropriate Legal Notices must display the words
342 * "Powered by SugarCRM".
343 ********************************************************************************/
344 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);}
345 return s;},init:function(){if(Rot13.map!=null)
346 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
347 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
348 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
349 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='';}
350 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='';}
351 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='';}}
353 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)
354 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
355 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id:'';URL='index.php?'
356 +'module='+module_name
359 +'&target='+pageTarget
360 +'&target1='+pageTarget
361 +'&server_url='+mail_server
362 +'&email_user='+words[0]
363 +'&protocol='+protocol
365 +'&email_password='+words[1]
366 +'&mailbox='+words[2]
369 +'&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)
370 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
371 this.body.style.width=w}}
372 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
373 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();}
374 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'));}
375 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
376 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
377 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
378 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
379 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";}
381 alert(out);return false;}else{return true;}}
382 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?'
383 +'module='+module_name
386 +'&target='+pageTarget
387 +'&target1='+pageTarget
388 +'&server_url='+mail_server
389 +'&email_user='+words[0]
390 +'&protocol='+protocol
392 +'&email_password='+words[1]
393 +'&mailbox='+words[2]
395 +'&personal='+isPersonal
396 +'&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)
397 this.body.style.width=w}}
398 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();}
399 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;}}}
400 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';}}}
401 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='';}
402 else{mailbox.value="INBOX";mailbox.disabled=false;try{mailbox.style.display="none";trashFolderRow.style.display="none";sentFolderRow.style.display="none";trashFolderRow1.style.display="none";subscribeFolderButton.style.display="none";}catch(e){};label_inbox.style.display="none";}}// End of File modules/InboundEmail/InboundEmail.js
404 /*********************************************************************************
405 * SugarCRM Community Edition is a customer relationship management program developed by
406 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
408 * This program is free software; you can redistribute it and/or modify it under
409 * the terms of the GNU Affero General Public License version 3 as published by the
410 * Free Software Foundation with the addition of the following permission added
411 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
412 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
413 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
415 * This program is distributed in the hope that it will be useful, but WITHOUT
416 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
417 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
420 * You should have received a copy of the GNU Affero General Public License along with
421 * this program; if not, see http://www.gnu.org/licenses or write to the Free
422 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
425 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
426 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
428 * The interactive user interfaces in modified source and object code versions
429 * of this program must display Appropriate Legal Notices, as required under
430 * Section 5 of the GNU Affero General Public License version 3.
432 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
433 * these Appropriate Legal Notices must retain the display of the "Powered by
434 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
435 * technical reasons, the Appropriate Legal Notices must display the words
436 * "Powered by SugarCRM".
437 ********************************************************************************/
440 cache : new Object(),
441 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
442 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
445 currentHtmleditor : ''
449 * preserves hits from email server
451 _setDetailCache : function(ret) {
453 var compKey = ret.meta.mbox + ret.meta.uid;
455 if(!SUGAR.email2.cache[compKey]) {
456 SUGAR.email2.cache[compKey] = ret;
461 autoSetLayout : function() {
462 var c = document.getElementById('container');
463 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
464 //Ensure a minimum height.
465 tHeight = Math.max(tHeight, 550);
466 c.style.height = tHeight + "px";
467 SUGAR.email2.complexLayout.set('height', tHeight);
468 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
469 SUGAR.email2.complexLayout.render();
470 SUGAR.email2.listViewLayout.resizePreview();
475 * Shows overlay progress message
477 function overlayModal(title, body) {
478 overlay(title, body);
480 function overlay(reqtitle, body, type, additconfig) {
482 if (typeof(additconfig) == "object") {
483 var config = additconfig;
486 config.title = reqtitle;
488 YAHOO.SUGAR.MessageBox.show(config);
491 function hideOverlay() {
492 YAHOO.SUGAR.MessageBox.hide();
494 // End of File modules/Emails/javascript/EmailUIShared.js
496 /*********************************************************************************
497 * SugarCRM Community Edition is a customer relationship management program developed by
498 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
500 * This program is free software; you can redistribute it and/or modify it under
501 * the terms of the GNU Affero General Public License version 3 as published by the
502 * Free Software Foundation with the addition of the following permission added
503 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
504 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
505 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
507 * This program is distributed in the hope that it will be useful, but WITHOUT
508 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
509 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
512 * You should have received a copy of the GNU Affero General Public License along with
513 * this program; if not, see http://www.gnu.org/licenses or write to the Free
514 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
517 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
518 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
520 * The interactive user interfaces in modified source and object code versions
521 * of this program must display Appropriate Legal Notices, as required under
522 * Section 5 of the GNU Affero General Public License version 3.
524 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
525 * these Appropriate Legal Notices must retain the display of the "Powered by
526 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
527 * technical reasons, the Appropriate Legal Notices must display the words
528 * "Powered by SugarCRM".
529 ********************************************************************************/
533 var sw = YAHOO.SUGAR,
534 Event = YAHOO.util.Event,
535 Connect = YAHOO.util.Connect,
539 ///////////////////////////////////////////////////////////////////////////////
542 outboundDialog : null,
543 inboundAccountEditDialog : null,
544 inboundAccountsSettingsTable : null,
545 outboundAccountsSettingsTable : null,
546 testOutboundDialog : null,
547 errorStyle : 'input-error',
549 newAddedOutboundId : '',
552 * makes async call to retrieve an outbound instance for editting
555 editOutbound : function(obi) {
557 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
560 deleteOutbound : function(obi) {
562 if(obi.match(/^(add|line|sendmail)+/)) {
563 alert('Invalid Operation');
565 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
566 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
570 getReplyAddress : function() {
573 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
574 var addy = SE.userPrefs.current_user.emailAddresses[i];
576 if(addy.primary_address == "1") {
577 primary = addy.email_address;
580 if(addy.reply_to == "1") {
581 return addy.email_address;
589 * Called on "Accounts" tab activation event
591 lazyLoad : function() {
593 this._setupInboundAccountTable();
594 this._setupOutboundAccountTable();
598 _setupInboundAccountTable: function()
600 //Setup the inbound mail settings
601 if(!this.inboundAccountsSettingsTable)
603 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
604 var clckEvent = oColumn.key;
606 var is_group = oRecord.getData("is_group");
609 if(oColumn.key == 'edit')
611 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
612 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
614 else if(oColumn.key == 'delete')
616 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
617 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
619 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
623 this.showBoolean = function(el, oRecord, oColumn, oData)
625 var is_group = oRecord.getData("is_group");
626 var bChecked = oData;
627 bChecked = (bChecked) ? " checked" : "";
630 el.innerHTML = "<input type=\"radio\"" + bChecked +
631 " name=\"col" + oColumn.getId() + "-radio\"" +
632 " class=\"yui-dt-radio\">";
637 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
638 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
640 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
641 '<img border="0" src="themes/default/images/helpInline.gif">' +
642 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
645 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
646 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
647 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
648 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
649 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
650 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
651 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
652 this.ieDataSource = new YAHOO.util.DataSource(query);
653 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
654 this.ieDataSource.responseSchema = {
655 resultsList: "account_list",
656 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
658 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
659 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
661 var elCheckbox = oArgs.target;
662 var oColumn = this.getColumn(elCheckbox);
663 if(oColumn.key == 'is_active')
665 var oRecord = this.getRecord(elCheckbox);
666 oRecord.setData("is_active",elCheckbox.checked);
667 var t_id = oRecord.getData('id');
668 var isGroupFolder = oRecord.getData('has_groupfolder');
671 SUGAR.email2.folders.updateSubscriptions();
673 SUGAR.email2.folders.setFolderSelection();
677 var lastDefaultSelectedId = "";
678 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
680 var elRadio = oArgs.target;
681 var oColumn = this.getColumn(elRadio);
682 if(oColumn.key == 'is_default')
684 var oRecord = this.getRecord(elRadio);
685 var t_id = oRecord.getData('id');
686 var t_isGroup = oRecord.getData('is_group');
687 if(t_id != lastDefaultSelectedId && !t_isGroup)
689 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
690 lastDefaultSelectedId = t_id;
691 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
694 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
699 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
700 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
703 _setupOutboundAccountTable: function()
705 if(!this.outboundAccountsSettingsTable)
707 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
708 var clckEvent = oColumn.key;
710 var isEditable = oRecord.getData("is_editable");
711 var type = oRecord.getData("type");
714 if(oColumn.key == 'edit')
716 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
717 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
719 else if(oColumn.key == 'delete' && type == 'user')
721 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
722 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
725 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
729 //Custom formatter to display any error messages.
730 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
732 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
733 SUGAR.email2.composeLayout.outboundAccountErrors = {};
735 var id = oRecord.getData('id');
736 var message = oRecord.getData("errors");
739 elLiner.innerHTML = '<span class="required">' + message + '</span>';
740 //Add the id and message for all outbound accounts.
741 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
745 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
746 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
749 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
750 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
752 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
753 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
754 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
755 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
757 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
758 this.obDataSource = new YAHOO.util.DataSource(query);
759 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
760 this.obDataSource.responseSchema = {
762 resultsList: "outbound_account_list",
763 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
766 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
769 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
770 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
771 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
775 * Displays a modal diaglogue to edit outbound account settings
777 showEditInboundAccountDialogue : function(clear) {
779 if(!this.inboundAccountEditDialog) {
780 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
784 constraintoviewport: true,
788 EAD.showEvent.subscribe(function() {
789 var el = this.element;
790 var viewH = YAHOO.util.Dom.getViewportHeight();
791 if (this.header && el && viewH - 50 < el.clientHeight) {
792 var body = this.header.nextElementSibling;
793 body.style.overflow = "hidden";
794 body.style.height = "100%";
797 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
798 Dom.removeClass("editAccountDialogue", "yui-hidden");
802 if(clear == undefined || clear == true)
804 SE.accounts.clearInboundAccountEditScreen();
805 //Set default protocol to IMAP when creating new records
806 document.forms['ieAccount'].elements['protocol'].value = "imap";
807 SE.accounts.setPortDefault();
810 //Check if we should display username/password fields for outbound account if errors were detected.
811 this.checkOutBoundSelection();
813 this.inboundAccountEditDialog.render();
814 this.inboundAccountEditDialog.show();
815 SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
819 * Set all fields on the outbound edit form to either enabled/disabled
820 * except for the username/password.
823 toggleOutboundAccountDisabledFields: function(disable)
825 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
826 for(var i=0;i<fields.length;i++)
828 document.getElementById(fields[i]).disabled = disable;
831 Dom.addClass("mail_smtpssl_row", "yui-hidden");
833 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
837 * Refresh the inbound accounts table.
839 refreshInboundAccountTable : function()
841 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
843 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
844 scope: this.inboundAccountsSettingsTable }
848 * Refresh the outbound accounts table.
850 refreshOuboundAccountTable : function()
852 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
854 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
855 scope: this.outboundAccountsSettingsTable }
859 * Displays a modal diaglogue to add a SMTP server
861 showAddSmtp : function() {
862 // lazy load dialogue
863 if(!this.outboundDialog) {
864 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
868 constraintoviewport: true,
872 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
873 this.outboundDialog.hideEvent.subscribe(function(){
874 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
875 var out = Dom.get("outbound_email");
876 if (out && out.value == "SYSTEM_ADD")
878 out.value = out.options[0].value;
880 //Check if we should display username/password for system account.
881 SE.accounts.checkOutBoundSelection();
885 Dom.removeClass("outboundDialog", "yui-hidden");
889 var form = document.getElementById('outboundEmailForm');
890 for(i=0; i<form.elements.length; i++) {
891 if(form.elements[i].name == 'mail_smtpport') {
892 form.elements[i].value = 25;
893 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
894 form.elements[i].value = '';
895 } else if(form.elements[i].type == 'checkbox') {
896 form.elements[i].checked = false;
899 //Render the SMTP buttons
900 if ( !SUGAR.smtpButtonGroup ) {
901 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
902 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
904 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
905 document.getElementById('smtp_settings').style.display = '';
906 form.mail_smtptype.value = e.newValue.get('value');
908 YAHOO.widget.Button.addHiddenFieldsToForm(form);
910 //Hide Username/Password
911 SUGAR.email2.accounts.smtp_authenticate_field_display();
912 //Unset readonly fields
913 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
914 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
915 this.outboundDialog.render();
916 this.outboundDialog.show();
920 * Accounts' Advanced Settings view toggle
922 toggleAdv : function() {
923 var adv = document.getElementById("ie_adv");
924 if(adv.style.display == 'none') {
925 adv.style.display = "";
927 adv.style.display = 'none';
931 smtp_authenticate_field_display : function() {
932 var smtpauth_req = document.getElementById("mail_smtpauth_req");
933 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
934 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
937 smtp_setDefaultSMTPPort : function() {
938 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
940 if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
941 document.getElementById("mail_smtpport").value = '465';
943 if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
944 document.getElementById("mail_smtpport").value = '25';
949 * Changes the display used in the outbound email SMTP dialog to match the
951 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
953 document.getElementById("smtpButtonGroupTD").style.display = '';
954 document.getElementById("chooseEmailProviderTD").style.display = '';
955 document.getElementById("mailsettings1").style.display = '';
956 document.getElementById("mailsettings2").style.display = '';
957 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
958 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
959 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
960 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
964 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
965 document.getElementById("mail_smtpport").value = '465';
966 document.getElementById("mail_smtpauth_req").checked = true;
967 var ssl = document.getElementById("mail_smtpssl");
968 for(var j=0;j<ssl.options.length;j++) {
969 if(ssl.options[j].text == 'SSL') {
970 ssl.options[j].selected = true;
974 document.getElementById("mailsettings1").style.display = 'none';
975 document.getElementById("mailsettings2").style.display = 'none';
976 document.getElementById("mail_smtppass_label").innerHTML =
977 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
978 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
981 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
982 document.getElementById("mail_smtpport").value = '587';
983 document.getElementById("mail_smtpauth_req").checked = true;
984 var ssl = document.getElementById("mail_smtpssl");
985 for(var j=0;j<ssl.options.length;j++) {
986 if(ssl.options[j].text == 'TLS') {
987 ssl.options[j].selected = true;
991 document.getElementById("mailsettings1").style.display = 'none';
992 document.getElementById("mailsettings2").style.display = 'none';
993 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
994 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
997 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
998 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
999 document.getElementById("mail_smtpserver").value = '';
1001 document.getElementById("mail_smtpport").value = '25';
1002 document.getElementById("mail_smtpauth_req").checked = true;
1003 document.getElementById("mailsettings1").style.display = '';
1004 document.getElementById("mailsettings2").style.display = '';
1005 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1006 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1007 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1008 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1011 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1013 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1014 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1015 document.getElementById("mailsettings2").style.display = 'none';
1018 SUGAR.email2.accounts.smtp_authenticate_field_display();
1019 SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1023 * Fill the gmail default values for inbound accounts.
1025 fillInboundGmailDefaults: function () {
1027 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1028 document.forms['ieAccount'].elements['ssl'].checked = true;
1029 document.forms['ieAccount'].elements['protocol'].value = "imap";
1030 SUGAR.email2.accounts.setPortDefault();
1031 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1034 * Sets Port field to selected protocol and SSL settings defaults
1036 setPortDefault : function() {
1037 var prot = document.getElementById('protocol');
1038 var ssl = document.getElementById('ssl');
1039 var port = document.getElementById('port');
1040 var stdPorts= new Array("110", "143", "993", "995");
1041 var stdBool = new Boolean(false);
1042 var mailboxdiv = document.getElementById("mailboxdiv");
1043 var trashFolderdiv = document.getElementById("trashFolderdiv");
1044 var sentFolderdiv = document.getElementById("sentFolderdiv");
1045 var monitoredFolder = document.getElementById("subscribeFolderButton");
1046 if(port.value == '') {
1047 stdBool.value = true;
1049 for(i=0; i<stdPorts.length; i++) {
1050 if(stdPorts[i] == port.value) {
1051 stdBool.value = true;
1056 if(stdBool.value == true) {
1057 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1059 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1061 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1063 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1068 if (prot.value == 'imap') {
1069 mailboxdiv.style.display = "";
1070 trashFolderdiv.style.display = "";
1071 sentFolderdiv.style.display = "";
1072 monitoredFolder.style.display = "";
1073 if (document.getElementById('mailbox').value == "") {
1074 document.getElementById('mailbox').value = "INBOX";
1077 mailboxdiv.style.display = "none";
1078 trashFolderdiv.style.display = "none";
1079 sentFolderdiv.style.display = "none";
1080 monitoredFolder.style.display = "none";
1081 document.getElementById('mailbox').value = "";
1086 * Draws/removes red boxes around required fields.
1088 ieAccountError : function(style) {
1089 document.getElementById('server_url').className = style;
1090 document.getElementById('email_user').className = style;
1091 document.getElementById('email_password').className = style;
1092 document.getElementById('protocol').className = style;
1093 document.getElementById('port').className = style;
1096 checkOutBoundSelection: function() {
1097 var select = Dom.get('outbound_email');
1098 if (!select || select.selectedIndex == -1) { return; }
1100 var v = select.options[select.selectedIndex].value;
1104 select.options[select.selectedIndex].selected = false;
1105 v = select.options[0].value;
1107 else if (v == 'SYSTEM_ADD')
1108 SUGAR.email2.accounts.showAddSmtp();
1110 var foundError = false;
1111 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1112 for(i in errorAccounts)
1121 //Should username/password fields for outbound account.
1123 this.toggleInboundOutboundFields(true);
1125 this.toggleInboundOutboundFields(false);
1130 toggleInboundOutboundFields : function (display)
1134 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1135 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1139 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1140 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1144 * rebuilds the select options for mailer options
1146 rebuildMailerOptions : function() {
1147 var select = document.forms['ieAccount'].elements['outbound_email'];
1148 SE.util.emptySelectOptions(select);
1150 //Get the available sugar mailers
1151 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1153 for(i=0;i<a_outbound.length;i++)
1155 var t_record = a_outbound[i];
1156 var key = t_record.getData('id');
1157 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1159 var opt = new Option(display, key);
1160 select.options.add(opt);
1161 if (key == SE.accounts.newAddedOutboundId) {
1162 select.options.selectedIndex = i;
1166 select.options.add(new Option('',''));
1167 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1168 //Hide/Show username password fields if necessary.
1169 SE.accounts.checkOutBoundSelection();
1172 * Empties all the fields in the accounts edit view
1174 clearInboundAccountEditScreen:function() {
1176 document.getElementById('ie_id').value = '';
1177 document.getElementById('ie_name').value = '';
1178 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1179 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1180 document.getElementById('reply_to_addr').value = '';
1181 document.getElementById('server_url').value = '';
1182 document.getElementById('email_user').value = '';
1183 document.getElementById('email_password').value = '';
1184 document.getElementById('port').value = '';
1185 document.getElementById('inbound_mail_smtpuser').value = '';
1186 document.getElementById('inbound_mail_smtppass').value = '';
1187 document.ieAccount.protocol.options[0].selected = true;
1189 document.getElementById('ssl').checked = false;
1190 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1194 * Populates an account's fields in Settings->Accounts
1196 fillIeAccount:function(jsonstr) {
1197 var o = JSON.parse(jsonstr);
1199 document.getElementById('ie_id').value = o.id;
1200 document.getElementById('ie_name').value = o.name;
1201 if (o.stored_options != null) {
1202 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1203 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1204 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1205 if (o.stored_options.trashFolder != null) {
1206 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1208 if (o.stored_options.sentFolder != null) {
1209 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1212 document.getElementById('server_url').value = o.server_url;
1213 document.getElementById('email_user').value = o.email_user;
1214 document.getElementById('port').value = o.port;
1215 document.getElementById('group_id').value = o.group_id;
1216 document.getElementById('mailbox').value = o.mailbox;
1222 if(typeof(o.service[2]) != 'undefined') {
1223 document.getElementById('ssl').checked = true;
1227 if(document.getElementById('protocol').value != o.protocol) {
1228 var prot = document.getElementById('protocol');
1229 for(i=0; i<prot.options.length; i++) {
1230 if(prot.options[i].value == o.service[3]) {
1231 prot.options[i].selected = true;
1232 this.setPortDefault();
1236 // handle SMTP selection
1237 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1238 var opts = document.getElementById('outbound_email').options;
1239 for(i=0; i<opts.length; i++) {
1240 if(opts[i].value == o.stored_options.outbound_email) {
1241 opts[i].selected = true;
1247 deleteIeAccount : function(IeAccountID,IeGroupID) {
1248 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1250 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1252 AjaxObject.target = 'frameFlex';
1253 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1254 SUGAR.email2.accounts.refreshInboundAccountTable();
1258 // Null check for Outbound Settings.
1259 checkOutboundSettings: function() {
1260 var errorMessage = '';
1261 var isError = false;
1262 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1263 var mailName = document.getElementById('mail_name').value;
1264 var smtpServer = document.getElementById('mail_smtpserver').value;
1265 var smtpPort = document.getElementById('mail_smtpport').value;
1267 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1268 if(trim(mailName) == '') {
1270 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1272 if(trim(smtpServer) == '') {
1274 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1276 if(trim(smtpPort) == '') {
1278 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1280 if(mailsmtpauthreq.checked) {
1281 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1283 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1288 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1295 testOutboundSettings: function() {
1296 var errorMessage = '';
1297 var isError = false;
1298 var fromAddress = document.getElementById("outboundtest_from_address").value;
1299 if (trim(fromAddress) == "") {
1300 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1301 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1305 else if (!isValidEmail(fromAddress)) {
1306 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1307 overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1311 //Hide the dialogue and show an in progress indicator.
1312 SE.accounts.testOutboundDialog.hide();
1313 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1315 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1316 //nothing is sent in the request.
1317 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1318 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1320 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1321 if(outboundType == 'system-override')
1322 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1324 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1325 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1329 testOutboundSettingsDialog: function() {
1330 //Ensure that all settings are correct before proceeding to send test email.
1331 if(!SE.accounts.checkOutboundSettings())
1334 // lazy load dialogue
1335 if(!SE.accounts.testOutboundDialog) {
1336 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1340 constraintoviewport: true,
1344 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1345 Dom.removeClass("testOutboundDialog", "yui-hidden");
1347 SE.accounts.testOutboundDialog.render();
1348 SE.accounts.testOutboundDialog.show();
1352 * Saves Outbound email settings
1354 saveOutboundSettings : function() {
1355 if(SE.accounts.checkOutboundSettings()) {
1356 //Enable the form fields for the post.
1357 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1358 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1359 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1365 saveIeAccount : function() {
1367 //Before saving check if there are any error messages associated with the outbound account.
1368 var outboundID = document.getElementById('outbound_email').value;
1370 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1371 'validateSMTPCreds':true}) )
1373 document.getElementById('saveButton').disabled = true;
1375 overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1377 var formObject = document.getElementById('ieAccount');
1378 YAHOO.util.Connect.setForm(formObject);
1380 AjaxObject._reset();
1381 AjaxObject.target = 'frameFlex';
1382 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1386 testSettings : function() {
1387 form = document.getElementById('ieAccount');
1389 if(SE.accounts.checkIeCreds()) {
1390 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);
1394 getFoldersListForInboundAccountForEmail2 : function() {
1395 form = document.getElementById('ieAccount');
1396 if(SE.accounts.checkIeCreds()) {
1397 var mailBoxValue = form.mailbox.value;
1398 if (form.searchField.value.length > 0) {
1401 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 );
1406 checkIeCreds : function(validateRules) {
1407 if(typeof(validateRules) == 'undefined')
1410 var errors = new Array();
1411 var out = new String();
1413 var ie_name = Dom.get('ie_name').value;
1414 var fromAddress = Dom.get('ie_from_addr').value;
1415 var server_url = Dom.get('server_url').value;
1416 var email_user = Dom.get('email_user').value;
1417 var email_password = Dom.get('email_password').value;
1418 var protocol = Dom.get('protocol').value;
1419 var port = Dom.get('port').value;
1420 var oe = Dom.get('outbound_email');
1421 var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1423 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1424 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1426 //If the username and password were provided then ignore the error messge
1428 var outboundCredentialsFound = false;
1430 if(outboundUserName != "" && outboundPass != "")
1431 outboundCredentialsFound = true;
1433 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1435 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1436 && validateSMTPCreds)
1438 if(trim(outboundUserName) == "") {
1439 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1441 if(trim(outboundPass) == "") {
1442 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1446 if(trim(ie_name) == "") {
1447 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1450 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1452 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1453 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1458 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1459 || trim(oe_value) == "SYSTEM_ADD") ) {
1460 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1462 if(trim(server_url) == "") {
1463 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1465 if(trim(email_user) == "") {
1466 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1468 if(protocol == "") {
1469 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1471 if (protocol == 'imap') {
1472 var mailbox = document.getElementById('mailbox').value;
1473 if (trim(mailbox) == "") {
1474 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1476 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1477 var trashFolder = document.getElementById('trashFolder').value;
1478 if (trim(trashFolder) == "") {
1479 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1484 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1487 if(errors.length > 0) {
1488 out = app_strings.LBL_EMAIL_ERROR_DESC;
1489 for(i=0; i<errors.length; i++) {
1504 getIeAccount : function(ieId) {
1508 overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1509 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1511 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1515 * Iterates through TreeView nodes to apply styles dependent nature of node
1517 renderTree:function() {
1518 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1522 //Sets the style for any nodes that need it.
1523 setNodeStyle : function(node) {
1524 if (!node.data.origText) {
1525 node.data.origText = node.data.text;
1528 if (typeof(node.data.unseen) != 'undefined') {
1529 if (node.data.unseen > 0) {
1530 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1533 node.setUpLabel(node.data.origText);
1536 node.setUpLabel('<span>' + node.data.origText + '</span>');
1538 SE.accounts.setupDDTarget(node);
1541 setupDDTarget : function(node) {
1542 if (node.ddTarget) {
1543 node.ddTarget.removeFromGroup();
1544 delete node.ddTarget;
1546 var id = node.getElId();
1547 var num = id.substring(4);
1548 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1549 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1550 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1552 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1554 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1555 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1560 * Async call to rebuild the folder list. After a folder delete or account delete
1562 rebuildFolderList : function() {
1563 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1564 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1568 * Returns the number of remote accounts the user has active.
1570 getAccountCount : function() {
1573 for(i=0; i<tree._nodes.length; i++) {
1574 var node = tree._nodes[i];
1576 if(typeof(node) != 'undefined' && node.data.ieId) {
1584 ///////////////////////////////////////////////////////////////////////////////
1589 ///////////////////////////////////////////////////////////////////////////////
1590 //// CONTEXT MENU CALLS
1593 assignToDialogue : null,
1595 * Archives from context menu
1597 * @param string ieId
1598 * @param string folder
1600 _archiveToSugar : function(uids, ieId, folder) {
1603 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1604 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1607 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1611 * Archives from context menu
1613 archiveToSugar : function(menuItem) {
1614 SE.contextMenus.emailListContextMenu.hide();
1616 var rows = SE.grid.getSelectedRows();
1618 /* iterate through available rows JIC a row is deleted - use first available */
1619 for(var i=0; i<rows.length; i++) {
1620 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1622 var data = SE.grid.getRecord(rows[0]).getData();
1623 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1627 * Popup the printable version and start system's print function.
1629 viewPrintable : function(menuItem) {
1630 var rows = SE.grid.getSelectedRows();
1631 var data = SE.grid.getRecord(rows[0]).getData();
1632 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1636 * Marks email flagged on mail server
1638 markRead : function(type, contextMenuId) {
1639 SE.contextMenus.markEmail('read');
1643 * Assign this emails to people based on assignment rules
1645 assignEmailsTo : function(type, contextMenuId) {
1646 if(!SE.contextMenus.assignToDialogue)
1648 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1652 constraintoviewport: true,
1656 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1660 Dom.removeClass("assignToDiv", "yui-hidden");
1661 SE.contextMenus.assignToDialogue.render();
1662 SE.contextMenus.assignToDialogue.show();
1666 * Marks email flagged on mail server
1668 markFlagged : function(contextMenuId) {
1669 SE.contextMenus.markEmail('flagged');
1673 * Marks email unflagged on mail server
1675 markUnflagged : function(contextMenuId) {
1676 SE.contextMenus.markEmail('unflagged');
1680 * Marks email unread on mail server
1682 markUnread : function() {
1683 SE.contextMenus.markEmail('unread');
1687 * Deletes an email from context menu
1689 markDeleted : function() {
1690 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1691 document.getElementById('_blank').innerHTML = "";
1692 SE.contextMenus.markEmail('deleted');
1697 * generic call API to apply a flag to emails on the server and on sugar
1698 * @param string type "read" | "unread" | "flagged" | "deleted"
1700 markEmail : function(type) {
1701 SE.contextMenus.emailListContextMenu.hide();
1703 //var dm = SE.grid.getStore();
1704 //var uids = SE.grid.getSelectedRowIds();
1705 //var indexes = SE.grid.getSelectedRowIndexes();
1706 var rows = SE.grid.getSelectedRows();
1707 if (rows.length == 0)
1708 rows = [SE.contextMenus.currentRow];
1711 for(var i=0; i<rows.length; i++) {
1712 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1715 ser = YAHOO.lang.JSON.stringify(ser);
1717 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1718 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1724 if(type == 'read' || type == 'deleted') {
1726 for(var j=0; j<rows.length; j++) {
1727 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1729 SE.grid.getRecord(rows[j]).setData("seen", "1");
1732 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1734 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1735 var unseenCount = node.data.unseen;
1736 if (isNaN(unseenCount)) {
1739 var finalCount = parseInt(unseenCount) - count;
1740 node.data.unseen = finalCount;
1742 SE.accounts.renderTree();
1744 } else if(type == 'unread') {
1746 for(var j=0; j<rows.length; j++) {
1747 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1752 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1753 var unseenCount = node.data.unseen;
1754 if (isNaN(unseenCount)) {
1757 var finalCount = parseInt(unseenCount) + count;
1758 node.data.unseen = finalCount;
1759 SE.accounts.renderTree();
1762 if (type == 'unread') {
1763 for(var i=0; i<rows.length; i++) {
1764 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1768 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1769 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1773 * refreshes the ListView to show changes to cache
1775 markEmailCleanup : function() {
1776 SE.accounts.renderTree();
1778 SE.listView.refreshGrid();
1781 showAssignmentDialog : function() {
1782 if (SE.contextMenus.assignmentDialog == null) {
1783 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1785 SE.contextMenus.assignmentDialog.show();
1790 * shows the import dialog with only relate visible.
1792 relateTo : function() {
1793 SE.contextMenus.emailListContextMenu.hide();
1795 var rows = SE.grid.getSelectedRows();
1796 var data = SE.grid.getRecord(rows[0]).getData();
1797 var ieId = data.ieId;
1798 var folder = data.mbox;
1800 /* iterate through available rows JIC a row is deleted - use first available */
1801 for(var i=0; i<rows.length; i++) {
1802 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1804 var ser = JSON.stringifyNoSecurity(uids);
1806 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1810 * shows the import dialog with only relate visible.
1812 showDetailView : function() {
1813 SE.contextMenus.emailListContextMenu.hide();
1814 var rows = SE.grid.getSelectedRows();
1815 if (rows.length > 1) {
1816 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1819 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1820 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1821 /* iterate through available rows JIC a row is deleted - use first available */
1822 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1823 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1829 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1830 overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1831 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1835 * Opens multiple messages from ListView context click
1837 openMultiple : function() {
1838 SE.contextMenus.emailListContextMenu.hide();
1840 var rows = SE.grid.getSelectedRows();
1841 var uids = SE.listView.getUidsFromSelection();
1843 if(uids.length > 0) {
1844 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1845 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1846 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1851 * Replies/forwards email
1853 replyForwardEmailContext : function() {
1854 SE.contextMenus.emailListContextMenu.hide();
1856 var indexes = SE.grid.getSelectedRows();
1857 //var dm = SE.grid.getDataModel();
1860 for(var i=0; i<indexes.length; i++) {
1861 var row = SE.grid.getRecord(indexes[i]).getData();
1862 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1866 //show menu functions
1867 showEmailsListMenu : function(grid, row) {
1869 var data = row.getData();
1870 var draft = (data.type == "draft");
1871 var menu = SE.contextMenus.emailListContextMenu;
1876 if (data.mbox == 'sugar::Emails')
1877 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1879 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1881 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1882 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1883 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1884 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1886 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1889 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1891 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1892 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1893 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1894 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1895 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1898 if (data.mbox == "sugar::Emails")
1900 //Allow users to reassign imported emails
1901 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1902 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1903 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1904 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1908 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1909 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1913 showFolderMenu : function(grid, rowIndex, event) {
1915 var coords = event.getXY();
1916 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1920 SE.contextMenus.dv = {
1921 archiveToSugar : function(contextMenuId) {
1923 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1926 replyForwardEmailContext : function(all) {
1927 SE.contextMenus.detailViewContextMenu.hide();
1936 //// END SE.contextMenus
1937 ///////////////////////////////////////////////////////////////////////////////
1941 ///////////////////////////////////////////////////////////////////////////////
1944 consumeMetaDetail : function(ret) {
1945 // handling if the Email drafts
1946 if(ret.type == 'draft') {
1947 SE.composeLayout.c0_composeDraft();
1952 // cache contents browser-side
1953 SE._setDetailCache(ret);
1955 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1956 // 2 below must be in global context
1958 meta['panelId'] = SE.util.getPanelId();
1960 email = ret.meta.email;
1961 var out = displayTemplate.exec({
1962 'app_strings' : app_strings,
1964 'idx' : targetDiv.id,
1966 'email' : meta.email,
1967 'linkBeans' : linkBeans
1969 var tabLabel = meta.email.name;
1970 if (tabLabel != null && tabLabel.length > 25) {
1971 tabLabel = tabLabel.substring(0, 25) + "...";
1973 targetDiv.set("label", tabLabel);
1974 targetDiv.set("content", out);
1976 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1977 if (SUGAR.email2.util.isIe()) {
1978 displayEmailFrameDiv.style.height = "390px";
1980 displayEmailFrameDiv.style.height = "410px";
1983 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1984 displayFrame.contentWindow.document.write(email.description);
1985 displayFrame.contentWindow.document.close();
1987 // hide archive links
1988 if(ret.meta.is_sugarEmail) {
1989 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1990 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1992 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1993 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1998 consumeMetaPreview : function(ret) {
1999 // cache contents browser-side
2000 SE._setDetailCache(ret);
2004 var currrow = SE.grid.getLastSelectedRecord();
2005 currrow = SE.grid.getRecord(currrow);
2007 document.getElementById('_blank').innerHTML = '';
2010 // handling if the Email drafts
2011 if(ret.type == 'draft'){
2012 if (currrow.getData().uid == ret.uid) {
2013 SE.composeLayout.c0_composeDraft();
2018 if (currrow.getData().uid != ret.meta.uid) {
2022 // remove loading sprite
2023 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2024 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2026 meta['panelId'] = SE.util.getPanelId();
2027 email = ret.meta.email;
2029 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2030 'app_strings' : app_strings,
2034 'email' :meta.email,
2035 'linkBeans' : linkBeans
2037 // document.getElementById('_blank').innerHTML = meta.email;
2038 /* displayTemplate.append('_blank', {
2039 'app_strings' : app_strings,
2043 'email' :meta.email,
2044 'linkBeans' : linkBeans
2047 var displayFrame = document.getElementById('displayEmailFramePreview');
2048 displayFrame.contentWindow.document.write(email.description);
2049 displayFrame.contentWindow.document.close();
2051 SE.listViewLayout.resizePreview();
2053 // hide archive links
2054 if(ret.meta.is_sugarEmail) {
2055 document.getElementById("archiveEmailPreview").innerHTML = " ";
2056 document.getElementById("btnEmailViewPreview").style.display = "none";
2057 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2059 //hide view relationship link
2060 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2065 * wraps emailDelete() for single messages, comes from preview or tab
2067 emailDeleteSingle : function(ieId, uid, mbox) {
2068 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2069 // find active panel and close if the user double clicked the email to view.
2070 var activeTabId = SE.util.getPanelId();
2071 if(activeTabId != 'Preview')
2072 SE.innerLayout.get("activeTab").close();
2074 document.getElementById('_blank').innerHTML = "";
2077 uid = JSON.stringifyNoSecurity(ser);
2078 this.emailDelete(ieId, uid, mbox);
2083 * Sends async call to delete a given message
2086 emailDelete : function(ieId, uid, mbox) {
2087 overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2088 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2089 uid + "&ieId=" + ieId + "&folder=" + mbox);
2093 * retrieves one email to display in the preview pane.
2095 getEmailPreview : function() {
2096 var row = SUGAR.email2.listView.currentRow;
2097 var data = row.getData();
2098 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2099 var setRead = (data['seen'] == 0) ? true : false;
2100 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2101 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2106 * Imports one email into Sugar
2108 importEmail : function(ieId, uid, mbox) {
2109 SE.util.clearHiddenFieldValues('emailUIForm');
2111 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2113 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2114 AjaxObject.target = '';
2115 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2119 * Populates the frameFlex div with the contents of an email
2121 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2122 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2124 var mboxStr = new String(mbox);
2125 var compKey = mbox + uid;
2127 if(setRead == true) {
2128 SE.listView.boldUnreadRows()
2129 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2132 if(destination == SE.innerLayout) {
2134 * loading email into a tab, peer with ListView
2135 * targetDiv must remain in the global namespace as it is used by AjaxObject
2137 //Check if we already have a tab of the email open
2138 var tabs = SE.innerLayout.get("tabs");
2139 for (var t in tabs) {
2140 if (tabs[t].id && tabs[t].id == uid) {
2141 SE.innerLayout.set("activeTab", tabs[t]);
2146 targetDiv = new YAHOO.SUGAR.ClosableTab({
2147 label: loadingSprite,
2153 SE.innerLayout.addTab(targetDiv);
2155 // use cache if available
2156 if(SE.cache[compKey]) {
2157 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2159 // open email as peer-tab to listView
2160 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2161 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2164 // loading email into preview pane
2165 document.getElementById('_blank').innerHTML = loadingSprite;
2167 // use cache if available
2168 if(SE.cache[compKey]) {
2169 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2171 AjaxObject.forceAbort = true;
2172 // open in preview window
2173 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2174 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2179 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2181 if(mboxStr.substring(0,7) == 'sugar::') {
2182 // display an email from Sugar
2183 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2185 // display an email from an email server
2186 document.getElementById('emailUIAction').value = 'getSingleMessage';
2188 document.getElementById('mbox').value = mbox;
2189 document.getElementById('ieId').value = ieId;
2190 document.getElementById('uid').value = uid;
2192 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2194 AjaxObject.forceAbort = true;
2195 AjaxObject.target = '_blank';
2196 AjaxObject.startRequest(callback, null);
2200 * Retrieves multiple emails for DetailView
2202 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2203 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2204 SE.util.clearHiddenFieldValues('emailUIForm');
2206 var mboxStr = new String(mbox);
2208 uids = SE.util.cleanUids(uids);
2210 if(mboxStr.substring(0,7) == 'sugar::') {
2211 // display an email from Sugar
2212 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2213 document.getElementById('uid').value = uids;
2215 // display an email from an email server
2216 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2217 document.getElementById('mbox').value = mbox;
2218 document.getElementById('ieId').value = ieId;
2219 document.getElementById('uid').value = uids;
2222 var formObject = document.getElementById('emailUIForm');
2223 YAHOO.util.Connect.setForm(formObject);
2225 AjaxObject.target = 'frameFlex';
2226 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2228 if(setRead == true) {
2229 var c = uids.split(",");
2230 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2235 * Makes async call to get QuickCreate form
2236 * Renders a modal edit view for a given module
2238 quickCreate : function(module, ieId, uid, mailbox) {
2239 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2241 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2242 get += "&sugarEmail=true";
2245 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2249 * Makes async call to save a quick create
2252 saveQuickCreate : function(action) {
2253 var qcd = SE.detailView.quickCreateDialog;
2254 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2255 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2256 var theCallback = callbackQuickCreateSave;
2257 var accountType = '&sugarEmail=true';
2258 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2259 accountType = '&ieId=' + qcd.ieId;
2262 if (action == 'reply') {
2263 theCallback = callbackQuickCreateSaveAndReply;
2264 } else if (action == true) {
2265 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2267 formObject.action.value = 'EmailUIAjax';
2268 YAHOO.util.Connect.setForm(formObject);
2269 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2270 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2271 accountType + '&mbox=' + qcd.mbox);
2276 * Code to show/hide long list of email address in DetailView
2278 showCroppedEmailList : function(el) {
2279 el.style.display = 'none';
2280 el.previousSibling.style.display = 'inline'
2282 showFullEmailList : function(el) {
2283 el.style.display = 'none';
2284 el.nextSibling.style.display = 'inline';
2288 * Shows the QuickCreate overlay
2289 * @param string ieId
2291 * @param string mailbox
2293 showQuickCreate : function(ieId, uid, mailbox) {
2294 var panelId = SE.util.getPanelId();
2295 var context = document.getElementById("quickCreateSpan" + panelId);
2297 if (!SE.detailView.cqMenus)
2298 SE.detailView.cqMenus = {};
2300 if (SE.detailView.cqMenus[context])
2301 SE.detailView.cqMenus[context].destroy();
2303 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2305 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2308 for (var i=0; i < this.qcmodules.length; i++) {
2309 var module = this.qcmodules[i];
2311 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2314 onclick: { fn: function() {
2315 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2321 menu.render(document.body);
2326 * Displays the "View" submenu in the detailView
2327 * @param string ieId
2329 * @param string mailbox
2331 showViewMenu : function(ieId, uid, mailbox) {
2332 var panelId = SE.util.getPanelId();
2333 var context = "btnEmailView" + panelId;
2334 if (!SE.detailView.viewMenus)
2335 SE.detailView.viewMenus = {};
2337 if (SE.detailView.viewMenus[context])
2338 SE.detailView.viewMenus[context].destroy();
2340 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2342 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2346 (ieId == 'null' || ieId == null) ?
2347 //No ieId - Sugar Email
2349 text: app_strings.LBL_EMAIL_VIEW_RAW,
2350 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2353 //IeID exists, on a remote server
2355 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2356 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2358 text: app_strings.LBL_EMAIL_VIEW_RAW,
2359 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2362 menu.render(document.body);
2367 //#23108 jchi@07/17/2008
2368 menu.render('quickCreateSpan'+ panelId);*/
2369 //this.viewMenu = menu;
2370 //this.viewMenu.show(context);
2373 * Makes async call to get an email's headers
2375 viewHeaders : function(ieId, uid, mailbox) {
2376 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2377 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2381 * Makes async call to get a printable version
2383 viewPrintable : function(ieId, uid, mailbox) {
2384 if(mailbox == 'sugar::Emails') {
2385 // display an email from Sugar
2386 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2388 // display an email from an email server
2389 var emailUIAction = '&emailUIAction=getSingleMessage';
2392 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2393 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2397 * Makes async call to get an email's raw source
2399 viewRaw : function(ieId, uid, mailbox) {
2400 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2401 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2405 * Display all email addresses in detailview.
2407 displayAllAddrs : function(el) {
2408 el.style.display = 'none';
2409 Dom.getNextSibling(el).style.display = 'inline';
2412 //// END SE.detailView
2413 ///////////////////////////////////////////////////////////////////////////////
2417 ///////////////////////////////////////////////////////////////////////////////
2420 contextMenuFocus : new Object(),
2423 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2424 * SugarFolder ID - folder strings
2426 _createFolderId : function(node) {
2432 if(node.data.ieId) {
2433 /* we have a local Sugar folder */
2434 if(node.data.ieId == 'folder') {
2435 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2436 } else if(node.data.ieId.match(SE.reGUID)) {
2437 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2446 addChildNode : function(parentNode, childNode) {
2447 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2448 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2449 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2451 if(childNode.nodes) {
2452 if(childNode.nodes.length > 0) {
2453 for(j=0; j<childNode.nodes.length; j++) {
2454 var newChildNode = childNode.nodes[j];
2455 this.addChildNode(node, newChildNode);
2462 * Builds and returns a new TreeView Node
2463 * @param string name
2465 * @param int is_group
2468 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2469 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2471 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2472 node.expanded = expanded;
2473 node.data = new Object;
2474 node.data['id'] = id;
2475 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2476 node.data['label'] = name;
2477 node.data['ieId'] = 'folder';
2478 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2479 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2480 node.data['unseen'] = unseen;
2485 * ensures that a new folder has a valid name
2487 checkFolderName : function(name) {
2491 this.folderAdd(name);
2495 * Pings email servers for new email - forces refresh of folder pane
2497 checkEmailAccounts : function() {
2498 this.checkEmailAccountsSilent(true);
2501 checkEmailAccountsSilent : function(showOverlay) {
2502 if(typeof(SE.folders.checkingMail)) {
2503 clearTimeout(SE.folders.checkingMail);
2506 // don't stomp an on-going request
2507 if(AjaxObject.currentRequestObject.conn == null) {
2509 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2510 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2512 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2514 // wait 5 secs before trying again.
2515 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2520 * Starts check of all email Accounts using a loading bar for large POP accounts
2522 startEmailAccountCheck : function() {
2523 // don't do two checks at the same time
2524 if(!AjaxObject.requestInProgress()) {
2525 overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2526 SE.accounts.ieIds = SE.folders.getIeIds();
2527 if (SE.accounts.ieIds.length > 0) {
2528 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2529 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2534 // wait 5 secs before trying again.
2535 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2540 * Checks a single Account check based on passed ieId
2542 startEmailCheckOneAccount : function(ieId, synch) {
2549 var node = SE.clickedFolderNode;
2550 if (node && !synch) {
2551 mbox = node.data.mbox;
2553 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2554 SE.accounts.ieIds = [ieId];
2555 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2556 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2561 * Empties trash for subscribed accounts
2563 emptyTrash : function() {
2564 SE.contextMenus.frameFoldersContextMenu.hide();
2565 overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2566 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2570 * Clears Cache files of the inboundemail account
2572 clearCacheFiles : function(ieId) {
2573 SE.contextMenus.frameFoldersContextMenu.hide();
2574 overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2575 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2580 * Returns an array of all the active accounts in the folder view
2582 getIeIds : function() {
2584 var root = SE.tree.getRoot();
2585 for(i=0; i < root.children.length; i++) {
2586 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2587 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2588 ieIds.push(root.children[i].children[0].data.ieId);
2595 * loads folder lists in Settings->Folders
2597 lazyLoadSettings : function() {
2598 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2599 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2603 * After the add new folder is done via folders tab on seetings, this function should get called
2604 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2606 loadSettingFolder : function() {
2607 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2608 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2612 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2614 removeSugarFolders : function() {
2616 var root = tree.getRoot();
2617 var folder = SE.util.findChildNode(root, "ieId", "folder");
2619 tree.removeNode(folder);
2620 folder = SE.util.findChildNode(root, "ieId", "folder");
2622 if (!root.childrenRendered) {
2623 root.childrenRendered = true;
2627 rebuildFolders : function(silent) {
2628 if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2629 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2635 * Updates TreeView with Sugar Folders
2637 setSugarFolders : function(delay) {
2638 this.removeSugarFolders();
2639 //AjaxObject.forceAbort = true;
2640 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2644 * Takes async data object and creates the sugar folders in TreeView
2646 setSugarFoldersEnd : function(o) {
2647 var root = SE.tree.getRoot();
2648 addChildNodes(root, {nodes: o});
2649 SE.accounts.renderTree();
2650 //If nothing is loaded in the grid, load "My Inbox"
2651 if (SE.grid.params.ieId == "undefined") {
2652 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2656 startCheckTimer : function() {
2657 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2658 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2660 if(typeof(SE.folders.checkTimer) != 'undefined') {
2661 clearTimeout(SE.folders.checkTimer);
2664 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2665 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2667 SE.userPrefs.emailSettings.firstAutoCheck = true;
2668 SE.folders.checkEmailAccountsSilent(false);
2674 * makes an async call to save user preference and refresh folder view
2675 * @param object SELECT list object
2677 setFolderSelection : function() {
2678 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2680 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2681 var a_active_accnts = "";
2682 for(i=0;i<a_rs.length;i++)
2684 var t_record = a_rs[i];
2685 var is_active = t_record.getData('is_active');
2687 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2690 if(a_active_accnts == "")
2691 a_active_accnts = "&ieIdShow[]=";
2693 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2695 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2699 * makes async call to save user preference for a given node's open state
2700 * @param object node YUI TextNode object
2702 setOpenState : function(node) {
2703 SE.util.clearHiddenFieldValues('emailUIForm');
2704 var nodePath = node.data.id;
2705 var nodeParent = node.parent;
2707 while(nodeParent != null) {
2708 // root node has no ID param
2709 if(nodeParent.data != null) {
2710 nodePath = nodeParent.data.id + "::" + nodePath;
2713 var nodeParent = nodeParent.parent;
2716 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2717 document.getElementById('focusFolder').value = nodePath;
2719 if(node.expanded == true) {
2720 document.getElementById('focusFolderOpen').value = 'open';
2722 document.getElementById('focusFolderOpen').value = 'closed';
2725 var formObject = document.getElementById('emailUIForm');
2726 YAHOO.util.Connect.setForm(formObject);
2728 AjaxObject.startRequest(null, null);
2731 getNodeFromMboxPath : function(path) {
2732 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2733 var a = JSON.parse(path);
2735 var node = tree.getRoot();
2738 while(i < a.length) {
2739 node = this.getChildNodeFromLabel(node, a[i]);
2746 getChildNodeFromLabel : function(node, nodeLabel) {
2747 for(i=0; i<node.children.length; i++) {
2748 if(node.children[i].data.id == nodeLabel) {
2749 return node.children[i];
2755 * returns the node that presumably under the user's right-click
2757 getNodeFromContextMenuFocus : function() {
2758 //// get the target(parent) node
2759 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2761 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2763 // filter local folders
2764 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2765 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2766 if(target.id == '') {
2767 target = target.parentNode;
2774 var targetNode = document.getElementById(target.id);
2775 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2778 var matches = re.exec(targetNode.id);
2780 return document.getElementById(ygtvlabelel1);
2786 // usually parent node
2787 matches = re.exec(targetNode.parentNode.id);
2794 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2795 parentNode.expand();
2801 * Decrements the Unread Email count in folder text
2802 * @param string ieId ID to look for
2803 * @param string mailbox name
2804 * @param count how many to decrement
2806 decrementUnreadCount : function(ieId, mbox, count) {
2811 if(mbox.indexOf("sugar::") === 0) {
2812 var node = this.getNodeFromId(ieId);
2814 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2817 var unseen = node.data.unseen;
2819 var check = unseen - count;
2820 var finalCount = (check >= 0) ? check : 0;
2821 node.data.unseen = finalCount;
2823 SE.accounts.renderTree();
2828 * gets the TreeView node with a given ID/ieId
2829 * @param string id ID to look for
2830 * @return object Node
2832 getNodeFromId : function(id) {
2833 SE.folders.focusNode = null;
2834 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2835 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2836 SE.folders.focusNode = this;
2840 return SE.folders.focusNode;
2844 * Uses ieId and mailbox to try to find a node in the tree
2846 getNodeFromIeIdAndMailbox : function(id, mbox) {
2847 SE.folders.focusNode = null;
2848 if (mbox == "sugar::Emails") {
2852 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2853 if (varsarray instanceof Array) {
2854 if (this.data.ieId && this.data.ieId == varsarray[0]
2855 && this.data.mbox == varsarray[1]) {
2856 SE.folders.focusNode = this;
2860 if (this.data.ieId && this.data.ieId == varsarray) {
2861 SE.folders.focusNode = this;
2865 }, null, [id, mbox]);
2866 return SE.folders.focusNode;
2869 unhighliteAll : function() {
2870 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2874 * Displays a short form
2876 folderAdd : function() {
2877 SE.contextMenus.frameFoldersContextMenu.hide();
2879 var node = SE.clickedFolderNode;
2881 if(node != null && node.data) {
2882 overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2883 app_strings.LBL_EMAIL_SETTINGS_NAME,
2884 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2886 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2890 folderAddRegisterEnter : function() {
2891 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2892 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2893 this.buttons[1].handler);
2895 this.enterKeyListener.enable();
2898 folderRemoveRegisterEnter : function() {
2899 this.enterKeyListener.disable();
2902 folderAddXmlCall : function(name) {
2903 if (trim(name) == "") {
2904 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2907 name = escape(name);
2911 var parentNode = SE.clickedFolderNode;
2913 this.contextMenuFocus = parentNode;
2915 if(parentNode.data.ieId) {
2916 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2920 if(type == 'imap') {
2921 // make an IMAP folder
2922 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2923 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2924 } else if(type == 'sugar') {
2925 // make a Sugar folder
2926 if(SE.folders.isUniqueFolderName(name)) {
2927 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2928 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2930 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2931 SE.folders.folderAdd();
2935 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2938 // hide add-folder diaglogue
2939 SE.e2overlay.hide();
2943 * Removes either an IMAP folder or a Sugar Folder
2945 folderDelete : function() {
2946 SE.contextMenus.frameFoldersContextMenu.hide();
2948 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2950 var parentNode = SE.clickedFolderNode;
2952 if(parentNode != null && parentNode.data) {
2953 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2954 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2958 AjaxObject.target = 'frameFlex';
2960 if(parentNode.data.ieId != 'folder') {
2961 // delete an IMAP folder
2962 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2964 // delete a sugar folder
2965 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2967 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2968 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2970 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2976 * Rename folder form
2979 folderRename : function() {
2980 SE.contextMenus.frameFoldersContextMenu.hide();
2981 var node = SE.clickedFolderNode;
2984 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2985 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2989 overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2990 app_strings.LBL_EMAIL_SETTINGS_NAME,
2992 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2994 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2999 * fills an Object with key-value pairs of available folders
3001 getAvailableFoldersObject : function() {
3002 var ret = new Object();
3003 var tree = SE.tree.root;
3006 for(var i=0; i<tree.children.length; i++) {
3007 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3010 ret['none'] = app_strings.LBL_NONE;
3017 * Fills in key-value pairs for dependent dropdowns
3018 * @param object ret Associative array
3019 * @param object node TreeView node in focus
3020 * @param string currentPath Built up path thus far
3021 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3023 getFolderFromChild : function(ret, node, currentPath, spacer) {
3024 if(node.data != null && node.depth > 0) {
3025 /* handle visual separtors differentiating b/t mailserver and local */
3026 if(node.data.ieId && node.data.ieId == 'folder') {
3027 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3031 ret['spacer0'] = spacer;
3032 } else if(ret.spacer0 != spacer) {
3033 ret['spacer1'] = spacer
3036 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3037 var depthMarker = currentPath;
3038 var retIndex = SE.folders._createFolderId(node);
3039 ret[retIndex] = depthMarker + theLabel;
3042 if(node.children != null) {
3044 currentPath += theLabel + "/";
3047 for(var i=0; i<node.children.length; i++) {
3048 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3056 * Wrapper to refresh folders tree
3058 getFolders : function() {
3059 SE.accounts.rebuildFolderList();
3063 * handles events around folder-rename input field changes
3064 * @param object YUI event object
3066 handleEnter : function(e) {
3067 switch(e.browserEvent.type) {
3069 e.preventDefault(); // click in text field
3073 SE.folders.submitFolderRename(e);
3077 var kc = e.browserEvent.keyCode;
3081 SE.folders.submitFolderRename(e);
3085 e.preventDefault(e);
3086 SE.folders.cancelFolderRename(e);
3093 * Called when a node is clicked on in the folder tree
3094 * @param node, The node clicked on
3095 * @param e, The click event
3097 handleClick : function(o) {
3099 //If the click was on a sugar folder
3100 if (node.data.ieId == "folder") {
3101 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3104 SE.listView.populateListFrame(node, node.data.ieId, false);
3106 //eval(node.data.click);
3111 * Called when a node is right-clicked on in the folder tree
3113 handleRightClick : function(e) {
3114 YAHOO.util.Event.preventDefault(e);
3116 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3117 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3119 //If the click was on a sugar folder
3120 SE.clickedFolderNode = node;
3121 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3122 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3123 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3124 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3125 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3126 menu.getItem(3).cfg.setProperty("disabled", false);
3127 menu.getItem(4).cfg.setProperty("disabled", false);
3128 menu.getItem(5).cfg.setProperty("disabled", false);
3129 menu.getItem(6).cfg.setProperty("disabled", true);
3131 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3132 menu.getItem(0).cfg.setProperty("disabled", true);
3133 menu.getItem(1).cfg.setProperty("disabled", true);
3134 menu.getItem(2).cfg.setProperty("disabled", true);
3135 menu.getItem(3).cfg.setProperty("disabled", true);
3136 menu.getItem(4).cfg.setProperty("disabled", true);
3138 if (node.data.protocol != null) {
3139 menu.getItem(6).cfg.setProperty("disabled", false);
3141 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3142 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3143 //Sent or Draft folders
3144 menu.getItem(3).cfg.setProperty("disabled", true);
3145 menu.getItem(4).cfg.setProperty("disabled", true);
3146 menu.getItem(5).cfg.setProperty("disabled", true);
3149 //For group with auto inbound, disable everything.
3150 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3152 menu.getItem(0).cfg.setProperty("disabled", true);
3153 menu.getItem(1).cfg.setProperty("disabled", true);
3154 menu.getItem(2).cfg.setProperty("disabled", true);
3155 menu.getItem(3).cfg.setProperty("disabled", true);
3156 menu.getItem(4).cfg.setProperty("disabled", true);
3157 menu.getItem(5).cfg.setProperty("disabled", true);
3158 menu.getItem(6).cfg.setProperty("disabled", true);
3161 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3166 * Called when a row is dropped on a node
3168 handleDrop : function(rows, targetFolder) {
3169 var rowData = rows[0].getData();
3170 if (rowData.mbox != targetFolder.data.mbox) {
3171 var srcIeId = rowData.ieId;
3172 var srcFolder = rowData.mbox;
3173 var destIeId = targetFolder.data.ieId;
3174 var destFolder = targetFolder.data.mbox;
3176 for(var i=0; i<rows.length; i++) {
3177 uids[i] = rows[i].getData().uid;
3179 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3184 * Called when something is dragged over a Folder Node
3186 dragOver : function(dragObject) {
3191 * Determines if a folder name is unique to the folder tree
3192 * @param string name
3194 isUniqueFolderName : function(name) {
3195 uniqueFolder = true;
3196 var root = SE.tree.getRoot();
3197 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3198 if (this.attributes && this.attributes.ieId == "folder") {
3199 if (this.attributes.text == name) {
3200 uniqueFolder = false;
3205 return uniqueFolder;
3209 * Makes async call to rename folder in focus
3210 * @param object e Event Object
3212 submitFolderRename : function(newName) {
3213 if (trim(newName) == "") {
3214 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3217 newName = escape(newName);
3218 var node = SE.clickedFolderNode;
3219 var origName = node.data.text
3221 if (newName == origName) {
3224 if(SE.folders.isUniqueFolderName(newName)) {
3225 overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3226 if (node.data.ieId == "folder") {
3228 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3231 //IMAP folder or POP mailbox
3232 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3233 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3234 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3238 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3243 moveFolder : function(folderId, parentFolderId) {
3244 if (folderId != parentFolderId)
3246 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3247 + folderId + "&newParentId=" + parentFolderId);
3252 * makes async call to do a full synchronization of all accounts
3254 synchronizeAccounts : function() {
3255 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3256 overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3257 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3262 * Updates user's folder subscriptsion (Sugar only)
3263 * @param object SELECT DOM object in focus
3264 * @param string type of Folder selection
3266 updateSubscriptions : function() {
3267 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3271 select = document.getElementById('userFolders');
3273 for(i=0; i<select.options.length; i++) {
3274 var opt = select.options[i];
3275 if(opt.selected && opt.value != "") {
3279 active += opt.value;
3283 //Add the group folder ids.
3284 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3285 for(i=0; i<group_folders.length; i++)
3287 active += ("::" + group_folders[i]);
3290 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3293 * Updates user's group folder subscriptsion (Sugar only)
3294 * @param ieID The group folder to add to the tree view
3296 retrieveGroupFolderSubscriptions : function() {
3298 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3299 var activeGroupFolders = "";
3300 var activeGroupIds = [];
3301 for(i=0;i<a_rs.length;i++)
3303 var t_record = a_rs[i];
3304 var is_active = t_record.getData('is_active');
3305 var isGroupFolder = t_record.getData('has_groupfolder');
3306 var ieID = t_record.getData('id');
3310 activeGroupIds.push(ieID);
3314 return activeGroupIds;
3319 SE.folders.checkEmail2 = function() {
3320 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3322 //// END FOLDERS OBJECT
3323 ///////////////////////////////////////////////////////////////////////////////
3326 ///////////////////////////////////////////////////////////////////////////////
3329 * Keypress Event capture and processing
3332 overall : function(e) {
3333 switch(e.charCode) {
3335 if(e.ctrlKey || e.altKey) {
3336 var focusRegion = SE.innerLayout.regions.center;
3337 if(focusRegion.activePanel.closable == true) {
3338 focusRegion.remove(focusRegion.activePanel);
3346 ///////////////////////////////////////////////////////////////////////////////
3349 ///////////////////////////////////////////////////////////////////////////////
3352 * ListView object methods and attributes
3358 * Fills the ListView pane with detected messages.
3360 populateListFrame : function(node, ieId, forceRefresh) {
3361 SE.innerLayout.selectTab(0);
3362 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3364 Dom.get('_blank').innerHTML = "";
3365 SE.grid.params['emailUIAction'] = 'getMessageList';
3366 SE.grid.params['mbox'] = node.data.mbox;
3367 SE.grid.params['ieId'] = ieId;
3368 forcePreview = true; // loads the preview pane with first item in grid
3369 SE.listView.refreshGrid();
3373 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3375 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3376 SE.innerLayout.selectTab(0);
3377 Dom.get('_blank').innerHTML = "";
3378 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3379 SE.grid.params['ieId'] = node.data.id;
3380 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3381 SE.listView.refreshGrid();
3385 * Sets sort order as user preference
3388 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3390 ieName = ieNamePassed;
3391 focusFolder = focusFolderPassed;
3393 SE.util.clearHiddenFieldValues('emailUIForm');
3394 var previousSort = document.getElementById('sortBy').value;
3396 document.getElementById('sortBy').value = sortBy;
3397 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3398 document.getElementById('focusFolder').value = focusFolder;
3399 document.getElementById('ieId').value = ieId;
3401 if(sortBy == previousSort) {
3402 document.getElementById('reverse').value = '1';
3405 var formObject = document.getElementById('emailUIForm');
3406 YAHOO.util.Connect.setForm(formObject);
3408 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3413 * Enables click/arrow select of grid items which then populate the preview pane.
3415 selectFirstRow : function() {
3416 SE.grid.selModel.selectFirstRow();
3419 selectLastRow : function() {
3420 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3423 setEmailListStyles : function() {
3424 SE.listView.boldUnreadRows();
3426 var ds = SE.grid.getStore();
3427 if (SE.grid.getSelections().length == 0) {
3428 document.getElementById('_blank').innerHTML = '';
3432 if(typeof(ds.baseParams.mbox) != 'undefined') {
3433 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3434 var cm = SE.grid.getColumnModel();
3435 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3436 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3438 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3439 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3443 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3444 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3447 // 4/20/2007 added to hide overlay after search
3449 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3450 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3451 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3452 if (node) node.data.unseen = unread;
3454 SE.accounts.renderTree();
3457 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3458 if(forcePreview && ds.totalCount > 0) {
3459 SE.detailView.getEmailPreview();
3460 forcePreview = false;
3465 * Removes a row if found via its UID
3467 removeRowByUid : function(uid) {
3468 uid = new String(uid);
3469 uids = uid.split(',');
3470 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3472 for(j=0; j<uids.length; j++) {
3473 var theUid = uids[j];
3474 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3475 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3476 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3482 displaySelectedEmails : function(rows) {
3483 var dm = SE.grid.getDataModel();
3486 for(i=0; i<rows.length; i++) {
3487 var rowIndex = rows[i].rowIndex;
3488 var metadata = dm.data[rowIndex];
3493 uids += metadata[5];
3495 // unbold unseen email
3496 this.unboldRow(rowIndex);
3499 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3503 * exception handler for data load failures
3505 loadException : function(dataModel, ex, response) {
3510 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3511 * @param string sourceIeId Email's source I-E id
3512 * @param string sourceFolder Email's current folder
3513 * @param destinationIeId Destination I-E id
3514 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3516 * @param array emailUids Array of email's UIDs
3518 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3519 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3520 overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3522 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3523 // remove rows from visibility
3524 for(row in selectedRows) {
3525 //SE.grid.getStore().remove(row);
3528 var baseUrl = '&sourceIeId=' + sourceIeId +
3529 '&sourceFolder=' + sourceFolder +
3530 '&destinationIeId=' + destinationIeId +
3531 '&destinationFolder=' + destinationFolder;
3534 for(i=0; i<emailUids.length; i++) {
3536 uids += app_strings.LBL_EMAIL_DELIMITER;
3538 uids += emailUids[i];
3540 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3541 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3543 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3549 * Unbolds text in the grid view to denote read status
3551 markRead : function(index, record) {
3552 // unbold unseen email
3553 var row = SE.grid.getRecord(record);
3554 row.getData().seen = 1;
3555 SE.grid.getTrEl(record).style.fontWeight = "normal";
3559 * grid row output, bolding unread emails
3561 boldUnreadRows : function() {
3562 // bold unread emails
3563 var trEl = SE.grid.getFirstTrEl();
3564 while(trEl != null) {
3565 if(SE.grid.getRecord(trEl).getData().seen == "0")
3566 trEl.style.fontWeight = "bold";
3568 trEl.style.fontWeight = "";
3569 trEl = SE.grid.getNextTrEl(trEl);
3574 * Show preview for an email if 1 and only 1 is selected
3575 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3577 handleRowSelect : function(e) {
3578 if(e.selectedRows.length == 1) {
3579 SE.detailView.getEmailPreview();
3583 handleDrop : function(e, dd, targetId, e2) {
3585 case 'htmleditordiv':
3586 var rows = SE.grid.getSelectedRows();
3587 if(rows.length > 0) {
3588 SE.listView.displaySelectedEmails(rows);
3593 var targetElId = new String(targetId);
3594 var targetIndex = targetElId.replace('ygtvlabelel',"");
3595 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3596 var dm = SE.grid.getDataModel();
3597 var emailUids = new Array();
3598 var destinationIeId = targetNode.data.ieId;
3599 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3602 var rows = SE.grid.getSelectedRows();
3603 // iterate through dragged rows
3604 for(i=0; i<rows.length; i++) {
3605 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3606 var rowIndex = rows[i].rowIndex;
3607 var dataModelRow = dm.data[rowIndex];
3608 var sourceIeId = dataModelRow[7];
3609 var sourceFolder = dataModelRow[6];
3610 emailUids[i] = dataModelRow[5];
3613 // event wrapped call - need FQ
3614 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3615 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3621 * Hack-around to get double-click and single clicks to work on the grid
3622 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3624 handleClick : function(o) {
3625 SUGAR.email2.grid.clearTextSelection();
3627 var el = SUGAR.email2.grid.getSelectedRows();
3629 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3630 if ( el.length == 1)
3633 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3634 SUGAR.email2.listView.currentRowIndex = rowId;
3635 clearTimeout(SUGAR.email2.detailView.previewTimer);
3636 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3641 * Custom handler for double-click/enter
3642 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3644 getEmail : function(e) {
3645 var rows = SE.grid.getSelectedRows();
3646 var row = SE.grid.getRecord(rows[0]).getData();
3648 clearTimeout(SE.detailView.previewTimer);
3649 document.getElementById("_blank").innerHTML = "";
3651 if(row.type != "draft") {
3652 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3654 // circumventing yui-ext tab generation, let callback handler build new view
3655 SE.util.clearHiddenFieldValues('emailUIForm');
3656 //function(uid, mbox, ieId, setRead, destination) {
3657 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3658 document.getElementById('uid').value = row.uid; // uid;
3659 document.getElementById('mbox').value = row.mbox; // mbox;
3660 document.getElementById('ieId').value = row.ieId; // ieId;
3662 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3663 AjaxObject.target = '_blank';
3664 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3669 * Retrieves a row if found via its UID
3673 getRowIndexByUid : function(uid) {
3674 uid = new String(uid);
3675 uids = uid.split(',');
3677 for(j=0; j<uids.length; j++) {
3678 var theUid = uids[j];
3680 for(i=0; i<SE.grid.getStore().data.length; i++) {
3681 if(SE.grid.getStore().data[i].id == theUid) {
3689 * Returns the UID's of the seleted rows
3692 getUidsFromSelection : function() {
3693 var rows = SE.grid.getSelectedRows();
3695 /* iterate through available rows JIC a row is deleted - use first available */
3696 for(var i=0; i<rows.length; i++) {
3697 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3702 refreshGrid : function() {
3703 SE.grid.getDataSource().sendRequest(
3704 SUGAR.util.paramsToUrl(SE.grid.params),
3705 SE.grid.onDataReturnInitializeTable,
3711 //// END SE.listView
3712 ///////////////////////////////////////////////////////////////////////////////
3714 ///////////////////////////////////////////////////////////////////////////////
3718 * sends search criteria
3719 * @param reference element search field
3721 search : function(el) {
3722 var searchCriteria = new String(el.value);
3724 if(searchCriteria == '') {
3725 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3729 var safeCriteria = escape(searchCriteria);
3731 var accountListSearch = document.getElementById('accountListSearch');
3732 //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3734 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3735 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3736 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3737 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3738 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3743 * sends advanced search criteria
3745 searchAdvanced : function() {
3746 var formObject = document.getElementById('advancedSearchForm');
3749 //Set assigned user id to blank if name is not present.
3750 if (formObject.elements['assigned_user_name'].value == "")
3751 formObject.elements['assigned_user_id'].value = "";
3753 for(i=0; i<formObject.elements.length; i++) {
3754 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3757 if(formObject.elements[i].type == 'text') {
3758 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3760 if(formObject.elements[i].type == 'hidden') {
3761 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3763 if(formObject.elements[i].type == 'select-one') {
3764 var el = formObject.elements[i];
3765 var v = el.options[el.selectedIndex].value;
3768 SE.grid.params[el.name] = v;
3771 //Clear previous search results if necessary
3772 if(typeof( SE.grid.params[el.name]) != 'undefined')
3773 delete SE.grid.params[el.name]
3780 if(! this.validateSearchFormInput() )
3783 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3784 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3785 var accountListSearch = document.getElementById('accountListSearch');
3786 SE.listView.refreshGrid();
3788 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3793 * Validates the search form inputs to ensure all parameters are valid
3796 validateSearchFormInput: function()
3798 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3799 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3800 var dateCheck = check_form('advancedSearchForm');
3802 //If the parent type is selected ensure the user selected a parent_id.
3803 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3809 * Toggles the advanced options, either hidding or showing the selection.
3811 toggleAdvancedOptions: function()
3813 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3815 for(var i=0;i<el.length;i++)
3817 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3818 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3820 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3824 * clears adv search form fields
3826 searchClearAdvanced : function() {
3827 var form = document.getElementById('advancedSearchForm');
3829 for(i=0; i<form.elements.length; i++) {
3830 if(form.elements[i].type != 'button') {
3831 form.elements[i].value = '';
3837 //////////////////////////////////////////////////////////////////////////////
3840 //////////////////////////////////////////////////////////////////////////////
3843 /******************************************************************************
3844 * USER SIGNATURES calls stolen from Users module
3845 *****************************************************************************/
3846 createSignature : function(record, the_user_id) {
3847 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3849 URL += "&record="+record;
3851 if(the_user_id != "") {
3852 URL += "&the_user_id="+the_user_id;
3854 var windowName = 'email_signature';
3855 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3857 var win = window.open(URL, windowName, windowFeatures);
3858 if(win && win.focus) {
3859 // put the focus on the popup if the browser supports the focus() method
3864 deleteSignature : function() {
3865 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3866 overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3867 var singature_id = document.getElementById('signature_id').value;
3868 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3872 saveOptionsGeneral : function(displayMessage) {
3873 var formObject = document.getElementById('formEmailSettingsGeneral');
3874 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3875 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3878 YAHOO.util.Connect.setForm(formObject);
3879 SE.composeLayout.emailTemplates = null;
3881 AjaxObject.target = 'frameFlex';
3882 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3885 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3887 SE.settings.settingsDialog.hide();
3891 * Shows settings container screen
3893 showSettings : function() {
3894 if(!SE.settings.settingsDialog) {
3895 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3901 constraintoviewport: true
3903 dlg.showEvent.subscribe( function (){
3904 var el = this.element;
3905 var viewH = YAHOO.util.Dom.getViewportHeight();
3906 if (this.header && el && viewH - 50 < el.clientHeight) {
3907 var body = this.header.nextElementSibling;
3908 body.style.overflow = "auto";
3909 body.style.height = (viewH - 50) + "px";
3912 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3913 dlg.setBody('<div id="settingsTabDiv"/>');
3914 dlg.beforeRenderEvent.subscribe(function() {
3915 var dd = new YAHOO.util.DDProxy(dlg.element);
3916 dd.setHandleElId(dlg.header);
3917 dd.on('endDragEvent', function() {
3923 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3924 var tabContent = Dom.get("tab_general");
3925 tp.addTab(new YAHOO.widget.Tab({
3926 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3928 content : tabContent.innerHTML,
3929 id : "generalSettings",
3932 tabContent.parentNode.removeChild(tabContent);
3933 tabContent = Dom.get("tab_accounts");
3934 var accountTab = new YAHOO.widget.Tab({
3935 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3937 content : tabContent.innerHTML,
3938 id : "accountSettings"
3940 tp.addTab(accountTab);
3941 tabContent.parentNode.removeChild(tabContent);
3943 tp.appendTo(dlg.body);
3946 SE.settings.settingsDialog.show();
3947 SE.folders.lazyLoadSettings();
3948 SE.accounts.lazyLoad();
3952 lazyLoadRules : function() {
3953 if(false/*!SE.settings.rules*/) {
3954 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3959 //// END SE.settings
3960 ///////////////////////////////////////////////////////////////////////////////
3963 /******************************************************************************
3965 *****************************************************************************/
3966 function removeHiddenNodes(nodes, grid) {
3968 for(var i = nodes.length - 1; i > -1; i--) {
3969 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3970 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3976 function strpad(val) {
3977 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3980 function refreshTodos() {
3981 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3982 AjaxObject.target = 'todo';
3983 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3986 /******************************************************************************
3987 * MUST STAY IN GLOBAL NAMESPACE
3988 *****************************************************************************/
3989 function refresh_signature_list(signature_id, signature_name) {
3990 var field=document.getElementById('signature_id');
3992 for (var i=0; i < field.options.length; i++) {
3993 if (field.options[i].value == signature_id) {
3994 if (field.options[i].selected==false) {
3995 field.options[i].selected=true;
4000 //add item to selection list.
4002 var newElement=document.createElement('option');
4003 newElement.text=signature_name;
4004 newElement.value=signature_id;
4005 field.options.add(newElement);
4006 newElement.selected=true;
4009 //enable the edit button.
4010 var field1=document.getElementById('edit_sig');
4011 field1.style.visibility="inherit";
4012 var deleteButt = document.getElementById('delete_sig');
4013 deleteButt.style.visibility="inherit";
4016 function setDefaultSigId(id) {
4017 var checkbox = document.getElementById("signature_default");
4018 var default_sig = document.getElementById("signatureDefault");
4020 if(checkbox.checked) {
4021 default_sig.value = id;
4023 default_sig.value = "";
4027 function setSigEditButtonVisibility() {
4028 var field = document.getElementById('signature_id');
4029 var editButt = document.getElementById('edit_sig');
4030 var deleteButt = document.getElementById('delete_sig');
4031 if(field.value != '') {
4032 editButt.style.visibility = "inherit";
4033 deleteButt.style.visibility = "inherit";
4035 editButt.style.visibility = "hidden";
4036 deleteButt.style.visibility = "hidden";
4038 }// End of File modules/Emails/javascript/EmailUI.js
4040 /*********************************************************************************
4041 * SugarCRM Community Edition is a customer relationship management program developed by
4042 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4044 * This program is free software; you can redistribute it and/or modify it under
4045 * the terms of the GNU Affero General Public License version 3 as published by the
4046 * Free Software Foundation with the addition of the following permission added
4047 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4048 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4049 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4051 * This program is distributed in the hope that it will be useful, but WITHOUT
4052 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4053 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4056 * You should have received a copy of the GNU Affero General Public License along with
4057 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4058 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4061 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4062 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4064 * The interactive user interfaces in modified source and object code versions
4065 * of this program must display Appropriate Legal Notices, as required under
4066 * Section 5 of the GNU Affero General Public License version 3.
4068 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4069 * these Appropriate Legal Notices must retain the display of the "Powered by
4070 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4071 * technical reasons, the Appropriate Legal Notices must display the words
4072 * "Powered by SugarCRM".
4073 ********************************************************************************/
4076 var sw = YAHOO.SUGAR,
4077 Event = YAHOO.util.Event,
4078 Connect = YAHOO.util.Connect,
4079 Dom = YAHOO.util.Dom
4082 ///////////////////////////////////////////////////////////////////////////////
4085 _contactCache : new Array(), // cache of contacts
4086 _dd : new Array(), // filtered list, same format as _contactCache
4087 _ddLists : new Array(), // list of Lists
4088 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4089 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4090 clickBubble : true, // hack to get around onclick event bubbling
4092 relatedBeanType : '',
4095 itemSpacing : 'white-space:nowrap; padding:2px;',
4101 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4103 initFixForDatatableSort: function () {
4104 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4105 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4106 var oColumn = this._oColumnSet.getColumn(column);
4109 // Validate TD element
4110 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4112 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4114 // Validate TH element
4116 elCell = this.getThEl(column);
4119 var allColumns = this._oColumnSet.flat;
4120 for(var i=0, len=allColumns.length; i<len; i++) {
4121 if(allColumns[i].getThEl().id === elCell.id) {
4122 oColumn = allColumns[i];
4133 cancelEdit : function() {
4134 if(this.editContactDialog)
4135 this.editContactDialog.hide();
4136 if(this.editMailingListDialog)
4137 this.editMailingListDialog.hide();
4141 * Clears filter form
4143 clear : function() {
4144 var t = document.getElementById('contactsFilter');
4150 * handle context-menu Compose-to call
4151 * @param string type 'contacts' or 'lists'
4153 composeTo : function(type, waited) {
4154 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4155 if (activePanel.substring(0, 10) != "composeTab") {
4156 SE.composeLayout.c0_composeNewEmail();
4157 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4158 SE.contextMenus.contactsContextMenu.hide();
4161 var idx = activePanel.substring(10);
4164 // determine if we have a selection to work with
4165 if(type == 'contacts') {
4166 var ids = SE.contactView.getSelectedRows();
4167 for (var i in ids) {
4168 rows[i] = SE.contactView.getRecord(ids[i]);
4170 removeHiddenNodes(rows, SE.contactView);
4174 if(rows.length > 0) {
4175 SE.composeLayout.handleDrop(
4176 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4177 null, rows, 'addressTO' + idx );
4179 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4183 editContact : function() {
4184 SE.contextMenus.contactsContextMenu.hide();
4185 var element = SE.contactView.getSelectedNodes()[0];
4187 if (element.className.indexOf('address-contact') > -1) {
4188 elementId = element.id;
4189 } else if (element.className.indexOf('address-exp-contact') > -1) {
4190 elementId = element.id.substring(2);
4196 * Filters contact entries based on user input
4198 filter : function(inputEl) {
4199 var ret = new Object();
4200 var re = new RegExp(inputEl.value, "gi");
4202 for(var i in this._contactCache) {
4203 if(this._contactCache[i].name.match(re)) {
4204 ret[i] = this._contactCache[i];
4208 this.buildContactList(ret);
4211 fullForm : function(id, module) {
4212 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4216 * returns a formatted email address from the addressBook cache
4218 getFormattedAddress : function(id) {
4219 var o = this._contactCache[id];
4220 var primaryEmail = '';
4222 for(var i=0; i<o.email.length; i++) {
4223 var currentEmail = o.email[i].email_address;
4225 if(o.email[i].primary_address == 1) {
4226 primaryEmail = o.email[i].email_address;
4230 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4231 var name = new String(o.name);
4232 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4233 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4239 * Sets up async call to query for matching contacts, users, etc.
4241 searchContacts : function() {
4242 var fn = document.getElementById('input_searchField').value;
4243 var pe = document.getElementById('input_searchPerson').value;
4245 var rb = document.getElementById('hasRelatedBean').checked;
4248 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4249 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4250 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4251 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4253 this.addressBookDataModel.params['related_bean_id'] = '';
4256 this.addressBookDataModel.params['search_field'] = fn;
4257 this.addressBookDataModel.params['person'] = pe;
4258 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4259 this.grid._oDataSource = this.addressBookDataModel;
4260 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4264 * Clear Search Crieteria For Addressbook
4266 clearAddressBookSearch : function() {
4267 document.getElementById('input_searchField').value = "";
4268 document.getElementById('input_searchPerson').selectedIndex = 0;
4272 * Opens modal select window to add contacts to addressbook
4274 selectContactsDialogue : function(destId) {
4275 if(!this.contactsDialogue) {
4276 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4280 constraintoviewport: true,
4282 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4283 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4285 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4287 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4288 dlg.setBody(body.innerHTML);
4289 dlg.renderEvent.subscribe(function() {
4290 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4291 if (iev && !SUGAR.isIE) {
4292 this.body.style.width = "950px";
4297 dlg.beforeRenderEvent.subscribe(function() {
4298 var dd = new YAHOO.util.DDProxy(dlg.element);
4299 dd.setHandleElId(dlg.header);
4300 dd.on('endDragEvent', function() {
4306 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4308 var tabContent = SUGAR.util.getAndRemove("searchForm");
4309 tp.addTab(new YAHOO.widget.Tab({
4310 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4312 content : tabContent.innerHTML,
4313 id : "addressSearchTab",
4317 var addListenerFields = ['input_searchPerson','input_searchField' ]
4318 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4319 if (e.keyCode == 13) {
4320 YAHOO.util.Event.stopEvent(e);
4321 SUGAR.email2.addressBook.searchContacts();
4325 this.contactsDialogue.render();
4328 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4329 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4333 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4334 var idx = activePanel.substring(10);
4336 SE.addressBook.idx = idx;
4339 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4340 document.getElementById('relatedBeanColumn').style.display = '';
4341 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4342 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4343 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4344 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4345 SE.addressBook.relatedBeanType = relatedBeanType;
4347 document.getElementById('relatedBeanColumn').style.display = 'none';
4348 document.getElementById('hasRelatedBean').checked = false;
4351 if (!SE.addressBook.grid)
4353 if (hasRelatedBeanId) {
4354 document.getElementById('hasRelatedBean').checked = true;
4356 AddressSearchGridInit();
4357 SE.addressBook.relatedBeanId = relatedBeanId;
4361 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4363 SE.addressBook.relatedBeanId = relatedBeanId;
4364 document.getElementById('hasRelatedBean').checked = true;
4366 if (document.getElementById('hasRelatedBean').checked == true)
4368 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4369 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4371 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4372 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4374 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4375 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4376 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4379 //Remove any lingering rows in the result set table if the module was closed.
4380 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4382 SE.addressBook.populateResulstTableEmailAddresses();
4384 this.contactsDialogue.show();
4387 * Clear all email addresses from result table.
4390 clearAllEmailAddressFieldsFromResultTable: function () {
4391 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4392 //Unhighlight any rows currently selected if the emails were cleared.
4393 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4394 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4397 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4398 * results table. This function is called when the address book is displayed.
4400 populateResulstTableEmailAddresses: function () {
4402 var idx = SE.addressBook.idx;
4403 var emailFields = ['to','cc','bcc'];
4405 for(var k=0;k<emailFields.length;k++)
4407 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4408 var allEmails = document.getElementById(elKey).value;
4412 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4414 for (var i=0; i<formatedEmails.length; i++)
4416 var t_name = formatedEmails[i].name;
4417 var t_emailAddr = formatedEmails[i].email_address;
4418 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4420 t_name = displayEmail = t_emailAddr;
4422 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4423 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4424 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4430 * Checks all entries in the result table against a particular email address, returning true
4431 * if the email address is found, false otherwise.
4433 doesEmailAdddressExistInResultTable: function(emailAddress)
4435 if(trim(emailAddress) == '')
4438 var emailAddressFound = false;
4439 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4440 for (var i=0; i < contacts.length; i++)
4442 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4443 //If we are adding to cc or bcc fields, make them visible.
4444 if(data.email_address == emailAddress)
4446 emailAddressFound = true;
4451 return emailAddressFound;
4454 * Takes all email addresses that the users wishes to add from the address book and populates the To
4455 * fields on the compose tab.
4457 populateEmailAddressFieldsFromResultTable: function()
4459 //Clear the fields first, all email addresses are stored in the address book
4460 var idx = SE.addressBook.idx;
4461 var emailFields = ['to','cc','bcc'];
4462 for(var k=0;k<emailFields.length;k++)
4464 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4465 document.getElementById(elKey).value = "";
4468 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4469 for (var i=0; i < contacts.length; i++)
4471 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4473 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4474 //If we are adding to cc or bcc fields, make them visible.
4475 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4476 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4477 //Construct the target id
4478 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4480 var target = document.getElementById(target_id);
4481 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4484 //Delete all rows from the result set table
4485 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4488 SE.addressBook.contactsDialogue.hide()
4491 * Insert contacts into the result table.
4493 insertContactToResultTable : function(event,address_type) {
4495 var contactsDialogue = SE.addressBook.contactsDialogue;
4496 var contacts = SE.addressBook.grid.getSelectedRows();
4498 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4499 for (var i = 0; i < rows.length; i++)
4501 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4503 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4504 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4505 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4506 rows[i].setData("selected",true);
4509 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4510 for (var i = 0; i < checkBoxes.length; i++) {
4511 checkBoxes[i].checked = false;
4517 insertContactRowToResultTable : function(rowId, addressType) {
4518 var data = SE.addressBook.grid.getRecord(rowId).getData();
4519 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4521 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4522 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4523 if(addressType == null)
4524 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4525 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});
4528 * Remove a row from the gridsResult table.
4530 removeRowFromGridResults : function(rowId,emailAddress)
4532 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4533 for (var i=0; i < contacts.length; i++)
4535 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4536 var data = rec.getData();
4537 if(data.email_address == emailAddress)
4539 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4544 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4547 * Translates between the addressType To|Cc|Bcc labels/keys.
4549 translateAddresType: function(addressType,fromKey)
4551 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4552 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4553 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4554 var mappingObject = {};
4557 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4560 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4561 mappingObject[displayCc] = 'cc';
4562 mappingObject[displayBcc] = 'bcc';
4565 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4571 toggleSearchRowIcon : function(rowId,show)
4575 var idToShow = rowId + '_add_img';
4576 var idToHide = rowId + '_rm_img';
4580 var idToShow = rowId + '_rm_img';
4581 var idToHide = rowId + '_add_img';
4585 Dom.addClass(idToHide, "yui-hidden");
4586 Dom.removeClass(idToShow, "yui-hidden");
4589 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4591 doesGridResultsEntryExist: function(emailAddrs)
4594 var contactExists = false;
4595 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4596 for (var i=0; i < contacts.length; i++)
4598 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4599 if(data.email_address == emailAddrs)
4601 contactExists = true;
4605 return contactExists;
4609 * adds an email address to a string, but first checks if it exists
4610 * @param string concat The string we are appending email addresses to
4611 * @param string addr Email address to add
4614 smartAddEmailAddressToComposeField : function(concat, addr) {
4615 var re = new RegExp(addr);
4617 if(!concat.match(re)) {
4619 concat += "; " + addr;
4628 //// END ADDRESS BOOK
4629 ///////////////////////////////////////////////////////////////////////////////
4633 ///////////////////////////////////////////////////////////////////////////////
4636 * Auto-complete object
4640 delimChar : [";", ","],
4644 prehighlightClassName : "yui-ac-prehighlight",
4647 instances : new Array(),
4650 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4651 * @param object Contact from AddressBook
4654 getPrimaryAddress : function(contact) {
4655 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4657 for(var eIndex in contact.email) {
4658 address = contact.email[eIndex].email_address;
4659 if(contact.email[eIndex].primary_address == 1) {
4660 return contact.email[eIndex].email_address;
4668 * initializes autocomplete widgets for a given compose view
4671 init : function(idx) {
4672 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4673 "queryMatchContains" : false,
4674 "queryMatchSubset" : true
4677 this.instances[idx] = {
4684 // instantiate the autoComplete widgets
4685 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4686 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4687 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4689 // enable hiding of interfering textareas
4690 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4691 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4692 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4694 // enable reshowing of hidden textareas
4695 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4696 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4697 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4699 // enable refreshes of contact lists
4700 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4701 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4702 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4705 refreshDataSource : function(sType, aArgs) {
4706 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4708 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4710 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4711 idx = textBoxId.substr(9);
4713 idx = textBoxId.substr(10);
4716 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4717 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4718 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4722 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4724 returnDataSource : function(contacts) {
4725 var ret = new Array();
4726 for(var id in contacts) {
4727 if (contacts[id].name) {
4728 var primary = this.getPrimaryAddress(contacts[id]);
4730 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4731 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4733 for(var emailIndex in contacts[id].email) {
4734 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4743 * Hides address textareas to prevent autocomplete dropdown from being obscured
4745 toggleTextareaHide : function(sType, aArgs) {
4746 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4750 if(textBoxId.indexOf("addressTO") > -1) {
4752 } else if(textBoxId.indexOf("addressCC") > -1) {
4755 idx = textBoxId.substr(9);
4757 // follow through if not BCC
4759 var cc = document.getElementById("addressCC" + idx);
4760 var bcc = document.getElementById("addressBCC" + idx);
4764 cc.style.visibility = 'hidden';
4766 bcc.style.visibility = 'hidden';
4773 * Redisplays the textareas after an address is commited
4775 toggleTextareaShow : function(sType, aArgs) {
4776 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4780 if(textBoxId.indexOf("addressTO") > -1) {
4782 } else if(textBoxId.indexOf("addressCC") > -1) {
4785 idx = textBoxId.substr(9);
4787 // follow through if not BCC
4789 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4790 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4795 //// END AUTOCOMPLETE
4796 ///////////////////////////////////////////////////////////////////////////////
4798 ///////////////////////////////////////////////////////////////////////////////
4801 * expands the options sidebar
4803 SE.composeLayout = {
4804 currentInstanceId : 0,
4807 outboundAccountErrors : null,
4808 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4810 showAddressDetails : function(e) {
4811 var linkElement = document.getElementById("More"+e.id);
4812 var spanElement = document.getElementById("Detail"+e.id);
4813 var emailAddressList = e.value;
4814 if(e.value.length > 96)
4816 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4817 var displayArray = [];
4818 for (var i=0; i<resultArray.length; i++)
4820 var t_name = resultArray[i].name;
4821 var t_emailAddr = resultArray[i].email_address;
4823 displayArray.push('<br/><' + t_emailAddr + '>');
4825 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4828 var result = displayArray.join('<br/>');
4830 linkElement.style.display = "inline";
4831 linkElement.style.height="10px";
4832 linkElement.style.overflow="visible";
4833 spanElement.innerHTML = result;
4836 linkElement.style.display = "none";
4841 * Given a string of email address, return an array containing the name portion (if available)
4842 * and email portion.
4844 _getEmailArrayFromString : function (emailAddressList){
4847 while ((results = reg.exec(emailAddressList)) != null)
4849 orignial = results[0];
4850 parsedResult = results[0].replace(';', ':::::');
4851 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4855 while ((results = reg.exec(emailAddressList)) != null)
4857 orignial = results[0];
4858 parsedResult = results[0].replace(',', ':::::');
4859 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4861 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4862 var emailArr = emailAddressList.split(":::::");
4863 var resultsArray = [];
4865 for (var i=0; i<emailArr.length; i++)
4867 var rposition = emailArr[i].indexOf('<');
4868 var lposition = emailArr[i].indexOf('>');
4870 if(trim(emailArr[i]) != '')
4872 if(rposition != -1 && lposition != -1)
4874 var t_name = emailArr[i].substr(0, rposition-1);
4875 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4876 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4880 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4884 return resultsArray;
4886 ///////////////////////////////////////////////////////////////////////////
4889 * Prepare bucket DIV and yui-ext tab panels
4891 _0_yui : function() {
4892 var idx = this.currentInstanceId;
4894 var composeTab = new YAHOO.SUGAR.ClosableTab({
4895 label: mod_strings.LNK_NEW_SEND_EMAIL,
4897 content : "<div id='htmleditordiv" + idx + "'/>",
4898 id : "composeTab" + idx,
4899 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4902 SE.innerLayout.addTab(composeTab);
4904 // get template engine with template
4905 if (!SE.composeLayout.composeTemplate) {
4906 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4909 // create Tab inner layout
4910 var composePanel = this.getComposeLayout();
4911 composePanel.getUnitByPosition("right").collapse();
4912 composePanel.autoSize();
4916 * Generate the quick compose layout
4917 * @method getQuickComposeLayout
4918 * @param {Pannel} parentPanel Parent pannel
4919 * @param {Object} o Options
4922 getQuickComposeLayout : function (parentPanel,o) {
4923 var idx = SE.composeLayout.currentInstanceId;
4925 //Before rendering the parent pannel we need to initalize the grid layout
4926 parentPanel.beforeRenderEvent.subscribe(function() {
4928 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4929 SE.composeLayout._createComposeLayout(idx);
4930 SE.composeLayout[idx].set('height', 350);
4931 SE.composeLayout[idx].render();
4935 //Wait until the Compose Layout has rendered, then add the
4936 //options tab and perform the tiny initialization.
4937 parentPanel.renderEvent.subscribe(function() {
4939 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4940 SE.composeLayout._initComposeOptionTabs(idx);
4941 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4942 //Initialize tinyMCE
4943 if (!SUGAR.util.isTouchScreen())
4944 SE.composeLayout._1_tiny();
4945 //Init templates and address book
4946 SE.composeLayout._2_final();
4948 SE.composeLayout.quickCreateComposePackage(o);
4953 //Check if we have the div override for the shortcut bar
4954 if(typeof o.menu_id != 'undefined') {
4955 parentPanel.render(o.menu_id);
4957 parentPanel.render(document.body);
4960 return SE.composeLayout[idx];
4963 * Fill in all fields into the quick compose layout.
4964 * @method quickCreateComposePackage
4965 * @param {Object} o Options
4968 quickCreateComposePackage: function(o)
4970 //If we have a compose package fill in defaults.
4971 if (typeof(o.composePackage) != 'undefined')
4973 composePackage = o.composePackage; //Set the compose data object
4974 //Hijack this method called by composePackage as it's not need for quick creates.
4975 SE.composeLayout.c0_composeNewEmail = function(){};
4976 SE.composeLayout.composePackage(); //Fill in defaults.
4979 getComposeLayout : function() {
4980 var idx = SE.composeLayout.currentInstanceId;
4982 this._createComposeLayout(idx);
4983 SE.composeLayout[idx].render();
4984 this._initComposeOptionTabs(idx);
4986 return SE.composeLayout[idx];
4990 * Create the layout manager for the compose window.
4992 _createComposeLayout : function(idx)
4994 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
4995 parent: SE.complexLayout,
5005 SE.composeLayout.composeTemplate.exec({
5006 'app_strings':app_strings,
5007 'mod_strings':mod_strings,
5009 'linkbeans_options' : linkBeans,
5010 'idx' : SE.composeLayout.currentInstanceId
5021 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5024 header: app_strings.LBL_EMAIL_OPTIONS
5030 * Create compose tab which will populate the 'right' container in the compose window.
5032 _initComposeOptionTabs : function(idx)
5034 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5035 var tab = new YAHOO.widget.Tab({
5036 label: app_strings.LBL_EMAIL_ATTACHMENT,
5038 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5039 id : "divAttachments" + idx,
5043 tab.layout = SE.composeLayout[idx];
5045 tab.on("activeChange", function(o){
5047 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5053 tab = new YAHOO.widget.Tab({
5054 label: app_strings.LBL_EMAIL_OPTIONS,
5056 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5057 id : "divOptions" + idx,
5061 tab.layout = SE.composeLayout[idx];
5062 tab.on("activeChange", function(o){
5064 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5069 SE.composeLayout[idx].autoSize = function() {
5070 var pEl = this.get("element").parentNode.parentNode.parentNode;
5071 this.set("height", pEl.clientHeight-30);
5075 SE.composeLayout[idx].rightTabs = cTabs;
5077 isParentTypeValid : function(idx) {
5078 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5079 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5080 if (trim(parentTypeValue) == ""){
5081 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5087 isParentTypeAndNameValid : function(idx) {
5088 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5089 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5090 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5091 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5092 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5093 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5099 callopenpopupForEmail2 : function(idx,options) {
5101 var formName = 'emailCompose' + idx;
5103 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5104 formName = options.form_name;
5106 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5107 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5108 if (!SE.composeLayout.isParentTypeValid(idx)) {
5111 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5113 call_back_function:"SE.composeLayout.popupAddEmail",
5115 field_to_name_array:{
5116 id:'data_parent_id' + idx,
5117 name:'data_parent_name' + idx,
5122 popupAddEmail : function(o)
5124 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5125 var data = o.name_to_value_array;
5126 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5127 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5129 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5130 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5137 _1_tiny : function() {
5138 var idx = SE.composeLayout.currentInstanceId;
5139 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5140 SE.tinyInstances[elId] = { };
5141 SE.tinyInstances[elId].ready = false;
5142 var t = tinyMCE.getInstanceById(elId);
5144 if(typeof(t) == 'undefined') {
5145 tinyMCE.execCommand('mceAddControl', false, elId);
5146 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5147 SE.composeLayout.resizeEditor(idx);
5148 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
5153 resizeEditor : function(idx)
5155 var cof = Dom.get('composeOverFrame' + idx);
5156 var head = Dom.get('composeHeaderTable' + idx);
5157 var targetHeight = cof.clientHeight - head.clientHeight;
5158 var instance = tinyMCE.get(SE.tinyInstances.currentHtmleditor);
5160 var parentEl = Dom.get(instance.editorId + '_parent');
5161 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5162 var contentEl = instance.contentAreaContainer;
5163 var iFrame = contentEl.firstChild;
5164 var tinMceToolbarOffset = 18;
5165 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5169 * Initializes d&d, auto-complete, email templates
5171 _2_final : function() {
5172 var idx = SE.composeLayout.currentInstanceId;
5174 if(this.emailTemplates) {
5175 this.setComposeOptions(idx);
5177 //populate email template cache
5178 AjaxObject.target = '';
5179 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5182 // handle drop targets for addressBook
5183 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5184 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5185 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5186 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5188 // auto-complete setup
5189 SE.autoComplete.init(idx);
5192 document.getElementById("addressTO" + idx).focus();
5196 * hide tinyMCE tool bar if send email as plaintext is checked
5198 renderTinyMCEToolBar : function (idx, hide) {
5200 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5202 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5206 c1_composeEmail : function(isReplyForward, retry) {
5210 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5211 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5216 if(isReplyForward) {
5217 this.replyForwardEmailStage2();
5223 * takes draft info and prepopulates
5225 c0_composeDraft : function() {
5226 this.getNewInstanceId();
5228 document.getElementById('_blank').innerHTML = '';
5229 var idx = SE.composeLayout.currentInstanceId;
5230 SE.composeLayout.draftObject = new Object();
5231 SE.composeLayout.draftObject.id = idx;
5232 SE.composeLayout.draftObject.isDraft = true;
5233 SE.composeLayout.currentInstanceId = idx;
5234 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5235 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5236 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5238 SE.composeLayout._0_yui();
5239 SE.composeLayout._1_tiny();
5242 SE.composeLayout._2_final();
5244 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5245 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5249 * Strip & Prep editor hidden fields
5251 c0_composeNewEmail : function() {
5252 this.getNewInstanceId();
5253 this.c1_composeEmail(false);
5257 * Sends async request to get the compose view.
5258 * Requests come from "reply" or "forwards"
5260 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5261 SE.composeLayout.replyForwardObj = new Object();
5262 SE.composeLayout.replyForwardObj.ieId = ieId;
5263 SE.composeLayout.replyForwardObj.uid = uid;
5264 SE.composeLayout.replyForwardObj.mbox = mbox;
5265 SE.composeLayout.replyForwardObj.type = type;
5267 if(mbox == 'sugar::Emails') {
5268 SE.composeLayout.replyForwardObj.sugarEmail = true;
5271 SE.composeLayout.getNewInstanceId();
5272 SE.composeLayout.c1_composeEmail(true);
5274 //// END COMPOSE FLOW
5275 ///////////////////////////////////////////////////////////////////////////
5278 * Called when a contact, email, or mailinglist is dropped
5279 * into one of the compose fields.
5281 handleDrop : function (source, event, data, target) {
5284 target = event.getTarget();
5286 data.nodes = [data.nodes];
5290 target = document.getElementById(target);
5294 if (target.id.indexOf('address') > -1) {
5295 // dropped onto email to/cc/bcc field
5296 for(var i in nodes) {
5297 var node = nodes[i].getData();
5299 if (node[1].indexOf('contact') > -1) {
5300 email = SE.addressBook.getFormattedAddress(node[0]);
5301 } else if (node[1].indexOf('address-email') > -1){
5302 email = node[3].replace(/ /gi, '');
5303 email = email.replace('<', '<').replace('>', '>');
5304 var tr = source.getTrEl(nodes[i]);
5305 while (tr && !Dom.hasClass(tr, "address-contact")) {
5306 tr = source.getPreviousTrEl(tr);
5308 var CID = source.getRecord(tr).getData()[0];
5309 var o = SE.addressBook._contactCache[CID];
5310 var name = new String(o.name);
5311 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5312 email = finalName + email;
5314 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5320 /*/////////////////////////////////////////////////////////////////////////////
5321 /// EMAIL TEMPLATE CODE
5323 applyEmailTemplate : function (idx, id) {
5326 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5327 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5328 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5331 var to_addr = document.getElementById('addressTO'+idx);
5332 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
5334 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5335 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5338 // id is selected index of email template drop-down
5339 if(id == '' || id == "0") {
5340 YAHOO.SUGAR.MessageBox.show({
5345 if(btn=='no'){return;};
5346 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5353 YAHOO.SUGAR.MessageBox.show({
5358 if(btn=='no'){return;};
5359 SUGAR.email2.composeLayout.processResult(idx, id);},
5365 processNoneResult : function(idx, id) {
5366 var tiny = SE.util.getTiny('htmleditor' + idx);
5367 var tinyHTML = tiny.getContent();
5368 var openTag = '<div><span><span>';
5369 var htmllow = tinyHTML.toLowerCase();
5370 var start = htmllow.indexOf(openTag);
5372 tinyHTML = tinyHTML.substr(start);
5373 tiny.setContent(tinyHTML);
5375 tiny.setContent('');
5379 processResult : function(idx , id){
5380 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5382 // get attachments if any
5383 AjaxObject.target = '';
5384 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5387 appendEmailTemplateJSON : function() {
5388 var idx = SE.composeLayout.currentInstanceId; // post increment
5390 // query based on template, contact_id0,related_to
5391 //jchi 09/10/2008 refix #7743
5392 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5393 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5396 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,'"');
5398 // cn: bug 14361 - text-only templates don't fill compose screen
5400 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/>");
5403 var tiny = SE.util.getTiny('htmleditor' + idx);
5404 var tinyHTML = tiny.getContent();
5405 var openTag = '<div><span><span>';
5406 var closeTag = '</span></span></div>';
5407 var htmllow = tinyHTML.toLowerCase();
5408 var start = htmllow.indexOf(openTag);
5410 var htmlPart2 = tinyHTML.substr(start);
5411 tinyHTML = text + htmlPart2;
5412 tiny.setContent(tinyHTML);
5414 tiny.setContent(text);
5419 * Writes out the signature in the email editor
5421 setSignature : function(idx) {
5424 var hide = document.getElementById('setEditor' + idx).checked;
5425 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5426 //wait for signatures to load before trying to set them
5427 if (!SE.composeLayout.signatures) {
5428 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5433 var sel = document.getElementById('signatures' + idx);
5435 var sel = document.getElementById('signature_id');
5436 idx = SE.tinyInstances.currentHtmleditor;
5439 //Ensure that the tinyMCE html has been rendered.
5440 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5441 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5448 signature = sel.options[sel.selectedIndex].value;
5453 var openTag = '<div><span><span>';
5454 var closeTag = '</span></span></div>';
5455 var t = SE.util.getTiny('htmleditor' + idx);
5457 if(typeof(t) != 'undefined')
5459 t.contentDocument = t.contentWindow.document;
5460 var html = t.getContent();
5465 var htmllow = html.toLowerCase();
5466 var start = htmllow.indexOf(openTag);
5467 var end = htmllow.indexOf(closeTag) + closeTag.length;
5469 // selected "none" - remove signature from email
5470 if(signature == '') {
5472 var htmlPart1 = html.substr(0, start);
5473 var htmlPart2 = html.substr(end, html.length);
5475 html = htmlPart1 + htmlPart2;
5478 SE.signatures.lastAttemptedLoad = '';
5482 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5483 SE.signatures.lastAttemptedLoad = '';
5485 SE.signatures.lastAttemptedLoad = signature;
5487 if(typeof(SE.signatures[signature]) == 'undefined') {
5489 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5490 SE.signatures.targetInstance = (idx) ? idx : "";
5491 AjaxObject.target = '';
5492 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5494 var newSignature = this.prepareSignature(SE.signatures[signature]);
5496 // clear out old signature
5497 if(SE.signatures.lastAttemptedLoad && start > -1) {
5498 var htmlPart1 = html.substr(0, start);
5499 var htmlPart2 = html.substr(end, html.length);
5501 html = htmlPart1 + htmlPart2;
5505 start = html.indexOf('<div><hr></div>');
5506 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5507 var htmlPart1 = html.substr(0, start);
5508 var htmlPart2 = html.substr(start, html.length);
5509 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5510 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5511 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5513 var newHtml = html + openTag + newSignature + closeTag;
5515 //tinyMCE.setContent(newHtml);
5516 t.setContent(newHtml);
5520 prepareSignature : function(str) {
5521 var signature = new String(str);
5523 signature = signature.replace(/</gi, '<');
5524 signature = signature.replace(/>/gi, '>');
5530 showAttachmentPanel : function(idx) {
5531 var east = SE.composeLayout[idx].getUnitByPosition("right");
5532 var tabs = SE.composeLayout[idx].rightTabs;
5534 tabs.set("activeTab", tabs.getTab(0));
5538 * expands sidebar and displays options panel
5540 showOptionsPanel : function(idx) {
5541 var east = SE.composeLayout[idx].getUnitByPosition("right");
5542 var tabs = SE.composeLayout[idx].rightTabs;
5544 tabs.set("activeTab", tabs.getTab(1));
5548 * Selects the Contacts tab
5550 showContactsPanel : function() {
5551 SE.complexLayout.regions.west.showPanel("contactsTab");
5555 * Generates fields for Select Document
5557 addDocumentField : function(idx) {
5558 var basket = document.getElementById('addedDocuments' + idx);
5560 var index = (basket.childNodes.length / 7) - 1;
5567 var test = document.getElementById('documentId' + idx + index);
5569 while(test != null) {
5571 test = document.getElementById('documentId' + idx + index);
5574 var documentCup = document.createElement("div");
5575 documentCup.id = 'documentCup' + idx + index;
5576 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5577 // document id field
5578 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5579 // document name field
5580 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5582 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5583 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5584 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5586 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5587 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5588 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5591 basket.appendChild(documentCup);
5592 //basket.innerHTML += out;
5597 * Makes async call to save a draft of the email
5598 * @param int Instance index
5600 saveDraft : function(tinyInstance) {
5601 this.sendEmail(tinyInstance, true);
5604 selectDocument : function(target) {
5605 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5606 windowName = 'selectDocument';
5607 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5609 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5611 // put the focus on the popup if the browser supports the focus() method
5617 * Modal popup for file attachment dialogue
5619 addFileField : function() {
5620 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5621 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5625 constraintoviewport: true,
5627 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5628 fn:function(){SE.addFileDialog.hide();}
5631 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5632 SE.addFileDialog.render();
5633 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5635 Dom.removeClass("addFileDialog", "yui-hidden");
5637 SE.addFileDialog.show();
5641 * Async upload of file to temp dir
5643 uploadAttachment : function() {
5644 if(document.getElementById('email_attachment').value != "") {
5645 var formObject = document.getElementById('uploadAttachment');
5646 YAHOO.util.Connect.setForm(formObject, true, true);
5647 AjaxObject.target = '';
5648 AjaxObject.startRequest(callbackUploadAttachment, null);
5650 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5655 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5656 * @param string target in focus compose layout
5658 setDocument : function(idx, target, documentId, documentName, docRevId) {
5659 // fields are named/id'd [fieldName][instanceId][index]
5660 var addedDocs = document.getElementById("addedDocuments" + idx);
5661 var docId = document.getElementById('documentId' + idx + target);
5662 var docName = document.getElementById('documentName' + idx + target);
5663 var docRevisionId = document.getElementById('document' + idx + target);
5664 docId.value = documentId;
5665 docName.value = documentName;
5666 docRevisionId.value = docRevId;
5670 * Removes the bucket div containing the document input fields
5672 deleteDocumentField : function(documentCup) {
5673 var f0 = document.getElementById(documentCup);
5674 f0.parentNode.removeChild(f0);
5678 * Removes a Template Attachment field
5682 deleteTemplateAttachmentField : function(idx, index) {
5683 // create not-in-array values for removal filtering
5684 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5690 r += document.getElementById('templateAttachmentId' + idx + index).value;
5691 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5693 var target = 'templateAttachmentCup' + idx + index;
5694 d = document.getElementById(target);
5695 d.parentNode.removeChild(d);
5699 * Async removal of uploaded temp file
5700 * @param string index Should be a concatenation of idx and index
5703 deleteUploadAttachment : function(index, file) {
5704 var d = document.getElementById('email_attachment_bucket' + index);
5705 d.parentNode.removeChild(d);
5707 // make async call to delete cached file
5708 AjaxObject.target = '';
5709 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5713 * Attaches files coming from Email Templates
5715 addTemplateAttachmentField : function(idx) {
5717 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5719 var basket = document.getElementById('addedTemplateAttachments' + idx);
5722 var index = basket.childNodes.length;
5729 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5731 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5732 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5733 idx + "\",\"" + index + "\");'/>" +
5735 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5736 // templateAttachment field
5737 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5739 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5741 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5742 "<br id='br" + index + "></br>" +
5743 "<br id='brdoc" + index + "></br>" +
5745 basket.innerHTML = basket.innerHTML + out;
5751 * Sends one email via async call
5752 * @param int idx Editor instance ID
5753 * @param bool isDraft
5755 sendEmail : function(idx, isDraft) {
5757 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5758 var obAccountID = document.getElementById('addressFrom' + idx).value;
5760 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5762 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5767 var form = document.getElementById('emailCompose' + idx);
5768 var composeOptionsFormName = "composeOptionsForm" + idx;
5769 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5770 var html = t.getContent();
5771 var subj = document.getElementById('emailSubject' + idx).value;
5772 var to = trim(document.getElementById('addressTO' + idx).value);
5773 var cc = trim(document.getElementById('addressCC' + idx).value);
5774 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5775 var email_id = document.getElementById('email_id' + idx).value;
5776 var composeType = document.getElementById('composeType').value;
5777 var parent_type = document.getElementById("parent_type").value;
5778 var parent_id = document.getElementById("parent_id").value;
5780 var el_uid = document.getElementById("uid");
5781 var uid = (el_uid == null) ? '' : el_uid.value;
5783 var el_ieId = document.getElementById("ieId");
5784 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5786 var el_mbox = document.getElementById("mbox");
5787 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5789 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5790 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5794 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5797 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5798 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5799 parent_id = parentIdValue;
5800 parent_type = parentTypeValue;
5802 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5803 // baseline viability check
5805 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5806 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5808 } else if(subj == '' && !isDraft) {
5809 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5812 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5814 } else if(html == '' && !isDraft) {
5815 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5820 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5821 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5822 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5823 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5824 html = html.replace(/</ig, "sugarLessThan");
5825 html = html.replace(/>/ig, "sugarGreaterThan");
5827 form.sendDescription.value = html;
5828 form.sendSubject.value = subj;
5829 form.sendTo.value = to;
5830 form.sendCc.value = cc;
5831 form.sendBcc.value = bcc;
5832 form.email_id.value = email_id;
5833 form.composeType.value = composeType;
5834 form.composeLayoutId.value = 'composeLayout' + idx;
5835 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5836 form.saveToSugar.value = 1;
5837 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5838 form.parent_type.value = parent_type;
5839 form.parent_id.value = parent_id;
5840 form.uid.value = uid;
5841 form.ieId.value = ieId;
5842 form.mbox.value = mbox;
5844 // email attachments
5845 var addedFiles = document.getElementById('addedFiles' + idx);
5847 for(i=0; i<addedFiles.childNodes.length; i++) {
5848 var bucket = addedFiles.childNodes[i];
5850 for(j=0; j<bucket.childNodes.length; j++) {
5851 var node = bucket.childNodes[j];
5852 var nName = new String(node.name);
5854 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5855 if(form.attachments.value != '') {
5856 form.attachments.value += "::";
5858 form.attachments.value += node.value;
5865 var addedDocs = document.getElementById('addedDocuments' + idx);
5867 for(i=0; i<addedDocs.childNodes.length; i++) {
5868 var cNode = addedDocs.childNodes[i];
5869 for(j=0; j<cNode.childNodes.length; j++) {
5870 var node = cNode.childNodes[j];
5871 var nName = new String(node.name);
5872 if(node.type == 'hidden' && nName.match(/documentId/)) {
5873 if(form.documents.value != '') {
5874 form.documents.value += "::";
5876 form.documents.value += node.value;
5882 // template attachments
5883 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5884 if(addedTemplateAttachments) {
5885 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5886 var cNode = addedTemplateAttachments.childNodes[i];
5887 for(j=0; j<cNode.childNodes.length; j++) {
5888 var node = cNode.childNodes[j];
5889 var nName = new String(node.name);
5890 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5891 if(form.templateAttachments.value != "") {
5892 form.templateAttachments.value += "::";
5894 form.templateAttachments.value += node.value;
5900 // remove attachments
5901 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5903 YAHOO.util.Connect.setForm(form);
5905 AjaxObject.target = 'frameFlex';
5907 // sending a draft email
5908 if(!isDraft && in_draft) {
5910 SE.listView.removeRowByUid(email_id);
5913 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5914 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5916 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5920 * Handles clicking the email address link from a given view
5922 composePackage : function() {
5923 if(composePackage != null) {
5924 SE.composeLayout.c0_composeNewEmail();
5927 if(composePackage.to_email_addrs) {
5928 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5930 if (composePackage.subject != null && composePackage.subject.length > 0) {
5931 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5934 //If no parent fields are set in the composePackage, ensure they are cleared.
5935 var parentFields = ['parent_type','parent_name','parent_id'];
5936 for(var i=0;i<parentFields.length;i++)
5938 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5939 composePackage[parentFields[i]] = "";
5942 document.getElementById("parent_type").value = composePackage.parent_type;
5943 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5944 document.getElementById("parent_id").value = composePackage.parent_id;
5945 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5946 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5948 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5949 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5951 if (composePackage.body != null && composePackage.body.length > 0) {
5952 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5953 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5954 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5956 if (composePackage.attachments != null) {
5957 SE.composeLayout.loadAttachments(composePackage.attachments);
5960 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5961 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5962 SE.util.emptySelectOptions(addressFrom);
5963 var fromAccountOpts = composePackage.fromAccounts.data;
5964 for(i=0; i<fromAccountOpts.length; i++) {
5965 var key = fromAccountOpts[i].value;
5966 var display = fromAccountOpts[i].text;
5967 var opt = new Option(display, key);
5968 if (fromAccountOpts[i].selected) {
5969 opt.selected = true;
5971 addressFrom.options.add(opt);
5978 setContentOnThisTiny : function() {
5979 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5980 var tinyHTML = tiny.getContent();
5981 composePackage.body = decodeURI(encodeURI(composePackage.body));
5982 // cn: bug 14361 - text-only templates don't fill compose screen
5983 if(composePackage.body == '') {
5984 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
5986 //Flag determines if we should clear the tiny contents or just append
5987 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5988 SE.composeLayout.tinyHTML = '';
5990 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
5992 tiny.setContent(SE.composeLayout.tinyHTML);
5993 //Indicate that the contents has been loaded successfully.
5994 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5997 * Confirms closure of a compose screen if "x" is clicked
5999 confirmClose : function(panel) {
6000 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6001 SE.composeLayout.closeCompose(panel.id);
6009 * forces close of a compose screen
6011 forceCloseCompose : function(id) {
6012 SE.composeLayout.closeCompose(id);
6014 // handle flow back to originating view
6015 if(composePackage) {
6016 // check if it's a module we need to return to
6017 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6018 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6019 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6020 window.location = url;
6027 * closes the editor that just sent email
6028 * @param string id ID of composeLayout tab
6030 closeCompose : function(id) {
6031 // destroy tinyMCE instance
6032 var idx = id.substr(13, id.length);
6033 var instanceId = "htmleditor" + idx;
6034 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6036 // nullify DOM and namespace values.
6038 SE.composeLayout[idx] = null;
6039 SE.tinyInstances[instanceId] = null;
6040 var tabsArray = SE.innerLayout.get("tabs");
6041 for (i = 0 ; i < tabsArray.length ; i++) {
6042 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6043 tabsArray[i].close();
6047 //SE.innerLayout.getTab(idx).close();
6051 * Enable the quick search for the compose relate field or search tab
6053 enableQuickSearchRelate: function(idx,overides){
6055 if(typeof overides != 'undefined')
6057 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6058 var newModule = document.getElementById(newModuleID).value;
6059 var formName = overides['formName'];
6060 var fieldName = overides['fieldName'];
6061 var fieldId = overides['fieldId'];
6062 var fullName = formName + "_" + fieldName;
6063 var postBlurFunction = null;
6067 var newModule = document.getElementById('data_parent_type'+idx).value;
6068 var formName = 'emailCompose'+idx;
6069 var fieldName = 'data_parent_name'+idx;
6070 var fieldId = 'data_parent_id'+idx;
6071 var fullName = formName + "_" + fieldName;
6072 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6075 if(typeof sqs_objects == 'undefined')
6076 window['sqs_objects'] = new Array;
6078 window['sqs_objects'][fullName] = {
6081 modules:[newModule],
6083 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6084 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6085 post_onblur_function: postBlurFunction,
6086 order:"name","limit":"30","no_match_text":"No Match"};
6089 if(typeof QSProcessedFieldsArray != 'undefined')
6090 QSProcessedFieldsArray[fullName] = false;
6091 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6092 QSFieldsArray[fullName].destroy();
6093 delete QSFieldsArray[fullName];
6095 if (Dom.get(fullName + "_results")) {
6096 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6102 qsAddAddress : function(o) {
6103 if (o.name != "" && o.email1 != "")
6105 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6106 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6110 * Returns a new instance ID, 0-index
6112 getNewInstanceId : function() {
6113 this.currentInstanceId = this.currentInstanceId + 1;
6114 return this.currentInstanceId;
6118 * 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.
6120 loadAttachments : function(result) {
6121 var idx = SE.composeLayout.currentInstanceId;
6123 if(typeof(result) == 'object') {
6124 //jchi #20680. Clean the former template attachments;
6125 var basket = document.getElementById('addedTemplateAttachments' + idx);
6126 if(basket.innerHTML != ''){
6127 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6129 basket.innerHTML = '';
6134 if(typeof result[i] == 'object') {
6135 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6136 var bean = result[i];
6137 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6138 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6145 * fills drop-down values for email templates and signatures
6147 setComposeOptions : function(idx) {
6148 // send from accounts
6149 var addressFrom = document.getElementById('addressFrom' + idx);
6151 if (addressFrom.options.length <= 0) {
6152 SE.util.emptySelectOptions(addressFrom);
6153 var fromAccountOpts = SE.composeLayout.fromAccounts;
6154 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6155 var key = fromAccountOpts[id].value;
6156 var display = fromAccountOpts[id].text;
6157 var is_default = false;
6158 if(key == SUGAR.default_inbound_accnt_id)
6160 var opt = new Option(display, key);
6161 addressFrom.options.add(opt);
6162 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6167 var et = document.getElementById('email_template' + idx);
6168 SE.util.emptySelectOptions(et);
6170 for(var key in this.emailTemplates) { // iterate through assoc array
6171 var display = this.emailTemplates[key];
6172 var opt = new Option(display, key);
6173 et.options.add(opt);
6177 var sigs = document.getElementById('signatures' + idx);
6178 SE.util.emptySelectOptions(sigs);
6180 for(var key in this.signatures) { // iterate through assoc array
6181 var display = this.signatures[key];
6182 var opt = new Option(display, key);
6184 if(key == SE.userPrefs.signatures.signature_default) {
6185 opt.selected = true;
6188 sigs.options.add(opt);
6191 // html/plain email?
6192 var htmlEmail = document.getElementById('setEditor' + idx);
6193 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6194 htmlEmail.checked = true;
6196 htmlEmail.checked = false;
6199 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6203 * After compose screen is rendered, async call to get email body from Sugar
6205 replyForwardEmailStage2 : function() {
6206 SE.util.clearHiddenFieldValues('emailUIForm');
6207 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6209 var ieId = SE.composeLayout.replyForwardObj.ieId;
6210 var uid = SE.composeLayout.replyForwardObj.uid;
6211 var mbox = SE.composeLayout.replyForwardObj.mbox;
6212 var type = SE.composeLayout.replyForwardObj.type;
6213 var idx = SE.composeLayout.currentInstanceId;
6215 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6217 document.getElementById('emailSubject' + idx).value = type;
6218 document.getElementById('emailUIAction').value = 'composeEmail';
6219 document.getElementById('composeType').value = type;
6220 document.getElementById('ieId').value = ieId;
6221 document.getElementById('uid').value = uid;
6222 document.getElementById('mbox').value = mbox;
6223 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6224 var formObject = document.getElementById('emailUIForm');
6225 YAHOO.util.Connect.setForm(formObject);
6227 var sendType = type;
6228 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6232 * Show the hidden cc or bcc fields
6234 showHiddenAddress: function(addrType,idx){
6236 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6237 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6238 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6239 this[addrType+'Hidden'+idx] = false;
6241 //After bcc or cc is added, move options below last addr field
6242 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6244 //If both cc and bcc hidden, remove the empty row containing text.
6245 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6246 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6247 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6249 SE.composeLayout.resizeEditor(idx);
6252 * Hide the cc and bcc fields if they were shown.
6254 hideHiddenAddresses: function(idx){
6256 var addrTypes = ['cc','bcc'];
6257 for(var i = 0;i<addrTypes.length;i++)
6259 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6260 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6261 this[addrTypes[i] + 'Hidden'+idx] = true
6264 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6265 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6266 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6270 //// END SE.composeLayout
6271 ///////////////////////////////////////////////////////////////////////////////
6272 ///////////////////////////////////////////////////////////////////////////////
6276 * Cleans serialized UID lists of duplicates
6280 cleanUids : function(str) {
6281 var seen = new Object();
6283 var arr = new String(str).split(",");
6285 for(var i=0; i<arr.length; i++) {
6290 clean += (clean != "") ? "," : "";
6292 seen[arr[i]] = true;
6299 * Clears hidden field values
6300 * @param string id ID of form element to clear
6302 clearHiddenFieldValues : function(id) {
6303 var form = document.getElementById(id);
6305 for(i=0; i<form.elements.length; i++) {
6306 if(form.elements[i].type == 'hidden') {
6307 var e = form.elements[i];
6308 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6316 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6318 emptySelectOptions : function(el) {
6320 for(i=el.childNodes.length - 1; i >= 0; i--) {
6321 if(el.childNodes[i]) {
6322 el.removeChild(el.childNodes[i]);
6329 * Returns the MBOX path in the manner php_imap expects:
6330 * ie: INBOX.DEBUG.test
6331 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6333 generateMboxPath : function(str) {
6334 var ex = str.split("::");
6336 /* we have a serialized MBOX path */
6340 for(var i=0; i<ex.length; i++) {
6341 if(ex[i] == 'INBOX') {
6353 /* we have a Sugar folder GUID - do nothing */
6361 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6362 * @param HTMLElement el
6363 * @return string GUID of found element or empty on failure
6365 getGuidFromElement : function(el) {
6371 for(var i=0; i<iterations; i++) {
6373 if(el.id.match(SE.reGUID)) {
6385 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6388 getPanelId : function() {
6389 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6393 * wrapper to handle weirdness with IE
6394 * @param string instanceId
6395 * @return tinyMCE Controller object
6397 getTiny : function(instanceId) {
6398 if(instanceId == '') {
6402 var t = tinyMCE.getInstanceById(instanceId);
6406 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6412 * Simple check for MSIE browser
6416 var nav = new String(navigator.appVersion);
6417 if(nav.match(/MSIE/)) {
6424 * Recursively removes an element from the DOM
6425 * @param HTMLElement
6427 removeElementRecursive : function(el) {
6428 this.emptySelectOptions(el);
6435 sleep : function(secs) {
6436 setTimeout("void(0);", secs);
6440 * Converts a <select> element to an Ext.form.combobox
6442 convertSelect : function(select) {
6443 alert('in convertSelect');
6444 if (typeof(select) == "string") {
6445 select = document.getElementById(select);
6449 findChildNode : function (parent, property, value) {
6450 for (i in parent.children) {
6451 var child = parent.children[i];
6452 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6454 var searchChild = SE.util.findChildNode(child, property, value);
6461 cascadeNodes : function (parent, fn, scope, args) {
6462 for (i in parent.children) {
6463 var child = parent.children[i];
6464 var s = scope ? scope : child;
6465 var a = args ? args : child;
6467 SE.util.cascadeNodes(child, fn, scope, args);
6474 ///////////////////////////////////////////////////////////////////////////////
6477 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6479 /*********************************************************************************
6480 * SugarCRM Community Edition is a customer relationship management program developed by
6481 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6483 * This program is free software; you can redistribute it and/or modify it under
6484 * the terms of the GNU Affero General Public License version 3 as published by the
6485 * Free Software Foundation with the addition of the following permission added
6486 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6487 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6488 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6490 * This program is distributed in the hope that it will be useful, but WITHOUT
6491 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6492 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6495 * You should have received a copy of the GNU Affero General Public License along with
6496 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6497 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6500 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6501 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6503 * The interactive user interfaces in modified source and object code versions
6504 * of this program must display Appropriate Legal Notices, as required under
6505 * Section 5 of the GNU Affero General Public License version 3.
6507 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6508 * these Appropriate Legal Notices must retain the display of the "Powered by
6509 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6510 * technical reasons, the Appropriate Legal Notices must display the words
6511 * "Powered by SugarCRM".
6512 ********************************************************************************/
6515 if (typeof console == "undefined")
6516 console = { log: function(o) {alert(o)} };
6520 currentRequestObject : null,
6521 //timeout : 30000, // 30 second timeout default
6522 timeout : 9999999999, // 30 second timeout default
6524 trail : new Array(),
6528 _reset : function() {
6529 this.timeout = 30000;
6530 this.forceAbort = false;
6533 folderRenameCleanup : function() {
6534 SUGAR.email2.folders.setSugarFolders();
6537 fullSyncCleanup : function(o) {
6538 this.folders.checkMailCleanup(o);
6539 SUGAR.email2.settings.settingsDialog.hide();
6544 composeCache : function(o) {
6545 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6546 // get email templates and user signatures
6547 var ret = JSON.parse(o.responseText);
6549 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6550 SUGAR.email2.composeLayout.signatures = ret.signatures;
6551 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6553 SUGAR.email2.composeLayout.setComposeOptions(idx);
6555 //Set the error array so we can notify the user when they try to hit send if any errors
6556 //are present. We will also notify them now (after hitting compose button).
6557 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6560 //if error element is returning an array, then check the length to make sure we have error messages
6561 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6562 //add error messages for display
6563 for(i in ret.errorArray)
6564 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6565 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6566 //if error element is returning an object, and the object value is not empty or null, then display error message
6567 for(i in ret.errorArray)
6568 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6571 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6573 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6575 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6581 handleDeleteSignature : function(o) {
6583 var ret = JSON.parse(o.responseText);
6584 SUGAR.email2.composeLayout.signatures = ret.signatures;
6585 var field = document.getElementById('signature_id');
6586 SUGAR.email2.util.emptySelectOptions(field);
6588 for(var i in ret.signatures) { // iterate through assoc array
6589 var opt = new Option(ret.signatures[i], i);
6590 field.options.add(opt);
6592 setSigEditButtonVisibility();
6597 handleDeleteReturn : function(o) {
6598 // force refresh ListView
6600 if(document.getElementById('focusEmailMbox')) {
6601 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6604 // need to display success message before calling next async call?
6605 document.getElementById(this.target).innerHTML = o.responseText;
6610 handleFailure : function(o) {
6612 overlay('Exception occurred...', o.statusText, 'alert');
6613 if(document.getElementById('saveButton')) {
6614 document.getElementById('saveButton').disabled = false;
6618 handleReplyForward : function(o) {
6619 var a = JSON.parse(o.responseText);
6621 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6623 document.getElementById('email_id' + idx).value = a.uid;
6624 document.getElementById('emailSubject' + idx).value = a.name;
6625 document.getElementById('addressTO' + idx).value = a.from;
6626 document.getElementById('uid' + idx).value = a.uid;
6628 document.getElementById('addressCC' + idx).value = a.cc;
6629 SE.composeLayout.showHiddenAddress('cc', idx);
6633 document.getElementById('type' + idx).value = a.type;
6636 // apply attachment values
6637 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6639 setTimeout("callbackReplyForward.finish(globalA);", 500);
6642 handleReplyForwardForDraft : function(o) {
6643 var a = JSON.parse(o.responseText);
6645 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6647 document.getElementById('email_id' + idx).value = a.uid;
6648 document.getElementById('emailSubject' + idx).value = a.name;
6649 document.getElementById('addressTO' + idx).value = a.to;
6652 document.getElementById('addressCC' + idx).value = a.cc;
6653 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6657 document.getElementById('addressBCC' + idx).value = a.bcc;
6658 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6663 document.getElementById('type' + idx).value = a.type;
6667 // apply attachment values
6668 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6670 setTimeout("callbackReplyForward.finish(globalA);", 500);
6675 handleSuccess : function(o) {
6676 document.getElementById(this.target).innerHTML = o.responseText;
6682 ieDeleteSuccess : function(o) {
6685 var ret = JSON.parse(o.responseText);
6687 SUGAR.email2.accounts.refreshInboundAccountTable();
6688 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6689 SUGAR.email2.accounts.rebuildFolderList();
6695 ieSaveSuccess : function(o) {
6696 document.getElementById('saveButton').disabled = false;
6697 var a = JSON.parse(o.responseText);
6700 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6701 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6703 resp = JSON.parse(o.responseText);
6704 SUGAR.email2.accounts.refreshInboundAccountTable();
6705 SUGAR.email2.accounts.refreshOuboundAccountTable();
6706 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6707 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6711 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6718 loadAttachments : function(o) {
6719 var result = JSON.parse(o.responseText);
6721 SUGAR.email2.composeLayout.loadAttachments(result);
6726 loadSignature : function(o) {
6727 var ret = JSON.parse(o.responseText);
6728 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6729 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6733 * Follow up to mark email read|unread|flagged
6735 markEmailCleanup : function(o) {
6736 var ret = JSON.parse(o.responseText);
6737 if (!ret['status']) {
6739 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6741 SUGAR.email2.contextMenus.markEmailCleanup();
6747 rebuildShowFolders : function(o) {
6748 var t = JSON.parse(o.responseText);
6749 var show = document.getElementById('ieAccountListShow');
6751 SUGAR.email2.util.emptySelectOptions(show);
6753 for(i=0; i<t.length; i++) { // iterate through assoc array
6754 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6755 opt.selected = t[i].selected;
6756 show.options.add(opt);
6759 SUGAR.email2.accounts.renderTree();
6763 saveListViewSortOrderPart2 : function() {
6764 // create the JSON string the func expects
6765 focusFolderPath = '[ "Home", "' + ieName + '"';
6767 var f = new String(focusFolder);
6768 var fEx = f.split('.');
6770 for(i=0; i<fEx.length; i++) {
6771 focusFolderPath += ', "' + fEx[i] +'"'
6774 focusFolderPath += ']';
6776 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6777 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6783 sendEmailCleanUp : function(o) {
6785 var ret = JSON.parse(o.responseText);
6787 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6788 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6789 } else if (o.responseText) {
6790 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6793 if (typeof(SE.grid) != 'undefined')
6794 SE.listView.refreshGrid();
6795 //Disabled while address book is disabled
6797 //If this call back was initiated by quick compose from a Detail View page, refresh the
6798 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6799 //close the shortcut bar menu
6800 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6801 if(action_sugar_grp1 == 'DetailView') {
6802 showSubPanel('history',null,true);
6803 } else if(action_sugar_grp1 == 'quickcreate') {
6804 closeEmailOverlay();
6810 ieSendSuccess : function(o) {
6812 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6817 settingsFolderRefresh : function(o) {
6818 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6819 var ret = JSON.parse(o.responseText);
6820 var user = document.getElementById('userFolders');
6822 SUGAR.email2.util.emptySelectOptions(user);
6824 for(i=0; i<ret.userFolders.length; i++) {
6825 var display = ret.userFolders[i].name;
6826 var value = ret.userFolders[i].id;
6827 var selected = (ret.userFolders[i].selected != "") ? true : false;
6828 var opt = new Option(display, value, selected);
6829 opt.selected = selected;
6830 user.options.add(opt);
6836 startRequest : function(callback, args, forceAbort) {
6837 if(this.currentRequestObject != null) {
6838 if(this.forceAbort == true) {
6839 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6842 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6846 requestInProgress : function() {
6847 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6852 updateFolderSubscriptions : function() {
6853 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6854 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6860 updateFrameFolder : function() {
6861 SUGAR.email2.folders.checkEmailAccounts();
6866 updateUserPrefs : function(o) {
6867 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6868 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6873 uploadAttachmentSuccessful : function(o) {
6875 document.getElementById('email_attachment').value = '';
6877 var ret = JSON.parse(o.responseText);
6878 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6879 var overall = document.getElementById('addedFiles' + idx);
6880 var index = overall.childNodes.length;
6882 "<div id='email_attachment_bucket" + idx + index + "'>" +
6884 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6885 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6886 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6888 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6889 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6891 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6893 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6896 overall.innerHTML += out;
6897 if(SUGAR.email2.util.isIe()) {
6898 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6902 SUGAR.email2.addFileDialog.hide();
6903 // focus attachments
6904 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6909 ///////////////////////////////////////////////////////////////////////////
6910 //// PER MODULE CALLBACK OBJECTS
6911 AjaxObject.accounts = {
6912 saveOutboundCleanup : function(o) {
6913 SUGAR.email2.accounts.refreshOuboundAccountTable();
6914 SUGAR.email2.accounts.outboundDialog.hide();
6915 var id = o.responseText;
6916 SUGAR.email2.accounts.newAddedOutboundId = id;
6918 saveDefaultOutboundCleanup: function(o){
6921 callbackEditOutbound : {
6922 success : function(o)
6924 var ret = JSON.parse(o.responseText);
6926 SUGAR.email2.accounts.showAddSmtp();
6929 document.getElementById("mail_id").value = ret.id;
6930 document.getElementById("type").value = ret.type;
6931 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6932 document.getElementById("mail_name").value = ret.name;
6933 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6934 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6935 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6936 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6937 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6938 SUGAR.email2.accounts.smtp_authenticate_field_display();
6939 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6941 if(ret.type == 'system-override') {
6942 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6943 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6946 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6947 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6949 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6952 failure : AjaxObject.handleFailure,
6953 timeout : AjaxObject.timeout,
6956 callbackDeleteOutbound : {
6957 success : function(o) {
6958 var ret = JSON.parse(o.responseText);
6961 if(confirm(ret.error_message))
6963 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6964 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6972 SUGAR.email2.accounts.refreshOuboundAccountTable();
6976 failure : AjaxObject.handleFailure,
6977 timeout : AjaxObject.timeout,
6981 callbackCheckMailProgress : {
6982 success : function(o) {
6983 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6984 SUGAR.email2.accounts.totalMsgCount = -1;
6987 //Check for server timeout / errors
6988 var ret = JSON.parse(o.responseText);
6991 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6993 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6994 SUGAR.email2.accounts.totalMsgCount = -1;
6995 //SUGAR.email2.folders.rebuildFolders();
6999 var currIeId = ret['ieid'];
7002 var serverCount = ret.count;
7004 if (ret['status'] == 'done') {
7005 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7006 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7010 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7011 //Go to next account
7012 currIeId = SUGAR.email2.accounts.ieIds[i+1];
7014 SUGAR.email2.accounts.totalMsgCount = -1;
7019 else if (ret.mbox && ret.totalcount && ret.count) {
7020 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7021 if (ret.count >= ret.totalcount) {
7024 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7025 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7028 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7029 SUGAR.email2.accounts.totalMsgCount = -1;
7034 SUGAR.email2.accounts.totalMsgCount = -1;
7036 SUGAR.email2.folders.rebuildFolders();
7037 SE.listView.refreshGrid();
7038 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7039 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7040 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7041 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7043 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7044 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7045 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7046 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7047 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7050 failure : AjaxObject.handleFailure,
7051 timeout : AjaxObject.timeout,
7056 ///////////////////////////////////////////////////////////////////////////////
7058 AjaxObject.composeLayout = {
7060 * Populates the record id
7062 saveDraftCleanup : function(o) {
7064 var ret = JSON.parse(o.responseText);
7066 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7067 else if (o.responseText)
7068 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7072 AjaxObject.composeLayout.callback = {
7074 success : AjaxObject.composeLayout.saveDraftCleanup,
7075 failure : AjaxObject.handleFailure,
7076 timeout : AjaxObject.timeout,
7081 AjaxObject.detailView = {
7083 * Pops-up a printable view of an email
7085 displayPrintable : function(o) {
7086 var ret = JSON.parse(o.responseText);
7087 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7088 // 2 below must be in global context
7090 meta['panelId'] = SUGAR.email2.util.getPanelId();
7091 email = ret.meta.email;
7092 if (typeof(email.cc) == 'undefined') {
7096 var out = displayTemplate.exec({
7097 'app_strings' : app_strings,
7101 'email' : meta.email
7104 // open popup window
7105 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7106 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7108 popup.document.write(out);
7109 popup.document.close();
7113 * Takes formatted response and creates a modal pop-over containing a title and content
7115 displayView : function(o) {
7116 var SED = SUGAR.email2.detailView;
7117 var ret = JSON.parse(o.responseText);
7119 if(!SED.viewDialog) {
7120 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7124 constraintoviewport: true,
7127 SED.viewDialog.renderEvent.subscribe(function() {
7128 var content = this.body.firstChild;
7129 var viewH = YAHOO.util.Dom.getViewportHeight();
7131 this.body.style.overflow = "auto";
7132 this.body.style.width = "800px";
7133 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7137 SED.viewDialog.setHeader(ret.title);
7138 SED.viewDialog.setBody(ret.html);
7139 SED.viewDialog.render();
7140 SED.viewDialog.show();
7144 * Generates a modal popup to populate with the contents of bean's full EditView
7146 showQuickCreateForm : function(o) {
7147 var SED = SUGAR.email2.detailView;
7148 var ret = JSON.parse(o.responseText);
7150 if(!SED.quickCreateDialog) {
7151 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7155 constraintoviewport: true,
7159 SED.quickCreateDialog.renderEvent.subscribe(function() {
7160 var viewH = YAHOO.util.Dom.getViewportHeight();
7162 for (var i in this.body.childNodes) {
7163 if (this.body.childNodes[i].clientHeight) {
7164 contH += this.body.childNodes[i].clientHeight;
7165 } else if (this.body.childNodes[i].offsetHeight) {
7166 contH += this.body.childNodes[i].offsetHeight;
7169 this.body.style.width = "800px";
7170 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7171 this.body.style.overflow = "auto";
7172 }, SED.quickCreateDialog);
7174 SED.quickCreateDialog.hideEvent.subscribe(function(){
7175 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7176 /*for(var qsField in qsFields){
7177 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7178 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7181 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7184 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7186 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7187 SED.quickCreateDialog.render();
7188 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7190 SED.quickCreateDialog.ieId = ret.ieId;
7191 SED.quickCreateDialog.uid = ret.uid;
7192 SED.quickCreateDialog.mbox = ret.mbox;
7193 SED.quickCreateDialog.qcmodule = ret.module;
7195 SED.quickCreateDialog.show();
7197 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7199 editForm.module.value = 'Emails';
7200 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7201 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7202 var instId = ret.module + count;
7203 SED.quickCreateEmailsToAdd = ret.emailAddress;
7204 SED.quickCreateEmailCallback = function(instId, tableId) {
7205 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7206 if (typeof(eaw) == "undefined")
7207 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7208 + instId + "','" + tableId + "');", 100);
7209 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7211 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7212 + instId + "','" + tableId + "');", 100);
7216 saveQuickCreateForm : function(o) {
7218 SUGAR.email2.detailView.quickCreateDialog.hide();
7219 validate['EditView'] = [ ];
7222 saveQuickCreateFormAndReply : function(o) {
7224 var ret = JSON.parse(o.responseText);
7225 SUGAR.email2.detailView.quickCreateDialog.hide();
7226 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7227 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7229 var emailID = ret.id;
7230 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7232 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7234 //Cean the validate cache to prevent errors on the next call
7235 validate['EditView'] = [ ];
7238 saveQuickCreateFormAndAddToAddressBook : function(o) {
7240 SUGAR.email2.detailView.quickCreateDialog.hide();
7241 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7242 validate['EditView'] = [ ];
7245 handleAssignmentDialogAssignAction : function() {
7248 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7250 var dist = 'direct';
7254 var found_teams = false;
7255 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7256 if(!found_teams && assign_user_id == '' )
7258 alert(warning_message);
7262 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7264 for(i=0; i<emailUids.length; i++) {
7266 uids += app_strings.LBL_EMAIL_DELIMITER;
7268 uids += emailUids[i];
7271 var row = SUGAR.email2.grid.getSelectedRows()[0];
7272 var data = SUGAR.email2.grid.getRecord(row).getData();
7273 var ieid = data.ieId;
7274 var mbox = data.mbox;
7275 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7276 SUGAR.email2.contextMenus.assignToDialogue.hide();
7277 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7281 handleAssignmentDialogDeleteAction : function() {
7282 // TO pass list of UIDS/emailIds
7283 var uids = SUGAR.email2.listView.getUidsFromSelection();
7284 var row = SUGAR.email2.grid.getSelections()[0];
7285 var ieid = row.data.ieId;
7286 var mbox = row.data.mbox;
7287 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7288 SUGAR.email2.contextMenus.assignmentDialog.hide();
7289 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7295 showEmailDetailView : function(o) {
7297 var SED = SUGAR.email2.detailView;
7298 var ret = JSON.parse(o.responseText);
7300 if(!SED.quickCreateDialog) {
7301 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7305 constraintoviewport: true,
7307 autofillheight: "body",
7310 SED.quickCreateDialog.renderEvent.subscribe(function() {
7311 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7313 for (var i in this.body.childNodes) {
7314 if (this.body.childNodes[i].offsetHeight)
7315 contH += this.body.childNodes[i].offsetHeight;
7317 this.body.style.overflow = "auto";
7318 this.body.style.width = "800px";
7319 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7321 }, SED.quickCreateDialog);
7323 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7324 SED.quickCreateDialog.setBody(ret.html);
7325 SED.quickCreateDialog.render();
7326 SUGAR.util.evalScript(ret.html);
7327 SED.quickCreateDialog.show();
7330 showAssignmentDialogWithData : function(o) {
7331 var SEC = SUGAR.email2.contextMenus;
7333 var ret = JSON.parse(o.responseText);
7334 if (!SEC.assignmentDialog) {
7335 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7338 constraintoviewport: true,
7341 SEC.assignmentDialog.setBody("");
7342 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7343 SEC.assignmentDialog.renderEvent.subscribe(function() {
7344 var iev = YAHOO.util.Dom.get("Distribute");
7346 this.body.style.width = "700px";
7348 }, SEC.assignmentDialog);
7349 SEC.assignmentDialog.render();
7351 SEC.assignmentDialog.setBody(ret);
7352 SEC.assignmentDialog.render();
7354 SEC.assignmentDialog.show();
7355 SUGAR.util.evalScript(ret);
7358 showImportForm : function(o) {
7359 var SED = SUGAR.email2.detailView;
7360 var ret = JSON.parse(o.responseText);
7362 document.getElementById('quickCreateContent').innerHTML = "";
7368 if(!SED.importDialog) {
7369 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7373 constraintoviewport: true,
7375 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7376 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7380 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7381 SED.importDialog.setBody("");
7382 SED.importDialog.hideEvent.subscribe(function(){
7383 for(var i in QSFieldsArray) {
7384 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7385 QSFieldsArray[i].destroy();
7386 delete QSFieldsArray[i];
7388 if (QSProcessedFieldsArray[i]) {
7389 QSProcessedFieldsArray[i] = false;
7393 SED.importDialog.renderEvent.subscribe(function() {
7394 var iev = YAHOO.util.Dom.get("ImportEditView");
7396 //this.body.style.height = (iev.clientHeight + 10) + "px";
7397 this.body.style.width = "600px";
7399 }, SED.importDialog);
7400 SED.importDialog.render();
7402 SED.importDialog.setBody(ret.html);
7403 SED.importDialog.ret = ret;
7404 SUGAR.util.evalScript(ret.html);
7405 SED.importDialog.render();
7407 SED.importDialog.show();
7408 SED.importDialog.focusFirstButton();
7410 getImportAction : function(ret) {
7411 if (!check_form('ImportEditView')) return false;
7412 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7413 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7417 var editView = document.getElementById('ImportEditView');
7418 if (editView.assigned_user_id != null) {
7419 get = get + "&user_id=" + editView.assigned_user_id.value
7420 //var user_id = editView.assigned_user_id.value;
7422 var parent_id = editView.parent_id.value;
7423 var parent_type = editView.parent_type.value;
7424 var row = SUGAR.email2.grid.getSelectedRows()[0];
7425 row = SUGAR.email2.grid.getRecord(row);
7426 var data = row.getData();
7427 var ieId = data.ieId;
7428 var mbox = data.mbox;
7429 var serverDelete = editView.serverDelete.checked;
7430 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7432 for(i=0; i<emailUids.length; i++) {
7434 uids += app_strings.LBL_EMAIL_DELIMITER;
7436 uids += emailUids[i];
7439 var action = 'importEmail&uid=';
7441 action = 'moveEmails';
7442 action = action + '&sourceFolder=' + ret['srcFolder'];
7443 action = action + '&sourceIeId=' + ret['srcIeId'];
7444 action = action + '&destinationFolder=' + ret['dstFolder'];
7445 action = action + '&destinationIeId=' + ret['dstIeId'];
7446 action = action + '&emailUids=';
7448 if (action.search(/importEmail/) != -1) {
7449 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7451 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7454 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7455 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7456 SUGAR.email2.detailView.importDialog.hide();
7457 document.getElementById('importDialogContent').innerHTML = "";
7460 showRelateForm : function(o) {
7461 var SED = SUGAR.email2.detailView;
7462 var ret = JSON.parse(o.responseText);
7463 document.getElementById('quickCreateContent').innerHTML = "";
7468 dialog_loaded = true;
7470 if(!SED.relateDialog) {
7471 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7476 constraintoviewport: true,
7478 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7479 if (!check_form('RelateEditView')) return false;
7481 var editView = document.getElementById('RelateEditView');
7482 var parent_id = editView.parent_id.value;
7483 var parent_type = editView.parent_type.value;
7484 var row = SUGAR.email2.grid.getSelectedRows()[0];
7485 row = SUGAR.email2.grid.getRecord(row);
7486 var ieId = row.getData().ieId;
7487 var mbox = row.getData().mbox;
7488 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7490 for(i=0; i<emailUids.length; i++) {
7492 uids += app_strings.LBL_EMAIL_DELIMITER;
7494 uids += emailUids[i];
7496 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7497 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7498 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7499 SED.relateDialog.hide();
7500 document.getElementById('relateDialogContent').innerHTML = "";
7505 SED.relateDialog.hideEvent.subscribe(function(){
7506 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7507 QSFieldsArray['ImportEditView_parent_name'].destroy();
7508 delete QSFieldsArray['ImportEditView_parent_name'];
7510 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7511 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7515 SED.relateDialog.renderEvent.subscribe(function() {
7516 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7518 for (var i in this.body.childNodes) {
7519 if (this.body.childNodes[i].clientHeight)
7520 contH += this.body.childNodes[i].clientHeight;
7522 }, SED.relateDialog);
7523 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7526 SED.relateDialog.setBody(ret.html);
7527 SED.relateDialog.render();
7528 SUGAR.util.evalScript(ret.html);
7529 SED.relateDialog.show();
7533 * DetailView callbacks
7535 AjaxObject.detailView.callback = {
7537 success : function(o) {
7539 var ret = JSON.parse(o.responseText);
7540 SUGAR.email2.detailView.consumeMetaDetail(ret);
7542 argument: [targetDiv],
7543 failure : AjaxObject.handleFailure,
7548 success : function(o) {
7550 var ret = JSON.parse(o.responseText);
7551 SUGAR.email2.detailView.consumeMetaPreview(ret);
7553 failure : AjaxObject.handleFailure,
7558 success : AjaxObject.detailView.displayPrintable,
7559 failure : AjaxObject.handleFailure,
7560 timeout : AjaxObject.timeout,
7564 success : AjaxObject.detailView.displayView,
7565 failure : AjaxObject.handleFailure,
7566 timeout : AjaxObject.timeout,
7575 AjaxObject.folders = {
7577 * check-mail post actions
7579 checkMailCleanup : function(o) {
7581 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7583 // refresh focus ListView
7584 SE.listView.refreshGrid();
7585 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7590 rebuildFolders : function(o) {
7593 var data = JSON.parse(o.responseText);
7595 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7596 SUGAR.email2.folders.setSugarFolders();
7599 AjaxObject.folders.callback = {
7601 success : AjaxObject.folders.checkMailCleanup,
7602 failure : AjaxObject.handleFailure,
7603 timeout : 600000, // 5 mins
7608 AjaxObject.rules = {
7609 loadRulesForSettings : function(o) {
7610 document.getElementById("rulesListCell").innerHTML = o.responseText;
7611 // assume we have the class we need
7612 SUGAR.routing.getStrings();
7613 SUGAR.routing.getDependentDropdowns();
7616 //// END PER MODULE CALLBACK OBJECTS
7617 ///////////////////////////////////////////////////////////////////////////
7621 success : AjaxObject.handleSuccess,
7622 failure : AjaxObject.handleFailure,
7623 timeout : AjaxObject.timeout,
7626 var callbackAccount = {
7627 success : AjaxObject.ieSaveSuccess,
7628 failure : AjaxObject.handleFailure,
7629 timeout : AjaxObject.timeout,
7632 var callbackAccountDelete = {
7633 success : AjaxObject.ieDeleteSuccess,
7634 failure : AjaxObject.handleFailure,
7635 timeout : AjaxObject.timeout,
7638 var callbackOutboundTest = {
7639 success : AjaxObject.ieSendSuccess,
7640 failure : AjaxObject.handleFailure,
7641 timeout : AjaxObject.timeout,
7647 var callbackTeamInfoForSettings = {
7648 success : function (o) {
7649 var data = JSON.parse(o.responseText);
7650 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7652 failure : AjaxObject.handleFailure,
7653 timeout : AjaxObject.timeout,
7658 var callbackStatusForImport = {
7659 success : function (o) {
7661 if (o.responseText != "") {
7662 var statusString = "";
7663 var data = JSON.parse(o.responseText);
7664 for(i=0; i<data.length; i++) {
7665 statusString = statusString + data[i] + '<br/>';
7667 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7669 SE.listView.refreshGrid();
7672 failure : AjaxObject.handleFailure,
7673 timeout : AjaxObject.timeout,
7677 var callbackComposeCache = {
7678 success : AjaxObject.composeCache,
7679 failure : AjaxObject.handleFailure,
7680 timeout : AjaxObject.timeout,
7683 var callbackDelete = {
7684 success : AjaxObject.handleDeleteReturn,
7685 failure : AjaxObject.handleFailure,
7686 timeout : AjaxObject.timeout,
7689 var callbackEmailDetailMultiple = {
7690 success : function(o) {
7692 var retMulti = JSON.parse(o.responseText);
7693 var ret = new Object();
7695 for(var i=0; i<retMulti.length; i++) {
7698 SUGAR.email2._setDetailCache(ret);
7699 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7702 failure : AjaxObject.handleFailure,
7706 var callbackListViewSortOrderChange = {
7707 success : AjaxObject.saveListViewSortOrderPart2,
7708 failure : AjaxObject.handleFailure,
7709 timeout : AjaxObject.timeout,
7711 argument : [ieId, ieName, focusFolder]
7713 var callbackEmptyTrash = {
7714 success : function(o) {
7716 AjaxObject.folderRenameCleanup;
7718 failure : AjaxObject.handleFailure,
7719 timeout : AjaxObject.timeout,
7722 var callbackClearCacheFiles = {
7723 success : function(o) {
7726 failure : AjaxObject.handleFailure,
7727 timeout : AjaxObject.timeout,
7730 var callbackFolderRename = {
7731 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7732 failure : AjaxObject.handleFailure,
7733 timeout : AjaxObject.timeout,
7736 var callbackFolderDelete = {
7737 success : function(o) {
7738 var ret = JSON.parse(o.responseText);
7740 if (ret.folder_id) {
7741 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7743 SUGAR.email2.tree.removeNode(node, true);
7744 } else if (ret.ieId && ret.mbox) {
7745 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7747 SUGAR.email2.tree.removeNode(node, true);
7750 //SUGAR.email2.folders.loadSettingFolder();
7753 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7756 failure : AjaxObject.handleFailure,
7757 timeout : AjaxObject.timeout,
7760 var callbackFolderSave = {
7761 success : function(o) {
7762 var ret = JSON.parse(o.responseText);
7764 switch(ret.action) {
7765 case 'newFolderSave':
7766 SUGAR.email2.folders.rebuildFolders();
7770 failure : AjaxObject.handleFailure,
7771 timeout : AjaxObject.timeout,
7774 var callbackFolderSubscriptions = {
7775 success : AjaxObject.updateFolderSubscriptions,
7776 failure : AjaxObject.handleFailure,
7777 timeout : AjaxObject.timeout,
7780 var callbackFolderUpdate = {
7781 success : AjaxObject.updateFrameFolder,
7782 failure : AjaxObject.handleFailure,
7783 timeout : AjaxObject.timeout,
7786 var callbackFolders = {
7787 success : AjaxObject.folders.rebuildFolders,
7788 //success : void(true),
7789 failure : AjaxObject.handleFailure,
7790 timeout : AjaxObject.timeout,
7793 var callbackFullSync = {
7794 success : AjaxObject.fullSyncCleanup,
7795 failure : AjaxObject.handleFailure,
7796 timeout : 9999999999999,
7799 var callbackGeneric = {
7800 success : function() {
7803 failure : AjaxObject.handleFailure,
7804 timeout : AjaxObject.timeout,
7807 var callbackIeAccountRetrieve = {
7808 success : function(o) {
7809 // return JSON encoding
7811 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7812 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7814 failure : AjaxObject.handleFailure,
7815 timeout : AjaxObject.timeout,
7818 var callbackImportOneEmail = {
7819 success : AjaxObject.detailView.showImportForm,
7820 failure : AjaxObject.handleFailure,
7821 timeout : AjaxObject.timeout,
7824 var callbackRelateEmail = {
7825 success : AjaxObject.detailView.showRelateForm,
7826 failure : AjaxObject.handleFailure,
7827 timeout : AjaxObject.timeout,
7830 var callbackEmailDetailView = {
7831 success : AjaxObject.detailView.showEmailDetailView,
7832 failure : AjaxObject.handleFailure,
7833 timeout : AjaxObject.timeout,
7836 var callbackAssignmentDialog = {
7837 success : AjaxObject.detailView.showAssignmentDialogWithData,
7838 failure : AjaxObject.handleFailure,
7839 timeout : AjaxObject.timeout,
7842 var callbackAssignmentAction = {
7843 success : function(o) {
7844 SE.listView.refreshGrid();
7846 if(o.responseText != '') {
7847 overlay('Assignment action result', o.responseText, 'alert');
7850 failure : AjaxObject.handleFailure,
7851 timeout : AjaxObject.timeout,
7854 var callbackMoveEmails = {
7855 success : function(o) {
7856 SE.listView.refreshGrid();
7858 if(o.responseText != '') {
7859 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7862 failure : AjaxObject.handleFailure,
7863 timeout : AjaxObject.timeout,
7866 var callbackLoadAttachments = {
7867 success : AjaxObject.loadAttachments,
7868 failure : AjaxObject.handleFailure,
7869 timeout : AjaxObject.timeout,
7872 var callbackLoadRules = {
7873 success : AjaxObject.rules.loadRulesForSettings,
7874 failure : AjaxObject.handleFailure,
7875 timeout : AjaxObject.timeout,
7878 var callbackLoadSignature = {
7879 success : AjaxObject.loadSignature,
7880 failure : AjaxObject.handleFailure,
7881 timeout : AjaxObject.timeout,
7884 var callbackDeleteSignature = {
7885 success : AjaxObject.handleDeleteSignature,
7886 failure : AjaxObject.handleFailure,
7887 timeout : AjaxObject.timeout,
7890 /*var callbackMoveEmails = {
7891 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7892 failure : AjaxObject.handleFailure,
7893 timeout : AjaxObject.timeout,
7896 var callbackOutboundSave = {
7897 success : AjaxObject.accounts.saveOutboundCleanup,
7898 failure : AjaxObject.handleFailure,
7899 timeout : AjaxObject.timeout,
7902 var callbackDefaultOutboundSave = {
7903 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7904 failure : AjaxObject.handleFailure,
7905 timeout : AjaxObject.timeout,
7908 var callbackQuickCreate = {
7909 success : AjaxObject.detailView.showQuickCreateForm,
7910 failure : AjaxObject.handleFailure,
7911 timeout : AjaxObject.timeout,
7914 var callbackQuickCreateSave = {
7915 success : AjaxObject.detailView.saveQuickCreateForm,
7916 failure : AjaxObject.handleFailure,
7917 timeout : AjaxObject.timeout,
7920 var callbackQuickCreateSaveAndAddToAddressBook = {
7921 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7922 failure : AjaxObject.handleFailure,
7923 timeout : AjaxObject.timeout,
7926 var callbackQuickCreateSaveAndReply = {
7927 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7928 failure : AjaxObject.handleFailure,
7929 timeout : AjaxObject.timeout,
7932 var callbackQuickCreateSaveAndReplyCase = {
7933 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7934 failure : AjaxObject.handleFailure,
7935 timeout : AjaxObject.timeout,
7938 var callbackRebuildShowAccountList = {
7939 success : AjaxObject.rebuildShowFolders,
7940 failure : AjaxObject.handleFailure,
7941 timeout : AjaxObject.timeout,
7945 var callbackRefreshSugarFolders = {
7946 success : function(o) {
7947 var t = JSON.parse(o.responseText);
7948 SUGAR.email2.folders.setSugarFoldersEnd(t);
7950 failure : AjaxObject.handleFailure,
7951 timeout : AjaxObject.timeout,
7954 var callbackReplyForward = {
7955 success : AjaxObject.handleReplyForward,
7956 finish : function(a, retryCount) {
7957 if (typeof(retryCount) == 'undefined') {
7962 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7963 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7965 var html = t.getContent();
7967 if (a.type != 'draft') {
7968 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7969 html += " <div><hr></div>" + a.description;
7971 html = " <div><hr></div>" + a.description + html;
7974 html = a.description;
7977 t.setContent(html);//
7980 if (retryCount < 5) {
7981 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7985 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7986 if (tabArray != null && tabArray.length > 0) {
7987 for (i = 0 ; i < tabArray.length ; i++) {
7988 var tabObject = tabArray[i];
7989 if (tabObject.get("id") == ("composeTab" + idx)) {
7990 var tabLabel = a.name;
7991 if (tabLabel != null && tabLabel.length > 25) {
7992 tabLabel = tabLabel.substring(0, 25) + "...";
7994 tabObject.get("labelEl").firstChild.data = tabLabel;
8000 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8001 if (a.parent_name != null && a.parent_name != "") {
8002 document.getElementById('data_parent_name' + idx).value = a.parent_name;
8004 if (a.parent_type != null && a.parent_type != "") {
8005 document.getElementById('data_parent_type' + idx).value = a.parent_type;
8007 if (a.parent_id != null && a.parent_id != "") {
8008 document.getElementById('data_parent_id' + idx).value = a.parent_id;
8010 if (a.fromAccounts.status) {
8011 var addressFrom = document.getElementById('addressFrom' + idx);
8012 SUGAR.email2.util.emptySelectOptions(addressFrom);
8013 var fromAccountOpts = a.fromAccounts.data;
8014 for(i=0; i<fromAccountOpts.length; i++) {
8015 var key = fromAccountOpts[i].value;
8016 var display = fromAccountOpts[i].text;
8017 var opt = new Option(display, key);
8018 if (fromAccountOpts[i].selected) {
8019 opt.selected = true;
8021 addressFrom.options.add(opt);
8027 failure : AjaxObject.handleFailure,
8028 timeout : AjaxObject.timeout,
8030 argument : [sendType]
8032 var callbackSendEmail = {
8033 success : AjaxObject.sendEmailCleanUp,
8034 failure : AjaxObject.handleFailure,
8035 timeout : AjaxObject.timeout,
8038 var callbackSettings = {
8039 success : AjaxObject.updateUserPrefs,
8040 failure : AjaxObject.handleFailure,
8041 timeout : AjaxObject.timeout,
8044 var callbackSettingsFolderRefresh = {
8045 success : AjaxObject.settingsFolderRefresh,
8046 failure : AjaxObject.handleFailure,
8047 timeout : AjaxObject.timeout,
8050 var callbackLoadSettingFolder = {
8051 success : function(o) {
8052 AjaxObject.settingsFolderRefresh(o);
8053 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8055 failure : AjaxObject.handleFailure,
8056 timeout : AjaxObject.timeout,
8060 var callbackUploadAttachment = {
8061 success : AjaxObject.uploadAttachmentSuccessful,
8062 upload : AjaxObject.uploadAttachmentSuccessful,
8063 failure : AjaxObject.handleFailure,
8064 timeout : AjaxObject.timeout,
8067 var callbackUserPrefs = {
8068 success : function(o) {
8069 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8071 failure : AjaxObject.handleFailure,
8072 timeout : AjaxObject.timeout,
8076 var callbackContextmenus = {
8078 success : AjaxObject.markEmailCleanup,
8079 failure : AjaxObject.handleFailure,
8080 timeout : AjaxObject.timeout,
8085 var callbackCheckEmail2 = {
8086 success : function(o) {
8087 var ret = JSON.parse(o.responseText);
8088 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8092 failure : AjaxObject.handleFailure,
8093 timeout : AjaxObject.timeout,
8095 }// End of File modules/Emails/javascript/ajax.js
8097 /*********************************************************************************
8098 * SugarCRM Community Edition is a customer relationship management program developed by
8099 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8101 * This program is free software; you can redistribute it and/or modify it under
8102 * the terms of the GNU Affero General Public License version 3 as published by the
8103 * Free Software Foundation with the addition of the following permission added
8104 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8105 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8106 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8108 * This program is distributed in the hope that it will be useful, but WITHOUT
8109 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8110 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8113 * You should have received a copy of the GNU Affero General Public License along with
8114 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8115 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8118 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8119 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8121 * The interactive user interfaces in modified source and object code versions
8122 * of this program must display Appropriate Legal Notices, as required under
8123 * Section 5 of the GNU Affero General Public License version 3.
8125 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8126 * these Appropriate Legal Notices must retain the display of the "Powered by
8127 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8128 * technical reasons, the Appropriate Legal Notices must display the words
8129 * "Powered by SugarCRM".
8130 ********************************************************************************/
8132 function gridInit() {
8133 if(SUGAR.email2.grid) {
8134 SUGAR.email2.grid.destroy();
8140 var Ck = YAHOO.util.Cookie;
8141 var widths = [ 10, 10, 150, 250, 175, 125 ];
8143 if (Ck.get("EmailGridWidths")) {
8144 for (var i=0; i < widths.length; i++) {
8145 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8148 for (var i=0; i < widths.length; i++) {
8149 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8153 // changes "F" to an icon
8154 function flaggedIcon(cell, record, column, value) {
8156 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8159 // changes "A" to replied icon
8160 function repliedIcon(cell, record, column, value) {
8162 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8165 function attachIcon(cell, record, column, value) {
8167 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8174 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8179 formatter: attachIcon,
8183 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8188 formatter: flaggedIcon,
8192 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8197 formatter: repliedIcon,
8201 label: app_strings.LBL_EMAIL_FROM,
8208 label: app_strings.LBL_EMAIL_SUBJECT,
8215 label: mod_strings.LBL_LIST_DATE,
8222 label: app_strings.LBL_EMAIL_TO,
8258 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8259 responseType: YAHOO.util.DataSource.TYPE_JSON,
8261 resultsList: 'Email',
8262 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8263 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8269 action : "EmailUIAjax",
8270 emailUIAction : "getMessageList",
8273 forceRefresh : "false"
8275 if(lazyLoadFolder != null) {
8276 params['mbox'] = lazyLoadFolder.folder;
8277 params['ieId'] = lazyLoadFolder.ieId;
8278 //Check if the folder is a Sugar Folder
8279 var test = new String(lazyLoadFolder.folder);
8280 if(test.match(/SUGAR\./)) {
8281 params['emailUIAction'] = 'getMessageListSugarFolders';
8282 params['mbox'] = test.substr(6);
8285 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8288 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8289 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8291 paginator: new YAHOO.widget.Paginator({
8292 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8293 containers : ["dt-pag-nav"],
8294 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8295 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8296 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8297 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8298 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8300 initialRequest:SUGAR.util.paramsToUrl(params),
8307 //Override Paging request construction
8308 grid.set("generateRequest", function(oState, oSelf) {
8309 oState = oState || {pagination:null, sortedBy:null};
8310 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8311 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8312 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8313 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8314 // Build the request
8316 SUGAR.util.paramsToUrl(oSelf.params) +
8319 "&start=" + startIndex +
8320 ((results !== null) ? "&limit=" + results : "");
8325 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8326 oPayload = oPayload || { };
8328 oPayload.totalRecords = oResponse.meta.total;
8329 oPayload.unreadRecords = oResponse.meta.unread;
8331 var tabObject = SE.innerLayout.get("tabs")[0];
8333 if (this.params.mbox != null) {
8334 mboxTitle = this.params.mbox;
8336 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8337 tabObject.get("labelEl").firstChild.data = tabtext;
8340 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8342 node.data.unseen = oResponse.meta.unread;
8343 SE.accounts.renderTree();
8349 var resize = grid.resizeGrid = function () {
8350 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8351 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8353 grid.convertDDRows = function() {
8354 var rowEl = this.getFirstTrEl();
8355 while (rowEl != null) {
8356 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8357 rowEl = this.getNextTrEl(rowEl);
8362 grid.on("columnResizeEvent", function(o) {
8363 //Find the index of the column
8364 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8365 for (var i=0; i < colSet.length; i++) {
8366 if (o.column == colSet[i]) {
8367 //Store it in the cookie
8368 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8371 //this.resizeGrid();
8374 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8375 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8376 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8378 SUGAR.email2.listViewLayout.on("render", resize);
8381 //Setup the default load parameters
8382 SUGAR.email2.grid.params = params;
8384 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8385 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8386 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8393 function initRowDD() {
8394 var sg = SUGAR.email2.grid,
8395 Dom = YAHOO.util.Dom;
8396 sg.DDRow = function(oDataTable, oRecord, elTr) {
8397 if(oDataTable && oRecord && elTr) {
8398 this.ddtable = oDataTable;
8399 this.table = oDataTable.getTableEl();
8402 this.newIndex = null;
8404 this.initFrame(); // Needed for DDProxy
8405 this.invalidHandleTypes = {};
8409 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8410 _resizeProxy: function() {
8411 this.constructor.superclass._resizeProxy.apply(this, arguments);
8412 var dragEl = this.getDragEl(),
8414 var xy = Dom.getXY(el);
8416 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8417 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8418 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8419 Dom.setStyle(dragEl, 'display', "");
8422 startDrag: function(x, y) {
8423 //Check if we should be dragging a set of rows rather than just the one.
8424 var selectedRows = this.ddtable.getSelectedRows();
8425 var iSelected = false;
8426 for (var i in selectedRows) {
8427 if (this.rowEl.id == selectedRows[i]) {
8434 for (var i in selectedRows) {
8435 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8438 this.rows = [this.row];
8439 this.ddtable.unselectAllRows();
8440 this.ddtable.selectRow(this.row);
8443 //Initialize the dragable proxy
8444 var dragEl = this.getDragEl();
8445 var clickEl = this.getEl();
8446 Dom.setStyle(clickEl, "opacity", "0.25");
8447 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8448 Dom.addClass(dragEl, "yui-dt-liner");
8449 Dom.setStyle(dragEl, "opacity", "0.5");
8450 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8451 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8452 Dom.setStyle(dragEl, "border", "2px solid gray");
8455 clickValidator: function(e) {
8456 if (this.row.getData()[0] == " ")
8458 var target = YAHOO.util.Event.getTarget(e);
8459 return ( this.isValidHandleChild(target) &&
8460 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8463 * This funciton checks that the target of the drag is a table row in this
8464 * DDGroup and simply moves the sourceEL to that location as a preview.
8466 onDragOver: function(ev, id) {
8467 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8468 if (node && node != this.targetNode) {
8469 this.targetNode = node;
8470 SUGAR.email2.folders.unhighliteAll();
8475 onDragOut: function(e, id) {
8476 if (this.targetNode) {
8477 SUGAR.email2.folders.unhighliteAll();
8478 this.targetNode = false;
8481 endDrag: function() {
8482 Dom.setStyle(this.getEl(), "opacity", "");
8483 Dom.setStyle(this.getDragEl(), "display", "none");
8484 if (this.targetNode) {
8485 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8487 SUGAR.email2.folders.unhighliteAll();
8493 function AddressSearchGridInit() {
8494 function moduleIcon(elCell, oRecord, oColumn, oData) {
8495 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8497 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8498 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8500 var checkHeader = '<input type="checkbox" ';
8501 if (SUGAR.email2.util.isIe()) {
8502 checkHeader += 'style="top:-5px" ';
8504 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8509 formatter: selectionCheckBox,
8513 label: mod_strings.LBL_LIST_TYPE,
8515 formatter: moduleIcon,
8519 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8525 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8531 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8532 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8534 resultsList: 'Person',
8535 fields: ['name', 'email', 'bean_id', 'bean_module'],
8536 metaFields: {total: 'TotalCount'}
8538 //enable sorting on the server accross all data
8541 dataModel.params = {
8544 action : "EmailUIAjax",
8545 emailUIAction:"getAddressSearchResults"
8547 var rb = document.getElementById('hasRelatedBean').checked;
8549 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8550 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8551 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8552 dataModel.params['related_bean_id'] = relatedBeanId;
8553 dataModel.params['related_bean_type'] = relatedBeanType;
8554 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8556 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8558 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8559 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8561 paginator: new YAHOO.widget.Paginator({
8563 containers : ["dt-pag-nav-addressbook"],
8564 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8565 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8566 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8567 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8568 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8570 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8574 //Override Paging request construction
8575 grid.set("generateRequest", function(oState, oSelf) {
8576 oState = oState || {pagination:null, sortedBy:null};
8577 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8578 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8579 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8580 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8581 // Build the request
8583 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8584 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8585 ((results !== null) ? "&limit=" + results : "");
8589 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8590 oPayload = oPayload || { };
8591 oPayload.totalRecords = oResponse.meta.total;
8595 grid.clickToggleSelect= function(args) {
8596 var isIE = (args.event.target == null);
8597 var targetElement = isIE ? args.event.srcElement : args.event.target;
8598 if(targetElement.type == null || targetElement.type != 'checkbox') {
8599 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8603 grid.reSelectRowsOnRender = function (){
8604 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8605 for (var i = 0; i < rows.length; i++)
8607 var emailAddress = rows[i].getData("email");
8608 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8611 rows[i].setData("selected", true);
8612 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8616 rows[i].setData("selected", false);
8617 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8621 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8622 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8623 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8624 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8627 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8628 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8630 grid.toggleSelectCheckbox = function(id,checked){
8631 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8632 row.setData("checked",checked);
8634 grid.toggleSelect = function(id, checked) {
8635 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8636 checked = row.getData("selected");
8639 SUGAR.email2.addressBook.grid.selectRow(row);
8640 SE.addressBook.insertContactRowToResultTable(id,null)
8643 SUGAR.email2.addressBook.grid.unselectRow(row);
8644 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8646 row.setData("selected", !checked);
8649 grid.toggleSelectAll = function(checked) {
8650 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8651 for (var i = 0; i < rows.length; i++) {
8652 if (typeof(rows[i]) != "undefined")
8653 rows[i].setData("checked", checked);
8655 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8656 for (var i = 0; i < checkBoxes.length; i++) {
8657 checkBoxes[i].checked = checked;
8661 //Initialize the grid result table.
8662 AddressSearchResultsGridInit();
8668 * Initalize the results table for the address book selection.
8671 function AddressSearchResultsGridInit()
8674 /* Full name sort funciton to compare by last name if available */
8675 var fullNameSort = function(a, b, desc) {
8676 // Deal with empty values
8677 if(!YAHOO.lang.isValue(a))
8678 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8679 else if(!YAHOO.lang.isValue(b))
8682 var aNames = a.getData("name").split(' ');
8683 var bNames = b.getData("name").split(' ');
8685 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8686 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8688 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8692 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8693 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8694 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8696 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})},
8697 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8699 var myDataSource = new YAHOO.util.DataSource([]);
8700 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8701 myDataSource.responseSchema = {
8702 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8705 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8706 width: "350px",height: "250px", MSG_EMPTY: " "});
8708 var highlightEditableCell = function(oArgs) {
8709 var elCell = oArgs.target;
8710 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8711 this.highlightCell(elCell);
8715 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8716 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8717 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8718 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8719 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8721 //Setup the context menus
8722 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8723 var task = p_aArgs[1];
8726 var elRow = this.contextEventTarget;
8727 elRow = p_myDataTable.getTrEl(elRow);
8734 var oRecord = p_myDataTable.getRecord(elRow);
8735 p_myDataTable.deleteRow(elRow);
8736 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8741 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8742 {trigger:gridResults.getTbodyEl()});
8743 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8744 contextMenu.render("addrSearchResultGrid");
8745 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8747 // End of File modules/Emails/javascript/grid.js
8749 /*********************************************************************************
8750 * SugarCRM Community Edition is a customer relationship management program developed by
8751 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8753 * This program is free software; you can redistribute it and/or modify it under
8754 * the terms of the GNU Affero General Public License version 3 as published by the
8755 * Free Software Foundation with the addition of the following permission added
8756 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8757 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8758 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8760 * This program is distributed in the hope that it will be useful, but WITHOUT
8761 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8762 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8765 * You should have received a copy of the GNU Affero General Public License along with
8766 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8767 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8770 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8771 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8773 * The interactive user interfaces in modified source and object code versions
8774 * of this program must display Appropriate Legal Notices, as required under
8775 * Section 5 of the GNU Affero General Public License version 3.
8777 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8778 * these Appropriate Legal Notices must retain the display of the "Powered by
8779 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8780 * technical reasons, the Appropriate Legal Notices must display the words
8781 * "Powered by SugarCRM".
8782 ********************************************************************************/
8787 function complexLayoutInit() {
8788 var se = SUGAR.email2;
8789 var Dom = YAHOO.util.Dom;
8791 getInnerLayout : function(rows) {
8792 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8793 parent: se.complexLayout,
8799 scroll:false, // grid should autoScroll itself
8801 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8809 body: "<div id='listBottom' />"
8817 body: "<div id='listRight' />",
8818 titlebar: false //,header: "right"
8821 se.complexLayout.on("render", function(){
8822 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8823 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8824 SUGAR.email2.listViewLayout.set("height", height);
8825 SUGAR.email2.listViewLayout.render();
8827 se.listViewLayout.render();
8829 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8830 var rp = se.listViewLayout.resizePreview = function() {
8831 var pre = Dom.get("displayEmailFramePreview");
8833 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8834 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8837 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8838 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8839 se.e2Layout.setPreviewPanel(rows);
8840 se.previewLayout = se.listViewLayout;
8841 return se.listViewLayout;
8844 getInnerLayout2Rows : function() {
8845 return this.getInnerLayout(true);
8847 getInnerLayout2Columns : function() {
8848 return this.getInnerLayout(false);
8852 // initialize state manager, we will use cookies
8853 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8854 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8855 se.complexLayout = new YAHOO.widget.Layout("container", {
8858 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8859 width: Dom.getViewportWidth() - 40,
8863 body: "<div id='emailtabs'></div>"
8868 body: "<div id='lefttabs'></div>",
8878 header: Dom.get('footerLinks').innerHTML,
8885 se.complexLayout.render();
8886 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8887 tp.addTab(new YAHOO.widget.Tab({
8890 content : "<div id='listViewDiv'/>",
8894 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8895 tp.appendTo(centerEl);
8897 tp.get("element").style.borderRight = "1px solid #666"
8899 var listV = this.getInnerLayout2Rows();
8900 listV.set("height", tp.get("element").clientHeight - 25);
8903 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8904 var folderTab = new YAHOO.widget.Tab({
8905 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8907 content : "<div id='emailtree'/>",
8911 folderTab.on("activeChange", function(o){
8913 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8916 se.leftTabs.addTab(folderTab);
8918 var tabContent = SUGAR.util.getAndRemove("searchTab");
8919 var searchTab = new YAHOO.widget.Tab({
8920 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8922 content : tabContent.innerHTML,
8925 searchTab.on("activeChange", function(o){
8928 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8929 //Setup the calendars if needed
8930 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
8931 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
8933 //Initalize sqs object for assigned user name
8934 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
8936 //Attach event handler for when the relate module option is selected for the correct sqs object
8937 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8938 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8939 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
8940 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8942 //If enter key is pressed, perform search
8943 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8944 for(var i=0; i < addKeyPressFields.length;i++)
8946 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8947 if (e.keyCode == 13) {
8948 YAHOO.util.Event.stopEvent(e);
8949 SUGAR.email2.search.searchAdvanced();
8953 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
8955 //Clear parent values if selecting another parent type.
8956 YAHOO.util.Event.addListener('data_parent_type_search','change',
8958 document.getElementById('data_parent_id_search').value ='';
8959 document.getElementById('data_parent_name_search').value ='';
8964 se.leftTabs.addTab(searchTab);
8966 var resizeTabBody = function() {
8967 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8968 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8971 se.complexLayout.on("render", resizeTabBody);
8972 se.leftTabs.on("activeTabChange", resizeTabBody);
8973 //hack to allow left pane scroll bar to fully show
8974 var lefttabsDiv = document.getElementById('lefttabs');
8975 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8976 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8977 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8980 initSQSObject: function(formName,fieldName)
8982 var fullFieldName = formName + '_' + fieldName; //SQS Convention
8983 var resultName = fullFieldName + '_' + 'results';
8985 if (QSFieldsArray[fullFieldName] != null)
8987 QSFieldsArray[fullFieldName].destroy();
8988 delete QSFieldsArray[fullFieldName];
8990 if (QSProcessedFieldsArray[fullFieldName])
8991 QSProcessedFieldsArray[fullFieldName] = false;
8993 if( Dom.get(resultName) )
8995 var obj = document.getElementById(resultName);
8996 obj.parentNode.removeChild(obj);
8999 setPreviewPanel: function(rows) {
9001 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9002 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9003 Dom.get("listRight").innerHTML = "";
9004 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9006 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9007 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9008 Dom.get("listBottom").innerHTML = "";
9009 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9016 var myBufferedListenerObject = new Object();
9017 myBufferedListenerObject.refit = function() {
9018 if(SUGAR.email2.grid) {
9019 SUGAR.email2.grid.autoSize();
9022 // End of File modules/Emails/javascript/complexLayout.js
9024 /*********************************************************************************
9025 * SugarCRM Community Edition is a customer relationship management program developed by
9026 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9028 * This program is free software; you can redistribute it and/or modify it under
9029 * the terms of the GNU Affero General Public License version 3 as published by the
9030 * Free Software Foundation with the addition of the following permission added
9031 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9032 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9033 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9035 * This program is distributed in the hope that it will be useful, but WITHOUT
9036 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9037 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9040 * You should have received a copy of the GNU Affero General Public License along with
9041 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9042 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9045 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9046 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9048 * The interactive user interfaces in modified source and object code versions
9049 * of this program must display Appropriate Legal Notices, as required under
9050 * Section 5 of the GNU Affero General Public License version 3.
9052 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9053 * these Appropriate Legal Notices must retain the display of the "Powered by
9054 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9055 * technical reasons, the Appropriate Legal Notices must display the words
9056 * "Powered by SugarCRM".
9057 ********************************************************************************/
9060 /******************************************************************************
9061 * Initialize Email 2.0 Application
9064 //Override Sugar Languge so quick creates work properly
9067 function email2init() {
9070 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9071 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9072 if (!SUGAR.util.isTouchScreen()) {
9074 convert_urls : false,
9075 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9076 width: tinyConfig.width,
9077 theme: tinyConfig.theme,
9078 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9079 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9080 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9081 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9082 plugins : tinyConfig.plugins,
9083 elements : tinyConfig.elements,
9084 language : tinyConfig.language,
9085 extended_valid_elements : tinyConfig.extended_valid_elements,
9086 mode: tinyConfig.mode,
9087 strict_loading_mode : true,
9088 force_br_newlines : true,
9089 forced_root_block : '',
9090 directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
9094 // initialze message overlay
9095 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9105 if (SUGAR.themes.tempHideLeftCol)
9106 SUGAR.themes.tempHideLeftCol();
9108 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9109 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9111 // set defaults for YAHOO.util.DragDropManager
9112 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9114 SUGAR.email2.nextYear = new Date();
9115 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9118 // initialize and display UI framework (complexLayout.js)
9119 complexLayoutInit();
9121 // initialize and display grid (grid.js)
9124 // initialize treeview for folders
9126 SUGAR.email2.folders.rebuildFolders(true);
9129 //Setup the Message Box overlay
9130 /*Ext.MessageBox.maxWidth = 350;
9131 Ext.MessageBox.minProgressWidth = 350;
9133 ///////////////////////////////////////////////////////////////////////////
9136 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9138 var SEC = SUGAR.email2.contextMenus;
9141 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9142 trigger: SUGAR.email2.grid.get("element"),
9145 emailMenu.subscribe("beforeShow", function() {
9146 var oTarget = this.contextEventTarget;
9147 if (typeof(oTarget) == "undefined")
9149 var grid = SUGAR.email2.grid;
9150 var selectedRows = grid.getSelectedRows();
9151 var multipleSelected = (selectedRows.length > 1) ? true: false;
9152 if (!multipleSelected)
9154 grid.unselectAllRows();
9155 grid.selectRow(oTarget);
9156 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9158 else if(multipleSelected)
9160 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9164 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9165 //us to access individual elements easier by name rather than by index
9166 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
9167 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9168 emailMenu.addItems([
9170 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9171 id: 'showDetailView',
9172 onclick: { fn: SEC.showDetailView }
9175 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9176 onclick: { fn: SEC.openMultiple }
9179 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9180 onclick: { fn: SEC.archiveToSugar }
9183 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9185 onclick: { fn: SEC.replyForwardEmailContext }
9188 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9190 onclick: { fn: SEC.replyForwardEmailContext }
9193 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9195 onclick: { fn: SEC.replyForwardEmailContext }
9198 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9200 onclick: { fn: SEC.markDeleted }
9203 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9205 onclick: { fn: SEC.viewPrintable }
9209 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9211 id: "markEmailMenu",
9214 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9215 onclick: { fn: SEC.markUnread }
9218 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9219 onclick: { fn: SEC.markRead }
9222 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9223 onclick: { fn: SEC.markFlagged }
9226 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9227 onclick: { fn: SEC.markUnflagged }
9233 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9235 onclick: { fn: SEC.assignEmailsTo }
9238 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9240 onclick: { fn: SEC.relateTo }
9243 SEC.emailListContextMenu.render();
9245 //Handle the Tree folder menu trigger ourselves
9246 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9250 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9254 SEC.frameFoldersContextMenu.addItems([
9255 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9256 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9257 onclick: { fn: function() {
9258 var node = SUGAR.email2.clickedFolderNode;
9259 if (node.data.ieId) {
9260 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9263 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9264 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9265 onclick: { fn: function() {
9266 var node = SUGAR.email2.clickedFolderNode;
9267 if (node.data.ieId) {
9268 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9272 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9273 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9274 onclick: { fn: SUGAR.email2.folders.folderAdd }
9277 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9278 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9279 onclick: { fn: SUGAR.email2.folders.folderDelete }
9282 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9283 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9284 onclick: { fn: SUGAR.email2.folders.folderRename }
9287 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9288 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9289 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9292 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9293 onclick: { fn: function() {
9294 var node = SUGAR.email2.clickedFolderNode;
9295 if (node.data.ieId) {
9296 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9300 SEC.frameFoldersContextMenu.render();
9302 SEC.initContactsMenu = function() {
9304 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9305 trigger: "contacts",
9308 SEC.contactsContextMenu.addItems([
9310 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9311 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9314 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9315 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9318 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9319 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9320 if (oTarget && !grid.isSelected(oTarget)) {
9321 grid.unselectAllRows();
9322 grid.selectRow(oTarget);
9325 SEC.contactsContextMenu.render();
9329 // set auto-check timer
9330 SUGAR.email2.folders.startCheckTimer();
9331 // check if we're coming from an email-link click
9332 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9334 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9336 //Init fix for YUI 2.7.0 datatable sort.
9337 SUGAR.email2.addressBook.initFixForDatatableSort();
9340 function createTreePanel(treeData, params) {
9341 var tree = new YAHOO.widget.TreeView(params.id);
9342 var root = tree.getRoot();
9344 //if (treeData.nodes && treeData[0].id == "Home")
9345 // treeData = treeData[0];
9347 addChildNodes(root, treeData);
9352 function addChildNodes(parentNode, parentData) {
9353 var Ck = YAHOO.util.Cookie;
9354 var nextyear = SUGAR.email2.nextYear;
9355 var nodes = parentData.nodes || parentData.children;
9357 if (typeof(nodes[i]) == 'object') {
9358 if (nodes[i].data) {
9359 nodes[i].data.href = '#';
9360 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9361 node.action = nodes[i].data.action;
9363 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9364 addChildNodes(parentNode, nodes[i]);
9367 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9368 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9370 nodes[i].className = nodes[i].cls;
9372 nodes[i].href = "#";
9373 if (nodes[i].text) nodes[i].label = nodes[i].text;
9374 //Override YUI child node creation
9375 if (nodes[i].children) {
9376 nodes[i].nodes = nodes[i].children;
9377 nodes[i].children = [ ];
9379 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9382 if (typeof(nodes[i].nodes) == 'object') {
9383 addChildNodes(node, nodes[i]);
9390 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9392 function email2treeinit(tree, treedata, treediv, params) {
9393 //ensure the tree data is not corrupt
9397 if (SUGAR.email2.tree) {
9398 SUGAR.email2.tree.destroy();
9399 SUGAR.email2.tree = null;
9402 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9406 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9407 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9408 tree.subscribe("expandComplete", function(node){
9409 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9410 for (var i in node.children) {
9411 SE.accounts.setupDDTarget(node.children[i]);
9414 tree.setCollapseAnim("TVSlideOut");
9415 tree.setExpandAnim("TVSlideIn");
9416 var root = tree.root;
9417 while (root.hasChildren()) {
9418 var node = root.children[0];
9420 tree.removeNode(root.children[0], false);
9422 addChildNodes(root, treedata);
9424 SUGAR.email2.accounts.renderTree();
9427 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9428 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9432 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9433 startDrag: function(x, y) {
9434 var Dom = YAHOO.util.Dom;
9435 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9438 var dragEl = this.getDragEl();
9439 var clickEl = this.getEl();
9440 Dom.setStyle(clickEl, "color", "#AAA");
9441 Dom.setStyle(clickEl, "opacity", "0.25");
9442 dragEl.innerHTML = clickEl.innerHTML;
9444 Dom.addClass(dragEl, "ygtvcell");
9445 Dom.addClass(dragEl, "ygtvcontent");
9446 Dom.addClass(dragEl, "folderDragProxy");
9447 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9448 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9449 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9450 Dom.setStyle(dragEl, "opacity", "0.5");
9451 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9454 onDragOver: function(ev, id) {
9455 var Dom = YAHOO.util.Dom;
9456 if (id != this.dragId)
9458 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9459 if(node.data.cls != "sugarFolder") {
9460 SUGAR.email2.folders.unhighliteAll();
9464 this.targetNode = node;
9465 SUGAR.email2.folders.unhighliteAll();
9470 onDragOut: function(e, id) {
9471 if (this.targetNode) {
9472 SUGAR.email2.folders.unhighliteAll();
9473 this.targetNode = false;
9474 this.dragId = false;
9478 endDrag: function() {
9479 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9480 if (this.targetNode) {
9481 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9484 });// End of File modules/Emails/javascript/init.js
9486 /*********************************************************************************
9487 * SugarCRM Community Edition is a customer relationship management program developed by
9488 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9490 * This program is free software; you can redistribute it and/or modify it under
9491 * the terms of the GNU Affero General Public License version 3 as published by the
9492 * Free Software Foundation with the addition of the following permission added
9493 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9494 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9495 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9497 * This program is distributed in the hope that it will be useful, but WITHOUT
9498 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9499 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9502 * You should have received a copy of the GNU Affero General Public License along with
9503 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9504 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9507 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9508 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9510 * The interactive user interfaces in modified source and object code versions
9511 * of this program must display Appropriate Legal Notices, as required under
9512 * Section 5 of the GNU Affero General Public License version 3.
9514 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9515 * these Appropriate Legal Notices must retain the display of the "Powered by
9516 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9517 * technical reasons, the Appropriate Legal Notices must display the words
9518 * "Powered by SugarCRM".
9519 ********************************************************************************/
9521 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9522 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9523 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9524 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9525 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9526 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9527 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9528 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9529 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9530 ' <input type="hidden" id="composeType" name="composeType">' +
9531 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9532 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9533 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9534 ' <input type="hidden" id="sendTo" name="sendTo">' +
9535 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9536 ' <input type="hidden" id="sendCc" name="sendCc">' +
9537 ' <input type="hidden" id="setEditor" name="setEditor">' +
9538 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9539 ' <input type="hidden" id="parent_id" name="parent_id">' +
9540 ' <input type="hidden" id="parent_type" name="parent_type">' +
9541 ' <input type="hidden" id="attachments" name="attachments">' +
9542 ' <input type="hidden" id="documents" name="documents">' +
9543 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9544 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9545 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9546 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9548 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9549 ' <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>' +
9550 ' <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>' +
9551 ' <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>' +
9552 ' <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>' +
9553 '</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>' +
9554 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9555 '<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>' +
9556 ' </td></tr></tbody></table></th>' +
9560 ' <div style="margin:5px;">' +
9561 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9563 ' <td class="emailUILabel" NOWRAP >' +
9564 ' {app_strings.LBL_EMAIL_FROM}:' +
9566 ' <td class="emailUIField" NOWRAP>' +
9568 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9573 ' <td class="emailUILabel" NOWRAP>' +
9574 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9575 ' {app_strings.LBL_EMAIL_TO}:' +
9578 ' <td class="emailUIField" NOWRAP>' +
9579 ' <div class="ac_autocomplete">' +
9580 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9581 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9582 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9586 ' <tr id="add_addr_options_tr{idx}">' +
9587 ' <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>'+
9589 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9590 ' <td class="emailUILabel" NOWRAP>' +
9591 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9592 ' {app_strings.LBL_EMAIL_CC}:' +
9595 ' <td class="emailUIField" NOWRAP>' +
9596 ' <div class="ac_autocomplete">' +
9597 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9598 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9599 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9603 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9604 ' <td class="emailUILabel" NOWRAP>' +
9605 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9606 ' {app_strings.LBL_EMAIL_BCC}:' +
9609 ' <td class="emailUIField" NOWRAP>' +
9610 ' <div class="ac_autocomplete">' +
9611 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9612 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9613 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9618 ' <td class="emailUILabel" NOWRAP width="1%">' +
9619 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9621 ' <td class="emailUIField" NOWRAP width="99%">' +
9622 ' <div class="ac_autocomplete">' +
9623 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9632 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9633 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9634 ' <div style="padding:5px;">' +
9635 ' <table cellpadding="2" cellspacing="0" border="0">' +
9638 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9645 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9646 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9658 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9665 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9666 ' <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>' +
9678 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9685 ' <div id="addedTemplateAttachments{idx}"></div>' +
9692 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9693 ' <div style="padding:5px;">' +
9694 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9695 ' <table border="0" width="100%">' +
9697 ' <td NOWRAP style="padding:2px;">' +
9698 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9702 ' <td NOWRAP style="padding:2px;">' +
9703 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9708 ' <table border="0" width="100%">' +
9710 ' <td NOWRAP style="padding:2px;">' +
9711 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9715 ' <td NOWRAP style="padding:2px;">' +
9716 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9720 ' <table border="0" width="100%">' +
9722 ' <td NOWRAP style="padding:2px;">' +
9723 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9724 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9732 // End of File modules/Emails/javascript/composeEmailTemplate.js
9734 /*********************************************************************************
9735 * SugarCRM Community Edition is a customer relationship management program developed by
9736 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9738 * This program is free software; you can redistribute it and/or modify it under
9739 * the terms of the GNU Affero General Public License version 3 as published by the
9740 * Free Software Foundation with the addition of the following permission added
9741 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9742 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9743 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9745 * This program is distributed in the hope that it will be useful, but WITHOUT
9746 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9747 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9750 * You should have received a copy of the GNU Affero General Public License along with
9751 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9752 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9755 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9756 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9758 * The interactive user interfaces in modified source and object code versions
9759 * of this program must display Appropriate Legal Notices, as required under
9760 * Section 5 of the GNU Affero General Public License version 3.
9762 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9763 * these Appropriate Legal Notices must retain the display of the "Powered by
9764 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9765 * technical reasons, the Appropriate Legal Notices must display the words
9766 * "Powered by SugarCRM".
9767 ********************************************************************************/
9769 SUGAR.email2.templates['displayOneEmail'] =
9770 '<div class="emailDetailTable" style="height:100%">' +
9771 '<div id="viewMenuDiv{idx}"></div>' +
9772 '<div width="100%" class="displayEmailValue">' +
9773 ' <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>' +
9774 ' <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>' +
9775 ' <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>' +
9776 ' <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>' +
9777 ' <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>' +
9778 ' <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>' +
9779 ' <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>' +
9780 ' <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>' +
9781 ' <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>' +
9783 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9785 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9786 ' {app_strings.LBL_EMAIL_FROM}:' +
9788 ' <td width="99%" class="displayEmailValue">' +
9789 ' {email.from_addr}' +
9793 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9794 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9796 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9797 ' <b>{email.name}</b>' +
9801 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9802 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9804 ' <td class="displayEmailValue">' +
9805 ' {email.date_start} {email.time_start}' +
9809 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9810 ' {app_strings.LBL_EMAIL_TO}:' +
9812 ' <td class="displayEmailValue">' +
9813 ' {email.toaddrs}' +
9816 ' <tr>{meta.cc}</tr>' +
9817 ' <tr>{email.attachments}</tr>' +
9819 ' <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>' +
9820 //' {email.description}' +
9822 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9824 /*********************************************************************************
9825 * SugarCRM Community Edition is a customer relationship management program developed by
9826 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9828 * This program is free software; you can redistribute it and/or modify it under
9829 * the terms of the GNU Affero General Public License version 3 as published by the
9830 * Free Software Foundation with the addition of the following permission added
9831 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9832 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9833 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9835 * This program is distributed in the hope that it will be useful, but WITHOUT
9836 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9837 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9840 * You should have received a copy of the GNU Affero General Public License along with
9841 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9842 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9845 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9846 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9848 * The interactive user interfaces in modified source and object code versions
9849 * of this program must display Appropriate Legal Notices, as required under
9850 * Section 5 of the GNU Affero General Public License version 3.
9852 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9853 * these Appropriate Legal Notices must retain the display of the "Powered by
9854 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9855 * technical reasons, the Appropriate Legal Notices must display the words
9856 * "Powered by SugarCRM".
9857 ********************************************************************************/
9859 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9860 '<body onload="javascript:window.print();">' +
9864 ' font-family: helvetica, impact, sans-serif;' +
9865 ' font-size : 12pt;' +
9872 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9875 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9877 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9878 ' {app_strings.LBL_EMAIL_FROM}:' +
9880 ' <td width="99%" class="displayEmailValue">' +
9881 ' {email.from_name} <{email.from_addr}>' +
9885 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9886 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9888 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9889 ' <b>{email.name}</b>' +
9893 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9894 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9896 ' <td class="displayEmailValue">' +
9897 ' {email.date_start} {email.time_start}' +
9901 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9902 ' {app_strings.LBL_EMAIL_TO}:' +
9904 ' <td class="displayEmailValue">' +
9905 ' {email.toaddrs}' +
9909 ' {email.attachments}' +
9915 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9917 ' <td style="border-top: 1px solid #333;">' +
9918 ' <div style="padding:5px;">' +
9919 '{email.description}' +
9929 // End of File modules/Emails/javascript/viewPrintable.js
9931 /*********************************************************************************
9932 * SugarCRM Community Edition is a customer relationship management program developed by
9933 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9935 * This program is free software; you can redistribute it and/or modify it under
9936 * the terms of the GNU Affero General Public License version 3 as published by the
9937 * Free Software Foundation with the addition of the following permission added
9938 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9939 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9940 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9942 * This program is distributed in the hope that it will be useful, but WITHOUT
9943 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9944 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9947 * You should have received a copy of the GNU Affero General Public License along with
9948 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9949 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9952 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9953 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9955 * The interactive user interfaces in modified source and object code versions
9956 * of this program must display Appropriate Legal Notices, as required under
9957 * Section 5 of the GNU Affero General Public License version 3.
9959 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9960 * these Appropriate Legal Notices must retain the display of the "Powered by
9961 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9962 * technical reasons, the Appropriate Legal Notices must display the words
9963 * "Powered by SugarCRM".
9964 ********************************************************************************/
9965 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9966 var Dom=YAHOO.util.Dom;var qsFields=Dom.getElementsByClassName('sqsEnabled');for(qsField in qsFields){if(typeof qsFields[qsField]=='function'||typeof qsFields[qsField].id=='undefined'){continue;}
9967 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');}
9968 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;}}
9969 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9970 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9971 if(!document.forms[qs_obj.form].elements[qsFields[qsField].id].readOnly&&qs_obj['disable']!=true){combo_id=qs_obj.form+'_'+qsFields[qsField].id;if(Dom.get(combo_id+"_results")){loaded=true}
9972 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;}}}},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="";}}
9973 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
9974 {search.clearFields=function(){};search.setFields=function(data,filter)
9975 {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])
9976 {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';}}}}
9977 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))
9978 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
9979 {if(this.inputElement.id=='shipping_account_name')
9980 {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)/;}
9981 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
9982 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9983 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];}}}
9984 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]];}
9985 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;}}}}});}
9986 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9987 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js