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 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 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;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];for(var i in properties)
299 {if(e[properties[i]])
300 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
301 newNode[properties[i]]=e[properties[i]];}}
303 {for(var i in e.childNodes)
304 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
305 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
306 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
308 /*********************************************************************************
309 * SugarCRM is a customer relationship management program developed by
310 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
312 * This program is free software; you can redistribute it and/or modify it under
313 * the terms of the GNU Affero General Public License version 3 as published by the
314 * Free Software Foundation with the addition of the following permission added
315 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
316 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
317 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
319 * This program is distributed in the hope that it will be useful, but WITHOUT
320 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
321 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
324 * You should have received a copy of the GNU Affero General Public License along with
325 * this program; if not, see http://www.gnu.org/licenses or write to the Free
326 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
329 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
330 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
332 * The interactive user interfaces in modified source and object code versions
333 * of this program must display Appropriate Legal Notices, as required under
334 * Section 5 of the GNU Affero General Public License version 3.
336 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
337 * these Appropriate Legal Notices must retain the display of the "Powered by
338 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
339 * technical reasons, the Appropriate Legal Notices must display the words
340 * "Powered by SugarCRM".
341 ********************************************************************************/
342 SUGAR.inboundEmail={};Rot13={map:null,convert:function(a){Rot13.init();var s="";for(i=0;i<a.length;i++){var b=a.charAt(i);s+=((b>='A'&&b<='Z')||(b>='a'&&b<='z')?Rot13.map[b]:b);}
343 return s;},init:function(){if(Rot13.map!=null)
344 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
345 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
346 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
347 function getEncryptedPassword(login,password,mailbox){var words=new Array(login,password,mailbox);for(i=0;i<3;i++){word=words[i];if(word.indexOf('&')>0){fragment1=word.substr(0,word.indexOf('&'));fragment2=word.substr(word.indexOf('&')+1,word.length);newWord=fragment1+'::amp::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
348 if(word.indexOf('+')>0){fragment1=word.substr(0,word.indexOf('+'));fragment2=word.substr(word.indexOf('+')+1,word.length);newWord=fragment1+'::plus::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
349 if(word.indexOf('%')>0){fragment1=word.substr(0,word.indexOf('%'));fragment2=word.substr(word.indexOf('%')+1,word.length);newWord=fragment1+'::percent::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}}
351 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName)
352 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
353 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id:'';URL='index.php?'
354 +'module='+module_name
357 +'&target='+pageTarget
358 +'&target1='+pageTarget
359 +'&server_url='+mail_server
360 +'&email_user='+words[0]
361 +'&protocol='+protocol
363 +'&email_password='+words[1]
364 +'&mailbox='+words[2]
367 +'&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)
368 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
369 this.body.style.width=w}}
370 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
371 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();}
372 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'));}
373 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
374 if(trim(formObject.email_password.value)==""&&trim(formObject.ie_id.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PASSWORD'));}
375 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
376 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
377 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
378 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";}
380 alert(out);return false;}else{return true;}}
381 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?'
382 +'module='+module_name
385 +'&target='+pageTarget
386 +'&target1='+pageTarget
387 +'&server_url='+mail_server
388 +'&email_user='+words[0]
389 +'&protocol='+protocol
391 +'&email_password='+words[1]
392 +'&mailbox='+words[2]
394 +'&personal='+isPersonal
395 +'&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)
396 this.body.style.width=w}}
397 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();}
398 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;}}}
399 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';}}}
400 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='';}
401 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
403 /*********************************************************************************
404 * SugarCRM is a customer relationship management program developed by
405 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
407 * This program is free software; you can redistribute it and/or modify it under
408 * the terms of the GNU Affero General Public License version 3 as published by the
409 * Free Software Foundation with the addition of the following permission added
410 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
411 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
412 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
414 * This program is distributed in the hope that it will be useful, but WITHOUT
415 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
416 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
419 * You should have received a copy of the GNU Affero General Public License along with
420 * this program; if not, see http://www.gnu.org/licenses or write to the Free
421 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
424 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
425 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
427 * The interactive user interfaces in modified source and object code versions
428 * of this program must display Appropriate Legal Notices, as required under
429 * Section 5 of the GNU Affero General Public License version 3.
431 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
432 * these Appropriate Legal Notices must retain the display of the "Powered by
433 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
434 * technical reasons, the Appropriate Legal Notices must display the words
435 * "Powered by SugarCRM".
436 ********************************************************************************/
439 cache : new Object(),
440 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
441 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
444 currentHtmleditor : ''
448 * preserves hits from email server
450 _setDetailCache : function(ret) {
452 var compKey = ret.meta.mbox + ret.meta.uid;
454 if(!SUGAR.email2.cache[compKey]) {
455 SUGAR.email2.cache[compKey] = ret;
460 autoSetLayout : function() {
461 var c = document.getElementById('container');
462 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
463 //Ensure a minimum height.
464 tHeight = Math.max(tHeight, 550);
465 c.style.height = tHeight + "px";
466 SUGAR.email2.complexLayout.set('height', tHeight);
467 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
468 SUGAR.email2.complexLayout.render();
469 SUGAR.email2.listViewLayout.resizePreview();
474 * Shows overlay progress message
476 function overlayModal(title, body) {
477 overlay(title, body);
479 function overlay(reqtitle, body, type, additconfig) {
481 if (typeof(additconfig) == "object") {
482 var config = additconfig;
485 config.title = reqtitle;
487 YAHOO.SUGAR.MessageBox.show(config);
490 function hideOverlay() {
491 YAHOO.SUGAR.MessageBox.hide();
493 // End of File modules/Emails/javascript/EmailUIShared.js
495 /*********************************************************************************
496 * SugarCRM is a customer relationship management program developed by
497 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
499 * This program is free software; you can redistribute it and/or modify it under
500 * the terms of the GNU Affero General Public License version 3 as published by the
501 * Free Software Foundation with the addition of the following permission added
502 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
503 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
504 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
506 * This program is distributed in the hope that it will be useful, but WITHOUT
507 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
508 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
511 * You should have received a copy of the GNU Affero General Public License along with
512 * this program; if not, see http://www.gnu.org/licenses or write to the Free
513 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
516 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
517 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
519 * The interactive user interfaces in modified source and object code versions
520 * of this program must display Appropriate Legal Notices, as required under
521 * Section 5 of the GNU Affero General Public License version 3.
523 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
524 * these Appropriate Legal Notices must retain the display of the "Powered by
525 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
526 * technical reasons, the Appropriate Legal Notices must display the words
527 * "Powered by SugarCRM".
528 ********************************************************************************/
532 var sw = YAHOO.SUGAR,
533 Event = YAHOO.util.Event,
534 Connect = YAHOO.util.Connect,
538 ///////////////////////////////////////////////////////////////////////////////
541 outboundDialog : null,
542 inboundAccountEditDialog : null,
543 inboundAccountsSettingsTable : null,
544 outboundAccountsSettingsTable : null,
545 testOutboundDialog : null,
546 errorStyle : 'input-error',
548 newAddedOutboundId : '',
551 * makes async call to retrieve an outbound instance for editting
554 editOutbound : function(obi) {
556 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
559 deleteOutbound : function(obi) {
561 if(obi.match(/^(add|line|sendmail)+/)) {
562 alert('Invalid Operation');
564 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
565 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
569 getReplyAddress : function() {
572 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
573 var addy = SE.userPrefs.current_user.emailAddresses[i];
575 if(addy.primary_address == "1") {
576 primary = addy.email_address;
579 if(addy.reply_to == "1") {
580 return addy.email_address;
588 * Called on "Accounts" tab activation event
590 lazyLoad : function() {
592 this._setupInboundAccountTable();
593 this._setupOutboundAccountTable();
597 _setupInboundAccountTable: function()
599 //Setup the inbound mail settings
600 if(!this.inboundAccountsSettingsTable)
602 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
603 var clckEvent = oColumn.key;
605 var is_group = oRecord.getData("is_group");
608 if(oColumn.key == 'edit')
610 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
611 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
613 else if(oColumn.key == 'delete')
615 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
616 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
618 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
622 this.showBoolean = function(el, oRecord, oColumn, oData)
624 var is_group = oRecord.getData("is_group");
625 var bChecked = oData;
626 bChecked = (bChecked) ? " checked" : "";
629 el.innerHTML = "<input type=\"radio\"" + bChecked +
630 " name=\"col" + oColumn.getId() + "-radio\"" +
631 " class=\"yui-dt-radio\">";
636 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
637 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
639 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
640 '<img border="0" src="themes/default/images/helpInline.gif">' +
641 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
644 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
645 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
646 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
647 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
648 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
649 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
650 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
651 this.ieDataSource = new YAHOO.util.DataSource(query);
652 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
653 this.ieDataSource.responseSchema = {
654 resultsList: "account_list",
655 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
657 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
658 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
660 var elCheckbox = oArgs.target;
661 var oColumn = this.getColumn(elCheckbox);
662 if(oColumn.key == 'is_active')
664 var oRecord = this.getRecord(elCheckbox);
665 oRecord.setData("is_active",elCheckbox.checked);
666 var t_id = oRecord.getData('id');
667 var isGroupFolder = oRecord.getData('has_groupfolder');
670 SUGAR.email2.folders.updateSubscriptions();
672 SUGAR.email2.folders.setFolderSelection();
676 var lastDefaultSelectedId = "";
677 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
679 var elRadio = oArgs.target;
680 var oColumn = this.getColumn(elRadio);
681 if(oColumn.key == 'is_default')
683 var oRecord = this.getRecord(elRadio);
684 var t_id = oRecord.getData('id');
685 var t_isGroup = oRecord.getData('is_group');
686 if(t_id != lastDefaultSelectedId && !t_isGroup)
688 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
689 lastDefaultSelectedId = t_id;
690 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
693 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
698 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
699 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
702 _setupOutboundAccountTable: function()
704 if(!this.outboundAccountsSettingsTable)
706 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
707 var clckEvent = oColumn.key;
709 var isEditable = oRecord.getData("is_editable");
710 var type = oRecord.getData("type");
713 if(oColumn.key == 'edit')
715 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
716 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
718 else if(oColumn.key == 'delete' && type == 'user')
720 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
721 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
724 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
728 //Custom formatter to display any error messages.
729 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
731 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
732 SUGAR.email2.composeLayout.outboundAccountErrors = {};
734 var id = oRecord.getData('id');
735 var message = oRecord.getData("errors");
738 elLiner.innerHTML = '<span class="required">' + message + '</span>';
739 //Add the id and message for all outbound accounts.
740 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
744 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
745 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
748 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
749 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
751 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
752 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
753 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
754 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
756 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
757 this.obDataSource = new YAHOO.util.DataSource(query);
758 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
759 this.obDataSource.responseSchema = {
761 resultsList: "outbound_account_list",
762 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
765 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
768 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
769 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
770 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
774 * Displays a modal diaglogue to edit outbound account settings
776 showEditInboundAccountDialogue : function(clear) {
778 if(!this.inboundAccountEditDialog) {
779 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
783 constraintoviewport: true,
787 EAD.showEvent.subscribe(function() {
788 var el = this.element;
789 var viewH = YAHOO.util.Dom.getViewportHeight();
790 if (this.header && el && viewH - 50 < el.clientHeight) {
791 var body = this.header.nextElementSibling;
792 body.style.overflow = "hidden";
793 body.style.height = "100%";
796 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
797 Dom.removeClass("editAccountDialogue", "yui-hidden");
801 if(clear == undefined || clear == true)
803 SE.accounts.clearInboundAccountEditScreen();
804 //Set default protocol to IMAP when creating new records
805 document.forms['ieAccount'].elements['protocol'].value = "imap";
806 SE.accounts.setPortDefault();
809 //Check if we should display username/password fields for outbound account if errors were detected.
810 this.checkOutBoundSelection();
812 this.inboundAccountEditDialog.render();
813 this.inboundAccountEditDialog.show();
817 * Set all fields on the outbound edit form to either enabled/disabled
818 * except for the username/password.
821 toggleOutboundAccountDisabledFields: function(disable)
823 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
824 for(var i=0;i<fields.length;i++)
826 document.getElementById(fields[i]).disabled = disable;
829 Dom.addClass("mail_smtpssl_row", "yui-hidden");
831 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
835 * Refresh the inbound accounts table.
837 refreshInboundAccountTable : function()
839 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
841 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
842 scope: this.inboundAccountsSettingsTable }
846 * Refresh the outbound accounts table.
848 refreshOuboundAccountTable : function()
850 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
852 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
853 scope: this.outboundAccountsSettingsTable }
857 * Displays a modal diaglogue to add a SMTP server
859 showAddSmtp : function() {
860 // lazy load dialogue
861 if(!this.outboundDialog) {
862 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
866 constraintoviewport: true,
870 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
871 this.outboundDialog.hideEvent.subscribe(function(){
872 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
873 var out = Dom.get("outbound_email");
874 if (out && out.value == "SYSTEM_ADD")
876 out.value = out.options[0].value;
878 //Check if we should display username/password for system account.
879 SE.accounts.checkOutBoundSelection();
883 Dom.removeClass("outboundDialog", "yui-hidden");
887 var form = document.getElementById('outboundEmailForm');
888 for(i=0; i<form.elements.length; i++) {
889 if(form.elements[i].name == 'mail_smtpport') {
890 form.elements[i].value = 25;
891 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
892 form.elements[i].value = '';
893 } else if(form.elements[i].type == 'checkbox') {
894 form.elements[i].checked = false;
897 //Render the SMTP buttons
898 if ( !SUGAR.smtpButtonGroup ) {
899 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
900 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
902 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
903 document.getElementById('smtp_settings').style.display = '';
904 form.mail_smtptype.value = e.newValue.get('value');
906 YAHOO.widget.Button.addHiddenFieldsToForm(form);
908 //Hide Username/Password
909 SUGAR.email2.accounts.smtp_authenticate_field_display();
910 //Unset readonly fields
911 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
912 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
913 this.outboundDialog.render();
914 this.outboundDialog.show();
918 * Accounts' Advanced Settings view toggle
920 toggleAdv : function() {
921 var adv = document.getElementById("ie_adv");
922 if(adv.style.display == 'none') {
923 adv.style.display = "";
925 adv.style.display = 'none';
929 smtp_authenticate_field_display : function() {
930 var smtpauth_req = document.getElementById("mail_smtpauth_req");
931 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
932 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
935 smtp_setDefaultSMTPPort : function() {
936 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
938 if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
939 document.getElementById("mail_smtpport").value = '465';
941 if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
942 document.getElementById("mail_smtpport").value = '25';
947 * Changes the display used in the outbound email SMTP dialog to match the
949 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
951 document.getElementById("smtpButtonGroupTD").style.display = '';
952 document.getElementById("chooseEmailProviderTD").style.display = '';
953 document.getElementById("mailsettings1").style.display = '';
954 document.getElementById("mailsettings2").style.display = '';
955 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
956 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
957 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
958 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
962 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
963 document.getElementById("mail_smtpport").value = '465';
964 document.getElementById("mail_smtpauth_req").checked = true;
965 var ssl = document.getElementById("mail_smtpssl");
966 for(var j=0;j<ssl.options.length;j++) {
967 if(ssl.options[j].text == 'SSL') {
968 ssl.options[j].selected = true;
972 document.getElementById("mailsettings1").style.display = 'none';
973 document.getElementById("mailsettings2").style.display = 'none';
974 document.getElementById("mail_smtppass_label").innerHTML =
975 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
976 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
979 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
980 document.getElementById("mail_smtpport").value = '587';
981 document.getElementById("mail_smtpauth_req").checked = true;
982 var ssl = document.getElementById("mail_smtpssl");
983 for(var j=0;j<ssl.options.length;j++) {
984 if(ssl.options[j].text == 'TLS') {
985 ssl.options[j].selected = true;
989 document.getElementById("mailsettings1").style.display = 'none';
990 document.getElementById("mailsettings2").style.display = 'none';
991 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
992 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
995 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
996 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
997 document.getElementById("mail_smtpserver").value = '';
999 document.getElementById("mail_smtpport").value = '25';
1000 document.getElementById("mail_smtpauth_req").checked = true;
1001 document.getElementById("mailsettings1").style.display = '';
1002 document.getElementById("mailsettings2").style.display = '';
1003 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1004 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1005 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1006 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1009 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1011 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1012 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1013 document.getElementById("mailsettings2").style.display = 'none';
1016 SUGAR.email2.accounts.smtp_authenticate_field_display();
1017 SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1021 * Fill the gmail default values for inbound accounts.
1023 fillInboundGmailDefaults: function () {
1025 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1026 document.forms['ieAccount'].elements['ssl'].checked = true;
1027 document.forms['ieAccount'].elements['protocol'].value = "imap";
1028 SUGAR.email2.accounts.setPortDefault();
1031 * Sets Port field to selected protocol and SSL settings defaults
1033 setPortDefault : function() {
1034 var prot = document.getElementById('protocol');
1035 var ssl = document.getElementById('ssl');
1036 var port = document.getElementById('port');
1037 var stdPorts= new Array("110", "143", "993", "995");
1038 var stdBool = new Boolean(false);
1039 var mailboxdiv = document.getElementById("mailboxdiv");
1040 var trashFolderdiv = document.getElementById("trashFolderdiv");
1041 var sentFolderdiv = document.getElementById("sentFolderdiv");
1042 var monitoredFolder = document.getElementById("subscribeFolderButton");
1043 if(port.value == '') {
1044 stdBool.value = true;
1046 for(i=0; i<stdPorts.length; i++) {
1047 if(stdPorts[i] == port.value) {
1048 stdBool.value = true;
1053 if(stdBool.value == true) {
1054 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1056 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1058 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1060 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1065 if (prot.value == 'imap') {
1066 mailboxdiv.style.display = "";
1067 trashFolderdiv.style.display = "";
1068 sentFolderdiv.style.display = "";
1069 monitoredFolder.style.display = "";
1070 if (document.getElementById('mailbox').value == "") {
1071 document.getElementById('mailbox').value = "INBOX";
1074 mailboxdiv.style.display = "none";
1075 trashFolderdiv.style.display = "none";
1076 sentFolderdiv.style.display = "none";
1077 monitoredFolder.style.display = "none";
1078 document.getElementById('mailbox').value = "";
1083 * Draws/removes red boxes around required fields.
1085 ieAccountError : function(style) {
1086 document.getElementById('server_url').className = style;
1087 document.getElementById('email_user').className = style;
1088 document.getElementById('email_password').className = style;
1089 document.getElementById('protocol').className = style;
1090 document.getElementById('port').className = style;
1093 checkOutBoundSelection: function() {
1094 var select = Dom.get('outbound_email');
1095 if (!select || select.selectedIndex == -1) { return; }
1097 var v = select.options[select.selectedIndex].value;
1101 select.options[select.selectedIndex].selected = false;
1102 v = select.options[0].value;
1104 else if (v == 'SYSTEM_ADD')
1105 SUGAR.email2.accounts.showAddSmtp();
1107 var foundError = false;
1108 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1109 for(i in errorAccounts)
1118 //Should username/password fields for outbound account.
1120 this.toggleInboundOutboundFields(true);
1122 this.toggleInboundOutboundFields(false);
1127 toggleInboundOutboundFields : function (display)
1131 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1132 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1136 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1137 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1141 * rebuilds the select options for mailer options
1143 rebuildMailerOptions : function() {
1144 var select = document.forms['ieAccount'].elements['outbound_email'];
1145 SE.util.emptySelectOptions(select);
1147 //Get the available sugar mailers
1148 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1150 for(i=0;i<a_outbound.length;i++)
1152 var t_record = a_outbound[i];
1153 var key = t_record.getData('id');
1154 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1156 var opt = new Option(display, key);
1157 select.options.add(opt);
1158 if (key == SE.accounts.newAddedOutboundId) {
1159 select.options.selectedIndex = i;
1163 select.options.add(new Option('',''));
1164 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1165 //Hide/Show username password fields if necessary.
1166 SE.accounts.checkOutBoundSelection();
1169 * Empties all the fields in the accounts edit view
1171 clearInboundAccountEditScreen:function() {
1173 document.getElementById('ie_id').value = '';
1174 document.getElementById('ie_name').value = '';
1175 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1176 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1177 document.getElementById('reply_to_addr').value = '';
1178 document.getElementById('server_url').value = '';
1179 document.getElementById('email_user').value = '';
1180 document.getElementById('email_password').value = '';
1181 document.getElementById('port').value = '';
1182 document.getElementById('inbound_mail_smtpuser').value = '';
1183 document.getElementById('inbound_mail_smtppass').value = '';
1184 document.ieAccount.protocol.options[0].selected = true;
1186 document.getElementById('ssl').checked = false;
1191 * Populates an account's fields in Settings->Accounts
1193 fillIeAccount:function(jsonstr) {
1194 var o = JSON.parse(jsonstr);
1196 document.getElementById('ie_id').value = o.id;
1197 document.getElementById('ie_name').value = o.name;
1198 if (o.stored_options != null) {
1199 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1200 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1201 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1202 if (o.stored_options.trashFolder != null) {
1203 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1205 if (o.stored_options.sentFolder != null) {
1206 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1209 document.getElementById('server_url').value = o.server_url;
1210 document.getElementById('email_user').value = o.email_user;
1211 document.getElementById('port').value = o.port;
1212 document.getElementById('group_id').value = o.group_id;
1213 document.getElementById('mailbox').value = o.mailbox;
1219 if(typeof(o.service[2]) != 'undefined') {
1220 document.getElementById('ssl').checked = true;
1224 if(document.getElementById('protocol').value != o.protocol) {
1225 var prot = document.getElementById('protocol');
1226 for(i=0; i<prot.options.length; i++) {
1227 if(prot.options[i].value == o.service[3]) {
1228 prot.options[i].selected = true;
1229 this.setPortDefault();
1233 // handle SMTP selection
1234 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1235 var opts = document.getElementById('outbound_email').options;
1236 for(i=0; i<opts.length; i++) {
1237 if(opts[i].value == o.stored_options.outbound_email) {
1238 opts[i].selected = true;
1244 deleteIeAccount : function(IeAccountID,IeGroupID) {
1245 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1247 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1249 AjaxObject.target = 'frameFlex';
1250 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1251 SUGAR.email2.accounts.refreshInboundAccountTable();
1255 // Null check for Outbound Settings.
1256 checkOutboundSettings: function() {
1257 var errorMessage = '';
1258 var isError = false;
1259 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1260 var mailName = document.getElementById('mail_name').value;
1261 var smtpServer = document.getElementById('mail_smtpserver').value;
1262 var smtpPort = document.getElementById('mail_smtpport').value;
1264 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1265 if(trim(mailName) == '') {
1267 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1269 if(trim(smtpServer) == '') {
1271 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1273 if(trim(smtpPort) == '') {
1275 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1277 if(mailsmtpauthreq.checked) {
1278 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1280 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1285 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1292 testOutboundSettings: function() {
1293 var errorMessage = '';
1294 var isError = false;
1295 var fromAddress = document.getElementById("outboundtest_from_address").value;
1296 if (trim(fromAddress) == "") {
1297 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1298 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1302 else if (!isValidEmail(fromAddress)) {
1303 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1304 overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1308 //Hide the dialogue and show an in progress indicator.
1309 SE.accounts.testOutboundDialog.hide();
1310 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1312 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1313 //nothing is sent in the request.
1314 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1315 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1317 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1318 if(outboundType == 'system-override')
1319 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1321 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1322 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1326 testOutboundSettingsDialog: function() {
1327 //Ensure that all settings are correct before proceeding to send test email.
1328 if(!SE.accounts.checkOutboundSettings())
1331 // lazy load dialogue
1332 if(!SE.accounts.testOutboundDialog) {
1333 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1337 constraintoviewport: true,
1341 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1342 Dom.removeClass("testOutboundDialog", "yui-hidden");
1344 SE.accounts.testOutboundDialog.render();
1345 SE.accounts.testOutboundDialog.show();
1349 * Saves Outbound email settings
1351 saveOutboundSettings : function() {
1352 if(SE.accounts.checkOutboundSettings()) {
1353 //Enable the form fields for the post.
1354 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1355 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1356 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1362 saveIeAccount : function() {
1364 //Before saving check if there are any error messages associated with the outbound account.
1365 var outboundID = document.getElementById('outbound_email').value;
1367 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1368 'validateSMTPCreds':true}) )
1370 document.getElementById('saveButton').disabled = true;
1372 overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1374 var formObject = document.getElementById('ieAccount');
1375 YAHOO.util.Connect.setForm(formObject);
1377 AjaxObject._reset();
1378 AjaxObject.target = 'frameFlex';
1379 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1383 testSettings : function() {
1384 form = document.getElementById('ieAccount');
1386 if(SE.accounts.checkIeCreds()) {
1387 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");
1391 getFoldersListForInboundAccountForEmail2 : function() {
1392 form = document.getElementById('ieAccount');
1393 if(SE.accounts.checkIeCreds()) {
1394 var mailBoxValue = form.mailbox.value;
1395 if (form.searchField.value.length > 0) {
1398 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 );
1403 checkIeCreds : function(validateRules) {
1404 if(typeof(validateRules) == 'undefined')
1407 var errors = new Array();
1408 var out = new String();
1410 var ie_name = Dom.get('ie_name').value;
1411 var fromAddress = Dom.get('ie_from_addr').value;
1412 var server_url = Dom.get('server_url').value;
1413 var email_user = Dom.get('email_user').value;
1414 var email_password = Dom.get('email_password').value;
1415 var protocol = Dom.get('protocol').value;
1416 var port = Dom.get('port').value;
1417 var oe = Dom.get('outbound_email');
1418 var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1420 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1421 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1423 //If the username and password were provided then ignore the error messge
1425 var outboundCredentialsFound = false;
1427 if(outboundUserName != "" && outboundPass != "")
1428 outboundCredentialsFound = true;
1430 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1432 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1433 && validateSMTPCreds)
1435 if(trim(outboundUserName) == "") {
1436 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1438 if(trim(outboundPass) == "") {
1439 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1443 if(trim(ie_name) == "") {
1444 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1447 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1449 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1450 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1455 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1456 || trim(oe_value) == "SYSTEM_ADD") ) {
1457 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1459 if(trim(server_url) == "") {
1460 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1462 if(trim(email_user) == "") {
1463 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1465 if(protocol == "") {
1466 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1468 if (protocol == 'imap') {
1469 var mailbox = document.getElementById('mailbox').value;
1470 if (trim(mailbox) == "") {
1471 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1473 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1474 var trashFolder = document.getElementById('trashFolder').value;
1475 if (trim(trashFolder) == "") {
1476 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1481 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1484 if(errors.length > 0) {
1485 out = app_strings.LBL_EMAIL_ERROR_DESC;
1486 for(i=0; i<errors.length; i++) {
1501 getIeAccount : function(ieId) {
1505 overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1506 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1508 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1512 * Iterates through TreeView nodes to apply styles dependent nature of node
1514 renderTree:function() {
1515 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1519 //Sets the style for any nodes that need it.
1520 setNodeStyle : function(node) {
1521 if (!node.data.origText) {
1522 node.data.origText = node.data.text;
1525 if (typeof(node.data.unseen) != 'undefined') {
1526 if (node.data.unseen > 0) {
1527 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1530 node.setUpLabel(node.data.origText);
1533 node.setUpLabel('<span>' + node.data.origText + '</span>');
1535 SE.accounts.setupDDTarget(node);
1538 setupDDTarget : function(node) {
1539 if (node.ddTarget) {
1540 node.ddTarget.removeFromGroup();
1541 delete node.ddTarget;
1543 var id = node.getElId();
1544 var num = id.substring(4);
1545 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1546 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1547 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1549 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1551 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1552 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1557 * Async call to rebuild the folder list. After a folder delete or account delete
1559 rebuildFolderList : function() {
1560 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1561 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1565 * Returns the number of remote accounts the user has active.
1567 getAccountCount : function() {
1570 for(i=0; i<tree._nodes.length; i++) {
1571 var node = tree._nodes[i];
1573 if(typeof(node) != 'undefined' && node.data.ieId) {
1581 ///////////////////////////////////////////////////////////////////////////////
1586 ///////////////////////////////////////////////////////////////////////////////
1587 //// CONTEXT MENU CALLS
1590 assignToDialogue : null,
1592 * Archives from context menu
1594 * @param string ieId
1595 * @param string folder
1597 _archiveToSugar : function(uids, ieId, folder) {
1600 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1601 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1604 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1608 * Archives from context menu
1610 archiveToSugar : function(menuItem) {
1611 SE.contextMenus.emailListContextMenu.hide();
1613 var rows = SE.grid.getSelectedRows();
1615 /* iterate through available rows JIC a row is deleted - use first available */
1616 for(var i=0; i<rows.length; i++) {
1617 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1619 var data = SE.grid.getRecord(rows[0]).getData();
1620 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1624 * Popup the printable version and start system's print function.
1626 viewPrintable : function(menuItem) {
1627 var rows = SE.grid.getSelectedRows();
1628 var data = SE.grid.getRecord(rows[0]).getData();
1629 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1633 * Marks email flagged on mail server
1635 markRead : function(type, contextMenuId) {
1636 SE.contextMenus.markEmail('read');
1640 * Assign this emails to people based on assignment rules
1642 assignEmailsTo : function(type, contextMenuId) {
1643 if(!SE.contextMenus.assignToDialogue)
1645 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1649 constraintoviewport: true,
1653 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1657 Dom.removeClass("assignToDiv", "yui-hidden");
1658 SE.contextMenus.assignToDialogue.render();
1659 SE.contextMenus.assignToDialogue.show();
1663 * Marks email flagged on mail server
1665 markFlagged : function(contextMenuId) {
1666 SE.contextMenus.markEmail('flagged');
1670 * Marks email unflagged on mail server
1672 markUnflagged : function(contextMenuId) {
1673 SE.contextMenus.markEmail('unflagged');
1677 * Marks email unread on mail server
1679 markUnread : function() {
1680 SE.contextMenus.markEmail('unread');
1684 * Deletes an email from context menu
1686 markDeleted : function() {
1687 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1688 document.getElementById('_blank').innerHTML = "";
1689 SE.contextMenus.markEmail('deleted');
1694 * generic call API to apply a flag to emails on the server and on sugar
1695 * @param string type "read" | "unread" | "flagged" | "deleted"
1697 markEmail : function(type) {
1698 SE.contextMenus.emailListContextMenu.hide();
1700 //var dm = SE.grid.getStore();
1701 //var uids = SE.grid.getSelectedRowIds();
1702 //var indexes = SE.grid.getSelectedRowIndexes();
1703 var rows = SE.grid.getSelectedRows();
1704 if (rows.length == 0)
1705 rows = [SE.contextMenus.currentRow];
1708 for(var i=0; i<rows.length; i++) {
1709 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1712 ser = YAHOO.lang.JSON.stringify(ser);
1714 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1715 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1721 if(type == 'read' || type == 'deleted') {
1723 for(var j=0; j<rows.length; j++) {
1724 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1726 SE.grid.getRecord(rows[j]).setData("seen", "1");
1729 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1731 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1732 var unseenCount = node.data.unseen;
1733 if (isNaN(unseenCount)) {
1736 var finalCount = parseInt(unseenCount) - count;
1737 node.data.unseen = finalCount;
1739 SE.accounts.renderTree();
1741 } else if(type == 'unread') {
1743 for(var j=0; j<rows.length; j++) {
1744 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1749 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1750 var unseenCount = node.data.unseen;
1751 if (isNaN(unseenCount)) {
1754 var finalCount = parseInt(unseenCount) + count;
1755 node.data.unseen = finalCount;
1756 SE.accounts.renderTree();
1759 if (type == 'unread') {
1760 for(var i=0; i<rows.length; i++) {
1761 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1765 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1766 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1770 * refreshes the ListView to show changes to cache
1772 markEmailCleanup : function() {
1773 SE.accounts.renderTree();
1775 SE.listView.refreshGrid();
1778 showAssignmentDialog : function() {
1779 if (SE.contextMenus.assignmentDialog == null) {
1780 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1782 SE.contextMenus.assignmentDialog.show();
1787 * shows the import dialog with only relate visible.
1789 relateTo : function() {
1790 SE.contextMenus.emailListContextMenu.hide();
1792 var rows = SE.grid.getSelectedRows();
1793 var data = SE.grid.getRecord(rows[0]).getData();
1794 var ieId = data.ieId;
1795 var folder = data.mbox;
1797 /* iterate through available rows JIC a row is deleted - use first available */
1798 for(var i=0; i<rows.length; i++) {
1799 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1801 var ser = JSON.stringifyNoSecurity(uids);
1803 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1807 * shows the import dialog with only relate visible.
1809 showDetailView : function() {
1810 SE.contextMenus.emailListContextMenu.hide();
1811 var rows = SE.grid.getSelectedRows();
1812 if (rows.length > 1) {
1813 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1816 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1817 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1818 /* iterate through available rows JIC a row is deleted - use first available */
1819 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1820 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1826 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1827 overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1828 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1832 * Opens multiple messages from ListView context click
1834 openMultiple : function() {
1835 SE.contextMenus.emailListContextMenu.hide();
1837 var rows = SE.grid.getSelectedRows();
1838 var uids = SE.listView.getUidsFromSelection();
1840 if(uids.length > 0) {
1841 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1842 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1843 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1848 * Replies/forwards email
1850 replyForwardEmailContext : function() {
1851 SE.contextMenus.emailListContextMenu.hide();
1853 var indexes = SE.grid.getSelectedRows();
1854 //var dm = SE.grid.getDataModel();
1857 for(var i=0; i<indexes.length; i++) {
1858 var row = SE.grid.getRecord(indexes[i]).getData();
1859 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1863 //show menu functions
1864 showEmailsListMenu : function(grid, row) {
1866 var data = row.getData();
1867 var draft = (data.type == "draft");
1868 var menu = SE.contextMenus.emailListContextMenu;
1873 if (data.mbox == 'sugar::Emails')
1874 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1876 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1878 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1879 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1880 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1881 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1883 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1886 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1888 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1889 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1890 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1891 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1892 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1895 if (data.mbox == "sugar::Emails")
1897 //Allow users to reassign imported emails
1898 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1899 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1900 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1901 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1905 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1906 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1910 showFolderMenu : function(grid, rowIndex, event) {
1912 var coords = event.getXY();
1913 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1917 SE.contextMenus.dv = {
1918 archiveToSugar : function(contextMenuId) {
1920 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1923 replyForwardEmailContext : function(all) {
1924 SE.contextMenus.detailViewContextMenu.hide();
1933 //// END SE.contextMenus
1934 ///////////////////////////////////////////////////////////////////////////////
1938 ///////////////////////////////////////////////////////////////////////////////
1941 consumeMetaDetail : function(ret) {
1942 // handling if the Email drafts
1943 if(ret.type == 'draft') {
1944 SE.composeLayout.c0_composeDraft();
1949 // cache contents browser-side
1950 SE._setDetailCache(ret);
1952 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1953 // 2 below must be in global context
1955 meta['panelId'] = SE.util.getPanelId();
1957 email = ret.meta.email;
1958 var out = displayTemplate.exec({
1959 'app_strings' : app_strings,
1961 'idx' : targetDiv.id,
1963 'email' : meta.email,
1964 'linkBeans' : linkBeans
1966 var tabLabel = meta.email.name;
1967 if (tabLabel != null && tabLabel.length > 25) {
1968 tabLabel = tabLabel.substring(0, 25) + "...";
1970 targetDiv.set("label", tabLabel);
1971 targetDiv.set("content", out);
1973 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1974 if (SUGAR.email2.util.isIe()) {
1975 displayEmailFrameDiv.style.height = "390px";
1977 displayEmailFrameDiv.style.height = "410px";
1980 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1981 displayFrame.contentWindow.document.write(email.description);
1982 displayFrame.contentWindow.document.close();
1984 // hide archive links
1985 if(ret.meta.is_sugarEmail) {
1986 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1987 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1989 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1990 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1995 consumeMetaPreview : function(ret) {
1996 // cache contents browser-side
1997 SE._setDetailCache(ret);
2001 var currrow = SE.grid.getLastSelectedRecord();
2002 currrow = SE.grid.getRecord(currrow);
2004 document.getElementById('_blank').innerHTML = '';
2007 // handling if the Email drafts
2008 if(ret.type == 'draft'){
2009 if (currrow.getData().uid == ret.uid) {
2010 SE.composeLayout.c0_composeDraft();
2015 if (currrow.getData().uid != ret.meta.uid) {
2019 // remove loading sprite
2020 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2021 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2023 meta['panelId'] = SE.util.getPanelId();
2024 email = ret.meta.email;
2026 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2027 'app_strings' : app_strings,
2031 'email' :meta.email,
2032 'linkBeans' : linkBeans
2034 // document.getElementById('_blank').innerHTML = meta.email;
2035 /* displayTemplate.append('_blank', {
2036 'app_strings' : app_strings,
2040 'email' :meta.email,
2041 'linkBeans' : linkBeans
2044 var displayFrame = document.getElementById('displayEmailFramePreview');
2045 displayFrame.contentWindow.document.write(email.description);
2046 displayFrame.contentWindow.document.close();
2048 SE.listViewLayout.resizePreview();
2050 // hide archive links
2051 if(ret.meta.is_sugarEmail) {
2052 document.getElementById("archiveEmailPreview").innerHTML = " ";
2053 document.getElementById("btnEmailViewPreview").style.display = "none";
2054 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2056 //hide view relationship link
2057 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2062 * wraps emailDelete() for single messages, comes from preview or tab
2064 emailDeleteSingle : function(ieId, uid, mbox) {
2065 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2066 // find active panel and close if the user double clicked the email to view.
2067 var activeTabId = SE.util.getPanelId();
2068 if(activeTabId != 'Preview')
2069 SE.innerLayout.get("activeTab").close();
2071 document.getElementById('_blank').innerHTML = "";
2074 uid = JSON.stringifyNoSecurity(ser);
2075 this.emailDelete(ieId, uid, mbox);
2080 * Sends async call to delete a given message
2083 emailDelete : function(ieId, uid, mbox) {
2084 overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2085 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2086 uid + "&ieId=" + ieId + "&folder=" + mbox);
2090 * retrieves one email to display in the preview pane.
2092 getEmailPreview : function() {
2093 var row = SUGAR.email2.listView.currentRow;
2094 var data = row.getData();
2095 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2096 var setRead = (data['seen'] == 0) ? true : false;
2097 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2098 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2103 * Imports one email into Sugar
2105 importEmail : function(ieId, uid, mbox) {
2106 SE.util.clearHiddenFieldValues('emailUIForm');
2108 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2110 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2111 AjaxObject.target = '';
2112 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2116 * Populates the frameFlex div with the contents of an email
2118 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2119 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2121 var mboxStr = new String(mbox);
2122 var compKey = mbox + uid;
2124 if(setRead == true) {
2125 SE.listView.boldUnreadRows()
2126 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2129 if(destination == SE.innerLayout) {
2131 * loading email into a tab, peer with ListView
2132 * targetDiv must remain in the global namespace as it is used by AjaxObject
2134 //Check if we already have a tab of the email open
2135 var tabs = SE.innerLayout.get("tabs");
2136 for (var t in tabs) {
2137 if (tabs[t].id && tabs[t].id == uid) {
2138 SE.innerLayout.set("activeTab", tabs[t]);
2143 targetDiv = new YAHOO.SUGAR.ClosableTab({
2144 label: loadingSprite,
2150 SE.innerLayout.addTab(targetDiv);
2152 // use cache if available
2153 if(SE.cache[compKey]) {
2154 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2156 // open email as peer-tab to listView
2157 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2158 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2161 // loading email into preview pane
2162 document.getElementById('_blank').innerHTML = loadingSprite;
2164 // use cache if available
2165 if(SE.cache[compKey]) {
2166 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2168 AjaxObject.forceAbort = true;
2169 // open in preview window
2170 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2171 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2176 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2178 if(mboxStr.substring(0,7) == 'sugar::') {
2179 // display an email from Sugar
2180 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2182 // display an email from an email server
2183 document.getElementById('emailUIAction').value = 'getSingleMessage';
2185 document.getElementById('mbox').value = mbox;
2186 document.getElementById('ieId').value = ieId;
2187 document.getElementById('uid').value = uid;
2189 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2191 AjaxObject.forceAbort = true;
2192 AjaxObject.target = '_blank';
2193 AjaxObject.startRequest(callback, null);
2197 * Retrieves multiple emails for DetailView
2199 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2200 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2201 SE.util.clearHiddenFieldValues('emailUIForm');
2203 var mboxStr = new String(mbox);
2205 uids = SE.util.cleanUids(uids);
2207 if(mboxStr.substring(0,7) == 'sugar::') {
2208 // display an email from Sugar
2209 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2210 document.getElementById('uid').value = uids;
2212 // display an email from an email server
2213 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2214 document.getElementById('mbox').value = mbox;
2215 document.getElementById('ieId').value = ieId;
2216 document.getElementById('uid').value = uids;
2219 var formObject = document.getElementById('emailUIForm');
2220 YAHOO.util.Connect.setForm(formObject);
2222 AjaxObject.target = 'frameFlex';
2223 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2225 if(setRead == true) {
2226 var c = uids.split(",");
2227 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2232 * Makes async call to get QuickCreate form
2233 * Renders a modal edit view for a given module
2235 quickCreate : function(module, ieId, uid, mailbox) {
2236 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2238 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2239 get += "&sugarEmail=true";
2242 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2246 * Makes async call to save a quick create
2249 saveQuickCreate : function(action) {
2250 var qcd = SE.detailView.quickCreateDialog;
2251 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2252 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2253 var theCallback = callbackQuickCreateSave;
2254 var accountType = '&sugarEmail=true';
2255 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2256 accountType = '&ieId=' + qcd.ieId;
2259 if (action == 'reply') {
2260 theCallback = callbackQuickCreateSaveAndReply;
2261 } else if (action == true) {
2262 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2264 formObject.action.value = 'EmailUIAjax';
2265 YAHOO.util.Connect.setForm(formObject);
2266 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2267 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2268 accountType + '&mbox=' + qcd.mbox);
2273 * Code to show/hide long list of email address in DetailView
2275 showCroppedEmailList : function(el) {
2276 el.style.display = 'none';
2277 el.previousSibling.style.display = 'inline'
2279 showFullEmailList : function(el) {
2280 el.style.display = 'none';
2281 el.nextSibling.style.display = 'inline';
2285 * Shows the QuickCreate overlay
2286 * @param string ieId
2288 * @param string mailbox
2290 showQuickCreate : function(ieId, uid, mailbox) {
2291 var panelId = SE.util.getPanelId();
2292 var context = document.getElementById("quickCreateSpan" + panelId);
2294 if (!SE.detailView.cqMenus)
2295 SE.detailView.cqMenus = {};
2297 if (SE.detailView.cqMenus[context])
2298 SE.detailView.cqMenus[context].destroy();
2300 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2302 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2305 for (var i=0; i < this.qcmodules.length; i++) {
2306 var module = this.qcmodules[i];
2308 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2311 onclick: { fn: function() {
2312 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2318 menu.render(document.body);
2323 * Displays the "View" submenu in the detailView
2324 * @param string ieId
2326 * @param string mailbox
2328 showViewMenu : function(ieId, uid, mailbox) {
2329 var panelId = SE.util.getPanelId();
2330 var context = "btnEmailView" + panelId;
2331 if (!SE.detailView.viewMenus)
2332 SE.detailView.viewMenus = {};
2334 if (SE.detailView.viewMenus[context])
2335 SE.detailView.viewMenus[context].destroy();
2337 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2339 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2343 (ieId == 'null' || ieId == null) ?
2344 //No ieId - Sugar Email
2346 text: app_strings.LBL_EMAIL_VIEW_RAW,
2347 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2350 //IeID exists, on a remote server
2352 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2353 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2355 text: app_strings.LBL_EMAIL_VIEW_RAW,
2356 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2359 menu.render(document.body);
2364 //#23108 jchi@07/17/2008
2365 menu.render('quickCreateSpan'+ panelId);*/
2366 //this.viewMenu = menu;
2367 //this.viewMenu.show(context);
2370 * Makes async call to get an email's headers
2372 viewHeaders : function(ieId, uid, mailbox) {
2373 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2374 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2378 * Makes async call to get a printable version
2380 viewPrintable : function(ieId, uid, mailbox) {
2381 if(mailbox == 'sugar::Emails') {
2382 // display an email from Sugar
2383 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2385 // display an email from an email server
2386 var emailUIAction = '&emailUIAction=getSingleMessage';
2389 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2390 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2394 * Makes async call to get an email's raw source
2396 viewRaw : function(ieId, uid, mailbox) {
2397 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2398 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2402 * Display all email addresses in detailview.
2404 displayAllAddrs : function(el) {
2405 el.style.display = 'none';
2406 Dom.getNextSibling(el).style.display = 'inline';
2409 //// END SE.detailView
2410 ///////////////////////////////////////////////////////////////////////////////
2414 ///////////////////////////////////////////////////////////////////////////////
2417 contextMenuFocus : new Object(),
2420 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2421 * SugarFolder ID - folder strings
2423 _createFolderId : function(node) {
2429 if(node.data.ieId) {
2430 /* we have a local Sugar folder */
2431 if(node.data.ieId == 'folder') {
2432 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2433 } else if(node.data.ieId.match(SE.reGUID)) {
2434 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2443 addChildNode : function(parentNode, childNode) {
2444 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2445 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2446 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2448 if(childNode.nodes) {
2449 if(childNode.nodes.length > 0) {
2450 for(j=0; j<childNode.nodes.length; j++) {
2451 var newChildNode = childNode.nodes[j];
2452 this.addChildNode(node, newChildNode);
2459 * Builds and returns a new TreeView Node
2460 * @param string name
2462 * @param int is_group
2465 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2466 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2468 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2469 node.expanded = expanded;
2470 node.data = new Object;
2471 node.data['id'] = id;
2472 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2473 node.data['label'] = name;
2474 node.data['ieId'] = 'folder';
2475 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2476 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2477 node.data['unseen'] = unseen;
2482 * ensures that a new folder has a valid name
2484 checkFolderName : function(name) {
2488 this.folderAdd(name);
2492 * Pings email servers for new email - forces refresh of folder pane
2494 checkEmailAccounts : function() {
2495 this.checkEmailAccountsSilent(true);
2498 checkEmailAccountsSilent : function(showOverlay) {
2499 if(typeof(SE.folders.checkingMail)) {
2500 clearTimeout(SE.folders.checkingMail);
2503 // don't stomp an on-going request
2504 if(AjaxObject.currentRequestObject.conn == null) {
2506 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2507 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2509 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2511 // wait 5 secs before trying again.
2512 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2517 * Starts check of all email Accounts using a loading bar for large POP accounts
2519 startEmailAccountCheck : function() {
2520 // don't do two checks at the same time
2521 if(!AjaxObject.requestInProgress()) {
2522 overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2523 SE.accounts.ieIds = SE.folders.getIeIds();
2524 if (SE.accounts.ieIds.length > 0) {
2525 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2526 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2531 // wait 5 secs before trying again.
2532 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2537 * Checks a single Account check based on passed ieId
2539 startEmailCheckOneAccount : function(ieId, synch) {
2546 var node = SE.clickedFolderNode;
2547 if (node && !synch) {
2548 mbox = node.data.mbox;
2550 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2551 SE.accounts.ieIds = [ieId];
2552 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2553 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2558 * Empties trash for subscribed accounts
2560 emptyTrash : function() {
2561 SE.contextMenus.frameFoldersContextMenu.hide();
2562 overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2563 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2567 * Clears Cache files of the inboundemail account
2569 clearCacheFiles : function(ieId) {
2570 SE.contextMenus.frameFoldersContextMenu.hide();
2571 overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2572 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2577 * Returns an array of all the active accounts in the folder view
2579 getIeIds : function() {
2581 var root = SE.tree.getRoot();
2582 for(i=0; i < root.children.length; i++) {
2583 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2584 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2585 ieIds.push(root.children[i].children[0].data.ieId);
2592 * loads folder lists in Settings->Folders
2594 lazyLoadSettings : function() {
2595 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2596 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2600 * After the add new folder is done via folders tab on seetings, this function should get called
2601 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2603 loadSettingFolder : function() {
2604 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2605 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2609 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2611 removeSugarFolders : function() {
2613 var root = tree.getRoot();
2614 var folder = SE.util.findChildNode(root, "ieId", "folder");
2616 tree.removeNode(folder);
2617 folder = SE.util.findChildNode(root, "ieId", "folder");
2619 if (!root.childrenRendered) {
2620 root.childrenRendered = true;
2624 rebuildFolders : function(silent) {
2625 if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2626 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2632 * Updates TreeView with Sugar Folders
2634 setSugarFolders : function(delay) {
2635 this.removeSugarFolders();
2636 //AjaxObject.forceAbort = true;
2637 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2641 * Takes async data object and creates the sugar folders in TreeView
2643 setSugarFoldersEnd : function(o) {
2644 var root = SE.tree.getRoot();
2645 addChildNodes(root, {nodes: o});
2646 SE.accounts.renderTree();
2647 //If nothing is loaded in the grid, load "My Inbox"
2648 if (SE.grid.params.ieId == "undefined") {
2649 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2653 startCheckTimer : function() {
2654 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2655 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2657 if(typeof(SE.folders.checkTimer) != 'undefined') {
2658 clearTimeout(SE.folders.checkTimer);
2661 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2662 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2664 SE.userPrefs.emailSettings.firstAutoCheck = true;
2665 SE.folders.checkEmailAccountsSilent(false);
2671 * makes an async call to save user preference and refresh folder view
2672 * @param object SELECT list object
2674 setFolderSelection : function() {
2675 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2677 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2678 var a_active_accnts = "";
2679 for(i=0;i<a_rs.length;i++)
2681 var t_record = a_rs[i];
2682 var is_active = t_record.getData('is_active');
2684 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2687 if(a_active_accnts == "")
2688 a_active_accnts = "&ieIdShow[]=";
2690 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2692 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2696 * makes async call to save user preference for a given node's open state
2697 * @param object node YUI TextNode object
2699 setOpenState : function(node) {
2700 SE.util.clearHiddenFieldValues('emailUIForm');
2701 var nodePath = node.data.id;
2702 var nodeParent = node.parent;
2704 while(nodeParent != null) {
2705 // root node has no ID param
2706 if(nodeParent.data != null) {
2707 nodePath = nodeParent.data.id + "::" + nodePath;
2710 var nodeParent = nodeParent.parent;
2713 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2714 document.getElementById('focusFolder').value = nodePath;
2716 if(node.expanded == true) {
2717 document.getElementById('focusFolderOpen').value = 'open';
2719 document.getElementById('focusFolderOpen').value = 'closed';
2722 var formObject = document.getElementById('emailUIForm');
2723 YAHOO.util.Connect.setForm(formObject);
2725 AjaxObject.startRequest(null, null);
2728 getNodeFromMboxPath : function(path) {
2729 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2730 var a = JSON.parse(path);
2732 var node = tree.getRoot();
2735 while(i < a.length) {
2736 node = this.getChildNodeFromLabel(node, a[i]);
2743 getChildNodeFromLabel : function(node, nodeLabel) {
2744 for(i=0; i<node.children.length; i++) {
2745 if(node.children[i].data.id == nodeLabel) {
2746 return node.children[i];
2752 * returns the node that presumably under the user's right-click
2754 getNodeFromContextMenuFocus : function() {
2755 //// get the target(parent) node
2756 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2758 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2760 // filter local folders
2761 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2762 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2763 if(target.id == '') {
2764 target = target.parentNode;
2771 var targetNode = document.getElementById(target.id);
2772 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2775 var matches = re.exec(targetNode.id);
2777 return document.getElementById(ygtvlabelel1);
2783 // usually parent node
2784 matches = re.exec(targetNode.parentNode.id);
2791 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2792 parentNode.expand();
2798 * Decrements the Unread Email count in folder text
2799 * @param string ieId ID to look for
2800 * @param string mailbox name
2801 * @param count how many to decrement
2803 decrementUnreadCount : function(ieId, mbox, count) {
2808 if(mbox.indexOf("sugar::") === 0) {
2809 var node = this.getNodeFromId(ieId);
2811 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2814 var unseen = node.data.unseen;
2816 var check = unseen - count;
2817 var finalCount = (check >= 0) ? check : 0;
2818 node.data.unseen = finalCount;
2820 SE.accounts.renderTree();
2825 * gets the TreeView node with a given ID/ieId
2826 * @param string id ID to look for
2827 * @return object Node
2829 getNodeFromId : function(id) {
2830 SE.folders.focusNode = null;
2831 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2832 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2833 SE.folders.focusNode = this;
2837 return SE.folders.focusNode;
2841 * Uses ieId and mailbox to try to find a node in the tree
2843 getNodeFromIeIdAndMailbox : function(id, mbox) {
2844 SE.folders.focusNode = null;
2845 if (mbox == "sugar::Emails") {
2849 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2850 if (varsarray instanceof Array) {
2851 if (this.data.ieId && this.data.ieId == varsarray[0]
2852 && this.data.mbox == varsarray[1]) {
2853 SE.folders.focusNode = this;
2857 if (this.data.ieId && this.data.ieId == varsarray) {
2858 SE.folders.focusNode = this;
2862 }, null, [id, mbox]);
2863 return SE.folders.focusNode;
2866 unhighliteAll : function() {
2867 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2871 * Displays a short form
2873 folderAdd : function() {
2874 SE.contextMenus.frameFoldersContextMenu.hide();
2876 var node = SE.clickedFolderNode;
2878 if(node != null && node.data) {
2879 overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2880 app_strings.LBL_EMAIL_SETTINGS_NAME,
2881 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2883 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2887 folderAddRegisterEnter : function() {
2888 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2889 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2890 this.buttons[1].handler);
2892 this.enterKeyListener.enable();
2895 folderRemoveRegisterEnter : function() {
2896 this.enterKeyListener.disable();
2899 folderAddXmlCall : function(name) {
2900 if (trim(name) == "") {
2901 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2904 name = escape(name);
2908 var parentNode = SE.clickedFolderNode;
2910 this.contextMenuFocus = parentNode;
2912 if(parentNode.data.ieId) {
2913 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2917 if(type == 'imap') {
2918 // make an IMAP folder
2919 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2920 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2921 } else if(type == 'sugar') {
2922 // make a Sugar folder
2923 if(SE.folders.isUniqueFolderName(name)) {
2924 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2925 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2927 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2928 SE.folders.folderAdd();
2932 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2935 // hide add-folder diaglogue
2936 SE.e2overlay.hide();
2940 * Removes either an IMAP folder or a Sugar Folder
2942 folderDelete : function() {
2943 SE.contextMenus.frameFoldersContextMenu.hide();
2945 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2947 var parentNode = SE.clickedFolderNode;
2949 if(parentNode != null && parentNode.data) {
2950 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2951 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2955 AjaxObject.target = 'frameFlex';
2957 if(parentNode.data.ieId != 'folder') {
2958 // delete an IMAP folder
2959 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2961 // delete a sugar folder
2962 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2964 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2965 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2967 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2973 * Rename folder form
2976 folderRename : function() {
2977 SE.contextMenus.frameFoldersContextMenu.hide();
2978 var node = SE.clickedFolderNode;
2981 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2982 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2986 overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2987 app_strings.LBL_EMAIL_SETTINGS_NAME,
2989 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2991 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2996 * fills an Object with key-value pairs of available folders
2998 getAvailableFoldersObject : function() {
2999 var ret = new Object();
3000 var tree = SE.tree.root;
3003 for(var i=0; i<tree.children.length; i++) {
3004 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3007 ret['none'] = app_strings.LBL_NONE;
3014 * Fills in key-value pairs for dependent dropdowns
3015 * @param object ret Associative array
3016 * @param object node TreeView node in focus
3017 * @param string currentPath Built up path thus far
3018 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3020 getFolderFromChild : function(ret, node, currentPath, spacer) {
3021 if(node.data != null && node.depth > 0) {
3022 /* handle visual separtors differentiating b/t mailserver and local */
3023 if(node.data.ieId && node.data.ieId == 'folder') {
3024 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3028 ret['spacer0'] = spacer;
3029 } else if(ret.spacer0 != spacer) {
3030 ret['spacer1'] = spacer
3033 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3034 var depthMarker = currentPath;
3035 var retIndex = SE.folders._createFolderId(node);
3036 ret[retIndex] = depthMarker + theLabel;
3039 if(node.children != null) {
3041 currentPath += theLabel + "/";
3044 for(var i=0; i<node.children.length; i++) {
3045 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3053 * Wrapper to refresh folders tree
3055 getFolders : function() {
3056 SE.accounts.rebuildFolderList();
3060 * handles events around folder-rename input field changes
3061 * @param object YUI event object
3063 handleEnter : function(e) {
3064 switch(e.browserEvent.type) {
3066 e.preventDefault(); // click in text field
3070 SE.folders.submitFolderRename(e);
3074 var kc = e.browserEvent.keyCode;
3078 SE.folders.submitFolderRename(e);
3082 e.preventDefault(e);
3083 SE.folders.cancelFolderRename(e);
3090 * Called when a node is clicked on in the folder tree
3091 * @param node, The node clicked on
3092 * @param e, The click event
3094 handleClick : function(o) {
3096 //If the click was on a sugar folder
3097 if (node.data.ieId == "folder") {
3098 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3101 SE.listView.populateListFrame(node, node.data.ieId, false);
3103 //eval(node.data.click);
3108 * Called when a node is right-clicked on in the folder tree
3110 handleRightClick : function(e) {
3111 YAHOO.util.Event.preventDefault(e);
3113 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3114 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3116 //If the click was on a sugar folder
3117 SE.clickedFolderNode = node;
3118 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3119 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3120 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3121 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3122 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3123 menu.getItem(3).cfg.setProperty("disabled", false);
3124 menu.getItem(4).cfg.setProperty("disabled", false);
3125 menu.getItem(5).cfg.setProperty("disabled", false);
3126 menu.getItem(6).cfg.setProperty("disabled", true);
3128 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3129 menu.getItem(0).cfg.setProperty("disabled", true);
3130 menu.getItem(1).cfg.setProperty("disabled", true);
3131 menu.getItem(2).cfg.setProperty("disabled", true);
3132 menu.getItem(3).cfg.setProperty("disabled", true);
3133 menu.getItem(4).cfg.setProperty("disabled", true);
3135 if (node.data.protocol != null) {
3136 menu.getItem(6).cfg.setProperty("disabled", false);
3138 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3139 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3140 //Sent or Draft folders
3141 menu.getItem(3).cfg.setProperty("disabled", true);
3142 menu.getItem(4).cfg.setProperty("disabled", true);
3143 menu.getItem(5).cfg.setProperty("disabled", true);
3146 //For group with auto inbound, disable everything.
3147 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3149 menu.getItem(0).cfg.setProperty("disabled", true);
3150 menu.getItem(1).cfg.setProperty("disabled", true);
3151 menu.getItem(2).cfg.setProperty("disabled", true);
3152 menu.getItem(3).cfg.setProperty("disabled", true);
3153 menu.getItem(4).cfg.setProperty("disabled", true);
3154 menu.getItem(5).cfg.setProperty("disabled", true);
3155 menu.getItem(6).cfg.setProperty("disabled", true);
3158 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3163 * Called when a row is dropped on a node
3165 handleDrop : function(rows, targetFolder) {
3166 var rowData = rows[0].getData();
3167 if (rowData.mbox != targetFolder.data.mbox) {
3168 var srcIeId = rowData.ieId;
3169 var srcFolder = rowData.mbox;
3170 var destIeId = targetFolder.data.ieId;
3171 var destFolder = targetFolder.data.mbox;
3173 for(var i=0; i<rows.length; i++) {
3174 uids[i] = rows[i].getData().uid;
3176 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3181 * Called when something is dragged over a Folder Node
3183 dragOver : function(dragObject) {
3188 * Determines if a folder name is unique to the folder tree
3189 * @param string name
3191 isUniqueFolderName : function(name) {
3192 uniqueFolder = true;
3193 var root = SE.tree.getRoot();
3194 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3195 if (this.attributes && this.attributes.ieId == "folder") {
3196 if (this.attributes.text == name) {
3197 uniqueFolder = false;
3202 return uniqueFolder;
3206 * Makes async call to rename folder in focus
3207 * @param object e Event Object
3209 submitFolderRename : function(newName) {
3210 if (trim(newName) == "") {
3211 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3214 newName = escape(newName);
3215 var node = SE.clickedFolderNode;
3216 var origName = node.data.text
3218 if (newName == origName) {
3221 if(SE.folders.isUniqueFolderName(newName)) {
3222 overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3223 if (node.data.ieId == "folder") {
3225 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3228 //IMAP folder or POP mailbox
3229 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3230 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3231 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3235 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3240 moveFolder : function(folderId, parentFolderId) {
3241 if (folderId != parentFolderId)
3243 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3244 + folderId + "&newParentId=" + parentFolderId);
3249 * makes async call to do a full synchronization of all accounts
3251 synchronizeAccounts : function() {
3252 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3253 overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3254 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3259 * Updates user's folder subscriptsion (Sugar only)
3260 * @param object SELECT DOM object in focus
3261 * @param string type of Folder selection
3263 updateSubscriptions : function() {
3264 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3268 select = document.getElementById('userFolders');
3270 for(i=0; i<select.options.length; i++) {
3271 var opt = select.options[i];
3272 if(opt.selected && opt.value != "") {
3276 active += opt.value;
3280 //Add the group folder ids.
3281 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3282 for(i=0; i<group_folders.length; i++)
3284 active += ("::" + group_folders[i]);
3287 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3290 * Updates user's group folder subscriptsion (Sugar only)
3291 * @param ieID The group folder to add to the tree view
3293 retrieveGroupFolderSubscriptions : function() {
3295 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3296 var activeGroupFolders = "";
3297 var activeGroupIds = [];
3298 for(i=0;i<a_rs.length;i++)
3300 var t_record = a_rs[i];
3301 var is_active = t_record.getData('is_active');
3302 var isGroupFolder = t_record.getData('has_groupfolder');
3303 var ieID = t_record.getData('id');
3307 activeGroupIds.push(ieID);
3311 return activeGroupIds;
3316 SE.folders.checkEmail2 = function() {
3317 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3319 //// END FOLDERS OBJECT
3320 ///////////////////////////////////////////////////////////////////////////////
3323 ///////////////////////////////////////////////////////////////////////////////
3326 * Keypress Event capture and processing
3329 overall : function(e) {
3330 switch(e.charCode) {
3332 if(e.ctrlKey || e.altKey) {
3333 var focusRegion = SE.innerLayout.regions.center;
3334 if(focusRegion.activePanel.closable == true) {
3335 focusRegion.remove(focusRegion.activePanel);
3343 ///////////////////////////////////////////////////////////////////////////////
3346 ///////////////////////////////////////////////////////////////////////////////
3349 * ListView object methods and attributes
3355 * Fills the ListView pane with detected messages.
3357 populateListFrame : function(node, ieId, forceRefresh) {
3358 SE.innerLayout.selectTab(0);
3359 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3361 Dom.get('_blank').innerHTML = "";
3362 SE.grid.params['emailUIAction'] = 'getMessageList';
3363 SE.grid.params['mbox'] = node.data.mbox;
3364 SE.grid.params['ieId'] = ieId;
3365 forcePreview = true; // loads the preview pane with first item in grid
3366 SE.listView.refreshGrid();
3370 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3372 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3373 SE.innerLayout.selectTab(0);
3374 Dom.get('_blank').innerHTML = "";
3375 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3376 SE.grid.params['ieId'] = node.data.id;
3377 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3378 SE.listView.refreshGrid();
3382 * Sets sort order as user preference
3385 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3387 ieName = ieNamePassed;
3388 focusFolder = focusFolderPassed;
3390 SE.util.clearHiddenFieldValues('emailUIForm');
3391 var previousSort = document.getElementById('sortBy').value;
3393 document.getElementById('sortBy').value = sortBy;
3394 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3395 document.getElementById('focusFolder').value = focusFolder;
3396 document.getElementById('ieId').value = ieId;
3398 if(sortBy == previousSort) {
3399 document.getElementById('reverse').value = '1';
3402 var formObject = document.getElementById('emailUIForm');
3403 YAHOO.util.Connect.setForm(formObject);
3405 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3410 * Enables click/arrow select of grid items which then populate the preview pane.
3412 selectFirstRow : function() {
3413 SE.grid.selModel.selectFirstRow();
3416 selectLastRow : function() {
3417 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3420 setEmailListStyles : function() {
3421 SE.listView.boldUnreadRows();
3423 var ds = SE.grid.getStore();
3424 if (SE.grid.getSelections().length == 0) {
3425 document.getElementById('_blank').innerHTML = '';
3429 if(typeof(ds.baseParams.mbox) != 'undefined') {
3430 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3431 var cm = SE.grid.getColumnModel();
3432 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3433 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3435 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3436 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3440 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3441 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3444 // 4/20/2007 added to hide overlay after search
3446 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3447 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3448 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3449 if (node) node.data.unseen = unread;
3451 SE.accounts.renderTree();
3454 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3455 if(forcePreview && ds.totalCount > 0) {
3456 SE.detailView.getEmailPreview();
3457 forcePreview = false;
3462 * Removes a row if found via its UID
3464 removeRowByUid : function(uid) {
3465 uid = new String(uid);
3466 uids = uid.split(',');
3467 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3469 for(j=0; j<uids.length; j++) {
3470 var theUid = uids[j];
3471 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3472 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3473 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3479 displaySelectedEmails : function(rows) {
3480 var dm = SE.grid.getDataModel();
3483 for(i=0; i<rows.length; i++) {
3484 var rowIndex = rows[i].rowIndex;
3485 var metadata = dm.data[rowIndex];
3490 uids += metadata[5];
3492 // unbold unseen email
3493 this.unboldRow(rowIndex);
3496 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3500 * exception handler for data load failures
3502 loadException : function(dataModel, ex, response) {
3507 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3508 * @param string sourceIeId Email's source I-E id
3509 * @param string sourceFolder Email's current folder
3510 * @param destinationIeId Destination I-E id
3511 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3513 * @param array emailUids Array of email's UIDs
3515 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3516 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3517 overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3519 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3520 // remove rows from visibility
3521 for(row in selectedRows) {
3522 //SE.grid.getStore().remove(row);
3525 var baseUrl = '&sourceIeId=' + sourceIeId +
3526 '&sourceFolder=' + sourceFolder +
3527 '&destinationIeId=' + destinationIeId +
3528 '&destinationFolder=' + destinationFolder;
3531 for(i=0; i<emailUids.length; i++) {
3533 uids += app_strings.LBL_EMAIL_DELIMITER;
3535 uids += emailUids[i];
3537 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3538 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3540 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3546 * Unbolds text in the grid view to denote read status
3548 markRead : function(index, record) {
3549 // unbold unseen email
3550 var row = SE.grid.getRecord(record);
3551 row.getData().seen = 1;
3552 SE.grid.getTrEl(record).style.fontWeight = "normal";
3556 * grid row output, bolding unread emails
3558 boldUnreadRows : function() {
3559 // bold unread emails
3560 var trEl = SE.grid.getFirstTrEl();
3561 while(trEl != null) {
3562 if(SE.grid.getRecord(trEl).getData().seen == "0")
3563 trEl.style.fontWeight = "bold";
3565 trEl.style.fontWeight = "";
3566 trEl = SE.grid.getNextTrEl(trEl);
3571 * Show preview for an email if 1 and only 1 is selected
3572 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3574 handleRowSelect : function(e) {
3575 if(e.selectedRows.length == 1) {
3576 SE.detailView.getEmailPreview();
3580 handleDrop : function(e, dd, targetId, e2) {
3582 case 'htmleditordiv':
3583 var rows = SE.grid.getSelectedRows();
3584 if(rows.length > 0) {
3585 SE.listView.displaySelectedEmails(rows);
3590 var targetElId = new String(targetId);
3591 var targetIndex = targetElId.replace('ygtvlabelel',"");
3592 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3593 var dm = SE.grid.getDataModel();
3594 var emailUids = new Array();
3595 var destinationIeId = targetNode.data.ieId;
3596 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3599 var rows = SE.grid.getSelectedRows();
3600 // iterate through dragged rows
3601 for(i=0; i<rows.length; i++) {
3602 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3603 var rowIndex = rows[i].rowIndex;
3604 var dataModelRow = dm.data[rowIndex];
3605 var sourceIeId = dataModelRow[7];
3606 var sourceFolder = dataModelRow[6];
3607 emailUids[i] = dataModelRow[5];
3610 // event wrapped call - need FQ
3611 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3612 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3618 * Hack-around to get double-click and single clicks to work on the grid
3619 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3621 handleClick : function(o) {
3622 SUGAR.email2.grid.clearTextSelection();
3624 var el = SUGAR.email2.grid.getSelectedRows();
3626 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3627 if ( el.length == 1)
3630 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3631 SUGAR.email2.listView.currentRowIndex = rowId;
3632 clearTimeout(SUGAR.email2.detailView.previewTimer);
3633 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3638 * Custom handler for double-click/enter
3639 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3641 getEmail : function(e) {
3642 var rows = SE.grid.getSelectedRows();
3643 var row = SE.grid.getRecord(rows[0]).getData();
3645 clearTimeout(SE.detailView.previewTimer);
3646 document.getElementById("_blank").innerHTML = "";
3648 if(row.type != "draft") {
3649 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3651 // circumventing yui-ext tab generation, let callback handler build new view
3652 SE.util.clearHiddenFieldValues('emailUIForm');
3653 //function(uid, mbox, ieId, setRead, destination) {
3654 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3655 document.getElementById('uid').value = row.uid; // uid;
3656 document.getElementById('mbox').value = row.mbox; // mbox;
3657 document.getElementById('ieId').value = row.ieId; // ieId;
3659 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3660 AjaxObject.target = '_blank';
3661 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3666 * Retrieves a row if found via its UID
3670 getRowIndexByUid : function(uid) {
3671 uid = new String(uid);
3672 uids = uid.split(',');
3674 for(j=0; j<uids.length; j++) {
3675 var theUid = uids[j];
3677 for(i=0; i<SE.grid.getStore().data.length; i++) {
3678 if(SE.grid.getStore().data[i].id == theUid) {
3686 * Returns the UID's of the seleted rows
3689 getUidsFromSelection : function() {
3690 var rows = SE.grid.getSelectedRows();
3692 /* iterate through available rows JIC a row is deleted - use first available */
3693 for(var i=0; i<rows.length; i++) {
3694 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3699 refreshGrid : function() {
3700 SE.grid.getDataSource().sendRequest(
3701 SUGAR.util.paramsToUrl(SE.grid.params),
3702 SE.grid.onDataReturnInitializeTable,
3708 //// END SE.listView
3709 ///////////////////////////////////////////////////////////////////////////////
3711 ///////////////////////////////////////////////////////////////////////////////
3715 * sends search criteria
3716 * @param reference element search field
3718 search : function(el) {
3719 var searchCriteria = new String(el.value);
3721 if(searchCriteria == '') {
3722 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3726 var safeCriteria = escape(searchCriteria);
3728 var accountListSearch = document.getElementById('accountListSearch');
3729 //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3731 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3732 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3733 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3734 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3735 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3740 * sends advanced search criteria
3742 searchAdvanced : function() {
3743 var formObject = document.getElementById('advancedSearchForm');
3746 //Set assigned user id to blank if name is not present.
3747 if (formObject.elements['assigned_user_name'].value == "")
3748 formObject.elements['assigned_user_id'].value = "";
3750 for(i=0; i<formObject.elements.length; i++) {
3751 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3754 if(formObject.elements[i].type == 'text') {
3755 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3757 if(formObject.elements[i].type == 'hidden') {
3758 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3760 if(formObject.elements[i].type == 'select-one') {
3761 var el = formObject.elements[i];
3762 var v = el.options[el.selectedIndex].value;
3765 SE.grid.params[el.name] = v;
3768 //Clear previous search results if necessary
3769 if(typeof( SE.grid.params[el.name]) != 'undefined')
3770 delete SE.grid.params[el.name]
3777 if(! this.validateSearchFormInput() )
3780 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3781 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3782 var accountListSearch = document.getElementById('accountListSearch');
3783 SE.listView.refreshGrid();
3785 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3790 * Validates the search form inputs to ensure all parameters are valid
3793 validateSearchFormInput: function()
3795 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3796 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3797 var dateCheck = check_form('advancedSearchForm');
3799 //If the parent type is selected ensure the user selected a parent_id.
3800 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3806 * Toggles the advanced options, either hidding or showing the selection.
3808 toggleAdvancedOptions: function()
3810 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3812 for(var i=0;i<el.length;i++)
3814 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3815 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3817 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3821 * clears adv search form fields
3823 searchClearAdvanced : function() {
3824 var form = document.getElementById('advancedSearchForm');
3826 for(i=0; i<form.elements.length; i++) {
3827 if(form.elements[i].type != 'button') {
3828 form.elements[i].value = '';
3834 //////////////////////////////////////////////////////////////////////////////
3837 //////////////////////////////////////////////////////////////////////////////
3840 /******************************************************************************
3841 * USER SIGNATURES calls stolen from Users module
3842 *****************************************************************************/
3843 createSignature : function(record, the_user_id) {
3844 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3846 URL += "&record="+record;
3848 if(the_user_id != "") {
3849 URL += "&the_user_id="+the_user_id;
3851 var windowName = 'email_signature';
3852 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3854 var win = window.open(URL, windowName, windowFeatures);
3855 if(win && win.focus) {
3856 // put the focus on the popup if the browser supports the focus() method
3861 deleteSignature : function() {
3862 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3863 overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3864 var singature_id = document.getElementById('signature_id').value;
3865 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3869 saveOptionsGeneral : function(displayMessage) {
3870 var formObject = document.getElementById('formEmailSettingsGeneral');
3871 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3872 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3875 YAHOO.util.Connect.setForm(formObject);
3876 SE.composeLayout.emailTemplates = null;
3878 AjaxObject.target = 'frameFlex';
3879 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3882 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3884 SE.settings.settingsDialog.hide();
3888 * Shows settings container screen
3890 showSettings : function() {
3891 if(!SE.settings.settingsDialog) {
3892 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3898 constraintoviewport: true
3900 dlg.showEvent.subscribe( function (){
3901 var el = this.element;
3902 var viewH = YAHOO.util.Dom.getViewportHeight();
3903 if (this.header && el && viewH - 50 < el.clientHeight) {
3904 var body = this.header.nextElementSibling;
3905 body.style.overflow = "auto";
3906 body.style.height = (viewH - 50) + "px";
3909 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3910 dlg.setBody('<div id="settingsTabDiv"/>');
3911 dlg.beforeRenderEvent.subscribe(function() {
3912 var dd = new YAHOO.util.DDProxy(dlg.element);
3913 dd.setHandleElId(dlg.header);
3914 dd.on('endDragEvent', function() {
3920 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3921 var tabContent = Dom.get("tab_general");
3922 tp.addTab(new YAHOO.widget.Tab({
3923 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3925 content : tabContent.innerHTML,
3926 id : "generalSettings",
3929 tabContent.parentNode.removeChild(tabContent);
3930 tabContent = Dom.get("tab_accounts");
3931 var accountTab = new YAHOO.widget.Tab({
3932 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3934 content : tabContent.innerHTML,
3935 id : "accountSettings"
3937 tp.addTab(accountTab);
3938 tabContent.parentNode.removeChild(tabContent);
3940 tp.appendTo(dlg.body);
3943 SE.settings.settingsDialog.show();
3944 SE.folders.lazyLoadSettings();
3945 SE.accounts.lazyLoad();
3949 lazyLoadRules : function() {
3950 if(false/*!SE.settings.rules*/) {
3951 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3957 //// END SE.settings
3958 ///////////////////////////////////////////////////////////////////////////////
3961 /******************************************************************************
3963 *****************************************************************************/
3964 function removeHiddenNodes(nodes, grid) {
3966 for(var i = nodes.length - 1; i > -1; i--) {
3967 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3968 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3974 function strpad(val) {
3975 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3978 function refreshTodos() {
3979 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3980 AjaxObject.target = 'todo';
3981 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3984 /******************************************************************************
3985 * MUST STAY IN GLOBAL NAMESPACE
3986 *****************************************************************************/
3987 function refresh_signature_list(signature_id, signature_name) {
3988 var field=document.getElementById('signature_id');
3990 for (var i=0; i < field.options.length; i++) {
3991 if (field.options[i].value == signature_id) {
3992 if (field.options[i].selected==false) {
3993 field.options[i].selected=true;
3998 //add item to selection list.
4000 var newElement=document.createElement('option');
4001 newElement.text=signature_name;
4002 newElement.value=signature_id;
4003 field.options.add(newElement);
4004 newElement.selected=true;
4007 //enable the edit button.
4008 var field1=document.getElementById('edit_sig');
4009 field1.style.visibility="inherit";
4010 var deleteButt = document.getElementById('delete_sig');
4011 deleteButt.style.visibility="inherit";
4014 function setDefaultSigId(id) {
4015 var checkbox = document.getElementById("signature_default");
4016 var default_sig = document.getElementById("signatureDefault");
4018 if(checkbox.checked) {
4019 default_sig.value = id;
4021 default_sig.value = "";
4025 function setSigEditButtonVisibility() {
4026 var field = document.getElementById('signature_id');
4027 var editButt = document.getElementById('edit_sig');
4028 var deleteButt = document.getElementById('delete_sig');
4029 if(field.value != '') {
4030 editButt.style.visibility = "inherit";
4031 deleteButt.style.visibility = "inherit";
4033 editButt.style.visibility = "hidden";
4034 deleteButt.style.visibility = "hidden";
4036 }// End of File modules/Emails/javascript/EmailUI.js
4038 /*********************************************************************************
4039 * SugarCRM is a customer relationship management program developed by
4040 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4042 * This program is free software; you can redistribute it and/or modify it under
4043 * the terms of the GNU Affero General Public License version 3 as published by the
4044 * Free Software Foundation with the addition of the following permission added
4045 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4046 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4047 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4049 * This program is distributed in the hope that it will be useful, but WITHOUT
4050 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4051 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4054 * You should have received a copy of the GNU Affero General Public License along with
4055 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4056 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4059 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4060 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4062 * The interactive user interfaces in modified source and object code versions
4063 * of this program must display Appropriate Legal Notices, as required under
4064 * Section 5 of the GNU Affero General Public License version 3.
4066 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4067 * these Appropriate Legal Notices must retain the display of the "Powered by
4068 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4069 * technical reasons, the Appropriate Legal Notices must display the words
4070 * "Powered by SugarCRM".
4071 ********************************************************************************/
4074 var sw = YAHOO.SUGAR,
4075 Event = YAHOO.util.Event,
4076 Connect = YAHOO.util.Connect,
4077 Dom = YAHOO.util.Dom
4080 ///////////////////////////////////////////////////////////////////////////////
4083 _contactCache : new Array(), // cache of contacts
4084 _dd : new Array(), // filtered list, same format as _contactCache
4085 _ddLists : new Array(), // list of Lists
4086 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4087 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4088 clickBubble : true, // hack to get around onclick event bubbling
4090 relatedBeanType : '',
4093 itemSpacing : 'white-space:nowrap; padding:2px;',
4099 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4101 initFixForDatatableSort: function () {
4102 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4103 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4104 var oColumn = this._oColumnSet.getColumn(column);
4107 // Validate TD element
4108 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4110 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4112 // Validate TH element
4114 elCell = this.getThEl(column);
4117 var allColumns = this._oColumnSet.flat;
4118 for(var i=0, len=allColumns.length; i<len; i++) {
4119 if(allColumns[i].getThEl().id === elCell.id) {
4120 oColumn = allColumns[i];
4131 cancelEdit : function() {
4132 if(this.editContactDialog)
4133 this.editContactDialog.hide();
4134 if(this.editMailingListDialog)
4135 this.editMailingListDialog.hide();
4139 * Clears filter form
4141 clear : function() {
4142 var t = document.getElementById('contactsFilter');
4148 * handle context-menu Compose-to call
4149 * @param string type 'contacts' or 'lists'
4151 composeTo : function(type, waited) {
4152 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4153 if (activePanel.substring(0, 10) != "composeTab") {
4154 SE.composeLayout.c0_composeNewEmail();
4155 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4156 SE.contextMenus.contactsContextMenu.hide();
4159 var idx = activePanel.substring(10);
4162 // determine if we have a selection to work with
4163 if(type == 'contacts') {
4164 var ids = SE.contactView.getSelectedRows();
4165 for (var i in ids) {
4166 rows[i] = SE.contactView.getRecord(ids[i]);
4168 removeHiddenNodes(rows, SE.contactView);
4172 if(rows.length > 0) {
4173 SE.composeLayout.handleDrop(
4174 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4175 null, rows, 'addressTO' + idx );
4177 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4181 editContact : function() {
4182 SE.contextMenus.contactsContextMenu.hide();
4183 var element = SE.contactView.getSelectedNodes()[0];
4185 if (element.className.indexOf('address-contact') > -1) {
4186 elementId = element.id;
4187 } else if (element.className.indexOf('address-exp-contact') > -1) {
4188 elementId = element.id.substring(2);
4194 * Filters contact entries based on user input
4196 filter : function(inputEl) {
4197 var ret = new Object();
4198 var re = new RegExp(inputEl.value, "gi");
4200 for(var i in this._contactCache) {
4201 if(this._contactCache[i].name.match(re)) {
4202 ret[i] = this._contactCache[i];
4206 this.buildContactList(ret);
4209 fullForm : function(id, module) {
4210 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4214 * returns a formatted email address from the addressBook cache
4216 getFormattedAddress : function(id) {
4217 var o = this._contactCache[id];
4218 var primaryEmail = '';
4220 for(var i=0; i<o.email.length; i++) {
4221 var currentEmail = o.email[i].email_address;
4223 if(o.email[i].primary_address == 1) {
4224 primaryEmail = o.email[i].email_address;
4228 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4229 var name = new String(o.name);
4230 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4231 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4237 * Sets up async call to query for matching contacts, users, etc.
4239 searchContacts : function() {
4240 var fn = document.getElementById('input_searchField').value;
4241 var pe = document.getElementById('input_searchPerson').value;
4243 var rb = document.getElementById('hasRelatedBean').checked;
4246 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4247 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4248 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4249 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4251 this.addressBookDataModel.params['related_bean_id'] = '';
4254 this.addressBookDataModel.params['search_field'] = fn;
4255 this.addressBookDataModel.params['person'] = pe;
4256 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4257 this.grid._oDataSource = this.addressBookDataModel;
4258 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4262 * Clear Search Crieteria For Addressbook
4264 clearAddressBookSearch : function() {
4265 document.getElementById('input_searchField').value = "";
4266 document.getElementById('input_searchPerson').selectedIndex = 0;
4270 * Opens modal select window to add contacts to addressbook
4272 selectContactsDialogue : function(destId) {
4273 if(!this.contactsDialogue) {
4274 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4278 constraintoviewport: true,
4280 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4281 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4283 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4285 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4286 dlg.setBody(body.innerHTML);
4287 dlg.renderEvent.subscribe(function() {
4288 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4289 if (iev && !SUGAR.isIE) {
4290 this.body.style.width = "950px";
4295 dlg.beforeRenderEvent.subscribe(function() {
4296 var dd = new YAHOO.util.DDProxy(dlg.element);
4297 dd.setHandleElId(dlg.header);
4298 dd.on('endDragEvent', function() {
4304 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4306 var tabContent = SUGAR.util.getAndRemove("searchForm");
4307 tp.addTab(new YAHOO.widget.Tab({
4308 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4310 content : tabContent.innerHTML,
4311 id : "addressSearchTab",
4315 var addListenerFields = ['input_searchPerson','input_searchField' ]
4316 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4317 if (e.keyCode == 13) {
4318 YAHOO.util.Event.stopEvent(e);
4319 SUGAR.email2.addressBook.searchContacts();
4323 this.contactsDialogue.render();
4326 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4327 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4331 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4332 var idx = activePanel.substring(10);
4334 SE.addressBook.idx = idx;
4337 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4338 document.getElementById('relatedBeanColumn').style.display = '';
4339 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4340 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4341 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4342 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4343 SE.addressBook.relatedBeanType = relatedBeanType;
4345 document.getElementById('relatedBeanColumn').style.display = 'none';
4346 document.getElementById('hasRelatedBean').checked = false;
4349 if (!SE.addressBook.grid)
4351 if (hasRelatedBeanId) {
4352 document.getElementById('hasRelatedBean').checked = true;
4354 AddressSearchGridInit();
4355 SE.addressBook.relatedBeanId = relatedBeanId;
4359 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4361 SE.addressBook.relatedBeanId = relatedBeanId;
4362 document.getElementById('hasRelatedBean').checked = true;
4364 if (document.getElementById('hasRelatedBean').checked == true)
4366 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4367 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4369 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4370 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4372 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4373 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4374 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4377 //Remove any lingering rows in the result set table if the module was closed.
4378 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4380 SE.addressBook.populateResulstTableEmailAddresses();
4382 this.contactsDialogue.show();
4385 * Clear all email addresses from result table.
4388 clearAllEmailAddressFieldsFromResultTable: function () {
4389 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4390 //Unhighlight any rows currently selected if the emails were cleared.
4391 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4392 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4395 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4396 * results table. This function is called when the address book is displayed.
4398 populateResulstTableEmailAddresses: function () {
4400 var idx = SE.addressBook.idx;
4401 var emailFields = ['to','cc','bcc'];
4403 for(var k=0;k<emailFields.length;k++)
4405 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4406 var allEmails = document.getElementById(elKey).value;
4410 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4412 for (var i=0; i<formatedEmails.length; i++)
4414 var t_name = formatedEmails[i].name;
4415 var t_emailAddr = formatedEmails[i].email_address;
4416 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4418 t_name = displayEmail = t_emailAddr;
4420 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4421 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4422 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4428 * Checks all entries in the result table against a particular email address, returning true
4429 * if the email address is found, false otherwise.
4431 doesEmailAdddressExistInResultTable: function(emailAddress)
4433 if(trim(emailAddress) == '')
4436 var emailAddressFound = false;
4437 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4438 for (var i=0; i < contacts.length; i++)
4440 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4441 //If we are adding to cc or bcc fields, make them visible.
4442 if(data.email_address == emailAddress)
4444 emailAddressFound = true;
4449 return emailAddressFound;
4452 * Takes all email addresses that the users wishes to add from the address book and populates the To
4453 * fields on the compose tab.
4455 populateEmailAddressFieldsFromResultTable: function()
4457 //Clear the fields first, all email addresses are stored in the address book
4458 var idx = SE.addressBook.idx;
4459 var emailFields = ['to','cc','bcc'];
4460 for(var k=0;k<emailFields.length;k++)
4462 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4463 document.getElementById(elKey).value = "";
4466 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4467 for (var i=0; i < contacts.length; i++)
4469 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4471 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4472 //If we are adding to cc or bcc fields, make them visible.
4473 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4474 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4475 //Construct the target id
4476 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4478 var target = document.getElementById(target_id);
4479 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4482 //Delete all rows from the result set table
4483 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4486 SE.addressBook.contactsDialogue.hide()
4489 * Insert contacts into the result table.
4491 insertContactToResultTable : function(event,address_type) {
4493 var contactsDialogue = SE.addressBook.contactsDialogue;
4494 var contacts = SE.addressBook.grid.getSelectedRows();
4496 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4497 for (var i = 0; i < rows.length; i++)
4499 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4501 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4502 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4503 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4504 rows[i].setData("selected",true);
4507 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4508 for (var i = 0; i < checkBoxes.length; i++) {
4509 checkBoxes[i].checked = false;
4515 insertContactRowToResultTable : function(rowId, addressType) {
4516 var data = SE.addressBook.grid.getRecord(rowId).getData();
4517 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4519 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4520 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4521 if(addressType == null)
4522 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4523 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});
4526 * Remove a row from the gridsResult table.
4528 removeRowFromGridResults : function(rowId,emailAddress)
4530 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4531 for (var i=0; i < contacts.length; i++)
4533 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4534 var data = rec.getData();
4535 if(data.email_address == emailAddress)
4537 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4542 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4545 * Translates between the addressType To|Cc|Bcc labels/keys.
4547 translateAddresType: function(addressType,fromKey)
4549 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4550 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4551 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4552 var mappingObject = {};
4555 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4558 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4559 mappingObject[displayCc] = 'cc';
4560 mappingObject[displayBcc] = 'bcc';
4563 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4569 toggleSearchRowIcon : function(rowId,show)
4573 var idToShow = rowId + '_add_img';
4574 var idToHide = rowId + '_rm_img';
4578 var idToShow = rowId + '_rm_img';
4579 var idToHide = rowId + '_add_img';
4583 Dom.addClass(idToHide, "yui-hidden");
4584 Dom.removeClass(idToShow, "yui-hidden");
4587 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4589 doesGridResultsEntryExist: function(emailAddrs)
4592 var contactExists = false;
4593 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4594 for (var i=0; i < contacts.length; i++)
4596 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4597 if(data.email_address == emailAddrs)
4599 contactExists = true;
4603 return contactExists;
4607 * adds an email address to a string, but first checks if it exists
4608 * @param string concat The string we are appending email addresses to
4609 * @param string addr Email address to add
4612 smartAddEmailAddressToComposeField : function(concat, addr) {
4613 var re = new RegExp(addr);
4615 if(!concat.match(re)) {
4617 concat += "; " + addr;
4626 //// END ADDRESS BOOK
4627 ///////////////////////////////////////////////////////////////////////////////
4631 ///////////////////////////////////////////////////////////////////////////////
4634 * Auto-complete object
4638 delimChar : [";", ","],
4642 prehighlightClassName : "yui-ac-prehighlight",
4645 instances : new Array(),
4648 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4649 * @param object Contact from AddressBook
4652 getPrimaryAddress : function(contact) {
4653 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4655 for(var eIndex in contact.email) {
4656 address = contact.email[eIndex].email_address;
4657 if(contact.email[eIndex].primary_address == 1) {
4658 return contact.email[eIndex].email_address;
4666 * initializes autocomplete widgets for a given compose view
4669 init : function(idx) {
4670 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4671 "queryMatchContains" : false,
4672 "queryMatchSubset" : true
4675 this.instances[idx] = {
4682 // instantiate the autoComplete widgets
4683 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4684 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4685 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4687 // enable hiding of interfering textareas
4688 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4689 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4690 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4692 // enable reshowing of hidden textareas
4693 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4694 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4695 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4697 // enable refreshes of contact lists
4698 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4699 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4700 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4703 refreshDataSource : function(sType, aArgs) {
4704 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4706 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4708 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4709 idx = textBoxId.substr(9);
4711 idx = textBoxId.substr(10);
4714 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4715 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4716 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4720 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4722 returnDataSource : function(contacts) {
4723 var ret = new Array();
4724 for(var id in contacts) {
4725 if (contacts[id].name) {
4726 var primary = this.getPrimaryAddress(contacts[id]);
4728 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4729 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4731 for(var emailIndex in contacts[id].email) {
4732 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4741 * Hides address textareas to prevent autocomplete dropdown from being obscured
4743 toggleTextareaHide : function(sType, aArgs) {
4744 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4748 if(textBoxId.indexOf("addressTO") > -1) {
4750 } else if(textBoxId.indexOf("addressCC") > -1) {
4753 idx = textBoxId.substr(9);
4755 // follow through if not BCC
4757 var cc = document.getElementById("addressCC" + idx);
4758 var bcc = document.getElementById("addressBCC" + idx);
4762 cc.style.visibility = 'hidden';
4764 bcc.style.visibility = 'hidden';
4771 * Redisplays the textareas after an address is commited
4773 toggleTextareaShow : function(sType, aArgs) {
4774 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4778 if(textBoxId.indexOf("addressTO") > -1) {
4780 } else if(textBoxId.indexOf("addressCC") > -1) {
4783 idx = textBoxId.substr(9);
4785 // follow through if not BCC
4787 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4788 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4793 //// END AUTOCOMPLETE
4794 ///////////////////////////////////////////////////////////////////////////////
4796 ///////////////////////////////////////////////////////////////////////////////
4799 * expands the options sidebar
4801 SE.composeLayout = {
4802 currentInstanceId : 0,
4805 outboundAccountErrors : null,
4806 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4808 showAddressDetails : function(e) {
4809 var linkElement = document.getElementById("More"+e.id);
4810 var spanElement = document.getElementById("Detail"+e.id);
4811 var emailAddressList = e.value;
4812 if(e.value.length > 96)
4814 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4815 var displayArray = [];
4816 for (var i=0; i<resultArray.length; i++)
4818 var t_name = resultArray[i].name;
4819 var t_emailAddr = resultArray[i].email_address;
4821 displayArray.push('<br/><' + t_emailAddr + '>');
4823 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4826 var result = displayArray.join('<br/>');
4828 linkElement.style.display = "inline";
4829 linkElement.style.height="10px";
4830 linkElement.style.overflow="visible";
4831 spanElement.innerHTML = result;
4834 linkElement.style.display = "none";
4839 * Given a string of email address, return an array containing the name portion (if available)
4840 * and email portion.
4842 _getEmailArrayFromString : function (emailAddressList){
4845 while ((results = reg.exec(emailAddressList)) != null)
4847 orignial = results[0];
4848 parsedResult = results[0].replace(';', ':::::');
4849 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4853 while ((results = reg.exec(emailAddressList)) != null)
4855 orignial = results[0];
4856 parsedResult = results[0].replace(',', ':::::');
4857 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4859 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4860 var emailArr = emailAddressList.split(":::::");
4861 var resultsArray = [];
4863 for (var i=0; i<emailArr.length; i++)
4865 var rposition = emailArr[i].indexOf('<');
4866 var lposition = emailArr[i].indexOf('>');
4868 if(trim(emailArr[i]) != '')
4870 if(rposition != -1 && lposition != -1)
4872 var t_name = emailArr[i].substr(0, rposition-1);
4873 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4874 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4878 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4882 return resultsArray;
4884 ///////////////////////////////////////////////////////////////////////////
4887 * Prepare bucket DIV and yui-ext tab panels
4889 _0_yui : function() {
4890 var idx = this.currentInstanceId;
4892 var composeTab = new YAHOO.SUGAR.ClosableTab({
4893 label: mod_strings.LNK_NEW_SEND_EMAIL,
4895 content : "<div id='htmleditordiv" + idx + "'/>",
4896 id : "composeTab" + idx,
4897 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4900 SE.innerLayout.addTab(composeTab);
4902 // get template engine with template
4903 if (!SE.composeLayout.composeTemplate) {
4904 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4907 // create Tab inner layout
4908 var composePanel = this.getComposeLayout();
4909 composePanel.getUnitByPosition("right").collapse();
4910 composePanel.autoSize();
4914 * Generate the quick compose layout
4915 * @method getQuickComposeLayout
4916 * @param {Pannel} parentPanel Parent pannel
4917 * @param {Object} o Options
4920 getQuickComposeLayout : function (parentPanel,o) {
4921 var idx = SE.composeLayout.currentInstanceId;
4923 //Before rendering the parent pannel we need to initalize the grid layout
4924 parentPanel.beforeRenderEvent.subscribe(function() {
4926 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4927 SE.composeLayout._createComposeLayout(idx);
4928 SE.composeLayout[idx].set('height', 350);
4929 SE.composeLayout[idx].render();
4933 //Wait until the Compose Layout has rendered, then add the
4934 //options tab and perform the tiny initialization.
4935 parentPanel.renderEvent.subscribe(function() {
4937 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4938 SE.composeLayout._initComposeOptionTabs(idx);
4939 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4940 //Initialize tinyMCE
4941 if (!SUGAR.util.isTouchScreen())
4942 SE.composeLayout._1_tiny();
4943 //Init templates and address book
4944 SE.composeLayout._2_final();
4946 SE.composeLayout.quickCreateComposePackage(o);
4951 //Check if we have the div override for the shortcut bar
4952 if(typeof o.menu_id != 'undefined') {
4953 parentPanel.render(o.menu_id);
4955 parentPanel.render(document.body);
4958 return SE.composeLayout[idx];
4961 * Fill in all fields into the quick compose layout.
4962 * @method quickCreateComposePackage
4963 * @param {Object} o Options
4966 quickCreateComposePackage: function(o)
4968 //If we have a compose package fill in defaults.
4969 if (typeof(o.composePackage) != 'undefined')
4971 composePackage = o.composePackage; //Set the compose data object
4972 //Hijack this method called by composePackage as it's not need for quick creates.
4973 SE.composeLayout.c0_composeNewEmail = function(){};
4974 SE.composeLayout.composePackage(); //Fill in defaults.
4977 getComposeLayout : function() {
4978 var idx = SE.composeLayout.currentInstanceId;
4980 this._createComposeLayout(idx);
4981 SE.composeLayout[idx].render();
4982 this._initComposeOptionTabs(idx);
4984 return SE.composeLayout[idx];
4988 * Create the layout manager for the compose window.
4990 _createComposeLayout : function(idx)
4992 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
4993 parent: SE.complexLayout,
5003 SE.composeLayout.composeTemplate.exec({
5004 'app_strings':app_strings,
5005 'mod_strings':mod_strings,
5007 'linkbeans_options' : linkBeans,
5008 'idx' : SE.composeLayout.currentInstanceId
5019 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5022 header: app_strings.LBL_EMAIL_OPTIONS
5028 * Create compose tab which will populate the 'right' container in the compose window.
5030 _initComposeOptionTabs : function(idx)
5032 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5033 var tab = new YAHOO.widget.Tab({
5034 label: app_strings.LBL_EMAIL_ATTACHMENT,
5036 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5037 id : "divAttachments" + idx,
5041 tab.layout = SE.composeLayout[idx];
5043 tab.on("activeChange", function(o){
5045 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5051 tab = new YAHOO.widget.Tab({
5052 label: app_strings.LBL_EMAIL_OPTIONS,
5054 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5055 id : "divOptions" + idx,
5059 tab.layout = SE.composeLayout[idx];
5060 tab.on("activeChange", function(o){
5062 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5067 SE.composeLayout[idx].autoSize = function() {
5068 var pEl = this.get("element").parentNode.parentNode.parentNode;
5069 this.set("height", pEl.clientHeight-30);
5073 SE.composeLayout[idx].rightTabs = cTabs;
5075 isParentTypeValid : function(idx) {
5076 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5077 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5078 if (trim(parentTypeValue) == ""){
5079 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5085 isParentTypeAndNameValid : function(idx) {
5086 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5087 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5088 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5089 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5090 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5091 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5097 callopenpopupForEmail2 : function(idx,options) {
5099 var formName = 'emailCompose' + idx;
5101 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5102 formName = options.form_name;
5104 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5105 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5106 if (!SE.composeLayout.isParentTypeValid(idx)) {
5109 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5111 call_back_function:"SE.composeLayout.popupAddEmail",
5113 field_to_name_array:{
5114 id:'data_parent_id' + idx,
5115 name:'data_parent_name' + idx,
5120 popupAddEmail : function(o)
5122 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5123 var data = o.name_to_value_array;
5124 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5125 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5127 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5128 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5135 _1_tiny : function() {
5136 var idx = SE.composeLayout.currentInstanceId;
5137 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5138 SE.tinyInstances[elId] = { };
5139 SE.tinyInstances[elId].ready = false;
5140 var t = tinyMCE.getInstanceById(elId);
5142 if(typeof(t) == 'undefined') {
5143 tinyMCE.execCommand('mceAddControl', false, elId);
5144 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5145 SE.composeLayout.resizeEditor(idx);
5146 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
5151 resizeEditor : function(idx)
5153 var cof = Dom.get('composeOverFrame' + idx);
5154 var head = Dom.get('composeHeaderTable' + idx);
5155 var targetHeight = cof.clientHeight - head.clientHeight;
5156 var instance = tinyMCE.get(SE.tinyInstances.currentHtmleditor);
5158 var parentEl = Dom.get(instance.editorId + '_parent');
5159 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5160 var contentEl = instance.contentAreaContainer;
5161 var iFrame = contentEl.firstChild;
5162 var tinMceToolbarOffset = 18;
5163 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5167 * Initializes d&d, auto-complete, email templates
5169 _2_final : function() {
5170 var idx = SE.composeLayout.currentInstanceId;
5172 if(this.emailTemplates) {
5173 this.setComposeOptions(idx);
5175 //populate email template cache
5176 AjaxObject.target = '';
5177 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5180 // handle drop targets for addressBook
5181 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5182 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5183 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5184 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5186 // auto-complete setup
5187 SE.autoComplete.init(idx);
5190 document.getElementById("addressTO" + idx).focus();
5194 * hide tinyMCE tool bar if send email as plaintext is checked
5196 renderTinyMCEToolBar : function (idx, hide) {
5198 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5200 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5204 c1_composeEmail : function(isReplyForward, retry) {
5208 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5209 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5214 if(isReplyForward) {
5215 this.replyForwardEmailStage2();
5221 * takes draft info and prepopulates
5223 c0_composeDraft : function() {
5224 this.getNewInstanceId();
5226 document.getElementById('_blank').innerHTML = '';
5227 var idx = SE.composeLayout.currentInstanceId;
5228 SE.composeLayout.draftObject = new Object();
5229 SE.composeLayout.draftObject.id = idx;
5230 SE.composeLayout.draftObject.isDraft = true;
5231 SE.composeLayout.currentInstanceId = idx;
5232 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5233 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5234 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5236 SE.composeLayout._0_yui();
5237 SE.composeLayout._1_tiny();
5240 SE.composeLayout._2_final();
5242 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5243 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5247 * Strip & Prep editor hidden fields
5249 c0_composeNewEmail : function() {
5250 this.getNewInstanceId();
5251 this.c1_composeEmail(false);
5255 * Sends async request to get the compose view.
5256 * Requests come from "reply" or "forwards"
5258 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5259 SE.composeLayout.replyForwardObj = new Object();
5260 SE.composeLayout.replyForwardObj.ieId = ieId;
5261 SE.composeLayout.replyForwardObj.uid = uid;
5262 SE.composeLayout.replyForwardObj.mbox = mbox;
5263 SE.composeLayout.replyForwardObj.type = type;
5265 if(mbox == 'sugar::Emails') {
5266 SE.composeLayout.replyForwardObj.sugarEmail = true;
5269 SE.composeLayout.getNewInstanceId();
5270 SE.composeLayout.c1_composeEmail(true);
5272 //// END COMPOSE FLOW
5273 ///////////////////////////////////////////////////////////////////////////
5276 * Called when a contact, email, or mailinglist is dropped
5277 * into one of the compose fields.
5279 handleDrop : function (source, event, data, target) {
5282 target = event.getTarget();
5284 data.nodes = [data.nodes];
5288 target = document.getElementById(target);
5292 if (target.id.indexOf('address') > -1) {
5293 // dropped onto email to/cc/bcc field
5294 for(var i in nodes) {
5295 var node = nodes[i].getData();
5297 if (node[1].indexOf('contact') > -1) {
5298 email = SE.addressBook.getFormattedAddress(node[0]);
5299 } else if (node[1].indexOf('address-email') > -1){
5300 email = node[3].replace(/ /gi, '');
5301 email = email.replace('<', '<').replace('>', '>');
5302 var tr = source.getTrEl(nodes[i]);
5303 while (tr && !Dom.hasClass(tr, "address-contact")) {
5304 tr = source.getPreviousTrEl(tr);
5306 var CID = source.getRecord(tr).getData()[0];
5307 var o = SE.addressBook._contactCache[CID];
5308 var name = new String(o.name);
5309 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5310 email = finalName + email;
5312 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5318 /*/////////////////////////////////////////////////////////////////////////////
5319 /// EMAIL TEMPLATE CODE
5321 applyEmailTemplate : function (idx, id) {
5324 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5325 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5326 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5328 var to_addr = document.getElementById('addressTO'+idx);
5329 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1) {
5330 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5331 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5334 // id is selected index of email template drop-down
5335 if(id == '' || id == "0") {
5336 YAHOO.SUGAR.MessageBox.show({
5341 if(btn=='no'){return;};
5342 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5349 YAHOO.SUGAR.MessageBox.show({
5354 if(btn=='no'){return;};
5355 SUGAR.email2.composeLayout.processResult(idx, id);},
5361 processNoneResult : function(idx, id) {
5362 var tiny = SE.util.getTiny('htmleditor' + idx);
5363 var tinyHTML = tiny.getContent();
5364 var openTag = '<div><span><span>';
5365 var htmllow = tinyHTML.toLowerCase();
5366 var start = htmllow.indexOf(openTag);
5368 tinyHTML = tinyHTML.substr(start);
5369 tiny.setContent(tinyHTML);
5371 tiny.setContent('');
5375 processResult : function(idx , id){
5376 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5378 // get attachments if any
5379 AjaxObject.target = '';
5380 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5383 appendEmailTemplateJSON : function() {
5384 var idx = SE.composeLayout.currentInstanceId; // post increment
5386 // query based on template, contact_id0,related_to
5387 //jchi 09/10/2008 refix #7743
5388 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5389 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5392 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,'"');
5394 // cn: bug 14361 - text-only templates don't fill compose screen
5396 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/>");
5399 var tiny = SE.util.getTiny('htmleditor' + idx);
5400 var tinyHTML = tiny.getContent();
5401 var openTag = '<div><span><span>';
5402 var closeTag = '</span></span></div>';
5403 var htmllow = tinyHTML.toLowerCase();
5404 var start = htmllow.indexOf(openTag);
5406 var htmlPart2 = tinyHTML.substr(start);
5407 tinyHTML = text + htmlPart2;
5408 tiny.setContent(tinyHTML);
5410 tiny.setContent(text);
5415 * Writes out the signature in the email editor
5417 setSignature : function(idx) {
5420 var hide = document.getElementById('setEditor' + idx).checked;
5421 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5422 //wait for signatures to load before trying to set them
5423 if (!SE.composeLayout.signatures) {
5424 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5429 var sel = document.getElementById('signatures' + idx);
5431 var sel = document.getElementById('signature_id');
5432 idx = SE.tinyInstances.currentHtmleditor;
5435 //Ensure that the tinyMCE html has been rendered.
5436 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5437 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5444 signature = sel.options[sel.selectedIndex].value;
5449 var openTag = '<div><span><span>';
5450 var closeTag = '</span></span></div>';
5451 var t = SE.util.getTiny('htmleditor' + idx);
5453 if(typeof(t) != 'undefined')
5455 t.contentDocument = t.contentWindow.document;
5456 var html = t.getContent();
5461 var htmllow = html.toLowerCase();
5462 var start = htmllow.indexOf(openTag);
5463 var end = htmllow.indexOf(closeTag) + closeTag.length;
5465 // selected "none" - remove signature from email
5466 if(signature == '') {
5468 var htmlPart1 = html.substr(0, start);
5469 var htmlPart2 = html.substr(end, html.length);
5471 html = htmlPart1 + htmlPart2;
5474 SE.signatures.lastAttemptedLoad = '';
5478 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5479 SE.signatures.lastAttemptedLoad = '';
5481 SE.signatures.lastAttemptedLoad = signature;
5483 if(typeof(SE.signatures[signature]) == 'undefined') {
5485 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5486 SE.signatures.targetInstance = (idx) ? idx : "";
5487 AjaxObject.target = '';
5488 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5490 var newSignature = this.prepareSignature(SE.signatures[signature]);
5492 // clear out old signature
5493 if(SE.signatures.lastAttemptedLoad && start > -1) {
5494 var htmlPart1 = html.substr(0, start);
5495 var htmlPart2 = html.substr(end, html.length);
5497 html = htmlPart1 + htmlPart2;
5501 start = html.indexOf('<div><hr></div>');
5502 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5503 var htmlPart1 = html.substr(0, start);
5504 var htmlPart2 = html.substr(start, html.length);
5505 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5506 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5507 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5509 var newHtml = html + openTag + newSignature + closeTag;
5511 //tinyMCE.setContent(newHtml);
5512 t.setContent(newHtml);
5516 prepareSignature : function(str) {
5517 var signature = new String(str);
5519 signature = signature.replace(/</gi, '<');
5520 signature = signature.replace(/>/gi, '>');
5526 showAttachmentPanel : function(idx) {
5527 var east = SE.composeLayout[idx].getUnitByPosition("right");
5528 var tabs = SE.composeLayout[idx].rightTabs;
5530 tabs.set("activeTab", tabs.getTab(0));
5534 * expands sidebar and displays options panel
5536 showOptionsPanel : function(idx) {
5537 var east = SE.composeLayout[idx].getUnitByPosition("right");
5538 var tabs = SE.composeLayout[idx].rightTabs;
5540 tabs.set("activeTab", tabs.getTab(1));
5544 * Selects the Contacts tab
5546 showContactsPanel : function() {
5547 SE.complexLayout.regions.west.showPanel("contactsTab");
5551 * Generates fields for Select Document
5553 addDocumentField : function(idx) {
5554 var basket = document.getElementById('addedDocuments' + idx);
5556 var index = (basket.childNodes.length / 7) - 1;
5563 var test = document.getElementById('documentId' + idx + index);
5565 while(test != null) {
5567 test = document.getElementById('documentId' + idx + index);
5570 var documentCup = document.createElement("div");
5571 documentCup.id = 'documentCup' + idx + index;
5572 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5573 // document id field
5574 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5575 // document name field
5576 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5578 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5579 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5580 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5582 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5583 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5584 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5587 basket.appendChild(documentCup);
5588 //basket.innerHTML += out;
5593 * Makes async call to save a draft of the email
5594 * @param int Instance index
5596 saveDraft : function(tinyInstance) {
5597 this.sendEmail(tinyInstance, true);
5600 selectDocument : function(target) {
5601 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5602 windowName = 'selectDocument';
5603 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5605 win = window.open(URL, windowName, windowFeatures);
5607 // put the focus on the popup if the browser supports the focus() method
5613 * Modal popup for file attachment dialogue
5615 addFileField : function() {
5616 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5617 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5621 constraintoviewport: true,
5623 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5624 fn:function(){SE.addFileDialog.hide();}
5627 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5628 SE.addFileDialog.render();
5629 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5631 Dom.removeClass("addFileDialog", "yui-hidden");
5633 SE.addFileDialog.show();
5637 * Async upload of file to temp dir
5639 uploadAttachment : function() {
5640 if(document.getElementById('email_attachment').value != "") {
5641 var formObject = document.getElementById('uploadAttachment');
5642 YAHOO.util.Connect.setForm(formObject, true, true);
5643 AjaxObject.target = '';
5644 AjaxObject.startRequest(callbackUploadAttachment, null);
5646 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5651 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5652 * @param string target in focus compose layout
5654 setDocument : function(idx, target, documentId, documentName, docRevId) {
5655 // fields are named/id'd [fieldName][instanceId][index]
5656 var addedDocs = document.getElementById("addedDocuments" + idx);
5657 var docId = document.getElementById('documentId' + idx + target);
5658 var docName = document.getElementById('documentName' + idx + target);
5659 var docRevisionId = document.getElementById('document' + idx + target);
5660 docId.value = documentId;
5661 docName.value = documentName;
5662 docRevisionId.value = docRevId;
5666 * Removes the bucket div containing the document input fields
5668 deleteDocumentField : function(documentCup) {
5669 var f0 = document.getElementById(documentCup);
5670 f0.parentNode.removeChild(f0);
5674 * Removes a Template Attachment field
5678 deleteTemplateAttachmentField : function(idx, index) {
5679 // create not-in-array values for removal filtering
5680 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5686 r += document.getElementById('templateAttachmentId' + idx + index).value;
5687 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5689 var target = 'templateAttachmentCup' + idx + index;
5690 d = document.getElementById(target);
5691 d.parentNode.removeChild(d);
5695 * Async removal of uploaded temp file
5696 * @param string index Should be a concatenation of idx and index
5699 deleteUploadAttachment : function(index, file) {
5700 var d = document.getElementById('email_attachment_bucket' + index);
5701 d.parentNode.removeChild(d);
5703 // make async call to delete cached file
5704 AjaxObject.target = '';
5705 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5709 * Attaches files coming from Email Templates
5711 addTemplateAttachmentField : function(idx) {
5713 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5715 var basket = document.getElementById('addedTemplateAttachments' + idx);
5718 var index = basket.childNodes.length;
5725 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5727 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5728 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5729 idx + "\",\"" + index + "\");'/>" +
5731 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5732 // templateAttachment field
5733 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5735 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5737 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5738 "<br id='br" + index + "></br>" +
5739 "<br id='brdoc" + index + "></br>" +
5741 basket.innerHTML = basket.innerHTML + out;
5747 * Sends one email via async call
5748 * @param int idx Editor instance ID
5749 * @param bool isDraft
5751 sendEmail : function(idx, isDraft) {
5753 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5754 var obAccountID = document.getElementById('addressFrom' + idx).value;
5756 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5758 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5763 var form = document.getElementById('emailCompose' + idx);
5764 var composeOptionsFormName = "composeOptionsForm" + idx;
5765 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5766 var html = t.getContent();
5767 var subj = document.getElementById('emailSubject' + idx).value;
5768 var to = trim(document.getElementById('addressTO' + idx).value);
5769 var cc = trim(document.getElementById('addressCC' + idx).value);
5770 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5771 var email_id = document.getElementById('email_id' + idx).value;
5772 var composeType = document.getElementById('composeType').value;
5773 var parent_type = document.getElementById("parent_type").value;
5774 var parent_id = document.getElementById("parent_id").value;
5776 var el_uid = document.getElementById("uid");
5777 var uid = (el_uid == null) ? '' : el_uid.value;
5779 var el_ieId = document.getElementById("ieId");
5780 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5782 var el_mbox = document.getElementById("mbox");
5783 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5785 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5786 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5790 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5793 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5794 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5795 parent_id = parentIdValue;
5796 parent_type = parentTypeValue;
5798 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5799 // baseline viability check
5801 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5802 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5804 } else if(subj == '' && !isDraft) {
5805 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5808 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5810 } else if(html == '' && !isDraft) {
5811 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5816 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5817 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5818 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5819 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5820 html = html.replace(/</ig, "sugarLessThan");
5821 html = html.replace(/>/ig, "sugarGreaterThan");
5823 form.sendDescription.value = html;
5824 form.sendSubject.value = subj;
5825 form.sendTo.value = to;
5826 form.sendCc.value = cc;
5827 form.sendBcc.value = bcc;
5828 form.email_id.value = email_id;
5829 form.composeType.value = composeType;
5830 form.composeLayoutId.value = 'composeLayout' + idx;
5831 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5832 form.saveToSugar.value = 1;
5833 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5834 form.parent_type.value = parent_type;
5835 form.parent_id.value = parent_id;
5836 form.uid.value = uid;
5837 form.ieId.value = ieId;
5838 form.mbox.value = mbox;
5840 // email attachments
5841 var addedFiles = document.getElementById('addedFiles' + idx);
5843 for(i=0; i<addedFiles.childNodes.length; i++) {
5844 var bucket = addedFiles.childNodes[i];
5846 for(j=0; j<bucket.childNodes.length; j++) {
5847 var node = bucket.childNodes[j];
5848 var nName = new String(node.name);
5850 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5851 if(form.attachments.value != '') {
5852 form.attachments.value += "::";
5854 form.attachments.value += node.value;
5861 var addedDocs = document.getElementById('addedDocuments' + idx);
5863 for(i=0; i<addedDocs.childNodes.length; i++) {
5864 var cNode = addedDocs.childNodes[i];
5865 for(j=0; j<cNode.childNodes.length; j++) {
5866 var node = cNode.childNodes[j];
5867 var nName = new String(node.name);
5868 if(node.type == 'hidden' && nName.match(/documentId/)) {
5869 if(form.documents.value != '') {
5870 form.documents.value += "::";
5872 form.documents.value += node.value;
5878 // template attachments
5879 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5880 if(addedTemplateAttachments) {
5881 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5882 var cNode = addedTemplateAttachments.childNodes[i];
5883 for(j=0; j<cNode.childNodes.length; j++) {
5884 var node = cNode.childNodes[j];
5885 var nName = new String(node.name);
5886 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5887 if(form.templateAttachments.value != "") {
5888 form.templateAttachments.value += "::";
5890 form.templateAttachments.value += node.value;
5896 // remove attachments
5897 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5899 YAHOO.util.Connect.setForm(form);
5901 AjaxObject.target = 'frameFlex';
5903 // sending a draft email
5904 if(!isDraft && in_draft) {
5906 SE.listView.removeRowByUid(email_id);
5909 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5910 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5912 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5916 * Handles clicking the email address link from a given view
5918 composePackage : function() {
5919 if(composePackage != null) {
5920 SE.composeLayout.c0_composeNewEmail();
5923 if(composePackage.to_email_addrs) {
5924 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5926 if (composePackage.subject != null && composePackage.subject.length > 0) {
5927 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5930 //If no parent fields are set in the composePackage, ensure they are cleared.
5931 var parentFields = ['parent_type','parent_name','parent_id'];
5932 for(var i=0;i<parentFields.length;i++)
5934 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5935 composePackage[parentFields[i]] = "";
5938 document.getElementById("parent_type").value = composePackage.parent_type;
5939 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5940 document.getElementById("parent_id").value = composePackage.parent_id;
5941 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5942 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5944 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5945 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5947 if (composePackage.body != null && composePackage.body.length > 0) {
5948 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5949 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5950 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5952 if (composePackage.attachments != null) {
5953 SE.composeLayout.loadAttachments(composePackage.attachments);
5956 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5957 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5958 SE.util.emptySelectOptions(addressFrom);
5959 var fromAccountOpts = composePackage.fromAccounts.data;
5960 for(i=0; i<fromAccountOpts.length; i++) {
5961 var key = fromAccountOpts[i].value;
5962 var display = fromAccountOpts[i].text;
5963 var opt = new Option(display, key);
5964 if (fromAccountOpts[i].selected) {
5965 opt.selected = true;
5967 addressFrom.options.add(opt);
5974 setContentOnThisTiny : function() {
5975 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5976 var tinyHTML = tiny.getContent();
5977 composePackage.body = decodeURI(encodeURI(composePackage.body));
5978 // cn: bug 14361 - text-only templates don't fill compose screen
5979 if(composePackage.body == '') {
5980 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
5982 //Flag determines if we should clear the tiny contents or just append
5983 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5984 SE.composeLayout.tinyHTML = '';
5986 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
5988 tiny.setContent(SE.composeLayout.tinyHTML);
5989 //Indicate that the contents has been loaded successfully.
5990 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5993 * Confirms closure of a compose screen if "x" is clicked
5995 confirmClose : function(panel) {
5996 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
5997 SE.composeLayout.closeCompose(panel.id);
6005 * forces close of a compose screen
6007 forceCloseCompose : function(id) {
6008 SE.composeLayout.closeCompose(id);
6010 // handle flow back to originating view
6011 if(composePackage) {
6012 // check if it's a module we need to return to
6013 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6014 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6015 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6016 window.location = url;
6023 * closes the editor that just sent email
6024 * @param string id ID of composeLayout tab
6026 closeCompose : function(id) {
6027 // destroy tinyMCE instance
6028 var idx = id.substr(13, id.length);
6029 var instanceId = "htmleditor" + idx;
6030 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6032 // nullify DOM and namespace values.
6034 SE.composeLayout[idx] = null;
6035 SE.tinyInstances[instanceId] = null;
6036 var tabsArray = SE.innerLayout.get("tabs");
6037 for (i = 0 ; i < tabsArray.length ; i++) {
6038 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6039 tabsArray[i].close();
6043 //SE.innerLayout.getTab(idx).close();
6047 * Enable the quick search for the compose relate field or search tab
6049 enableQuickSearchRelate: function(idx,overides){
6051 if(typeof overides != 'undefined')
6053 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6054 var newModule = document.getElementById(newModuleID).value;
6055 var formName = overides['formName'];
6056 var fieldName = overides['fieldName'];
6057 var fieldId = overides['fieldId'];
6058 var fullName = formName + "_" + fieldName;
6059 var postBlurFunction = null;
6063 var newModule = document.getElementById('data_parent_type'+idx).value;
6064 var formName = 'emailCompose'+idx;
6065 var fieldName = 'data_parent_name'+idx;
6066 var fieldId = 'data_parent_id'+idx;
6067 var fullName = formName + "_" + fieldName;
6068 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6071 if(typeof sqs_objects == 'undefined')
6072 window['sqs_objects'] = new Array;
6074 window['sqs_objects'][fullName] = {
6077 modules:[newModule],
6079 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6080 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6081 post_onblur_function: postBlurFunction,
6082 order:"name","limit":"30","no_match_text":"No Match"};
6085 if(typeof QSProcessedFieldsArray != 'undefined')
6086 QSProcessedFieldsArray[fullName] = false;
6087 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6088 QSFieldsArray[fullName].destroy();
6089 delete QSFieldsArray[fullName];
6091 if (Dom.get(fullName + "_results")) {
6092 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6098 qsAddAddress : function(o) {
6099 if (o.name != "" && o.email1 != "")
6101 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6102 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6106 * Returns a new instance ID, 0-index
6108 getNewInstanceId : function() {
6109 this.currentInstanceId = this.currentInstanceId + 1;
6110 return this.currentInstanceId;
6114 * 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.
6116 loadAttachments : function(result) {
6117 var idx = SE.composeLayout.currentInstanceId;
6119 if(typeof(result) == 'object') {
6120 //jchi #20680. Clean the former template attachments;
6121 var basket = document.getElementById('addedTemplateAttachments' + idx);
6122 if(basket.innerHTML != ''){
6123 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6125 basket.innerHTML = '';
6130 if(typeof result[i] == 'object') {
6131 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6132 var bean = result[i];
6133 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6134 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6141 * fills drop-down values for email templates and signatures
6143 setComposeOptions : function(idx) {
6144 // send from accounts
6145 var addressFrom = document.getElementById('addressFrom' + idx);
6147 if (addressFrom.options.length <= 0) {
6148 SE.util.emptySelectOptions(addressFrom);
6149 var fromAccountOpts = SE.composeLayout.fromAccounts;
6150 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6151 var key = fromAccountOpts[id].value;
6152 var display = fromAccountOpts[id].text;
6153 var is_default = false;
6154 if(key == SUGAR.default_inbound_accnt_id)
6156 var opt = new Option(display, key);
6157 addressFrom.options.add(opt);
6158 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6163 var et = document.getElementById('email_template' + idx);
6164 SE.util.emptySelectOptions(et);
6166 for(var key in this.emailTemplates) { // iterate through assoc array
6167 var display = this.emailTemplates[key];
6168 var opt = new Option(display, key);
6169 et.options.add(opt);
6173 var sigs = document.getElementById('signatures' + idx);
6174 SE.util.emptySelectOptions(sigs);
6176 for(var key in this.signatures) { // iterate through assoc array
6177 var display = this.signatures[key];
6178 var opt = new Option(display, key);
6180 if(key == SE.userPrefs.signatures.signature_default) {
6181 opt.selected = true;
6184 sigs.options.add(opt);
6187 // html/plain email?
6188 var htmlEmail = document.getElementById('setEditor' + idx);
6189 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6190 htmlEmail.checked = true;
6192 htmlEmail.checked = false;
6195 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6199 * After compose screen is rendered, async call to get email body from Sugar
6201 replyForwardEmailStage2 : function() {
6202 SE.util.clearHiddenFieldValues('emailUIForm');
6203 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6205 var ieId = SE.composeLayout.replyForwardObj.ieId;
6206 var uid = SE.composeLayout.replyForwardObj.uid;
6207 var mbox = SE.composeLayout.replyForwardObj.mbox;
6208 var type = SE.composeLayout.replyForwardObj.type;
6209 var idx = SE.composeLayout.currentInstanceId;
6211 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6213 document.getElementById('emailSubject' + idx).value = type;
6214 document.getElementById('emailUIAction').value = 'composeEmail';
6215 document.getElementById('composeType').value = type;
6216 document.getElementById('ieId').value = ieId;
6217 document.getElementById('uid').value = uid;
6218 document.getElementById('mbox').value = mbox;
6219 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6220 var formObject = document.getElementById('emailUIForm');
6221 YAHOO.util.Connect.setForm(formObject);
6223 var sendType = type;
6224 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6228 * Show the hidden cc or bcc fields
6230 showHiddenAddress: function(addrType,idx){
6232 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6233 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6234 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6235 this[addrType+'Hidden'+idx] = false;
6237 //After bcc or cc is added, move options below last addr field
6238 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6240 //If both cc and bcc hidden, remove the empty row containing text.
6241 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6242 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6243 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6245 SE.composeLayout.resizeEditor(idx);
6248 * Hide the cc and bcc fields if they were shown.
6250 hideHiddenAddresses: function(idx){
6252 var addrTypes = ['cc','bcc'];
6253 for(var i = 0;i<addrTypes.length;i++)
6255 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6256 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6257 this[addrTypes[i] + 'Hidden'+idx] = true
6260 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6261 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6262 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6266 //// END SE.composeLayout
6267 ///////////////////////////////////////////////////////////////////////////////
6268 ///////////////////////////////////////////////////////////////////////////////
6272 * Cleans serialized UID lists of duplicates
6276 cleanUids : function(str) {
6277 var seen = new Object();
6279 var arr = new String(str).split(",");
6281 for(var i=0; i<arr.length; i++) {
6286 clean += (clean != "") ? "," : "";
6288 seen[arr[i]] = true;
6295 * Clears hidden field values
6296 * @param string id ID of form element to clear
6298 clearHiddenFieldValues : function(id) {
6299 var form = document.getElementById(id);
6301 for(i=0; i<form.elements.length; i++) {
6302 if(form.elements[i].type == 'hidden') {
6303 var e = form.elements[i];
6304 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6312 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6314 emptySelectOptions : function(el) {
6316 for(i=el.childNodes.length - 1; i >= 0; i--) {
6317 if(el.childNodes[i]) {
6318 el.removeChild(el.childNodes[i]);
6325 * Returns the MBOX path in the manner php_imap expects:
6326 * ie: INBOX.DEBUG.test
6327 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6329 generateMboxPath : function(str) {
6330 var ex = str.split("::");
6332 /* we have a serialized MBOX path */
6336 for(var i=0; i<ex.length; i++) {
6337 if(ex[i] == 'INBOX') {
6349 /* we have a Sugar folder GUID - do nothing */
6357 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6358 * @param HTMLElement el
6359 * @return string GUID of found element or empty on failure
6361 getGuidFromElement : function(el) {
6367 for(var i=0; i<iterations; i++) {
6369 if(el.id.match(SE.reGUID)) {
6381 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6384 getPanelId : function() {
6385 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6389 * wrapper to handle weirdness with IE
6390 * @param string instanceId
6391 * @return tinyMCE Controller object
6393 getTiny : function(instanceId) {
6394 if(instanceId == '') {
6398 var t = tinyMCE.getInstanceById(instanceId);
6402 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6408 * Simple check for MSIE browser
6412 var nav = new String(navigator.appVersion);
6413 if(nav.match(/MSIE/)) {
6420 * Recursively removes an element from the DOM
6421 * @param HTMLElement
6423 removeElementRecursive : function(el) {
6424 this.emptySelectOptions(el);
6431 sleep : function(secs) {
6432 setTimeout("void(0);", secs);
6436 * Converts a <select> element to an Ext.form.combobox
6438 convertSelect : function(select) {
6439 alert('in convertSelect');
6440 if (typeof(select) == "string") {
6441 select = document.getElementById(select);
6445 findChildNode : function (parent, property, value) {
6446 for (i in parent.children) {
6447 var child = parent.children[i];
6448 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6450 var searchChild = SE.util.findChildNode(child, property, value);
6457 cascadeNodes : function (parent, fn, scope, args) {
6458 for (i in parent.children) {
6459 var child = parent.children[i];
6460 var s = scope ? scope : child;
6461 var a = args ? args : child;
6463 SE.util.cascadeNodes(child, fn, scope, args);
6470 ///////////////////////////////////////////////////////////////////////////////
6473 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6475 /*********************************************************************************
6476 * SugarCRM is a customer relationship management program developed by
6477 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6479 * This program is free software; you can redistribute it and/or modify it under
6480 * the terms of the GNU Affero General Public License version 3 as published by the
6481 * Free Software Foundation with the addition of the following permission added
6482 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6483 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6484 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6486 * This program is distributed in the hope that it will be useful, but WITHOUT
6487 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6488 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6491 * You should have received a copy of the GNU Affero General Public License along with
6492 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6493 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6496 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6497 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6499 * The interactive user interfaces in modified source and object code versions
6500 * of this program must display Appropriate Legal Notices, as required under
6501 * Section 5 of the GNU Affero General Public License version 3.
6503 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6504 * these Appropriate Legal Notices must retain the display of the "Powered by
6505 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6506 * technical reasons, the Appropriate Legal Notices must display the words
6507 * "Powered by SugarCRM".
6508 ********************************************************************************/
6511 if (typeof console == "undefined")
6512 console = { log: function(o) {alert(o)} };
6516 currentRequestObject : null,
6517 //timeout : 30000, // 30 second timeout default
6518 timeout : 9999999999, // 30 second timeout default
6520 trail : new Array(),
6524 _reset : function() {
6525 this.timeout = 30000;
6526 this.forceAbort = false;
6529 folderRenameCleanup : function() {
6530 SUGAR.email2.folders.setSugarFolders();
6533 fullSyncCleanup : function(o) {
6534 this.folders.checkMailCleanup(o);
6535 SUGAR.email2.settings.settingsDialog.hide();
6540 composeCache : function(o) {
6541 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6542 // get email templates and user signatures
6543 var ret = JSON.parse(o.responseText);
6545 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6546 SUGAR.email2.composeLayout.signatures = ret.signatures;
6547 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6549 SUGAR.email2.composeLayout.setComposeOptions(idx);
6551 //Set the error array so we can notify the user when they try to hit send if any errors
6552 //are present. We will also notify them now (after hitting compose button).
6553 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6556 //if error element is returning an array, then check the length to make sure we have error messages
6557 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6558 //add error messages for display
6559 for(i in ret.errorArray)
6560 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6561 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6562 //if error element is returning an object, and the object value is not empty or null, then display error message
6563 for(i in ret.errorArray)
6564 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6567 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6569 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6571 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6577 handleDeleteSignature : function(o) {
6579 var ret = JSON.parse(o.responseText);
6580 SUGAR.email2.composeLayout.signatures = ret.signatures;
6581 var field = document.getElementById('signature_id');
6582 SUGAR.email2.util.emptySelectOptions(field);
6584 for(var i in ret.signatures) { // iterate through assoc array
6585 var opt = new Option(ret.signatures[i], i);
6586 field.options.add(opt);
6588 setSigEditButtonVisibility();
6593 handleDeleteReturn : function(o) {
6594 // force refresh ListView
6596 if(document.getElementById('focusEmailMbox')) {
6597 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6600 // need to display success message before calling next async call?
6601 document.getElementById(this.target).innerHTML = o.responseText;
6606 handleFailure : function(o) {
6608 overlay('Exception occurred...', o.statusText, 'alert');
6609 if(document.getElementById('saveButton')) {
6610 document.getElementById('saveButton').disabled = false;
6614 handleReplyForward : function(o) {
6615 var a = JSON.parse(o.responseText);
6617 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6619 document.getElementById('email_id' + idx).value = a.uid;
6620 document.getElementById('emailSubject' + idx).value = a.name;
6621 document.getElementById('addressTO' + idx).value = a.from;
6622 document.getElementById('uid' + idx).value = a.uid;
6624 document.getElementById('addressCC' + idx).value = a.cc;
6625 SE.composeLayout.showHiddenAddress('cc', idx);
6629 document.getElementById('type' + idx).value = a.type;
6632 // apply attachment values
6633 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6635 setTimeout("callbackReplyForward.finish(globalA);", 500);
6638 handleReplyForwardForDraft : function(o) {
6639 var a = JSON.parse(o.responseText);
6641 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6643 document.getElementById('email_id' + idx).value = a.uid;
6644 document.getElementById('emailSubject' + idx).value = a.name;
6645 document.getElementById('addressTO' + idx).value = a.to;
6648 document.getElementById('addressCC' + idx).value = a.cc;
6649 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6653 document.getElementById('addressBCC' + idx).value = a.bcc;
6654 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6659 document.getElementById('type' + idx).value = a.type;
6663 // apply attachment values
6664 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6666 setTimeout("callbackReplyForward.finish(globalA);", 500);
6671 handleSuccess : function(o) {
6672 document.getElementById(this.target).innerHTML = o.responseText;
6678 ieDeleteSuccess : function(o) {
6681 var ret = JSON.parse(o.responseText);
6683 SUGAR.email2.accounts.refreshInboundAccountTable();
6684 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6685 SUGAR.email2.accounts.rebuildFolderList();
6691 ieSaveSuccess : function(o) {
6692 document.getElementById('saveButton').disabled = false;
6693 var a = JSON.parse(o.responseText);
6696 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6697 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6699 resp = JSON.parse(o.responseText);
6700 SUGAR.email2.accounts.refreshInboundAccountTable();
6701 SUGAR.email2.accounts.refreshOuboundAccountTable();
6702 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6703 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6707 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6714 loadAttachments : function(o) {
6715 var result = JSON.parse(o.responseText);
6717 SUGAR.email2.composeLayout.loadAttachments(result);
6722 loadSignature : function(o) {
6723 var ret = JSON.parse(o.responseText);
6724 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6725 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6729 * Follow up to mark email read|unread|flagged
6731 markEmailCleanup : function(o) {
6732 var ret = JSON.parse(o.responseText);
6733 if (!ret['status']) {
6735 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6737 SUGAR.email2.contextMenus.markEmailCleanup();
6743 rebuildShowFolders : function(o) {
6744 var t = JSON.parse(o.responseText);
6745 var show = document.getElementById('ieAccountListShow');
6747 SUGAR.email2.util.emptySelectOptions(show);
6749 for(i=0; i<t.length; i++) { // iterate through assoc array
6750 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6751 opt.selected = t[i].selected;
6752 show.options.add(opt);
6755 SUGAR.email2.accounts.renderTree();
6759 saveListViewSortOrderPart2 : function() {
6760 // create the JSON string the func expects
6761 focusFolderPath = '[ "Home", "' + ieName + '"';
6763 var f = new String(focusFolder);
6764 var fEx = f.split('.');
6766 for(i=0; i<fEx.length; i++) {
6767 focusFolderPath += ', "' + fEx[i] +'"'
6770 focusFolderPath += ']';
6772 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6773 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6779 sendEmailCleanUp : function(o) {
6781 var ret = JSON.parse(o.responseText);
6783 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6784 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6785 } else if (o.responseText) {
6786 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6789 if (typeof(SE.grid) != 'undefined')
6790 SE.listView.refreshGrid();
6791 //Disabled while address book is disabled
6793 //If this call back was initiated by quick compose from a Detail View page, refresh the
6794 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6795 //close the shortcut bar menu
6796 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6797 if(action_sugar_grp1 == 'DetailView') {
6798 showSubPanel('history',null,true);
6799 } else if(action_sugar_grp1 == 'quickcreate') {
6800 closeEmailOverlay();
6806 ieSendSuccess : function(o) {
6808 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6813 settingsFolderRefresh : function(o) {
6814 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6815 var ret = JSON.parse(o.responseText);
6816 var user = document.getElementById('userFolders');
6818 SUGAR.email2.util.emptySelectOptions(user);
6820 for(i=0; i<ret.userFolders.length; i++) {
6821 var display = ret.userFolders[i].name;
6822 var value = ret.userFolders[i].id;
6823 var selected = (ret.userFolders[i].selected != "") ? true : false;
6824 var opt = new Option(display, value, selected);
6825 opt.selected = selected;
6826 user.options.add(opt);
6832 startRequest : function(callback, args, forceAbort) {
6833 if(this.currentRequestObject != null) {
6834 if(this.forceAbort == true) {
6835 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6838 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6842 requestInProgress : function() {
6843 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6848 updateFolderSubscriptions : function() {
6849 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6850 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6856 updateFrameFolder : function() {
6857 SUGAR.email2.folders.checkEmailAccounts();
6862 updateUserPrefs : function(o) {
6863 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6864 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6869 uploadAttachmentSuccessful : function(o) {
6871 document.getElementById('email_attachment').value = '';
6873 var ret = JSON.parse(o.responseText);
6874 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6875 var overall = document.getElementById('addedFiles' + idx);
6876 var index = overall.childNodes.length;
6878 "<div id='email_attachment_bucket" + idx + index + "'>" +
6880 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6881 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6882 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6884 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6885 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6887 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6889 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6892 overall.innerHTML += out;
6893 if(SUGAR.email2.util.isIe()) {
6894 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6898 SUGAR.email2.addFileDialog.hide();
6899 // focus attachments
6900 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6905 ///////////////////////////////////////////////////////////////////////////
6906 //// PER MODULE CALLBACK OBJECTS
6907 AjaxObject.accounts = {
6908 saveOutboundCleanup : function(o) {
6909 SUGAR.email2.accounts.refreshOuboundAccountTable();
6910 SUGAR.email2.accounts.outboundDialog.hide();
6911 var id = o.responseText;
6912 SUGAR.email2.accounts.newAddedOutboundId = id;
6914 saveDefaultOutboundCleanup: function(o){
6917 callbackEditOutbound : {
6918 success : function(o)
6920 var ret = JSON.parse(o.responseText);
6922 SUGAR.email2.accounts.showAddSmtp();
6925 document.getElementById("mail_id").value = ret.id;
6926 document.getElementById("type").value = ret.type;
6927 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6928 document.getElementById("mail_name").value = ret.name;
6929 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6930 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6931 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6932 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6933 //document.getElementById("mail_smtppass").value = ret.mail_smtppass;
6934 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6935 SUGAR.email2.accounts.smtp_authenticate_field_display();
6936 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6938 if(ret.type == 'system-override') {
6939 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6940 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6943 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6944 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6949 failure : AjaxObject.handleFailure,
6950 timeout : AjaxObject.timeout,
6953 callbackDeleteOutbound : {
6954 success : function(o) {
6955 var ret = JSON.parse(o.responseText);
6958 if(confirm(ret.error_message))
6960 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6961 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6969 SUGAR.email2.accounts.refreshOuboundAccountTable();
6973 failure : AjaxObject.handleFailure,
6974 timeout : AjaxObject.timeout,
6978 callbackCheckMailProgress : {
6979 success : function(o) {
6980 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6981 SUGAR.email2.accounts.totalMsgCount = -1;
6984 //Check for server timeout / errors
6985 var ret = JSON.parse(o.responseText);
6988 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6990 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6991 SUGAR.email2.accounts.totalMsgCount = -1;
6992 //SUGAR.email2.folders.rebuildFolders();
6996 var currIeId = ret['ieid'];
6999 var serverCount = ret.count;
7001 if (ret['status'] == 'done') {
7002 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7003 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7007 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7008 //Go to next account
7009 currIeId = SUGAR.email2.accounts.ieIds[i+1];
7011 SUGAR.email2.accounts.totalMsgCount = -1;
7016 else if (ret.mbox && ret.totalcount && ret.count) {
7017 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7018 if (ret.count >= ret.totalcount) {
7021 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7022 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7025 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7026 SUGAR.email2.accounts.totalMsgCount = -1;
7031 SUGAR.email2.accounts.totalMsgCount = -1;
7033 SUGAR.email2.folders.rebuildFolders();
7034 SE.listView.refreshGrid();
7035 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7036 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7037 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7038 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7040 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7041 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7042 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7043 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7044 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7047 failure : AjaxObject.handleFailure,
7048 timeout : AjaxObject.timeout,
7053 ///////////////////////////////////////////////////////////////////////////////
7055 AjaxObject.composeLayout = {
7057 * Populates the record id
7059 saveDraftCleanup : function(o) {
7061 var ret = JSON.parse(o.responseText);
7063 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7064 else if (o.responseText)
7065 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7069 AjaxObject.composeLayout.callback = {
7071 success : AjaxObject.composeLayout.saveDraftCleanup,
7072 failure : AjaxObject.handleFailure,
7073 timeout : AjaxObject.timeout,
7078 AjaxObject.detailView = {
7080 * Pops-up a printable view of an email
7082 displayPrintable : function(o) {
7083 var ret = JSON.parse(o.responseText);
7084 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7085 // 2 below must be in global context
7087 meta['panelId'] = SUGAR.email2.util.getPanelId();
7088 email = ret.meta.email;
7089 if (typeof(email.cc) == 'undefined') {
7093 var out = displayTemplate.exec({
7094 'app_strings' : app_strings,
7098 'email' : meta.email
7101 // open popup window
7102 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7103 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7105 popup.document.write(out);
7106 popup.document.close();
7110 * Takes formatted response and creates a modal pop-over containing a title and content
7112 displayView : function(o) {
7113 var SED = SUGAR.email2.detailView;
7114 var ret = JSON.parse(o.responseText);
7116 if(!SED.viewDialog) {
7117 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7121 constraintoviewport: true,
7124 SED.viewDialog.renderEvent.subscribe(function() {
7125 var content = this.body.firstChild;
7126 var viewH = YAHOO.util.Dom.getViewportHeight();
7128 this.body.style.overflow = "auto";
7129 this.body.style.width = "800px";
7130 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7134 SED.viewDialog.setHeader(ret.title);
7135 SED.viewDialog.setBody(ret.html);
7136 SED.viewDialog.render();
7137 SED.viewDialog.show();
7141 * Generates a modal popup to populate with the contents of bean's full EditView
7143 showQuickCreateForm : function(o) {
7144 var SED = SUGAR.email2.detailView;
7145 var ret = JSON.parse(o.responseText);
7147 if(!SED.quickCreateDialog) {
7148 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7152 constraintoviewport: true,
7156 SED.quickCreateDialog.renderEvent.subscribe(function() {
7157 var viewH = YAHOO.util.Dom.getViewportHeight();
7159 for (var i in this.body.childNodes) {
7160 if (this.body.childNodes[i].clientHeight) {
7161 contH += this.body.childNodes[i].clientHeight;
7162 } else if (this.body.childNodes[i].offsetHeight) {
7163 contH += this.body.childNodes[i].offsetHeight;
7166 this.body.style.width = "800px";
7167 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7168 this.body.style.overflow = "auto";
7169 }, SED.quickCreateDialog);
7171 SED.quickCreateDialog.hideEvent.subscribe(function(){
7172 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7173 /*for(var qsField in qsFields){
7174 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7175 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7178 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7181 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7183 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7184 SED.quickCreateDialog.render();
7185 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7187 SED.quickCreateDialog.ieId = ret.ieId;
7188 SED.quickCreateDialog.uid = ret.uid;
7189 SED.quickCreateDialog.mbox = ret.mbox;
7190 SED.quickCreateDialog.qcmodule = ret.module;
7192 SED.quickCreateDialog.show();
7194 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7196 editForm.module.value = 'Emails';
7197 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7198 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7199 var instId = ret.module + count;
7200 SED.quickCreateEmailsToAdd = ret.emailAddress;
7201 SED.quickCreateEmailCallback = function(instId, tableId) {
7202 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7203 if (typeof(eaw) == "undefined")
7204 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7205 + instId + "','" + tableId + "');", 100);
7206 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7208 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7209 + instId + "','" + tableId + "');", 100);
7213 saveQuickCreateForm : function(o) {
7215 SUGAR.email2.detailView.quickCreateDialog.hide();
7216 validate['EditView'] = [ ];
7219 saveQuickCreateFormAndReply : function(o) {
7221 var ret = JSON.parse(o.responseText);
7222 SUGAR.email2.detailView.quickCreateDialog.hide();
7223 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7224 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7226 var emailID = ret.id;
7227 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7229 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7231 //Cean the validate cache to prevent errors on the next call
7232 validate['EditView'] = [ ];
7235 saveQuickCreateFormAndAddToAddressBook : function(o) {
7237 SUGAR.email2.detailView.quickCreateDialog.hide();
7238 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7239 validate['EditView'] = [ ];
7242 handleAssignmentDialogAssignAction : function() {
7245 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7247 var dist = 'direct';
7251 var found_teams = false;
7252 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7253 if(!found_teams && assign_user_id == '' )
7255 alert(warning_message);
7259 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7261 for(i=0; i<emailUids.length; i++) {
7263 uids += app_strings.LBL_EMAIL_DELIMITER;
7265 uids += emailUids[i];
7268 var row = SUGAR.email2.grid.getSelectedRows()[0];
7269 var data = SUGAR.email2.grid.getRecord(row).getData();
7270 var ieid = data.ieId;
7271 var mbox = data.mbox;
7272 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7273 SUGAR.email2.contextMenus.assignToDialogue.hide();
7274 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7278 handleAssignmentDialogDeleteAction : function() {
7279 // TO pass list of UIDS/emailIds
7280 var uids = SUGAR.email2.listView.getUidsFromSelection();
7281 var row = SUGAR.email2.grid.getSelections()[0];
7282 var ieid = row.data.ieId;
7283 var mbox = row.data.mbox;
7284 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7285 SUGAR.email2.contextMenus.assignmentDialog.hide();
7286 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7292 showEmailDetailView : function(o) {
7294 var SED = SUGAR.email2.detailView;
7295 var ret = JSON.parse(o.responseText);
7297 if(!SED.quickCreateDialog) {
7298 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7302 constraintoviewport: true,
7304 autofillheight: "body",
7307 SED.quickCreateDialog.renderEvent.subscribe(function() {
7308 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7310 for (var i in this.body.childNodes) {
7311 if (this.body.childNodes[i].offsetHeight)
7312 contH += this.body.childNodes[i].offsetHeight;
7314 this.body.style.overflow = "auto";
7315 this.body.style.width = "800px";
7316 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7318 }, SED.quickCreateDialog);
7320 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7321 SED.quickCreateDialog.setBody(ret.html);
7322 SED.quickCreateDialog.render();
7323 SUGAR.util.evalScript(ret.html);
7324 SED.quickCreateDialog.show();
7327 showAssignmentDialogWithData : function(o) {
7328 var SEC = SUGAR.email2.contextMenus;
7330 var ret = JSON.parse(o.responseText);
7331 if (!SEC.assignmentDialog) {
7332 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7335 constraintoviewport: true,
7338 SEC.assignmentDialog.setBody("");
7339 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7340 SEC.assignmentDialog.renderEvent.subscribe(function() {
7341 var iev = YAHOO.util.Dom.get("Distribute");
7343 this.body.style.width = "700px";
7345 }, SEC.assignmentDialog);
7346 SEC.assignmentDialog.render();
7348 SEC.assignmentDialog.setBody(ret);
7349 SEC.assignmentDialog.render();
7351 SEC.assignmentDialog.show();
7352 SUGAR.util.evalScript(ret);
7355 showImportForm : function(o) {
7356 var SED = SUGAR.email2.detailView;
7357 var ret = JSON.parse(o.responseText);
7359 document.getElementById('quickCreateContent').innerHTML = "";
7365 if(!SED.importDialog) {
7366 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7370 constraintoviewport: true,
7372 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7373 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7377 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7378 SED.importDialog.setBody("");
7379 SED.importDialog.hideEvent.subscribe(function(){
7380 for(var i in QSFieldsArray) {
7381 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7382 QSFieldsArray[i].destroy();
7383 delete QSFieldsArray[i];
7385 if (QSProcessedFieldsArray[i]) {
7386 QSProcessedFieldsArray[i] = false;
7390 SED.importDialog.renderEvent.subscribe(function() {
7391 var iev = YAHOO.util.Dom.get("ImportEditView");
7393 //this.body.style.height = (iev.clientHeight + 10) + "px";
7394 this.body.style.width = "600px";
7396 }, SED.importDialog);
7397 SED.importDialog.render();
7399 SED.importDialog.setBody(ret.html);
7400 SED.importDialog.ret = ret;
7401 SUGAR.util.evalScript(ret.html);
7402 SED.importDialog.render();
7404 SED.importDialog.show();
7405 SED.importDialog.focusFirstButton();
7407 getImportAction : function(ret) {
7408 if (!check_form('ImportEditView')) return false;
7409 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7410 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7414 var editView = document.getElementById('ImportEditView');
7415 if (editView.assigned_user_id != null) {
7416 get = get + "&user_id=" + editView.assigned_user_id.value
7417 //var user_id = editView.assigned_user_id.value;
7419 var parent_id = editView.parent_id.value;
7420 var parent_type = editView.parent_type.value;
7421 var row = SUGAR.email2.grid.getSelectedRows()[0];
7422 row = SUGAR.email2.grid.getRecord(row);
7423 var data = row.getData();
7424 var ieId = data.ieId;
7425 var mbox = data.mbox;
7426 var serverDelete = editView.serverDelete.checked;
7427 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7429 for(i=0; i<emailUids.length; i++) {
7431 uids += app_strings.LBL_EMAIL_DELIMITER;
7433 uids += emailUids[i];
7436 var action = 'importEmail&uid=';
7438 action = 'moveEmails';
7439 action = action + '&sourceFolder=' + ret['srcFolder'];
7440 action = action + '&sourceIeId=' + ret['srcIeId'];
7441 action = action + '&destinationFolder=' + ret['dstFolder'];
7442 action = action + '&destinationIeId=' + ret['dstIeId'];
7443 action = action + '&emailUids=';
7445 if (action.search(/importEmail/) != -1) {
7446 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7448 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7451 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7452 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7453 SUGAR.email2.detailView.importDialog.hide();
7454 document.getElementById('importDialogContent').innerHTML = "";
7457 showRelateForm : function(o) {
7458 var SED = SUGAR.email2.detailView;
7459 var ret = JSON.parse(o.responseText);
7460 document.getElementById('quickCreateContent').innerHTML = "";
7465 dialog_loaded = true;
7467 if(!SED.relateDialog) {
7468 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7473 constraintoviewport: true,
7475 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7476 if (!check_form('RelateEditView')) return false;
7478 var editView = document.getElementById('RelateEditView');
7479 var parent_id = editView.parent_id.value;
7480 var parent_type = editView.parent_type.value;
7481 var row = SUGAR.email2.grid.getSelectedRows()[0];
7482 row = SUGAR.email2.grid.getRecord(row);
7483 var ieId = row.getData().ieId;
7484 var mbox = row.getData().mbox;
7485 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7487 for(i=0; i<emailUids.length; i++) {
7489 uids += app_strings.LBL_EMAIL_DELIMITER;
7491 uids += emailUids[i];
7493 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7494 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7495 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7496 SED.relateDialog.hide();
7497 document.getElementById('relateDialogContent').innerHTML = "";
7502 SED.relateDialog.hideEvent.subscribe(function(){
7503 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7504 QSFieldsArray['ImportEditView_parent_name'].destroy();
7505 delete QSFieldsArray['ImportEditView_parent_name'];
7507 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7508 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7512 SED.relateDialog.renderEvent.subscribe(function() {
7513 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7515 for (var i in this.body.childNodes) {
7516 if (this.body.childNodes[i].clientHeight)
7517 contH += this.body.childNodes[i].clientHeight;
7519 }, SED.relateDialog);
7520 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7523 SED.relateDialog.setBody(ret.html);
7524 SED.relateDialog.render();
7525 SUGAR.util.evalScript(ret.html);
7526 SED.relateDialog.show();
7530 * DetailView callbacks
7532 AjaxObject.detailView.callback = {
7534 success : function(o) {
7536 var ret = JSON.parse(o.responseText);
7537 SUGAR.email2.detailView.consumeMetaDetail(ret);
7539 argument: [targetDiv],
7540 failure : AjaxObject.handleFailure,
7545 success : function(o) {
7547 var ret = JSON.parse(o.responseText);
7548 SUGAR.email2.detailView.consumeMetaPreview(ret);
7550 failure : AjaxObject.handleFailure,
7555 success : AjaxObject.detailView.displayPrintable,
7556 failure : AjaxObject.handleFailure,
7557 timeout : AjaxObject.timeout,
7561 success : AjaxObject.detailView.displayView,
7562 failure : AjaxObject.handleFailure,
7563 timeout : AjaxObject.timeout,
7572 AjaxObject.folders = {
7574 * check-mail post actions
7576 checkMailCleanup : function(o) {
7578 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7580 // refresh focus ListView
7581 SE.listView.refreshGrid();
7582 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7587 rebuildFolders : function(o) {
7590 var data = JSON.parse(o.responseText);
7592 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7593 SUGAR.email2.folders.setSugarFolders();
7596 AjaxObject.folders.callback = {
7598 success : AjaxObject.folders.checkMailCleanup,
7599 failure : AjaxObject.handleFailure,
7600 timeout : 600000, // 5 mins
7605 AjaxObject.rules = {
7606 loadRulesForSettings : function(o) {
7607 document.getElementById("rulesListCell").innerHTML = o.responseText;
7608 // assume we have the class we need
7609 SUGAR.routing.getStrings();
7610 SUGAR.routing.getDependentDropdowns();
7613 //// END PER MODULE CALLBACK OBJECTS
7614 ///////////////////////////////////////////////////////////////////////////
7618 success : AjaxObject.handleSuccess,
7619 failure : AjaxObject.handleFailure,
7620 timeout : AjaxObject.timeout,
7623 var callbackAccount = {
7624 success : AjaxObject.ieSaveSuccess,
7625 failure : AjaxObject.handleFailure,
7626 timeout : AjaxObject.timeout,
7629 var callbackAccountDelete = {
7630 success : AjaxObject.ieDeleteSuccess,
7631 failure : AjaxObject.handleFailure,
7632 timeout : AjaxObject.timeout,
7635 var callbackOutboundTest = {
7636 success : AjaxObject.ieSendSuccess,
7637 failure : AjaxObject.handleFailure,
7638 timeout : AjaxObject.timeout,
7644 var callbackTeamInfoForSettings = {
7645 success : function (o) {
7646 var data = JSON.parse(o.responseText);
7647 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7649 failure : AjaxObject.handleFailure,
7650 timeout : AjaxObject.timeout,
7655 var callbackStatusForImport = {
7656 success : function (o) {
7658 if (o.responseText != "") {
7659 var statusString = "";
7660 var data = JSON.parse(o.responseText);
7661 for(i=0; i<data.length; i++) {
7662 statusString = statusString + data[i] + '<br/>';
7664 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7666 SE.listView.refreshGrid();
7669 failure : AjaxObject.handleFailure,
7670 timeout : AjaxObject.timeout,
7674 var callbackComposeCache = {
7675 success : AjaxObject.composeCache,
7676 failure : AjaxObject.handleFailure,
7677 timeout : AjaxObject.timeout,
7680 var callbackDelete = {
7681 success : AjaxObject.handleDeleteReturn,
7682 failure : AjaxObject.handleFailure,
7683 timeout : AjaxObject.timeout,
7686 var callbackEmailDetailMultiple = {
7687 success : function(o) {
7689 var retMulti = JSON.parse(o.responseText);
7690 var ret = new Object();
7692 for(var i=0; i<retMulti.length; i++) {
7695 SUGAR.email2._setDetailCache(ret);
7696 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7699 failure : AjaxObject.handleFailure,
7703 var callbackListViewSortOrderChange = {
7704 success : AjaxObject.saveListViewSortOrderPart2,
7705 failure : AjaxObject.handleFailure,
7706 timeout : AjaxObject.timeout,
7708 argument : [ieId, ieName, focusFolder]
7710 var callbackEmptyTrash = {
7711 success : function(o) {
7713 AjaxObject.folderRenameCleanup;
7715 failure : AjaxObject.handleFailure,
7716 timeout : AjaxObject.timeout,
7719 var callbackClearCacheFiles = {
7720 success : function(o) {
7723 failure : AjaxObject.handleFailure,
7724 timeout : AjaxObject.timeout,
7727 var callbackFolderRename = {
7728 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7729 failure : AjaxObject.handleFailure,
7730 timeout : AjaxObject.timeout,
7733 var callbackFolderDelete = {
7734 success : function(o) {
7735 var ret = JSON.parse(o.responseText);
7737 if (ret.folder_id) {
7738 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7740 SUGAR.email2.tree.removeNode(node, true);
7741 } else if (ret.ieId && ret.mbox) {
7742 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7744 SUGAR.email2.tree.removeNode(node, true);
7747 //SUGAR.email2.folders.loadSettingFolder();
7750 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7753 failure : AjaxObject.handleFailure,
7754 timeout : AjaxObject.timeout,
7757 var callbackFolderSave = {
7758 success : function(o) {
7759 var ret = JSON.parse(o.responseText);
7761 switch(ret.action) {
7762 case 'newFolderSave':
7763 SUGAR.email2.folders.rebuildFolders();
7767 failure : AjaxObject.handleFailure,
7768 timeout : AjaxObject.timeout,
7771 var callbackFolderSubscriptions = {
7772 success : AjaxObject.updateFolderSubscriptions,
7773 failure : AjaxObject.handleFailure,
7774 timeout : AjaxObject.timeout,
7777 var callbackFolderUpdate = {
7778 success : AjaxObject.updateFrameFolder,
7779 failure : AjaxObject.handleFailure,
7780 timeout : AjaxObject.timeout,
7783 var callbackFolders = {
7784 success : AjaxObject.folders.rebuildFolders,
7785 //success : void(true),
7786 failure : AjaxObject.handleFailure,
7787 timeout : AjaxObject.timeout,
7790 var callbackFullSync = {
7791 success : AjaxObject.fullSyncCleanup,
7792 failure : AjaxObject.handleFailure,
7793 timeout : 9999999999999,
7796 var callbackGeneric = {
7797 success : function() {
7800 failure : AjaxObject.handleFailure,
7801 timeout : AjaxObject.timeout,
7804 var callbackIeAccountRetrieve = {
7805 success : function(o) {
7806 // return JSON encoding
7808 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7809 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7811 failure : AjaxObject.handleFailure,
7812 timeout : AjaxObject.timeout,
7815 var callbackImportOneEmail = {
7816 success : AjaxObject.detailView.showImportForm,
7817 failure : AjaxObject.handleFailure,
7818 timeout : AjaxObject.timeout,
7821 var callbackRelateEmail = {
7822 success : AjaxObject.detailView.showRelateForm,
7823 failure : AjaxObject.handleFailure,
7824 timeout : AjaxObject.timeout,
7827 var callbackEmailDetailView = {
7828 success : AjaxObject.detailView.showEmailDetailView,
7829 failure : AjaxObject.handleFailure,
7830 timeout : AjaxObject.timeout,
7833 var callbackAssignmentDialog = {
7834 success : AjaxObject.detailView.showAssignmentDialogWithData,
7835 failure : AjaxObject.handleFailure,
7836 timeout : AjaxObject.timeout,
7839 var callbackAssignmentAction = {
7840 success : function(o) {
7841 SE.listView.refreshGrid();
7843 if(o.responseText != '') {
7844 overlay('Assignment action result', o.responseText, 'alert');
7847 failure : AjaxObject.handleFailure,
7848 timeout : AjaxObject.timeout,
7851 var callbackMoveEmails = {
7852 success : function(o) {
7853 SE.listView.refreshGrid();
7855 if(o.responseText != '') {
7856 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7859 failure : AjaxObject.handleFailure,
7860 timeout : AjaxObject.timeout,
7863 var callbackLoadAttachments = {
7864 success : AjaxObject.loadAttachments,
7865 failure : AjaxObject.handleFailure,
7866 timeout : AjaxObject.timeout,
7869 var callbackLoadRules = {
7870 success : AjaxObject.rules.loadRulesForSettings,
7871 failure : AjaxObject.handleFailure,
7872 timeout : AjaxObject.timeout,
7875 var callbackLoadSignature = {
7876 success : AjaxObject.loadSignature,
7877 failure : AjaxObject.handleFailure,
7878 timeout : AjaxObject.timeout,
7881 var callbackDeleteSignature = {
7882 success : AjaxObject.handleDeleteSignature,
7883 failure : AjaxObject.handleFailure,
7884 timeout : AjaxObject.timeout,
7887 /*var callbackMoveEmails = {
7888 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7889 failure : AjaxObject.handleFailure,
7890 timeout : AjaxObject.timeout,
7893 var callbackOutboundSave = {
7894 success : AjaxObject.accounts.saveOutboundCleanup,
7895 failure : AjaxObject.handleFailure,
7896 timeout : AjaxObject.timeout,
7899 var callbackDefaultOutboundSave = {
7900 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7901 failure : AjaxObject.handleFailure,
7902 timeout : AjaxObject.timeout,
7905 var callbackQuickCreate = {
7906 success : AjaxObject.detailView.showQuickCreateForm,
7907 failure : AjaxObject.handleFailure,
7908 timeout : AjaxObject.timeout,
7911 var callbackQuickCreateSave = {
7912 success : AjaxObject.detailView.saveQuickCreateForm,
7913 failure : AjaxObject.handleFailure,
7914 timeout : AjaxObject.timeout,
7917 var callbackQuickCreateSaveAndAddToAddressBook = {
7918 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7919 failure : AjaxObject.handleFailure,
7920 timeout : AjaxObject.timeout,
7923 var callbackQuickCreateSaveAndReply = {
7924 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7925 failure : AjaxObject.handleFailure,
7926 timeout : AjaxObject.timeout,
7929 var callbackQuickCreateSaveAndReplyCase = {
7930 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7931 failure : AjaxObject.handleFailure,
7932 timeout : AjaxObject.timeout,
7935 var callbackRebuildShowAccountList = {
7936 success : AjaxObject.rebuildShowFolders,
7937 failure : AjaxObject.handleFailure,
7938 timeout : AjaxObject.timeout,
7942 var callbackRefreshSugarFolders = {
7943 success : function(o) {
7944 var t = JSON.parse(o.responseText);
7945 SUGAR.email2.folders.setSugarFoldersEnd(t);
7947 failure : AjaxObject.handleFailure,
7948 timeout : AjaxObject.timeout,
7951 var callbackReplyForward = {
7952 success : AjaxObject.handleReplyForward,
7953 finish : function(a, retryCount) {
7954 if (typeof(retryCount) == 'undefined') {
7959 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7960 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7962 var html = t.getContent();
7964 if (a.type != 'draft') {
7965 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7966 html += " <div><hr></div>" + a.description;
7968 html = " <div><hr></div>" + a.description + html;
7971 html = a.description;
7974 t.setContent(html);//
7977 if (retryCount < 5) {
7978 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7982 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7983 if (tabArray != null && tabArray.length > 0) {
7984 for (i = 0 ; i < tabArray.length ; i++) {
7985 var tabObject = tabArray[i];
7986 if (tabObject.get("id") == ("composeTab" + idx)) {
7987 var tabLabel = a.name;
7988 if (tabLabel != null && tabLabel.length > 25) {
7989 tabLabel = tabLabel.substring(0, 25) + "...";
7991 tabObject.get("labelEl").firstChild.data = tabLabel;
7997 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
7998 if (a.parent_name != null && a.parent_name != "") {
7999 document.getElementById('data_parent_name' + idx).value = a.parent_name;
8001 if (a.parent_type != null && a.parent_type != "") {
8002 document.getElementById('data_parent_type' + idx).value = a.parent_type;
8004 if (a.parent_id != null && a.parent_id != "") {
8005 document.getElementById('data_parent_id' + idx).value = a.parent_id;
8007 if (a.fromAccounts.status) {
8008 var addressFrom = document.getElementById('addressFrom' + idx);
8009 SUGAR.email2.util.emptySelectOptions(addressFrom);
8010 var fromAccountOpts = a.fromAccounts.data;
8011 for(i=0; i<fromAccountOpts.length; i++) {
8012 var key = fromAccountOpts[i].value;
8013 var display = fromAccountOpts[i].text;
8014 var opt = new Option(display, key);
8015 if (fromAccountOpts[i].selected) {
8016 opt.selected = true;
8018 addressFrom.options.add(opt);
8024 failure : AjaxObject.handleFailure,
8025 timeout : AjaxObject.timeout,
8027 argument : [sendType]
8029 var callbackSendEmail = {
8030 success : AjaxObject.sendEmailCleanUp,
8031 failure : AjaxObject.handleFailure,
8032 timeout : AjaxObject.timeout,
8035 var callbackSettings = {
8036 success : AjaxObject.updateUserPrefs,
8037 failure : AjaxObject.handleFailure,
8038 timeout : AjaxObject.timeout,
8041 var callbackSettingsFolderRefresh = {
8042 success : AjaxObject.settingsFolderRefresh,
8043 failure : AjaxObject.handleFailure,
8044 timeout : AjaxObject.timeout,
8047 var callbackLoadSettingFolder = {
8048 success : function(o) {
8049 AjaxObject.settingsFolderRefresh(o);
8050 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8052 failure : AjaxObject.handleFailure,
8053 timeout : AjaxObject.timeout,
8057 var callbackUploadAttachment = {
8058 success : AjaxObject.uploadAttachmentSuccessful,
8059 upload : AjaxObject.uploadAttachmentSuccessful,
8060 failure : AjaxObject.handleFailure,
8061 timeout : AjaxObject.timeout,
8064 var callbackUserPrefs = {
8065 success : function(o) {
8066 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8068 failure : AjaxObject.handleFailure,
8069 timeout : AjaxObject.timeout,
8073 var callbackContextmenus = {
8075 success : AjaxObject.markEmailCleanup,
8076 failure : AjaxObject.handleFailure,
8077 timeout : AjaxObject.timeout,
8082 var callbackCheckEmail2 = {
8083 success : function(o) {
8084 var ret = JSON.parse(o.responseText);
8085 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8089 failure : AjaxObject.handleFailure,
8090 timeout : AjaxObject.timeout,
8092 }// End of File modules/Emails/javascript/ajax.js
8094 /*********************************************************************************
8095 * SugarCRM is a customer relationship management program developed by
8096 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8098 * This program is free software; you can redistribute it and/or modify it under
8099 * the terms of the GNU Affero General Public License version 3 as published by the
8100 * Free Software Foundation with the addition of the following permission added
8101 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8102 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8103 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8105 * This program is distributed in the hope that it will be useful, but WITHOUT
8106 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8107 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8110 * You should have received a copy of the GNU Affero General Public License along with
8111 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8112 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8115 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8116 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8118 * The interactive user interfaces in modified source and object code versions
8119 * of this program must display Appropriate Legal Notices, as required under
8120 * Section 5 of the GNU Affero General Public License version 3.
8122 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8123 * these Appropriate Legal Notices must retain the display of the "Powered by
8124 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8125 * technical reasons, the Appropriate Legal Notices must display the words
8126 * "Powered by SugarCRM".
8127 ********************************************************************************/
8129 function gridInit() {
8130 if(SUGAR.email2.grid) {
8131 SUGAR.email2.grid.destroy();
8137 var Ck = YAHOO.util.Cookie;
8138 var widths = [ 10, 10, 150, 250, 175, 125 ];
8140 if (Ck.get("EmailGridWidths")) {
8141 for (var i=0; i < widths.length; i++) {
8142 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8145 for (var i=0; i < widths.length; i++) {
8146 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8150 // changes "F" to an icon
8151 function flaggedIcon(cell, record, column, value) {
8153 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8156 // changes "A" to replied icon
8157 function repliedIcon(cell, record, column, value) {
8159 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8162 function attachIcon(cell, record, column, value) {
8164 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8171 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8176 formatter: attachIcon,
8180 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8185 formatter: flaggedIcon,
8189 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8194 formatter: repliedIcon,
8198 label: app_strings.LBL_EMAIL_FROM,
8205 label: app_strings.LBL_EMAIL_SUBJECT,
8212 label: mod_strings.LBL_LIST_DATE,
8219 label: app_strings.LBL_EMAIL_TO,
8255 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8256 responseType: YAHOO.util.DataSource.TYPE_JSON,
8258 resultsList: 'Email',
8259 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8260 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8266 action : "EmailUIAjax",
8267 emailUIAction : "getMessageList",
8270 forceRefresh : "false"
8272 if(lazyLoadFolder != null) {
8273 params['mbox'] = lazyLoadFolder.folder;
8274 params['ieId'] = lazyLoadFolder.ieId;
8275 //Check if the folder is a Sugar Folder
8276 var test = new String(lazyLoadFolder.folder);
8277 if(test.match(/SUGAR\./)) {
8278 params['emailUIAction'] = 'getMessageListSugarFolders';
8279 params['mbox'] = test.substr(6);
8282 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8285 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8286 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8288 paginator: new YAHOO.widget.Paginator({
8289 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8290 containers : ["dt-pag-nav"],
8291 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8292 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8293 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8294 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8295 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8297 initialRequest:SUGAR.util.paramsToUrl(params),
8304 //Override Paging request construction
8305 grid.set("generateRequest", function(oState, oSelf) {
8306 oState = oState || {pagination:null, sortedBy:null};
8307 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8308 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8309 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8310 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8311 // Build the request
8313 SUGAR.util.paramsToUrl(oSelf.params) +
8316 "&start=" + startIndex +
8317 ((results !== null) ? "&limit=" + results : "");
8322 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8323 oPayload = oPayload || { };
8325 oPayload.totalRecords = oResponse.meta.total;
8326 oPayload.unreadRecords = oResponse.meta.unread;
8328 var tabObject = SE.innerLayout.get("tabs")[0];
8330 if (this.params.mbox != null) {
8331 mboxTitle = this.params.mbox;
8333 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8334 tabObject.get("labelEl").firstChild.data = tabtext;
8337 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8339 node.data.unseen = oResponse.meta.unread;
8340 SE.accounts.renderTree();
8346 var resize = grid.resizeGrid = function () {
8347 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8348 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8350 grid.convertDDRows = function() {
8351 var rowEl = this.getFirstTrEl();
8352 while (rowEl != null) {
8353 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8354 rowEl = this.getNextTrEl(rowEl);
8359 grid.on("columnResizeEvent", function(o) {
8360 //Find the index of the column
8361 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8362 for (var i=0; i < colSet.length; i++) {
8363 if (o.column == colSet[i]) {
8364 //Store it in the cookie
8365 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8368 //this.resizeGrid();
8371 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8372 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8373 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8375 SUGAR.email2.listViewLayout.on("render", resize);
8378 //Setup the default load parameters
8379 SUGAR.email2.grid.params = params;
8381 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8382 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8383 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8390 function initRowDD() {
8391 var sg = SUGAR.email2.grid,
8392 Dom = YAHOO.util.Dom;
8393 sg.DDRow = function(oDataTable, oRecord, elTr) {
8394 if(oDataTable && oRecord && elTr) {
8395 this.ddtable = oDataTable;
8396 this.table = oDataTable.getTableEl();
8399 this.newIndex = null;
8401 this.initFrame(); // Needed for DDProxy
8402 this.invalidHandleTypes = {};
8406 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8407 _resizeProxy: function() {
8408 this.constructor.superclass._resizeProxy.apply(this, arguments);
8409 var dragEl = this.getDragEl(),
8411 var xy = Dom.getXY(el);
8413 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8414 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8415 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8416 Dom.setStyle(dragEl, 'display', "");
8419 startDrag: function(x, y) {
8420 //Check if we should be dragging a set of rows rather than just the one.
8421 var selectedRows = this.ddtable.getSelectedRows();
8422 var iSelected = false;
8423 for (var i in selectedRows) {
8424 if (this.rowEl.id == selectedRows[i]) {
8431 for (var i in selectedRows) {
8432 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8435 this.rows = [this.row];
8436 this.ddtable.unselectAllRows();
8437 this.ddtable.selectRow(this.row);
8440 //Initialize the dragable proxy
8441 var dragEl = this.getDragEl();
8442 var clickEl = this.getEl();
8443 Dom.setStyle(clickEl, "opacity", "0.25");
8444 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8445 Dom.addClass(dragEl, "yui-dt-liner");
8446 Dom.setStyle(dragEl, "opacity", "0.5");
8447 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8448 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8449 Dom.setStyle(dragEl, "border", "2px solid gray");
8452 clickValidator: function(e) {
8453 if (this.row.getData()[0] == " ")
8455 var target = YAHOO.util.Event.getTarget(e);
8456 return ( this.isValidHandleChild(target) &&
8457 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8460 * This funciton checks that the target of the drag is a table row in this
8461 * DDGroup and simply moves the sourceEL to that location as a preview.
8463 onDragOver: function(ev, id) {
8464 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8465 if (node && node != this.targetNode) {
8466 this.targetNode = node;
8467 SUGAR.email2.folders.unhighliteAll();
8472 onDragOut: function(e, id) {
8473 if (this.targetNode) {
8474 SUGAR.email2.folders.unhighliteAll();
8475 this.targetNode = false;
8478 endDrag: function() {
8479 Dom.setStyle(this.getEl(), "opacity", "");
8480 Dom.setStyle(this.getDragEl(), "display", "none");
8481 if (this.targetNode) {
8482 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8484 SUGAR.email2.folders.unhighliteAll();
8490 function AddressSearchGridInit() {
8491 function moduleIcon(elCell, oRecord, oColumn, oData) {
8492 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8494 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8495 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8497 var checkHeader = '<input type="checkbox" ';
8498 if (SUGAR.email2.util.isIe()) {
8499 checkHeader += 'style="top:-5px" ';
8501 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8506 formatter: selectionCheckBox,
8510 label: mod_strings.LBL_LIST_TYPE,
8512 formatter: moduleIcon,
8516 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8522 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8528 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8529 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8531 resultsList: 'Person',
8532 fields: ['name', 'email', 'bean_id', 'bean_module'],
8533 metaFields: {total: 'TotalCount'}
8535 //enable sorting on the server accross all data
8538 dataModel.params = {
8541 action : "EmailUIAjax",
8542 emailUIAction:"getAddressSearchResults"
8544 var rb = document.getElementById('hasRelatedBean').checked;
8546 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8547 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8548 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8549 dataModel.params['related_bean_id'] = relatedBeanId;
8550 dataModel.params['related_bean_type'] = relatedBeanType;
8551 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8553 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8555 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8556 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8558 paginator: new YAHOO.widget.Paginator({
8560 containers : ["dt-pag-nav-addressbook"],
8561 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8562 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8563 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8564 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8565 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8567 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8571 //Override Paging request construction
8572 grid.set("generateRequest", function(oState, oSelf) {
8573 oState = oState || {pagination:null, sortedBy:null};
8574 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8575 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8576 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8577 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8578 // Build the request
8580 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8581 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8582 ((results !== null) ? "&limit=" + results : "");
8586 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8587 oPayload = oPayload || { };
8588 oPayload.totalRecords = oResponse.meta.total;
8592 grid.clickToggleSelect= function(args) {
8593 var isIE = (args.event.target == null);
8594 var targetElement = isIE ? args.event.srcElement : args.event.target;
8595 if(targetElement.type == null || targetElement.type != 'checkbox') {
8596 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8600 grid.reSelectRowsOnRender = function (){
8601 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8602 for (var i = 0; i < rows.length; i++)
8604 var emailAddress = rows[i].getData("email");
8605 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8608 rows[i].setData("selected", true);
8609 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8613 rows[i].setData("selected", false);
8614 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8618 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8619 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8620 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8621 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8624 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8625 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8627 grid.toggleSelectCheckbox = function(id,checked){
8628 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8629 row.setData("checked",checked);
8631 grid.toggleSelect = function(id, checked) {
8632 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8633 checked = row.getData("selected");
8636 SUGAR.email2.addressBook.grid.selectRow(row);
8637 SE.addressBook.insertContactRowToResultTable(id,null)
8640 SUGAR.email2.addressBook.grid.unselectRow(row);
8641 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8643 row.setData("selected", !checked);
8646 grid.toggleSelectAll = function(checked) {
8647 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8648 for (var i = 0; i < rows.length; i++) {
8649 if (typeof(rows[i]) != "undefined")
8650 rows[i].setData("checked", checked);
8652 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8653 for (var i = 0; i < checkBoxes.length; i++) {
8654 checkBoxes[i].checked = checked;
8658 //Initialize the grid result table.
8659 AddressSearchResultsGridInit();
8665 * Initalize the results table for the address book selection.
8668 function AddressSearchResultsGridInit()
8671 /* Full name sort funciton to compare by last name if available */
8672 var fullNameSort = function(a, b, desc) {
8673 // Deal with empty values
8674 if(!YAHOO.lang.isValue(a))
8675 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8676 else if(!YAHOO.lang.isValue(b))
8679 var aNames = a.getData("name").split(' ');
8680 var bNames = b.getData("name").split(' ');
8682 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8683 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8685 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8689 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8690 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8691 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8693 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})},
8694 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8696 var myDataSource = new YAHOO.util.DataSource([]);
8697 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8698 myDataSource.responseSchema = {
8699 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8702 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8703 width: "350px",height: "250px", MSG_EMPTY: " "});
8705 var highlightEditableCell = function(oArgs) {
8706 var elCell = oArgs.target;
8707 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8708 this.highlightCell(elCell);
8712 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8713 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8714 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8715 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8716 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8718 //Setup the context menus
8719 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8720 var task = p_aArgs[1];
8723 var elRow = this.contextEventTarget;
8724 elRow = p_myDataTable.getTrEl(elRow);
8731 var oRecord = p_myDataTable.getRecord(elRow);
8732 p_myDataTable.deleteRow(elRow);
8733 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8738 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8739 {trigger:gridResults.getTbodyEl()});
8740 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8741 contextMenu.render("addrSearchResultGrid");
8742 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8744 // End of File modules/Emails/javascript/grid.js
8746 /*********************************************************************************
8747 * SugarCRM is a customer relationship management program developed by
8748 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8750 * This program is free software; you can redistribute it and/or modify it under
8751 * the terms of the GNU Affero General Public License version 3 as published by the
8752 * Free Software Foundation with the addition of the following permission added
8753 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8754 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8755 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8757 * This program is distributed in the hope that it will be useful, but WITHOUT
8758 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8759 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8762 * You should have received a copy of the GNU Affero General Public License along with
8763 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8764 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8767 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8768 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8770 * The interactive user interfaces in modified source and object code versions
8771 * of this program must display Appropriate Legal Notices, as required under
8772 * Section 5 of the GNU Affero General Public License version 3.
8774 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8775 * these Appropriate Legal Notices must retain the display of the "Powered by
8776 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8777 * technical reasons, the Appropriate Legal Notices must display the words
8778 * "Powered by SugarCRM".
8779 ********************************************************************************/
8784 function complexLayoutInit() {
8785 var se = SUGAR.email2;
8786 var Dom = YAHOO.util.Dom;
8788 getInnerLayout : function(rows) {
8789 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8790 parent: se.complexLayout,
8796 scroll:false, // grid should autoScroll itself
8798 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8806 body: "<div id='listBottom' />"
8814 body: "<div id='listRight' />",
8815 titlebar: false //,header: "right"
8818 se.complexLayout.on("render", function(){
8819 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8820 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8821 SUGAR.email2.listViewLayout.set("height", height);
8822 SUGAR.email2.listViewLayout.render();
8824 se.listViewLayout.render();
8826 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8827 var rp = se.listViewLayout.resizePreview = function() {
8828 var pre = Dom.get("displayEmailFramePreview");
8830 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8831 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8834 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8835 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8836 se.e2Layout.setPreviewPanel(rows);
8837 se.previewLayout = se.listViewLayout;
8838 return se.listViewLayout;
8841 getInnerLayout2Rows : function() {
8842 return this.getInnerLayout(true);
8844 getInnerLayout2Columns : function() {
8845 return this.getInnerLayout(false);
8849 // initialize state manager, we will use cookies
8850 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8851 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8852 se.complexLayout = new YAHOO.widget.Layout("container", {
8855 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8856 width: Dom.getViewportWidth() - 40,
8860 body: "<div id='emailtabs'></div>"
8865 body: "<div id='lefttabs'></div>",
8875 header: Dom.get('footerLinks').innerHTML,
8882 se.complexLayout.render();
8883 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8884 tp.addTab(new YAHOO.widget.Tab({
8887 content : "<div id='listViewDiv'/>",
8891 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8892 tp.appendTo(centerEl);
8894 tp.get("element").style.borderRight = "1px solid #666"
8896 var listV = this.getInnerLayout2Rows();
8897 listV.set("height", tp.get("element").clientHeight - 25);
8900 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8901 var folderTab = new YAHOO.widget.Tab({
8902 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8904 content : "<div id='emailtree'/>",
8908 folderTab.on("activeChange", function(o){
8910 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8913 se.leftTabs.addTab(folderTab);
8915 var tabContent = SUGAR.util.getAndRemove("searchTab");
8916 var searchTab = new YAHOO.widget.Tab({
8917 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8919 content : tabContent.innerHTML,
8922 searchTab.on("activeChange", function(o){
8925 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8926 //Setup the calendars if needed
8927 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
8928 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
8930 //Initalize sqs object for assigned user name
8931 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
8933 //Attach event handler for when the relate module option is selected for the correct sqs object
8934 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8935 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8936 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
8937 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8939 //If enter key is pressed, perform search
8940 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8941 for(var i=0; i < addKeyPressFields.length;i++)
8943 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8944 if (e.keyCode == 13) {
8945 YAHOO.util.Event.stopEvent(e);
8946 SUGAR.email2.search.searchAdvanced();
8950 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
8952 //Clear parent values if selecting another parent type.
8953 YAHOO.util.Event.addListener('data_parent_type_search','change',
8955 document.getElementById('data_parent_id_search').value ='';
8956 document.getElementById('data_parent_name_search').value ='';
8961 se.leftTabs.addTab(searchTab);
8963 var resizeTabBody = function() {
8964 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8965 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8968 se.complexLayout.on("render", resizeTabBody);
8969 se.leftTabs.on("activeTabChange", resizeTabBody);
8970 //hack to allow left pane scroll bar to fully show
8971 var lefttabsDiv = document.getElementById('lefttabs');
8972 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8973 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8974 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8977 initSQSObject: function(formName,fieldName)
8979 var fullFieldName = formName + '_' + fieldName; //SQS Convention
8980 var resultName = fullFieldName + '_' + 'results';
8982 if (QSFieldsArray[fullFieldName] != null)
8984 QSFieldsArray[fullFieldName].destroy();
8985 delete QSFieldsArray[fullFieldName];
8987 if (QSProcessedFieldsArray[fullFieldName])
8988 QSProcessedFieldsArray[fullFieldName] = false;
8990 if( Dom.get(resultName) )
8992 var obj = document.getElementById(resultName);
8993 obj.parentNode.removeChild(obj);
8996 setPreviewPanel: function(rows) {
8998 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
8999 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9000 Dom.get("listRight").innerHTML = "";
9001 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9003 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9004 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9005 Dom.get("listBottom").innerHTML = "";
9006 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9013 var myBufferedListenerObject = new Object();
9014 myBufferedListenerObject.refit = function() {
9015 if(SUGAR.email2.grid) {
9016 SUGAR.email2.grid.autoSize();
9019 // End of File modules/Emails/javascript/complexLayout.js
9021 /*********************************************************************************
9022 * SugarCRM is a customer relationship management program developed by
9023 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9025 * This program is free software; you can redistribute it and/or modify it under
9026 * the terms of the GNU Affero General Public License version 3 as published by the
9027 * Free Software Foundation with the addition of the following permission added
9028 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9029 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9030 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9032 * This program is distributed in the hope that it will be useful, but WITHOUT
9033 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9034 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9037 * You should have received a copy of the GNU Affero General Public License along with
9038 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9039 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9042 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9043 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9045 * The interactive user interfaces in modified source and object code versions
9046 * of this program must display Appropriate Legal Notices, as required under
9047 * Section 5 of the GNU Affero General Public License version 3.
9049 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9050 * these Appropriate Legal Notices must retain the display of the "Powered by
9051 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9052 * technical reasons, the Appropriate Legal Notices must display the words
9053 * "Powered by SugarCRM".
9054 ********************************************************************************/
9057 /******************************************************************************
9058 * Initialize Email 2.0 Application
9061 //Override Sugar Languge so quick creates work properly
9064 function email2init() {
9067 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9068 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9069 if (!SUGAR.util.isTouchScreen()) {
9071 convert_urls : false,
9072 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9073 width: tinyConfig.width,
9074 theme: tinyConfig.theme,
9075 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9076 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9077 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9078 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9079 plugins : tinyConfig.plugins,
9080 elements : tinyConfig.elements,
9081 language : tinyConfig.language,
9082 extended_valid_elements : tinyConfig.extended_valid_elements,
9083 mode: tinyConfig.mode,
9084 strict_loading_mode : true,
9085 force_br_newlines : true,
9086 forced_root_block : '',
9087 directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
9091 // initialze message overlay
9092 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9102 if (SUGAR.themes.tempHideLeftCol)
9103 SUGAR.themes.tempHideLeftCol();
9105 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9106 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9108 // set defaults for YAHOO.util.DragDropManager
9109 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9111 SUGAR.email2.nextYear = new Date();
9112 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9115 // initialize and display UI framework (complexLayout.js)
9116 complexLayoutInit();
9118 // initialize and display grid (grid.js)
9121 // initialize treeview for folders
9123 SUGAR.email2.folders.rebuildFolders(true);
9126 //Setup the Message Box overlay
9127 /*Ext.MessageBox.maxWidth = 350;
9128 Ext.MessageBox.minProgressWidth = 350;
9130 ///////////////////////////////////////////////////////////////////////////
9133 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9135 var SEC = SUGAR.email2.contextMenus;
9138 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9139 trigger: SUGAR.email2.grid.get("element"),
9142 emailMenu.subscribe("beforeShow", function() {
9143 var oTarget = this.contextEventTarget;
9144 if (typeof(oTarget) == "undefined")
9146 var grid = SUGAR.email2.grid;
9147 var selectedRows = grid.getSelectedRows();
9148 var multipleSelected = (selectedRows.length > 1) ? true: false;
9149 if (!multipleSelected)
9151 grid.unselectAllRows();
9152 grid.selectRow(oTarget);
9153 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9155 else if(multipleSelected)
9157 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9161 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9162 //us to access individual elements easier by name rather than by index
9163 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
9164 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9165 emailMenu.addItems([
9167 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9168 id: 'showDetailView',
9169 onclick: { fn: SEC.showDetailView }
9172 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9173 onclick: { fn: SEC.openMultiple }
9176 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9177 onclick: { fn: SEC.archiveToSugar }
9180 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9182 onclick: { fn: SEC.replyForwardEmailContext }
9185 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9187 onclick: { fn: SEC.replyForwardEmailContext }
9190 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9192 onclick: { fn: SEC.replyForwardEmailContext }
9195 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9197 onclick: { fn: SEC.markDeleted }
9200 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9202 onclick: { fn: SEC.viewPrintable }
9206 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9208 id: "markEmailMenu",
9211 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9212 onclick: { fn: SEC.markUnread }
9215 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9216 onclick: { fn: SEC.markRead }
9219 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9220 onclick: { fn: SEC.markFlagged }
9223 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9224 onclick: { fn: SEC.markUnflagged }
9230 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9232 onclick: { fn: SEC.assignEmailsTo }
9235 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9237 onclick: { fn: SEC.relateTo }
9240 SEC.emailListContextMenu.render();
9242 //Handle the Tree folder menu trigger ourselves
9243 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9247 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9251 SEC.frameFoldersContextMenu.addItems([
9252 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9253 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9254 onclick: { fn: function() {
9255 var node = SUGAR.email2.clickedFolderNode;
9256 if (node.data.ieId) {
9257 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9260 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9261 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9262 onclick: { fn: function() {
9263 var node = SUGAR.email2.clickedFolderNode;
9264 if (node.data.ieId) {
9265 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9269 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9270 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9271 onclick: { fn: SUGAR.email2.folders.folderAdd }
9274 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9275 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9276 onclick: { fn: SUGAR.email2.folders.folderDelete }
9279 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9280 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9281 onclick: { fn: SUGAR.email2.folders.folderRename }
9284 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9285 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9286 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9289 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9290 onclick: { fn: function() {
9291 var node = SUGAR.email2.clickedFolderNode;
9292 if (node.data.ieId) {
9293 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9297 SEC.frameFoldersContextMenu.render();
9299 SEC.initContactsMenu = function() {
9301 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9302 trigger: "contacts",
9305 SEC.contactsContextMenu.addItems([
9307 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9308 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9311 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9312 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9315 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9316 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9317 if (oTarget && !grid.isSelected(oTarget)) {
9318 grid.unselectAllRows();
9319 grid.selectRow(oTarget);
9322 SEC.contactsContextMenu.render();
9326 // set auto-check timer
9327 SUGAR.email2.folders.startCheckTimer();
9328 // check if we're coming from an email-link click
9329 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9331 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9333 //Init fix for YUI 2.7.0 datatable sort.
9334 SUGAR.email2.addressBook.initFixForDatatableSort();
9337 function createTreePanel(treeData, params) {
9338 var tree = new YAHOO.widget.TreeView(params.id);
9339 var root = tree.getRoot();
9341 //if (treeData.nodes && treeData[0].id == "Home")
9342 // treeData = treeData[0];
9344 addChildNodes(root, treeData);
9349 function addChildNodes(parentNode, parentData) {
9350 var Ck = YAHOO.util.Cookie;
9351 var nextyear = SUGAR.email2.nextYear;
9352 var nodes = parentData.nodes || parentData.children;
9354 if (typeof(nodes[i]) == 'object') {
9355 if (nodes[i].data) {
9356 nodes[i].data.href = '#';
9357 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9358 node.action = nodes[i].data.action;
9360 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9361 addChildNodes(parentNode, nodes[i]);
9364 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9365 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9367 nodes[i].className = nodes[i].cls;
9369 nodes[i].href = "#";
9370 if (nodes[i].text) nodes[i].label = nodes[i].text;
9371 //Override YUI child node creation
9372 if (nodes[i].children) {
9373 nodes[i].nodes = nodes[i].children;
9374 nodes[i].children = [ ];
9376 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9379 if (typeof(nodes[i].nodes) == 'object') {
9380 addChildNodes(node, nodes[i]);
9387 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9389 function email2treeinit(tree, treedata, treediv, params) {
9390 //ensure the tree data is not corrupt
9394 if (SUGAR.email2.tree) {
9395 SUGAR.email2.tree.destroy();
9396 SUGAR.email2.tree = null;
9399 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9403 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9404 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9405 tree.subscribe("expandComplete", function(node){
9406 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9407 for (var i in node.children) {
9408 SE.accounts.setupDDTarget(node.children[i]);
9411 tree.setCollapseAnim("TVSlideOut");
9412 tree.setExpandAnim("TVSlideIn");
9413 var root = tree.root;
9414 while (root.hasChildren()) {
9415 var node = root.children[0];
9417 tree.removeNode(root.children[0], false);
9419 addChildNodes(root, treedata);
9421 SUGAR.email2.accounts.renderTree();
9424 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9425 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9429 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9430 startDrag: function(x, y) {
9431 var Dom = YAHOO.util.Dom;
9432 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9435 var dragEl = this.getDragEl();
9436 var clickEl = this.getEl();
9437 Dom.setStyle(clickEl, "color", "#AAA");
9438 Dom.setStyle(clickEl, "opacity", "0.25");
9439 dragEl.innerHTML = clickEl.innerHTML;
9441 Dom.addClass(dragEl, "ygtvcell");
9442 Dom.addClass(dragEl, "ygtvcontent");
9443 Dom.addClass(dragEl, "folderDragProxy");
9444 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9445 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9446 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9447 Dom.setStyle(dragEl, "opacity", "0.5");
9448 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9451 onDragOver: function(ev, id) {
9452 var Dom = YAHOO.util.Dom;
9453 if (id != this.dragId)
9455 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9456 if(node.data.cls != "sugarFolder") {
9457 SUGAR.email2.folders.unhighliteAll();
9461 this.targetNode = node;
9462 SUGAR.email2.folders.unhighliteAll();
9467 onDragOut: function(e, id) {
9468 if (this.targetNode) {
9469 SUGAR.email2.folders.unhighliteAll();
9470 this.targetNode = false;
9471 this.dragId = false;
9475 endDrag: function() {
9476 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9477 if (this.targetNode) {
9478 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9481 });// End of File modules/Emails/javascript/init.js
9483 /*********************************************************************************
9484 * SugarCRM is a customer relationship management program developed by
9485 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9487 * This program is free software; you can redistribute it and/or modify it under
9488 * the terms of the GNU Affero General Public License version 3 as published by the
9489 * Free Software Foundation with the addition of the following permission added
9490 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9491 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9492 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9494 * This program is distributed in the hope that it will be useful, but WITHOUT
9495 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9496 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9499 * You should have received a copy of the GNU Affero General Public License along with
9500 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9501 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9504 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9505 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9507 * The interactive user interfaces in modified source and object code versions
9508 * of this program must display Appropriate Legal Notices, as required under
9509 * Section 5 of the GNU Affero General Public License version 3.
9511 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9512 * these Appropriate Legal Notices must retain the display of the "Powered by
9513 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9514 * technical reasons, the Appropriate Legal Notices must display the words
9515 * "Powered by SugarCRM".
9516 ********************************************************************************/
9518 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9519 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9520 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9521 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9522 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9523 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9524 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9525 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9526 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9527 ' <input type="hidden" id="composeType" name="composeType">' +
9528 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9529 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9530 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9531 ' <input type="hidden" id="sendTo" name="sendTo">' +
9532 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9533 ' <input type="hidden" id="sendCc" name="sendCc">' +
9534 ' <input type="hidden" id="setEditor" name="setEditor">' +
9535 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9536 ' <input type="hidden" id="parent_id" name="parent_id">' +
9537 ' <input type="hidden" id="parent_type" name="parent_type">' +
9538 ' <input type="hidden" id="attachments" name="attachments">' +
9539 ' <input type="hidden" id="documents" name="documents">' +
9540 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9541 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9542 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9543 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9545 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9546 ' <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>' +
9547 ' <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>' +
9548 ' <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>' +
9549 ' <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>' +
9550 '</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>' +
9551 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9552 '<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>' +
9553 ' </td></tr></tbody></table></th>' +
9557 ' <div style="margin:5px;">' +
9558 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9560 ' <td class="emailUILabel" NOWRAP >' +
9561 ' {app_strings.LBL_EMAIL_FROM}:' +
9563 ' <td class="emailUIField" NOWRAP>' +
9565 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9570 ' <td class="emailUILabel" NOWRAP>' +
9571 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9572 ' {app_strings.LBL_EMAIL_TO}:' +
9575 ' <td class="emailUIField" NOWRAP>' +
9576 ' <div class="ac_autocomplete">' +
9577 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9578 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9579 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9583 ' <tr id="add_addr_options_tr{idx}">' +
9584 ' <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>'+
9586 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9587 ' <td class="emailUILabel" NOWRAP>' +
9588 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9589 ' {app_strings.LBL_EMAIL_CC}:' +
9592 ' <td class="emailUIField" NOWRAP>' +
9593 ' <div class="ac_autocomplete">' +
9594 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9595 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9596 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9600 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9601 ' <td class="emailUILabel" NOWRAP>' +
9602 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9603 ' {app_strings.LBL_EMAIL_BCC}:' +
9606 ' <td class="emailUIField" NOWRAP>' +
9607 ' <div class="ac_autocomplete">' +
9608 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9609 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9610 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9615 ' <td class="emailUILabel" NOWRAP width="1%">' +
9616 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9618 ' <td class="emailUIField" NOWRAP width="99%">' +
9619 ' <div class="ac_autocomplete">' +
9620 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9629 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9630 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9631 ' <div style="padding:5px;">' +
9632 ' <table cellpadding="2" cellspacing="0" border="0">' +
9635 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9642 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9643 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9655 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9662 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9663 ' <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>' +
9675 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9682 ' <div id="addedTemplateAttachments{idx}"></div>' +
9689 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9690 ' <div style="padding:5px;">' +
9691 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9692 ' <table border="0" width="100%">' +
9694 ' <td NOWRAP style="padding:2px;">' +
9695 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9699 ' <td NOWRAP style="padding:2px;">' +
9700 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9705 ' <table border="0" width="100%">' +
9707 ' <td NOWRAP style="padding:2px;">' +
9708 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9712 ' <td NOWRAP style="padding:2px;">' +
9713 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9717 ' <table border="0" width="100%">' +
9719 ' <td NOWRAP style="padding:2px;">' +
9720 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9721 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9729 // End of File modules/Emails/javascript/composeEmailTemplate.js
9731 /*********************************************************************************
9732 * SugarCRM is a customer relationship management program developed by
9733 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9735 * This program is free software; you can redistribute it and/or modify it under
9736 * the terms of the GNU Affero General Public License version 3 as published by the
9737 * Free Software Foundation with the addition of the following permission added
9738 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9739 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9740 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9742 * This program is distributed in the hope that it will be useful, but WITHOUT
9743 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9744 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9747 * You should have received a copy of the GNU Affero General Public License along with
9748 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9749 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9752 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9753 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9755 * The interactive user interfaces in modified source and object code versions
9756 * of this program must display Appropriate Legal Notices, as required under
9757 * Section 5 of the GNU Affero General Public License version 3.
9759 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9760 * these Appropriate Legal Notices must retain the display of the "Powered by
9761 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9762 * technical reasons, the Appropriate Legal Notices must display the words
9763 * "Powered by SugarCRM".
9764 ********************************************************************************/
9766 SUGAR.email2.templates['displayOneEmail'] =
9767 '<div class="emailDetailTable" style="height:100%">' +
9768 '<div id="viewMenuDiv{idx}"></div>' +
9769 '<div width="100%" class="displayEmailValue">' +
9770 ' <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>' +
9771 ' <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>' +
9772 ' <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>' +
9773 ' <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>' +
9774 ' <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>' +
9775 ' <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>' +
9776 ' <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>' +
9777 ' <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>' +
9778 ' <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>' +
9780 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9782 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9783 ' {app_strings.LBL_EMAIL_FROM}:' +
9785 ' <td width="99%" class="displayEmailValue">' +
9786 ' {email.from_addr}' +
9790 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9791 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9793 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9794 ' <b>{email.name}</b>' +
9798 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9799 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9801 ' <td class="displayEmailValue">' +
9802 ' {email.date_start} {email.time_start}' +
9806 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9807 ' {app_strings.LBL_EMAIL_TO}:' +
9809 ' <td class="displayEmailValue">' +
9810 ' {email.toaddrs}' +
9813 ' <tr>{meta.cc}</tr>' +
9814 ' <tr>{email.attachments}</tr>' +
9816 ' <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>' +
9817 //' {email.description}' +
9819 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9821 /*********************************************************************************
9822 * SugarCRM is a customer relationship management program developed by
9823 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9825 * This program is free software; you can redistribute it and/or modify it under
9826 * the terms of the GNU Affero General Public License version 3 as published by the
9827 * Free Software Foundation with the addition of the following permission added
9828 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9829 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9830 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9832 * This program is distributed in the hope that it will be useful, but WITHOUT
9833 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9834 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9837 * You should have received a copy of the GNU Affero General Public License along with
9838 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9839 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9842 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9843 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9845 * The interactive user interfaces in modified source and object code versions
9846 * of this program must display Appropriate Legal Notices, as required under
9847 * Section 5 of the GNU Affero General Public License version 3.
9849 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9850 * these Appropriate Legal Notices must retain the display of the "Powered by
9851 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9852 * technical reasons, the Appropriate Legal Notices must display the words
9853 * "Powered by SugarCRM".
9854 ********************************************************************************/
9856 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9857 '<body onload="javascript:window.print();">' +
9861 ' font-family: helvetica, impact, sans-serif;' +
9862 ' font-size : 12pt;' +
9869 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9872 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9874 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9875 ' {app_strings.LBL_EMAIL_FROM}:' +
9877 ' <td width="99%" class="displayEmailValue">' +
9878 ' {email.from_name} <{email.from_addr}>' +
9882 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9883 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9885 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9886 ' <b>{email.name}</b>' +
9890 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9891 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9893 ' <td class="displayEmailValue">' +
9894 ' {email.date_start} {email.time_start}' +
9898 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9899 ' {app_strings.LBL_EMAIL_TO}:' +
9901 ' <td class="displayEmailValue">' +
9902 ' {email.toaddrs}' +
9906 ' {email.attachments}' +
9912 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9914 ' <td style="border-top: 1px solid #333;">' +
9915 ' <div style="padding:5px;">' +
9916 '{email.description}' +
9926 // End of File modules/Emails/javascript/viewPrintable.js
9928 /*********************************************************************************
9929 * SugarCRM is a customer relationship management program developed by
9930 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9932 * This program is free software; you can redistribute it and/or modify it under
9933 * the terms of the GNU Affero General Public License version 3 as published by the
9934 * Free Software Foundation with the addition of the following permission added
9935 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9936 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9937 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9939 * This program is distributed in the hope that it will be useful, but WITHOUT
9940 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9941 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9944 * You should have received a copy of the GNU Affero General Public License along with
9945 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9946 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9949 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9950 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9952 * The interactive user interfaces in modified source and object code versions
9953 * of this program must display Appropriate Legal Notices, as required under
9954 * Section 5 of the GNU Affero General Public License version 3.
9956 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9957 * these Appropriate Legal Notices must retain the display of the "Powered by
9958 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9959 * technical reasons, the Appropriate Legal Notices must display the words
9960 * "Powered by SugarCRM".
9961 ********************************************************************************/
9962 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9963 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;}
9964 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');}
9965 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;}}
9966 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9967 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9968 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}
9969 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="";}}
9970 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
9971 {search.clearFields=function(){};search.setFields=function(data,filter)
9972 {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])
9973 {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';}}}}
9974 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))
9975 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
9976 {if(this.inputElement.id=='shipping_account_name')
9977 {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)/;}
9978 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
9979 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9980 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];}}}
9981 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]];}
9982 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;}}}}});}
9983 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9984 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js