2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
5 * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6 * dragged element is inserted before the dragged-over element.
8 * @extends YAHOO.util.DDProxy
10 * @param {String} id the id of the linked element
11 * @param {String} sGroup the group of related DragDrop objects
13 function ygDDList(id, sGroup) {
16 this.init(id, sGroup);
18 //this.logger = new ygLogger("ygDDList");
21 var s = this.getDragEl().style;
22 s.borderColor = "transparent";
23 s.backgroundColor = "#f6f5e5";
25 s.filter = "alpha(opacity=76)";
28 ygDDList.prototype = new YAHOO.util.DDProxy();
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
33 ygDDList.prototype.startDrag = function(x, y) {
34 //this.logger.debug(this.id + " startDrag");
36 var dragEl = this.getDragEl();
37 var clickEl = this.getEl();
39 dragEl.innerHTML = clickEl.innerHTML;
40 dragElObjects = dragEl.getElementsByTagName('object');
43 dragEl.className = clickEl.className;
44 dragEl.style.color = clickEl.style.color;
45 dragEl.style.border = "1px solid #aaa";
47 // save the style of the object
48 clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
50 this.borderDiv = document.createElement('div'); // create a div to display border
51 this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52 this.borderDiv.style.border = '2px dashed #cccccc';
54 for(i in clickEl.childNodes) { // hide contents of the target elements contents
55 if(typeof clickEl.childNodes[i].style != 'undefined') {
56 this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57 clickEl.childNodes[i].style.display = 'none';
61 clickEl.appendChild(this.borderDiv);
64 ygDDList.prototype.endDrag = function(e) {
65 // disable moving the linked element
66 var clickEl = this.getEl();
68 clickEl.removeChild(this.borderDiv); // remove border div
70 for(i in clickEl.childNodes) { // show target elements contents
71 if(typeof clickEl.childNodes[i].style != 'undefined') {
72 clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
77 clickEl.style.height = this.clickHeight;
79 clickEl.style.height = '';
82 clickEl.style.border = this.clickBorder;
84 clickEl.style.border = '';
86 dragEl = this.getDragEl();
87 dragEl.innerHTML = '';
92 ygDDList.prototype.afterEndDrag = function(e) {
96 ygDDList.prototype.onDrag = function(e, id) {
100 ygDDList.prototype.onDragOver = function(e, id) {
101 // this.logger.debug(this.id.toString() + " onDragOver " + id);
104 if ("string" == typeof id) {
105 el = YAHOO.util.DDM.getElement(id);
107 el = YAHOO.util.DDM.getBestMatch(id).getEl();
110 dragEl = this.getDragEl();
111 elRegion = YAHOO.util.Dom.getRegion(el);
113 // this.logger.debug('id: ' + el.id);
114 // this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 // this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116 var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 // this.logger.debug('mid: ' + mid);
119 // this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " < " + mid);
120 // this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
122 if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123 var el2 = this.getEl();
124 var p = el.parentNode;
125 p.insertBefore(el2, el);
127 if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128 var el2 = this.getEl();
129 var p = el.parentNode;
130 p.insertBefore(el2, el.nextSibling);
134 ygDDList.prototype.onDragEnter = function(e, id) {
135 // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136 // this.getDragEl().style.border = "1px solid #449629";
139 ygDDList.prototype.onDragOut = function(e, id) {
140 // I need to know when we are over nothing
141 // this.getDragEl().style.border = "1px solid #964428";
144 /////////////////////////////////////////////////////////////////////////////
146 function ygDDListBoundary(id, sGroup) {
148 this.init(id, sGroup);
149 //this.logger = new ygLogger("ygDDListBoundary");
150 this.isBoundary = true;
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
157 /*********************************************************************************
158 * SugarCRM Community Edition is a customer relationship management program developed by
159 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
161 * This program is free software; you can redistribute it and/or modify it under
162 * the terms of the GNU Affero General Public License version 3 as published by the
163 * Free Software Foundation with the addition of the following permission added
164 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
168 * This program is distributed in the hope that it will be useful, but WITHOUT
169 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
173 * You should have received a copy of the GNU Affero General Public License along with
174 * this program; if not, see http://www.gnu.org/licenses or write to the Free
175 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
178 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
181 * The interactive user interfaces in modified source and object code versions
182 * of this program must display Appropriate Legal Notices, as required under
183 * Section 5 of the GNU Affero General Public License version 3.
185 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186 * these Appropriate Legal Notices must retain the display of the "Powered by
187 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188 * technical reasons, the Appropriate Legal Notices must display the words
189 * "Powered by SugarCRM".
190 ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span> </span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&themeName=Sugar&imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace(''',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML=' ';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};addToValidate(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,'email',this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
216 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
217 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
218 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
219 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
220 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
221 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
222 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
223 if(SUGAR.isIE){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
224 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
225 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();// End of File include/SugarEmailAddress/SugarEmailAddress.js
227 /*********************************************************************************
228 * SugarCRM Community Edition is a customer relationship management program developed by
229 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
231 * This program is free software; you can redistribute it and/or modify it under
232 * the terms of the GNU Affero General Public License version 3 as published by the
233 * Free Software Foundation with the addition of the following permission added
234 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
235 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
236 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
238 * This program is distributed in the hope that it will be useful, but WITHOUT
239 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
240 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
243 * You should have received a copy of the GNU Affero General Public License along with
244 * this program; if not, see http://www.gnu.org/licenses or write to the Free
245 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
248 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
249 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
251 * The interactive user interfaces in modified source and object code versions
252 * of this program must display Appropriate Legal Notices, as required under
253 * Section 5 of the GNU Affero General Public License version 3.
255 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
256 * these Appropriate Legal Notices must retain the display of the "Powered by
257 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
258 * technical reasons, the Appropriate Legal Notices must display the words
259 * "Powered by SugarCRM".
260 ********************************************************************************/
261 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
262 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
263 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
264 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
265 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
266 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
267 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
268 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
269 this.js_more();this.js_more();}
270 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
271 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
272 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
273 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
274 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&¤tNode.tagName=='SPAN'){currentNode.id=/_input/.test(currentNode.id)?this.field_element_name+'_input_div_'+this.fields_count:this.field_element_name+'_radio_div_'+this.fields_count;if(/_input/.test(currentNode.id)){currentNode.name='teamset_div';}
275 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
276 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
277 currentNode.name=new_name;currentNode.id=new_name;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_name;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
278 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
279 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
281 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
283 if(!has_primary){return false;}
285 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
286 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
287 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
288 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
289 if(noAdd){enableQS(false);}
290 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_collection_"+i);var id_field=document.getElementById("id_"+this.field+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].id==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
292 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
293 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
295 SUGAR.collection.safe_clone=function(e,recursive)
296 {if(e.nodeName=="#text")
297 {return document.createTextNode(e.data);}
298 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;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 Community Edition 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,ie_id)
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(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
375 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
376 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
377 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";}
379 alert(out);return false;}else{return true;}}
380 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?'
381 +'module='+module_name
384 +'&target='+pageTarget
385 +'&target1='+pageTarget
386 +'&server_url='+mail_server
387 +'&email_user='+words[0]
388 +'&protocol='+protocol
390 +'&email_password='+words[1]
391 +'&mailbox='+words[2]
393 +'&personal='+isPersonal
394 +'&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)
395 this.body.style.width=w}}
396 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();}
397 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;}}}
398 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';}}}
399 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='';}
400 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
402 /*********************************************************************************
403 * SugarCRM Community Edition is a customer relationship management program developed by
404 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
406 * This program is free software; you can redistribute it and/or modify it under
407 * the terms of the GNU Affero General Public License version 3 as published by the
408 * Free Software Foundation with the addition of the following permission added
409 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
410 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
411 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
413 * This program is distributed in the hope that it will be useful, but WITHOUT
414 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
415 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
418 * You should have received a copy of the GNU Affero General Public License along with
419 * this program; if not, see http://www.gnu.org/licenses or write to the Free
420 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
423 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
424 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
426 * The interactive user interfaces in modified source and object code versions
427 * of this program must display Appropriate Legal Notices, as required under
428 * Section 5 of the GNU Affero General Public License version 3.
430 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
431 * these Appropriate Legal Notices must retain the display of the "Powered by
432 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
433 * technical reasons, the Appropriate Legal Notices must display the words
434 * "Powered by SugarCRM".
435 ********************************************************************************/
438 cache : new Object(),
439 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
440 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
443 currentHtmleditor : ''
447 * preserves hits from email server
449 _setDetailCache : function(ret) {
451 var compKey = ret.meta.mbox + ret.meta.uid;
453 if(!SUGAR.email2.cache[compKey]) {
454 SUGAR.email2.cache[compKey] = ret;
459 autoSetLayout : function() {
460 var c = document.getElementById('container');
461 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
462 //Ensure a minimum height.
463 tHeight = Math.max(tHeight, 550);
464 c.style.height = tHeight + "px";
465 SUGAR.email2.complexLayout.set('height', tHeight);
466 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
467 SUGAR.email2.complexLayout.render();
468 SUGAR.email2.listViewLayout.resizePreview();
473 * Shows overlay progress message
475 function overlayModal(title, body) {
476 overlay(title, body);
478 function overlay(reqtitle, body, type, additconfig) {
480 if (typeof(additconfig) == "object") {
481 var config = additconfig;
484 config.title = reqtitle;
486 YAHOO.SUGAR.MessageBox.show(config);
489 function hideOverlay() {
490 YAHOO.SUGAR.MessageBox.hide();
492 // End of File modules/Emails/javascript/EmailUIShared.js
494 /*********************************************************************************
495 * SugarCRM Community Edition is a customer relationship management program developed by
496 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
498 * This program is free software; you can redistribute it and/or modify it under
499 * the terms of the GNU Affero General Public License version 3 as published by the
500 * Free Software Foundation with the addition of the following permission added
501 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
502 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
503 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
505 * This program is distributed in the hope that it will be useful, but WITHOUT
506 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
507 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
510 * You should have received a copy of the GNU Affero General Public License along with
511 * this program; if not, see http://www.gnu.org/licenses or write to the Free
512 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
515 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
516 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
518 * The interactive user interfaces in modified source and object code versions
519 * of this program must display Appropriate Legal Notices, as required under
520 * Section 5 of the GNU Affero General Public License version 3.
522 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
523 * these Appropriate Legal Notices must retain the display of the "Powered by
524 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
525 * technical reasons, the Appropriate Legal Notices must display the words
526 * "Powered by SugarCRM".
527 ********************************************************************************/
531 var sw = YAHOO.SUGAR,
532 Event = YAHOO.util.Event,
533 Connect = YAHOO.util.Connect,
537 ///////////////////////////////////////////////////////////////////////////////
540 outboundDialog : null,
541 inboundAccountEditDialog : null,
542 inboundAccountsSettingsTable : null,
543 outboundAccountsSettingsTable : null,
544 testOutboundDialog : null,
545 errorStyle : 'input-error',
547 newAddedOutboundId : '',
550 * makes async call to retrieve an outbound instance for editting
553 editOutbound : function(obi) {
555 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
558 deleteOutbound : function(obi) {
560 if(obi.match(/^(add|line|sendmail)+/)) {
561 alert('Invalid Operation');
563 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
564 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
568 getReplyAddress : function() {
571 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
572 var addy = SE.userPrefs.current_user.emailAddresses[i];
574 if(addy.primary_address == "1") {
575 primary = addy.email_address;
578 if(addy.reply_to == "1") {
579 return addy.email_address;
587 * Called on "Accounts" tab activation event
589 lazyLoad : function() {
591 this._setupInboundAccountTable();
592 this._setupOutboundAccountTable();
596 _setupInboundAccountTable: function()
598 //Setup the inbound mail settings
599 if(!this.inboundAccountsSettingsTable)
601 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
602 var clckEvent = oColumn.key;
604 var is_group = oRecord.getData("is_group");
607 if(oColumn.key == 'edit')
609 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
610 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
612 else if(oColumn.key == 'delete')
614 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
615 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
617 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
621 this.showBoolean = function(el, oRecord, oColumn, oData)
623 var is_group = oRecord.getData("is_group");
624 var bChecked = oData;
625 bChecked = (bChecked) ? " checked" : "";
628 el.innerHTML = "<input type=\"radio\"" + bChecked +
629 " name=\"col" + oColumn.getId() + "-radio\"" +
630 " class=\"yui-dt-radio\">";
635 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
636 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
638 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
639 '<img border="0" src="themes/default/images/helpInline.gif">' +
640 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
643 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
644 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
645 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
646 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
647 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
648 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
649 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
650 this.ieDataSource = new YAHOO.util.DataSource(query);
651 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
652 this.ieDataSource.responseSchema = {
653 resultsList: "account_list",
654 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
656 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
657 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
659 var elCheckbox = oArgs.target;
660 var oColumn = this.getColumn(elCheckbox);
661 if(oColumn.key == 'is_active')
663 var oRecord = this.getRecord(elCheckbox);
664 oRecord.setData("is_active",elCheckbox.checked);
665 var t_id = oRecord.getData('id');
666 var isGroupFolder = oRecord.getData('has_groupfolder');
669 SUGAR.email2.folders.updateSubscriptions();
671 SUGAR.email2.folders.setFolderSelection();
675 var lastDefaultSelectedId = "";
676 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
678 var elRadio = oArgs.target;
679 var oColumn = this.getColumn(elRadio);
680 if(oColumn.key == 'is_default')
682 var oRecord = this.getRecord(elRadio);
683 var t_id = oRecord.getData('id');
684 var t_isGroup = oRecord.getData('is_group');
685 if(t_id != lastDefaultSelectedId && !t_isGroup)
687 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
688 lastDefaultSelectedId = t_id;
689 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
692 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
697 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
698 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
701 _setupOutboundAccountTable: function()
703 if(!this.outboundAccountsSettingsTable)
705 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
706 var clckEvent = oColumn.key;
708 var isEditable = oRecord.getData("is_editable");
709 var type = oRecord.getData("type");
712 if(oColumn.key == 'edit')
714 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
715 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
717 else if(oColumn.key == 'delete' && type == 'user')
719 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
720 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
723 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
727 //Custom formatter to display any error messages.
728 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
730 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
731 SUGAR.email2.composeLayout.outboundAccountErrors = {};
733 var id = oRecord.getData('id');
734 var message = oRecord.getData("errors");
737 elLiner.innerHTML = '<span class="required">' + message + '</span>';
738 //Add the id and message for all outbound accounts.
739 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
743 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
744 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
747 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
748 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
750 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
751 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
752 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
753 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
755 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
756 this.obDataSource = new YAHOO.util.DataSource(query);
757 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
758 this.obDataSource.responseSchema = {
760 resultsList: "outbound_account_list",
761 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
764 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
767 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
768 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
769 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
773 * Displays a modal diaglogue to edit outbound account settings
775 showEditInboundAccountDialogue : function(clear) {
777 if(!this.inboundAccountEditDialog) {
778 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
782 constraintoviewport: true,
786 EAD.showEvent.subscribe(function() {
787 var el = this.element;
788 var viewH = YAHOO.util.Dom.getViewportHeight();
789 if (this.header && el && viewH - 50 < el.clientHeight) {
790 var body = this.header.nextElementSibling;
791 body.style.overflow = "hidden";
792 body.style.height = "100%";
795 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
796 Dom.removeClass("editAccountDialogue", "yui-hidden");
800 if(clear == undefined || clear == true)
802 SE.accounts.clearInboundAccountEditScreen();
803 //Set default protocol to IMAP when creating new records
804 document.forms['ieAccount'].elements['protocol'].value = "imap";
805 SE.accounts.setPortDefault();
808 //Check if we should display username/password fields for outbound account if errors were detected.
809 this.checkOutBoundSelection();
811 this.inboundAccountEditDialog.render();
812 this.inboundAccountEditDialog.show();
813 SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
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();
1029 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1032 * Sets Port field to selected protocol and SSL settings defaults
1034 setPortDefault : function() {
1035 var prot = document.getElementById('protocol');
1036 var ssl = document.getElementById('ssl');
1037 var port = document.getElementById('port');
1038 var stdPorts= new Array("110", "143", "993", "995");
1039 var stdBool = new Boolean(false);
1040 var mailboxdiv = document.getElementById("mailboxdiv");
1041 var trashFolderdiv = document.getElementById("trashFolderdiv");
1042 var sentFolderdiv = document.getElementById("sentFolderdiv");
1043 var monitoredFolder = document.getElementById("subscribeFolderButton");
1044 if(port.value == '') {
1045 stdBool.value = true;
1047 for(i=0; i<stdPorts.length; i++) {
1048 if(stdPorts[i] == port.value) {
1049 stdBool.value = true;
1054 if(stdBool.value == true) {
1055 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1057 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1059 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1061 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1066 if (prot.value == 'imap') {
1067 mailboxdiv.style.display = "";
1068 trashFolderdiv.style.display = "";
1069 sentFolderdiv.style.display = "";
1070 monitoredFolder.style.display = "";
1071 if (document.getElementById('mailbox').value == "") {
1072 document.getElementById('mailbox').value = "INBOX";
1075 mailboxdiv.style.display = "none";
1076 trashFolderdiv.style.display = "none";
1077 sentFolderdiv.style.display = "none";
1078 monitoredFolder.style.display = "none";
1079 document.getElementById('mailbox').value = "";
1084 * Draws/removes red boxes around required fields.
1086 ieAccountError : function(style) {
1087 document.getElementById('server_url').className = style;
1088 document.getElementById('email_user').className = style;
1089 document.getElementById('email_password').className = style;
1090 document.getElementById('protocol').className = style;
1091 document.getElementById('port').className = style;
1094 checkOutBoundSelection: function() {
1095 var select = Dom.get('outbound_email');
1096 if (!select || select.selectedIndex == -1) { return; }
1098 var v = select.options[select.selectedIndex].value;
1102 select.options[select.selectedIndex].selected = false;
1103 v = select.options[0].value;
1105 else if (v == 'SYSTEM_ADD')
1106 SUGAR.email2.accounts.showAddSmtp();
1108 var foundError = false;
1109 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1110 for(i in errorAccounts)
1119 //Should username/password fields for outbound account.
1121 this.toggleInboundOutboundFields(true);
1123 this.toggleInboundOutboundFields(false);
1128 toggleInboundOutboundFields : function (display)
1132 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1133 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1137 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1138 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1142 * rebuilds the select options for mailer options
1144 rebuildMailerOptions : function() {
1145 var select = document.forms['ieAccount'].elements['outbound_email'];
1146 SE.util.emptySelectOptions(select);
1148 //Get the available sugar mailers
1149 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1151 for(i=0;i<a_outbound.length;i++)
1153 var t_record = a_outbound[i];
1154 var key = t_record.getData('id');
1155 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1157 var opt = new Option(display, key);
1158 select.options.add(opt);
1159 if (key == SE.accounts.newAddedOutboundId) {
1160 select.options.selectedIndex = i;
1164 select.options.add(new Option('',''));
1165 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1166 //Hide/Show username password fields if necessary.
1167 SE.accounts.checkOutBoundSelection();
1170 * Empties all the fields in the accounts edit view
1172 clearInboundAccountEditScreen:function() {
1174 document.getElementById('ie_id').value = '';
1175 document.getElementById('ie_name').value = '';
1176 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1177 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1178 document.getElementById('reply_to_addr').value = '';
1179 document.getElementById('server_url').value = '';
1180 document.getElementById('email_user').value = '';
1181 document.getElementById('email_password').value = '';
1182 document.getElementById('port').value = '';
1183 document.getElementById('inbound_mail_smtpuser').value = '';
1184 document.getElementById('inbound_mail_smtppass').value = '';
1185 document.ieAccount.protocol.options[0].selected = true;
1187 document.getElementById('ssl').checked = false;
1188 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1192 * Populates an account's fields in Settings->Accounts
1194 fillIeAccount:function(jsonstr) {
1195 var o = JSON.parse(jsonstr);
1197 document.getElementById('ie_id').value = o.id;
1198 document.getElementById('ie_name').value = o.name;
1199 if (o.stored_options != null) {
1200 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1201 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1202 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1203 if (o.stored_options.trashFolder != null) {
1204 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1206 if (o.stored_options.sentFolder != null) {
1207 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1210 document.getElementById('server_url').value = o.server_url;
1211 document.getElementById('email_user').value = o.email_user;
1212 document.getElementById('port').value = o.port;
1213 document.getElementById('group_id').value = o.group_id;
1214 document.getElementById('mailbox').value = o.mailbox;
1220 if(typeof(o.service[2]) != 'undefined') {
1221 document.getElementById('ssl').checked = true;
1225 if(document.getElementById('protocol').value != o.protocol) {
1226 var prot = document.getElementById('protocol');
1227 for(i=0; i<prot.options.length; i++) {
1228 if(prot.options[i].value == o.service[3]) {
1229 prot.options[i].selected = true;
1230 this.setPortDefault();
1234 // handle SMTP selection
1235 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1236 var opts = document.getElementById('outbound_email').options;
1237 for(i=0; i<opts.length; i++) {
1238 if(opts[i].value == o.stored_options.outbound_email) {
1239 opts[i].selected = true;
1245 deleteIeAccount : function(IeAccountID,IeGroupID) {
1246 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1248 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1250 AjaxObject.target = 'frameFlex';
1251 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1252 SUGAR.email2.accounts.refreshInboundAccountTable();
1256 // Null check for Outbound Settings.
1257 checkOutboundSettings: function() {
1258 var errorMessage = '';
1259 var isError = false;
1260 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1261 var mailName = document.getElementById('mail_name').value;
1262 var smtpServer = document.getElementById('mail_smtpserver').value;
1263 var smtpPort = document.getElementById('mail_smtpport').value;
1265 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1266 if(trim(mailName) == '') {
1268 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1270 if(trim(smtpServer) == '') {
1272 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1274 if(trim(smtpPort) == '') {
1276 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1278 if(mailsmtpauthreq.checked) {
1279 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1281 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1286 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1293 testOutboundSettings: function() {
1294 var errorMessage = '';
1295 var isError = false;
1296 var fromAddress = document.getElementById("outboundtest_from_address").value;
1297 if (trim(fromAddress) == "") {
1298 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1299 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1303 else if (!isValidEmail(fromAddress)) {
1304 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1305 overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1309 //Hide the dialogue and show an in progress indicator.
1310 SE.accounts.testOutboundDialog.hide();
1311 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1313 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1314 //nothing is sent in the request.
1315 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1316 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1318 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1319 if(outboundType == 'system-override')
1320 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1322 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1323 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1327 testOutboundSettingsDialog: function() {
1328 //Ensure that all settings are correct before proceeding to send test email.
1329 if(!SE.accounts.checkOutboundSettings())
1332 // lazy load dialogue
1333 if(!SE.accounts.testOutboundDialog) {
1334 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1338 constraintoviewport: true,
1342 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1343 Dom.removeClass("testOutboundDialog", "yui-hidden");
1345 SE.accounts.testOutboundDialog.render();
1346 SE.accounts.testOutboundDialog.show();
1350 * Saves Outbound email settings
1352 saveOutboundSettings : function() {
1353 if(SE.accounts.checkOutboundSettings()) {
1354 //Enable the form fields for the post.
1355 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1356 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1357 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1363 saveIeAccount : function() {
1365 //Before saving check if there are any error messages associated with the outbound account.
1366 var outboundID = document.getElementById('outbound_email').value;
1368 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1369 'validateSMTPCreds':true}) )
1371 document.getElementById('saveButton').disabled = true;
1373 overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1375 var formObject = document.getElementById('ieAccount');
1376 YAHOO.util.Connect.setForm(formObject);
1378 AjaxObject._reset();
1379 AjaxObject.target = 'frameFlex';
1380 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1384 testSettings : function() {
1385 form = document.getElementById('ieAccount');
1387 if(SE.accounts.checkIeCreds()) {
1388 ie_test_open_popup_with_submit("InboundEmail", "Popup", "Popup", 400, 300, trim(form.server_url.value), form.protocol.value, trim(form.port.value), trim(form.email_user.value), Rot13.write(form.email_password.value), trim(form.mailbox.value), form.ssl.checked, true, "ieAccount", form.ie_id.value);
1392 getFoldersListForInboundAccountForEmail2 : function() {
1393 form = document.getElementById('ieAccount');
1394 if(SE.accounts.checkIeCreds()) {
1395 var mailBoxValue = form.mailbox.value;
1396 if (form.searchField.value.length > 0) {
1399 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 );
1404 checkIeCreds : function(validateRules) {
1405 if(typeof(validateRules) == 'undefined')
1408 var errors = new Array();
1409 var out = new String();
1411 var ie_name = Dom.get('ie_name').value;
1412 var fromAddress = Dom.get('ie_from_addr').value;
1413 var server_url = Dom.get('server_url').value;
1414 var email_user = Dom.get('email_user').value;
1415 var email_password = Dom.get('email_password').value;
1416 var protocol = Dom.get('protocol').value;
1417 var port = Dom.get('port').value;
1418 var oe = Dom.get('outbound_email');
1419 var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1421 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1422 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1424 //If the username and password were provided then ignore the error messge
1426 var outboundCredentialsFound = false;
1428 if(outboundUserName != "" && outboundPass != "")
1429 outboundCredentialsFound = true;
1431 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1433 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1434 && validateSMTPCreds)
1436 if(trim(outboundUserName) == "") {
1437 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1439 if(trim(outboundPass) == "") {
1440 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1444 if(trim(ie_name) == "") {
1445 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1448 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1450 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1451 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1456 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1457 || trim(oe_value) == "SYSTEM_ADD") ) {
1458 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1460 if(trim(server_url) == "") {
1461 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1463 if(trim(email_user) == "") {
1464 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1466 if(protocol == "") {
1467 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1469 if (protocol == 'imap') {
1470 var mailbox = document.getElementById('mailbox').value;
1471 if (trim(mailbox) == "") {
1472 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1474 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1475 var trashFolder = document.getElementById('trashFolder').value;
1476 if (trim(trashFolder) == "") {
1477 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1482 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1485 if(errors.length > 0) {
1486 out = app_strings.LBL_EMAIL_ERROR_DESC;
1487 for(i=0; i<errors.length; i++) {
1502 getIeAccount : function(ieId) {
1506 overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1507 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1509 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1513 * Iterates through TreeView nodes to apply styles dependent nature of node
1515 renderTree:function() {
1516 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1520 //Sets the style for any nodes that need it.
1521 setNodeStyle : function(node) {
1522 if (!node.data.origText) {
1523 node.data.origText = node.data.text;
1526 if (typeof(node.data.unseen) != 'undefined') {
1527 if (node.data.unseen > 0) {
1528 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1531 node.setUpLabel(node.data.origText);
1534 node.setUpLabel('<span>' + node.data.origText + '</span>');
1536 SE.accounts.setupDDTarget(node);
1539 setupDDTarget : function(node) {
1540 if (node.ddTarget) {
1541 node.ddTarget.removeFromGroup();
1542 delete node.ddTarget;
1544 var id = node.getElId();
1545 var num = id.substring(4);
1546 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1547 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1548 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1550 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1552 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1553 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1558 * Async call to rebuild the folder list. After a folder delete or account delete
1560 rebuildFolderList : function() {
1561 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1562 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1566 * Returns the number of remote accounts the user has active.
1568 getAccountCount : function() {
1571 for(i=0; i<tree._nodes.length; i++) {
1572 var node = tree._nodes[i];
1574 if(typeof(node) != 'undefined' && node.data.ieId) {
1582 ///////////////////////////////////////////////////////////////////////////////
1587 ///////////////////////////////////////////////////////////////////////////////
1588 //// CONTEXT MENU CALLS
1591 assignToDialogue : null,
1593 * Archives from context menu
1595 * @param string ieId
1596 * @param string folder
1598 _archiveToSugar : function(uids, ieId, folder) {
1601 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1602 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1605 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1609 * Archives from context menu
1611 archiveToSugar : function(menuItem) {
1612 SE.contextMenus.emailListContextMenu.hide();
1614 var rows = SE.grid.getSelectedRows();
1616 /* iterate through available rows JIC a row is deleted - use first available */
1617 for(var i=0; i<rows.length; i++) {
1618 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1620 var data = SE.grid.getRecord(rows[0]).getData();
1621 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1625 * Popup the printable version and start system's print function.
1627 viewPrintable : function(menuItem) {
1628 var rows = SE.grid.getSelectedRows();
1629 var data = SE.grid.getRecord(rows[0]).getData();
1630 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1634 * Marks email flagged on mail server
1636 markRead : function(type, contextMenuId) {
1637 SE.contextMenus.markEmail('read');
1641 * Assign this emails to people based on assignment rules
1643 assignEmailsTo : function(type, contextMenuId) {
1644 if(!SE.contextMenus.assignToDialogue)
1646 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1650 constraintoviewport: true,
1654 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1658 Dom.removeClass("assignToDiv", "yui-hidden");
1659 SE.contextMenus.assignToDialogue.render();
1660 SE.contextMenus.assignToDialogue.show();
1664 * Marks email flagged on mail server
1666 markFlagged : function(contextMenuId) {
1667 SE.contextMenus.markEmail('flagged');
1671 * Marks email unflagged on mail server
1673 markUnflagged : function(contextMenuId) {
1674 SE.contextMenus.markEmail('unflagged');
1678 * Marks email unread on mail server
1680 markUnread : function() {
1681 SE.contextMenus.markEmail('unread');
1685 * Deletes an email from context menu
1687 markDeleted : function() {
1688 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1689 document.getElementById('_blank').innerHTML = "";
1690 SE.contextMenus.markEmail('deleted');
1695 * generic call API to apply a flag to emails on the server and on sugar
1696 * @param string type "read" | "unread" | "flagged" | "deleted"
1698 markEmail : function(type) {
1699 SE.contextMenus.emailListContextMenu.hide();
1701 //var dm = SE.grid.getStore();
1702 //var uids = SE.grid.getSelectedRowIds();
1703 //var indexes = SE.grid.getSelectedRowIndexes();
1704 var rows = SE.grid.getSelectedRows();
1705 if (rows.length == 0)
1706 rows = [SE.contextMenus.currentRow];
1709 for(var i=0; i<rows.length; i++) {
1710 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1713 ser = YAHOO.lang.JSON.stringify(ser);
1715 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1716 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1722 if(type == 'read' || type == 'deleted') {
1724 for(var j=0; j<rows.length; j++) {
1725 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1727 SE.grid.getRecord(rows[j]).setData("seen", "1");
1730 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1732 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1733 var unseenCount = node.data.unseen;
1734 if (isNaN(unseenCount)) {
1737 var finalCount = parseInt(unseenCount) - count;
1738 node.data.unseen = finalCount;
1740 SE.accounts.renderTree();
1742 } else if(type == 'unread') {
1744 for(var j=0; j<rows.length; j++) {
1745 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1750 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1751 var unseenCount = node.data.unseen;
1752 if (isNaN(unseenCount)) {
1755 var finalCount = parseInt(unseenCount) + count;
1756 node.data.unseen = finalCount;
1757 SE.accounts.renderTree();
1760 if (type == 'unread') {
1761 for(var i=0; i<rows.length; i++) {
1762 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1766 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1767 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1771 * refreshes the ListView to show changes to cache
1773 markEmailCleanup : function() {
1774 SE.accounts.renderTree();
1776 SE.listView.refreshGrid();
1779 showAssignmentDialog : function() {
1780 if (SE.contextMenus.assignmentDialog == null) {
1781 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1783 SE.contextMenus.assignmentDialog.show();
1788 * shows the import dialog with only relate visible.
1790 relateTo : function() {
1791 SE.contextMenus.emailListContextMenu.hide();
1793 var rows = SE.grid.getSelectedRows();
1794 var data = SE.grid.getRecord(rows[0]).getData();
1795 var ieId = data.ieId;
1796 var folder = data.mbox;
1798 /* iterate through available rows JIC a row is deleted - use first available */
1799 for(var i=0; i<rows.length; i++) {
1800 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1802 var ser = JSON.stringifyNoSecurity(uids);
1804 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1808 * shows the import dialog with only relate visible.
1810 showDetailView : function() {
1811 SE.contextMenus.emailListContextMenu.hide();
1812 var rows = SE.grid.getSelectedRows();
1813 if (rows.length > 1) {
1814 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1817 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1818 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1819 /* iterate through available rows JIC a row is deleted - use first available */
1820 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1821 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1827 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1828 overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1829 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1833 * Opens multiple messages from ListView context click
1835 openMultiple : function() {
1836 SE.contextMenus.emailListContextMenu.hide();
1838 var rows = SE.grid.getSelectedRows();
1839 var uids = SE.listView.getUidsFromSelection();
1841 if(uids.length > 0) {
1842 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1843 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1844 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1849 * Replies/forwards email
1851 replyForwardEmailContext : function() {
1852 SE.contextMenus.emailListContextMenu.hide();
1854 var indexes = SE.grid.getSelectedRows();
1855 //var dm = SE.grid.getDataModel();
1858 for(var i=0; i<indexes.length; i++) {
1859 var row = SE.grid.getRecord(indexes[i]).getData();
1860 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1864 //show menu functions
1865 showEmailsListMenu : function(grid, row) {
1867 var data = row.getData();
1868 var draft = (data.type == "draft");
1869 var menu = SE.contextMenus.emailListContextMenu;
1874 if (data.mbox == 'sugar::Emails')
1875 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1877 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1879 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1880 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1881 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1882 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1884 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1887 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1889 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1890 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1891 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1892 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1893 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1896 if (data.mbox == "sugar::Emails")
1898 //Allow users to reassign imported emails
1899 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1900 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1901 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1902 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1906 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1907 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1911 showFolderMenu : function(grid, rowIndex, event) {
1913 var coords = event.getXY();
1914 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1918 SE.contextMenus.dv = {
1919 archiveToSugar : function(contextMenuId) {
1921 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1924 replyForwardEmailContext : function(all) {
1925 SE.contextMenus.detailViewContextMenu.hide();
1934 //// END SE.contextMenus
1935 ///////////////////////////////////////////////////////////////////////////////
1939 ///////////////////////////////////////////////////////////////////////////////
1942 consumeMetaDetail : function(ret) {
1943 // handling if the Email drafts
1944 if(ret.type == 'draft') {
1945 SE.composeLayout.c0_composeDraft();
1950 // cache contents browser-side
1951 SE._setDetailCache(ret);
1953 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1954 // 2 below must be in global context
1956 meta['panelId'] = SE.util.getPanelId();
1958 email = ret.meta.email;
1959 var out = displayTemplate.exec({
1960 'app_strings' : app_strings,
1962 'idx' : targetDiv.id,
1964 'email' : meta.email,
1965 'linkBeans' : linkBeans
1967 var tabLabel = meta.email.name;
1968 if (tabLabel != null && tabLabel.length > 25) {
1969 tabLabel = tabLabel.substring(0, 25) + "...";
1971 targetDiv.set("label", tabLabel);
1972 targetDiv.set("content", out);
1974 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1975 if (SUGAR.email2.util.isIe()) {
1976 displayEmailFrameDiv.style.height = "390px";
1978 displayEmailFrameDiv.style.height = "410px";
1981 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1982 displayFrame.contentWindow.document.write(email.description);
1983 displayFrame.contentWindow.document.close();
1985 // hide archive links
1986 if(ret.meta.is_sugarEmail) {
1987 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1988 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1990 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1991 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1996 consumeMetaPreview : function(ret) {
1997 // cache contents browser-side
1998 SE._setDetailCache(ret);
2002 var currrow = SE.grid.getLastSelectedRecord();
2003 currrow = SE.grid.getRecord(currrow);
2005 document.getElementById('_blank').innerHTML = '';
2008 // handling if the Email drafts
2009 if(ret.type == 'draft'){
2010 if (currrow.getData().uid == ret.uid) {
2011 SE.composeLayout.c0_composeDraft();
2016 if (currrow.getData().uid != ret.meta.uid) {
2020 // remove loading sprite
2021 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2022 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2024 meta['panelId'] = SE.util.getPanelId();
2025 email = ret.meta.email;
2027 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2028 'app_strings' : app_strings,
2032 'email' :meta.email,
2033 'linkBeans' : linkBeans
2035 // document.getElementById('_blank').innerHTML = meta.email;
2036 /* displayTemplate.append('_blank', {
2037 'app_strings' : app_strings,
2041 'email' :meta.email,
2042 'linkBeans' : linkBeans
2045 var displayFrame = document.getElementById('displayEmailFramePreview');
2046 displayFrame.contentWindow.document.write(email.description);
2047 displayFrame.contentWindow.document.close();
2049 SE.listViewLayout.resizePreview();
2051 // hide archive links
2052 if(ret.meta.is_sugarEmail) {
2053 document.getElementById("archiveEmailPreview").innerHTML = " ";
2054 document.getElementById("btnEmailViewPreview").style.display = "none";
2055 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2057 //hide view relationship link
2058 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2063 * wraps emailDelete() for single messages, comes from preview or tab
2065 emailDeleteSingle : function(ieId, uid, mbox) {
2066 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2067 // find active panel and close if the user double clicked the email to view.
2068 var activeTabId = SE.util.getPanelId();
2069 if(activeTabId != 'Preview')
2070 SE.innerLayout.get("activeTab").close();
2072 document.getElementById('_blank').innerHTML = "";
2075 uid = JSON.stringifyNoSecurity(ser);
2076 this.emailDelete(ieId, uid, mbox);
2081 * Sends async call to delete a given message
2084 emailDelete : function(ieId, uid, mbox) {
2085 overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2086 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2087 uid + "&ieId=" + ieId + "&folder=" + mbox);
2091 * retrieves one email to display in the preview pane.
2093 getEmailPreview : function() {
2094 var row = SUGAR.email2.listView.currentRow;
2095 var data = row.getData();
2096 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2097 var setRead = (data['seen'] == 0) ? true : false;
2098 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2099 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2104 * Imports one email into Sugar
2106 importEmail : function(ieId, uid, mbox) {
2107 SE.util.clearHiddenFieldValues('emailUIForm');
2109 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2111 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2112 AjaxObject.target = '';
2113 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2117 * Populates the frameFlex div with the contents of an email
2119 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2120 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2122 var mboxStr = new String(mbox);
2123 var compKey = mbox + uid;
2125 if(setRead == true) {
2126 SE.listView.boldUnreadRows()
2127 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2130 if(destination == SE.innerLayout) {
2132 * loading email into a tab, peer with ListView
2133 * targetDiv must remain in the global namespace as it is used by AjaxObject
2135 //Check if we already have a tab of the email open
2136 var tabs = SE.innerLayout.get("tabs");
2137 for (var t in tabs) {
2138 if (tabs[t].id && tabs[t].id == uid) {
2139 SE.innerLayout.set("activeTab", tabs[t]);
2144 targetDiv = new YAHOO.SUGAR.ClosableTab({
2145 label: loadingSprite,
2151 SE.innerLayout.addTab(targetDiv);
2153 // use cache if available
2154 if(SE.cache[compKey]) {
2155 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2157 // open email as peer-tab to listView
2158 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2159 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2162 // loading email into preview pane
2163 document.getElementById('_blank').innerHTML = loadingSprite;
2165 // use cache if available
2166 if(SE.cache[compKey]) {
2167 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2169 AjaxObject.forceAbort = true;
2170 // open in preview window
2171 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2172 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2177 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2179 if(mboxStr.substring(0,7) == 'sugar::') {
2180 // display an email from Sugar
2181 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2183 // display an email from an email server
2184 document.getElementById('emailUIAction').value = 'getSingleMessage';
2186 document.getElementById('mbox').value = mbox;
2187 document.getElementById('ieId').value = ieId;
2188 document.getElementById('uid').value = uid;
2190 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2192 AjaxObject.forceAbort = true;
2193 AjaxObject.target = '_blank';
2194 AjaxObject.startRequest(callback, null);
2198 * Retrieves multiple emails for DetailView
2200 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2201 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2202 SE.util.clearHiddenFieldValues('emailUIForm');
2204 var mboxStr = new String(mbox);
2206 uids = SE.util.cleanUids(uids);
2208 if(mboxStr.substring(0,7) == 'sugar::') {
2209 // display an email from Sugar
2210 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2211 document.getElementById('uid').value = uids;
2213 // display an email from an email server
2214 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2215 document.getElementById('mbox').value = mbox;
2216 document.getElementById('ieId').value = ieId;
2217 document.getElementById('uid').value = uids;
2220 var formObject = document.getElementById('emailUIForm');
2221 YAHOO.util.Connect.setForm(formObject);
2223 AjaxObject.target = 'frameFlex';
2224 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2226 if(setRead == true) {
2227 var c = uids.split(",");
2228 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2233 * Makes async call to get QuickCreate form
2234 * Renders a modal edit view for a given module
2236 quickCreate : function(module, ieId, uid, mailbox) {
2237 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2239 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2240 get += "&sugarEmail=true";
2243 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2247 * Makes async call to save a quick create
2250 saveQuickCreate : function(action) {
2251 var qcd = SE.detailView.quickCreateDialog;
2252 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2253 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2254 var theCallback = callbackQuickCreateSave;
2255 var accountType = '&sugarEmail=true';
2256 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2257 accountType = '&ieId=' + qcd.ieId;
2260 if (action == 'reply') {
2261 theCallback = callbackQuickCreateSaveAndReply;
2262 } else if (action == true) {
2263 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2265 formObject.action.value = 'EmailUIAjax';
2266 YAHOO.util.Connect.setForm(formObject);
2267 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2268 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2269 accountType + '&mbox=' + qcd.mbox);
2274 * Code to show/hide long list of email address in DetailView
2276 showCroppedEmailList : function(el) {
2277 el.style.display = 'none';
2278 el.previousSibling.style.display = 'inline'
2280 showFullEmailList : function(el) {
2281 el.style.display = 'none';
2282 el.nextSibling.style.display = 'inline';
2286 * Shows the QuickCreate overlay
2287 * @param string ieId
2289 * @param string mailbox
2291 showQuickCreate : function(ieId, uid, mailbox) {
2292 var panelId = SE.util.getPanelId();
2293 var context = document.getElementById("quickCreateSpan" + panelId);
2295 if (!SE.detailView.cqMenus)
2296 SE.detailView.cqMenus = {};
2298 if (SE.detailView.cqMenus[context])
2299 SE.detailView.cqMenus[context].destroy();
2301 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2303 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2306 for (var i=0; i < this.qcmodules.length; i++) {
2307 var module = this.qcmodules[i];
2309 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2312 onclick: { fn: function() {
2313 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2319 menu.render(document.body);
2324 * Displays the "View" submenu in the detailView
2325 * @param string ieId
2327 * @param string mailbox
2329 showViewMenu : function(ieId, uid, mailbox) {
2330 var panelId = SE.util.getPanelId();
2331 var context = "btnEmailView" + panelId;
2332 if (!SE.detailView.viewMenus)
2333 SE.detailView.viewMenus = {};
2335 if (SE.detailView.viewMenus[context])
2336 SE.detailView.viewMenus[context].destroy();
2338 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2340 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2344 (ieId == 'null' || ieId == null) ?
2345 //No ieId - Sugar Email
2347 text: app_strings.LBL_EMAIL_VIEW_RAW,
2348 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2351 //IeID exists, on a remote server
2353 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2354 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2356 text: app_strings.LBL_EMAIL_VIEW_RAW,
2357 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2360 menu.render(document.body);
2365 //#23108 jchi@07/17/2008
2366 menu.render('quickCreateSpan'+ panelId);*/
2367 //this.viewMenu = menu;
2368 //this.viewMenu.show(context);
2371 * Makes async call to get an email's headers
2373 viewHeaders : function(ieId, uid, mailbox) {
2374 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2375 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2379 * Makes async call to get a printable version
2381 viewPrintable : function(ieId, uid, mailbox) {
2382 if(mailbox == 'sugar::Emails') {
2383 // display an email from Sugar
2384 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2386 // display an email from an email server
2387 var emailUIAction = '&emailUIAction=getSingleMessage';
2390 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2391 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2395 * Makes async call to get an email's raw source
2397 viewRaw : function(ieId, uid, mailbox) {
2398 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2399 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2403 * Display all email addresses in detailview.
2405 displayAllAddrs : function(el) {
2406 el.style.display = 'none';
2407 Dom.getNextSibling(el).style.display = 'inline';
2410 //// END SE.detailView
2411 ///////////////////////////////////////////////////////////////////////////////
2415 ///////////////////////////////////////////////////////////////////////////////
2418 contextMenuFocus : new Object(),
2421 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2422 * SugarFolder ID - folder strings
2424 _createFolderId : function(node) {
2430 if(node.data.ieId) {
2431 /* we have a local Sugar folder */
2432 if(node.data.ieId == 'folder') {
2433 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2434 } else if(node.data.ieId.match(SE.reGUID)) {
2435 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2444 addChildNode : function(parentNode, childNode) {
2445 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2446 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2447 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2449 if(childNode.nodes) {
2450 if(childNode.nodes.length > 0) {
2451 for(j=0; j<childNode.nodes.length; j++) {
2452 var newChildNode = childNode.nodes[j];
2453 this.addChildNode(node, newChildNode);
2460 * Builds and returns a new TreeView Node
2461 * @param string name
2463 * @param int is_group
2466 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2467 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2469 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2470 node.expanded = expanded;
2471 node.data = new Object;
2472 node.data['id'] = id;
2473 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2474 node.data['label'] = name;
2475 node.data['ieId'] = 'folder';
2476 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2477 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2478 node.data['unseen'] = unseen;
2483 * ensures that a new folder has a valid name
2485 checkFolderName : function(name) {
2489 this.folderAdd(name);
2493 * Pings email servers for new email - forces refresh of folder pane
2495 checkEmailAccounts : function() {
2496 this.checkEmailAccountsSilent(true);
2499 checkEmailAccountsSilent : function(showOverlay) {
2500 if(typeof(SE.folders.checkingMail)) {
2501 clearTimeout(SE.folders.checkingMail);
2504 // don't stomp an on-going request
2505 if(AjaxObject.currentRequestObject.conn == null) {
2507 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2508 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2510 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2512 // wait 5 secs before trying again.
2513 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2518 * Starts check of all email Accounts using a loading bar for large POP accounts
2520 startEmailAccountCheck : function() {
2521 // don't do two checks at the same time
2522 if(!AjaxObject.requestInProgress()) {
2523 overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2524 SE.accounts.ieIds = SE.folders.getIeIds();
2525 if (SE.accounts.ieIds.length > 0) {
2526 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2527 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2532 // wait 5 secs before trying again.
2533 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2538 * Checks a single Account check based on passed ieId
2540 startEmailCheckOneAccount : function(ieId, synch) {
2547 var node = SE.clickedFolderNode;
2548 if (node && !synch) {
2549 mbox = node.data.mbox;
2551 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2552 SE.accounts.ieIds = [ieId];
2553 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2554 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2559 * Empties trash for subscribed accounts
2561 emptyTrash : function() {
2562 SE.contextMenus.frameFoldersContextMenu.hide();
2563 overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2564 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2568 * Clears Cache files of the inboundemail account
2570 clearCacheFiles : function(ieId) {
2571 SE.contextMenus.frameFoldersContextMenu.hide();
2572 overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2573 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2578 * Returns an array of all the active accounts in the folder view
2580 getIeIds : function() {
2582 var root = SE.tree.getRoot();
2583 for(i=0; i < root.children.length; i++) {
2584 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2585 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2586 ieIds.push(root.children[i].children[0].data.ieId);
2593 * loads folder lists in Settings->Folders
2595 lazyLoadSettings : function() {
2596 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2597 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2601 * After the add new folder is done via folders tab on seetings, this function should get called
2602 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2604 loadSettingFolder : function() {
2605 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2606 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2610 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2612 removeSugarFolders : function() {
2614 var root = tree.getRoot();
2615 var folder = SE.util.findChildNode(root, "ieId", "folder");
2617 tree.removeNode(folder);
2618 folder = SE.util.findChildNode(root, "ieId", "folder");
2620 if (!root.childrenRendered) {
2621 root.childrenRendered = true;
2625 rebuildFolders : function(silent) {
2626 if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2627 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2633 * Updates TreeView with Sugar Folders
2635 setSugarFolders : function(delay) {
2636 this.removeSugarFolders();
2637 //AjaxObject.forceAbort = true;
2638 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2642 * Takes async data object and creates the sugar folders in TreeView
2644 setSugarFoldersEnd : function(o) {
2645 var root = SE.tree.getRoot();
2646 addChildNodes(root, {nodes: o});
2647 SE.accounts.renderTree();
2648 //If nothing is loaded in the grid, load "My Inbox"
2649 if (SE.grid.params.ieId == "undefined") {
2650 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2654 startCheckTimer : function() {
2655 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2656 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2658 if(typeof(SE.folders.checkTimer) != 'undefined') {
2659 clearTimeout(SE.folders.checkTimer);
2662 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2663 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2665 SE.userPrefs.emailSettings.firstAutoCheck = true;
2666 SE.folders.checkEmailAccountsSilent(false);
2672 * makes an async call to save user preference and refresh folder view
2673 * @param object SELECT list object
2675 setFolderSelection : function() {
2676 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2678 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2679 var a_active_accnts = "";
2680 for(i=0;i<a_rs.length;i++)
2682 var t_record = a_rs[i];
2683 var is_active = t_record.getData('is_active');
2685 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2688 if(a_active_accnts == "")
2689 a_active_accnts = "&ieIdShow[]=";
2691 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2693 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2697 * makes async call to save user preference for a given node's open state
2698 * @param object node YUI TextNode object
2700 setOpenState : function(node) {
2701 SE.util.clearHiddenFieldValues('emailUIForm');
2702 var nodePath = node.data.id;
2703 var nodeParent = node.parent;
2705 while(nodeParent != null) {
2706 // root node has no ID param
2707 if(nodeParent.data != null) {
2708 nodePath = nodeParent.data.id + "::" + nodePath;
2711 var nodeParent = nodeParent.parent;
2714 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2715 document.getElementById('focusFolder').value = nodePath;
2717 if(node.expanded == true) {
2718 document.getElementById('focusFolderOpen').value = 'open';
2720 document.getElementById('focusFolderOpen').value = 'closed';
2723 var formObject = document.getElementById('emailUIForm');
2724 YAHOO.util.Connect.setForm(formObject);
2726 AjaxObject.startRequest(null, null);
2729 getNodeFromMboxPath : function(path) {
2730 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2731 var a = JSON.parse(path);
2733 var node = tree.getRoot();
2736 while(i < a.length) {
2737 node = this.getChildNodeFromLabel(node, a[i]);
2744 getChildNodeFromLabel : function(node, nodeLabel) {
2745 for(i=0; i<node.children.length; i++) {
2746 if(node.children[i].data.id == nodeLabel) {
2747 return node.children[i];
2753 * returns the node that presumably under the user's right-click
2755 getNodeFromContextMenuFocus : function() {
2756 //// get the target(parent) node
2757 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2759 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2761 // filter local folders
2762 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2763 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2764 if(target.id == '') {
2765 target = target.parentNode;
2772 var targetNode = document.getElementById(target.id);
2773 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2776 var matches = re.exec(targetNode.id);
2778 return document.getElementById(ygtvlabelel1);
2784 // usually parent node
2785 matches = re.exec(targetNode.parentNode.id);
2792 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2793 parentNode.expand();
2799 * Decrements the Unread Email count in folder text
2800 * @param string ieId ID to look for
2801 * @param string mailbox name
2802 * @param count how many to decrement
2804 decrementUnreadCount : function(ieId, mbox, count) {
2809 if(mbox.indexOf("sugar::") === 0) {
2810 var node = this.getNodeFromId(ieId);
2812 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2815 var unseen = node.data.unseen;
2817 var check = unseen - count;
2818 var finalCount = (check >= 0) ? check : 0;
2819 node.data.unseen = finalCount;
2821 SE.accounts.renderTree();
2826 * gets the TreeView node with a given ID/ieId
2827 * @param string id ID to look for
2828 * @return object Node
2830 getNodeFromId : function(id) {
2831 SE.folders.focusNode = null;
2832 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2833 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2834 SE.folders.focusNode = this;
2838 return SE.folders.focusNode;
2842 * Uses ieId and mailbox to try to find a node in the tree
2844 getNodeFromIeIdAndMailbox : function(id, mbox) {
2845 SE.folders.focusNode = null;
2846 if (mbox == "sugar::Emails") {
2850 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2851 if (varsarray instanceof Array) {
2852 if (this.data.ieId && this.data.ieId == varsarray[0]
2853 && this.data.mbox == varsarray[1]) {
2854 SE.folders.focusNode = this;
2858 if (this.data.ieId && this.data.ieId == varsarray) {
2859 SE.folders.focusNode = this;
2863 }, null, [id, mbox]);
2864 return SE.folders.focusNode;
2867 unhighliteAll : function() {
2868 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2872 * Displays a short form
2874 folderAdd : function() {
2875 SE.contextMenus.frameFoldersContextMenu.hide();
2877 var node = SE.clickedFolderNode;
2879 if(node != null && node.data) {
2880 overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2881 app_strings.LBL_EMAIL_SETTINGS_NAME,
2882 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2884 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2888 folderAddRegisterEnter : function() {
2889 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2890 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2891 this.buttons[1].handler);
2893 this.enterKeyListener.enable();
2896 folderRemoveRegisterEnter : function() {
2897 this.enterKeyListener.disable();
2900 folderAddXmlCall : function(name) {
2901 if (trim(name) == "") {
2902 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2905 name = escape(name);
2909 var parentNode = SE.clickedFolderNode;
2911 this.contextMenuFocus = parentNode;
2913 if(parentNode.data.ieId) {
2914 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2918 if(type == 'imap') {
2919 // make an IMAP folder
2920 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2921 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2922 } else if(type == 'sugar') {
2923 // make a Sugar folder
2924 if(SE.folders.isUniqueFolderName(name)) {
2925 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2926 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2928 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2929 SE.folders.folderAdd();
2933 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2936 // hide add-folder diaglogue
2937 SE.e2overlay.hide();
2941 * Removes either an IMAP folder or a Sugar Folder
2943 folderDelete : function() {
2944 SE.contextMenus.frameFoldersContextMenu.hide();
2946 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2948 var parentNode = SE.clickedFolderNode;
2950 if(parentNode != null && parentNode.data) {
2951 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2952 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2956 AjaxObject.target = 'frameFlex';
2958 if(parentNode.data.ieId != 'folder') {
2959 // delete an IMAP folder
2960 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2962 // delete a sugar folder
2963 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2965 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2966 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2968 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2974 * Rename folder form
2977 folderRename : function() {
2978 SE.contextMenus.frameFoldersContextMenu.hide();
2979 var node = SE.clickedFolderNode;
2982 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2983 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2987 overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2988 app_strings.LBL_EMAIL_SETTINGS_NAME,
2990 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2992 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2997 * fills an Object with key-value pairs of available folders
2999 getAvailableFoldersObject : function() {
3000 var ret = new Object();
3001 var tree = SE.tree.root;
3004 for(var i=0; i<tree.children.length; i++) {
3005 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3008 ret['none'] = app_strings.LBL_NONE;
3015 * Fills in key-value pairs for dependent dropdowns
3016 * @param object ret Associative array
3017 * @param object node TreeView node in focus
3018 * @param string currentPath Built up path thus far
3019 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3021 getFolderFromChild : function(ret, node, currentPath, spacer) {
3022 if(node.data != null && node.depth > 0) {
3023 /* handle visual separtors differentiating b/t mailserver and local */
3024 if(node.data.ieId && node.data.ieId == 'folder') {
3025 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3029 ret['spacer0'] = spacer;
3030 } else if(ret.spacer0 != spacer) {
3031 ret['spacer1'] = spacer
3034 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3035 var depthMarker = currentPath;
3036 var retIndex = SE.folders._createFolderId(node);
3037 ret[retIndex] = depthMarker + theLabel;
3040 if(node.children != null) {
3042 currentPath += theLabel + "/";
3045 for(var i=0; i<node.children.length; i++) {
3046 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3054 * Wrapper to refresh folders tree
3056 getFolders : function() {
3057 SE.accounts.rebuildFolderList();
3061 * handles events around folder-rename input field changes
3062 * @param object YUI event object
3064 handleEnter : function(e) {
3065 switch(e.browserEvent.type) {
3067 e.preventDefault(); // click in text field
3071 SE.folders.submitFolderRename(e);
3075 var kc = e.browserEvent.keyCode;
3079 SE.folders.submitFolderRename(e);
3083 e.preventDefault(e);
3084 SE.folders.cancelFolderRename(e);
3091 * Called when a node is clicked on in the folder tree
3092 * @param node, The node clicked on
3093 * @param e, The click event
3095 handleClick : function(o) {
3097 //If the click was on a sugar folder
3098 if (node.data.ieId == "folder") {
3099 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3102 SE.listView.populateListFrame(node, node.data.ieId, false);
3104 //eval(node.data.click);
3109 * Called when a node is right-clicked on in the folder tree
3111 handleRightClick : function(e) {
3112 YAHOO.util.Event.preventDefault(e);
3114 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3115 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3117 //If the click was on a sugar folder
3118 SE.clickedFolderNode = node;
3119 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3120 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3121 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3122 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3123 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3124 menu.getItem(3).cfg.setProperty("disabled", false);
3125 menu.getItem(4).cfg.setProperty("disabled", false);
3126 menu.getItem(5).cfg.setProperty("disabled", false);
3127 menu.getItem(6).cfg.setProperty("disabled", true);
3129 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3130 menu.getItem(0).cfg.setProperty("disabled", true);
3131 menu.getItem(1).cfg.setProperty("disabled", true);
3132 menu.getItem(2).cfg.setProperty("disabled", true);
3133 menu.getItem(3).cfg.setProperty("disabled", true);
3134 menu.getItem(4).cfg.setProperty("disabled", true);
3136 if (node.data.protocol != null) {
3137 menu.getItem(6).cfg.setProperty("disabled", false);
3139 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3140 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3141 //Sent or Draft folders
3142 menu.getItem(3).cfg.setProperty("disabled", true);
3143 menu.getItem(4).cfg.setProperty("disabled", true);
3144 menu.getItem(5).cfg.setProperty("disabled", true);
3147 //For group with auto inbound, disable everything.
3148 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3150 menu.getItem(0).cfg.setProperty("disabled", true);
3151 menu.getItem(1).cfg.setProperty("disabled", true);
3152 menu.getItem(2).cfg.setProperty("disabled", true);
3153 menu.getItem(3).cfg.setProperty("disabled", true);
3154 menu.getItem(4).cfg.setProperty("disabled", true);
3155 menu.getItem(5).cfg.setProperty("disabled", true);
3156 menu.getItem(6).cfg.setProperty("disabled", true);
3159 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3164 * Called when a row is dropped on a node
3166 handleDrop : function(rows, targetFolder) {
3167 var rowData = rows[0].getData();
3168 if (rowData.mbox != targetFolder.data.mbox) {
3169 var srcIeId = rowData.ieId;
3170 var srcFolder = rowData.mbox;
3171 var destIeId = targetFolder.data.ieId;
3172 var destFolder = targetFolder.data.mbox;
3174 for(var i=0; i<rows.length; i++) {
3175 uids[i] = rows[i].getData().uid;
3177 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3182 * Called when something is dragged over a Folder Node
3184 dragOver : function(dragObject) {
3189 * Determines if a folder name is unique to the folder tree
3190 * @param string name
3192 isUniqueFolderName : function(name) {
3193 uniqueFolder = true;
3194 var root = SE.tree.getRoot();
3195 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3196 if (this.attributes && this.attributes.ieId == "folder") {
3197 if (this.attributes.text == name) {
3198 uniqueFolder = false;
3203 return uniqueFolder;
3207 * Makes async call to rename folder in focus
3208 * @param object e Event Object
3210 submitFolderRename : function(newName) {
3211 if (trim(newName) == "") {
3212 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3215 newName = escape(newName);
3216 var node = SE.clickedFolderNode;
3217 var origName = node.data.text
3219 if (newName == origName) {
3222 if(SE.folders.isUniqueFolderName(newName)) {
3223 overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3224 if (node.data.ieId == "folder") {
3226 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3229 //IMAP folder or POP mailbox
3230 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3231 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3232 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3236 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3241 moveFolder : function(folderId, parentFolderId) {
3242 if (folderId != parentFolderId)
3244 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3245 + folderId + "&newParentId=" + parentFolderId);
3250 * makes async call to do a full synchronization of all accounts
3252 synchronizeAccounts : function() {
3253 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3254 overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3255 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3260 * Updates user's folder subscriptsion (Sugar only)
3261 * @param object SELECT DOM object in focus
3262 * @param string type of Folder selection
3264 updateSubscriptions : function() {
3265 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3269 select = document.getElementById('userFolders');
3271 for(i=0; i<select.options.length; i++) {
3272 var opt = select.options[i];
3273 if(opt.selected && opt.value != "") {
3277 active += opt.value;
3281 //Add the group folder ids.
3282 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3283 for(i=0; i<group_folders.length; i++)
3285 active += ("::" + group_folders[i]);
3288 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3291 * Updates user's group folder subscriptsion (Sugar only)
3292 * @param ieID The group folder to add to the tree view
3294 retrieveGroupFolderSubscriptions : function() {
3296 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3297 var activeGroupFolders = "";
3298 var activeGroupIds = [];
3299 for(i=0;i<a_rs.length;i++)
3301 var t_record = a_rs[i];
3302 var is_active = t_record.getData('is_active');
3303 var isGroupFolder = t_record.getData('has_groupfolder');
3304 var ieID = t_record.getData('id');
3308 activeGroupIds.push(ieID);
3312 return activeGroupIds;
3317 SE.folders.checkEmail2 = function() {
3318 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3320 //// END FOLDERS OBJECT
3321 ///////////////////////////////////////////////////////////////////////////////
3324 ///////////////////////////////////////////////////////////////////////////////
3327 * Keypress Event capture and processing
3330 overall : function(e) {
3331 switch(e.charCode) {
3333 if(e.ctrlKey || e.altKey) {
3334 var focusRegion = SE.innerLayout.regions.center;
3335 if(focusRegion.activePanel.closable == true) {
3336 focusRegion.remove(focusRegion.activePanel);
3344 ///////////////////////////////////////////////////////////////////////////////
3347 ///////////////////////////////////////////////////////////////////////////////
3350 * ListView object methods and attributes
3356 * Fills the ListView pane with detected messages.
3358 populateListFrame : function(node, ieId, forceRefresh) {
3359 SE.innerLayout.selectTab(0);
3360 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3362 Dom.get('_blank').innerHTML = "";
3363 SE.grid.params['emailUIAction'] = 'getMessageList';
3364 SE.grid.params['mbox'] = node.data.mbox;
3365 SE.grid.params['ieId'] = ieId;
3366 forcePreview = true; // loads the preview pane with first item in grid
3367 SE.listView.refreshGrid();
3371 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3373 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3374 SE.innerLayout.selectTab(0);
3375 Dom.get('_blank').innerHTML = "";
3376 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3377 SE.grid.params['ieId'] = node.data.id;
3378 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3379 SE.listView.refreshGrid();
3383 * Sets sort order as user preference
3386 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3388 ieName = ieNamePassed;
3389 focusFolder = focusFolderPassed;
3391 SE.util.clearHiddenFieldValues('emailUIForm');
3392 var previousSort = document.getElementById('sortBy').value;
3394 document.getElementById('sortBy').value = sortBy;
3395 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3396 document.getElementById('focusFolder').value = focusFolder;
3397 document.getElementById('ieId').value = ieId;
3399 if(sortBy == previousSort) {
3400 document.getElementById('reverse').value = '1';
3403 var formObject = document.getElementById('emailUIForm');
3404 YAHOO.util.Connect.setForm(formObject);
3406 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3411 * Enables click/arrow select of grid items which then populate the preview pane.
3413 selectFirstRow : function() {
3414 SE.grid.selModel.selectFirstRow();
3417 selectLastRow : function() {
3418 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3421 setEmailListStyles : function() {
3422 SE.listView.boldUnreadRows();
3424 var ds = SE.grid.getStore();
3425 if (SE.grid.getSelections().length == 0) {
3426 document.getElementById('_blank').innerHTML = '';
3430 if(typeof(ds.baseParams.mbox) != 'undefined') {
3431 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3432 var cm = SE.grid.getColumnModel();
3433 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3434 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3436 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3437 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3441 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3442 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3445 // 4/20/2007 added to hide overlay after search
3447 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3448 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3449 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3450 if (node) node.data.unseen = unread;
3452 SE.accounts.renderTree();
3455 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3456 if(forcePreview && ds.totalCount > 0) {
3457 SE.detailView.getEmailPreview();
3458 forcePreview = false;
3463 * Removes a row if found via its UID
3465 removeRowByUid : function(uid) {
3466 uid = new String(uid);
3467 uids = uid.split(',');
3468 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3470 for(j=0; j<uids.length; j++) {
3471 var theUid = uids[j];
3472 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3473 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3474 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3480 displaySelectedEmails : function(rows) {
3481 var dm = SE.grid.getDataModel();
3484 for(i=0; i<rows.length; i++) {
3485 var rowIndex = rows[i].rowIndex;
3486 var metadata = dm.data[rowIndex];
3491 uids += metadata[5];
3493 // unbold unseen email
3494 this.unboldRow(rowIndex);
3497 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3501 * exception handler for data load failures
3503 loadException : function(dataModel, ex, response) {
3508 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3509 * @param string sourceIeId Email's source I-E id
3510 * @param string sourceFolder Email's current folder
3511 * @param destinationIeId Destination I-E id
3512 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3514 * @param array emailUids Array of email's UIDs
3516 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3517 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3518 overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3520 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3521 // remove rows from visibility
3522 for(row in selectedRows) {
3523 //SE.grid.getStore().remove(row);
3526 var baseUrl = '&sourceIeId=' + sourceIeId +
3527 '&sourceFolder=' + sourceFolder +
3528 '&destinationIeId=' + destinationIeId +
3529 '&destinationFolder=' + destinationFolder;
3532 for(i=0; i<emailUids.length; i++) {
3534 uids += app_strings.LBL_EMAIL_DELIMITER;
3536 uids += emailUids[i];
3538 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3539 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3541 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3547 * Unbolds text in the grid view to denote read status
3549 markRead : function(index, record) {
3550 // unbold unseen email
3551 var row = SE.grid.getRecord(record);
3552 row.getData().seen = 1;
3553 SE.grid.getTrEl(record).style.fontWeight = "normal";
3557 * grid row output, bolding unread emails
3559 boldUnreadRows : function() {
3560 // bold unread emails
3561 var trEl = SE.grid.getFirstTrEl();
3562 while(trEl != null) {
3563 if(SE.grid.getRecord(trEl).getData().seen == "0")
3564 trEl.style.fontWeight = "bold";
3566 trEl.style.fontWeight = "";
3567 trEl = SE.grid.getNextTrEl(trEl);
3572 * Show preview for an email if 1 and only 1 is selected
3573 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3575 handleRowSelect : function(e) {
3576 if(e.selectedRows.length == 1) {
3577 SE.detailView.getEmailPreview();
3581 handleDrop : function(e, dd, targetId, e2) {
3583 case 'htmleditordiv':
3584 var rows = SE.grid.getSelectedRows();
3585 if(rows.length > 0) {
3586 SE.listView.displaySelectedEmails(rows);
3591 var targetElId = new String(targetId);
3592 var targetIndex = targetElId.replace('ygtvlabelel',"");
3593 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3594 var dm = SE.grid.getDataModel();
3595 var emailUids = new Array();
3596 var destinationIeId = targetNode.data.ieId;
3597 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3600 var rows = SE.grid.getSelectedRows();
3601 // iterate through dragged rows
3602 for(i=0; i<rows.length; i++) {
3603 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3604 var rowIndex = rows[i].rowIndex;
3605 var dataModelRow = dm.data[rowIndex];
3606 var sourceIeId = dataModelRow[7];
3607 var sourceFolder = dataModelRow[6];
3608 emailUids[i] = dataModelRow[5];
3611 // event wrapped call - need FQ
3612 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3613 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3619 * Hack-around to get double-click and single clicks to work on the grid
3620 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3622 handleClick : function(o) {
3623 SUGAR.email2.grid.clearTextSelection();
3625 var el = SUGAR.email2.grid.getSelectedRows();
3627 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3628 if ( el.length == 1)
3631 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3632 SUGAR.email2.listView.currentRowIndex = rowId;
3633 clearTimeout(SUGAR.email2.detailView.previewTimer);
3634 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3639 * Custom handler for double-click/enter
3640 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3642 getEmail : function(e) {
3643 var rows = SE.grid.getSelectedRows();
3644 var row = SE.grid.getRecord(rows[0]).getData();
3646 clearTimeout(SE.detailView.previewTimer);
3647 document.getElementById("_blank").innerHTML = "";
3649 if(row.type != "draft") {
3650 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3652 // circumventing yui-ext tab generation, let callback handler build new view
3653 SE.util.clearHiddenFieldValues('emailUIForm');
3654 //function(uid, mbox, ieId, setRead, destination) {
3655 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3656 document.getElementById('uid').value = row.uid; // uid;
3657 document.getElementById('mbox').value = row.mbox; // mbox;
3658 document.getElementById('ieId').value = row.ieId; // ieId;
3660 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3661 AjaxObject.target = '_blank';
3662 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3667 * Retrieves a row if found via its UID
3671 getRowIndexByUid : function(uid) {
3672 uid = new String(uid);
3673 uids = uid.split(',');
3675 for(j=0; j<uids.length; j++) {
3676 var theUid = uids[j];
3678 for(i=0; i<SE.grid.getStore().data.length; i++) {
3679 if(SE.grid.getStore().data[i].id == theUid) {
3687 * Returns the UID's of the seleted rows
3690 getUidsFromSelection : function() {
3691 var rows = SE.grid.getSelectedRows();
3693 /* iterate through available rows JIC a row is deleted - use first available */
3694 for(var i=0; i<rows.length; i++) {
3695 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3700 refreshGrid : function() {
3701 SE.grid.getDataSource().sendRequest(
3702 SUGAR.util.paramsToUrl(SE.grid.params),
3703 SE.grid.onDataReturnInitializeTable,
3709 //// END SE.listView
3710 ///////////////////////////////////////////////////////////////////////////////
3712 ///////////////////////////////////////////////////////////////////////////////
3716 * sends search criteria
3717 * @param reference element search field
3719 search : function(el) {
3720 var searchCriteria = new String(el.value);
3722 if(searchCriteria == '') {
3723 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3727 var safeCriteria = escape(searchCriteria);
3729 var accountListSearch = document.getElementById('accountListSearch');
3730 //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3732 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3733 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3734 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3735 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3736 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3741 * sends advanced search criteria
3743 searchAdvanced : function() {
3744 var formObject = document.getElementById('advancedSearchForm');
3747 //Set assigned user id to blank if name is not present.
3748 if (formObject.elements['assigned_user_name'].value == "")
3749 formObject.elements['assigned_user_id'].value = "";
3751 for(i=0; i<formObject.elements.length; i++) {
3752 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3755 if(formObject.elements[i].type == 'text') {
3756 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3758 if(formObject.elements[i].type == 'hidden') {
3759 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3761 if(formObject.elements[i].type == 'select-one') {
3762 var el = formObject.elements[i];
3763 var v = el.options[el.selectedIndex].value;
3766 SE.grid.params[el.name] = v;
3769 //Clear previous search results if necessary
3770 if(typeof( SE.grid.params[el.name]) != 'undefined')
3771 delete SE.grid.params[el.name]
3778 if(! this.validateSearchFormInput() )
3781 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3782 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3783 var accountListSearch = document.getElementById('accountListSearch');
3784 SE.listView.refreshGrid();
3786 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3791 * Validates the search form inputs to ensure all parameters are valid
3794 validateSearchFormInput: function()
3796 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3797 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3798 var dateCheck = check_form('advancedSearchForm');
3800 //If the parent type is selected ensure the user selected a parent_id.
3801 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3807 * Toggles the advanced options, either hidding or showing the selection.
3809 toggleAdvancedOptions: function()
3811 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3813 for(var i=0;i<el.length;i++)
3815 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3816 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3818 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3822 * clears adv search form fields
3824 searchClearAdvanced : function() {
3825 var form = document.getElementById('advancedSearchForm');
3827 for(i=0; i<form.elements.length; i++) {
3828 if(form.elements[i].type != 'button') {
3829 form.elements[i].value = '';
3835 //////////////////////////////////////////////////////////////////////////////
3838 //////////////////////////////////////////////////////////////////////////////
3841 /******************************************************************************
3842 * USER SIGNATURES calls stolen from Users module
3843 *****************************************************************************/
3844 createSignature : function(record, the_user_id) {
3845 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3847 URL += "&record="+record;
3849 if(the_user_id != "") {
3850 URL += "&the_user_id="+the_user_id;
3852 var windowName = 'email_signature';
3853 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3855 var win = window.open(URL, windowName, windowFeatures);
3856 if(win && win.focus) {
3857 // put the focus on the popup if the browser supports the focus() method
3862 deleteSignature : function() {
3863 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3864 overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3865 var singature_id = document.getElementById('signature_id').value;
3866 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3870 saveOptionsGeneral : function(displayMessage) {
3871 var formObject = document.getElementById('formEmailSettingsGeneral');
3872 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3873 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3876 YAHOO.util.Connect.setForm(formObject);
3877 SE.composeLayout.emailTemplates = null;
3879 AjaxObject.target = 'frameFlex';
3880 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3883 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3885 SE.settings.settingsDialog.hide();
3889 * Shows settings container screen
3891 showSettings : function() {
3892 if(!SE.settings.settingsDialog) {
3893 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3899 constraintoviewport: true
3901 dlg.showEvent.subscribe( function (){
3902 var el = this.element;
3903 var viewH = YAHOO.util.Dom.getViewportHeight();
3904 if (this.header && el && viewH - 50 < el.clientHeight) {
3905 var body = this.header.nextElementSibling;
3906 body.style.overflow = "auto";
3907 body.style.height = (viewH - 50) + "px";
3910 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3911 dlg.setBody('<div id="settingsTabDiv"/>');
3912 dlg.beforeRenderEvent.subscribe(function() {
3913 var dd = new YAHOO.util.DDProxy(dlg.element);
3914 dd.setHandleElId(dlg.header);
3915 dd.on('endDragEvent', function() {
3921 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3922 var tabContent = Dom.get("tab_general");
3923 tp.addTab(new YAHOO.widget.Tab({
3924 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3926 content : tabContent.innerHTML,
3927 id : "generalSettings",
3930 tabContent.parentNode.removeChild(tabContent);
3931 tabContent = Dom.get("tab_accounts");
3932 var accountTab = new YAHOO.widget.Tab({
3933 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3935 content : tabContent.innerHTML,
3936 id : "accountSettings"
3938 tp.addTab(accountTab);
3939 tabContent.parentNode.removeChild(tabContent);
3941 tp.appendTo(dlg.body);
3944 SE.settings.settingsDialog.show();
3945 SE.folders.lazyLoadSettings();
3946 SE.accounts.lazyLoad();
3950 lazyLoadRules : function() {
3951 if(false/*!SE.settings.rules*/) {
3952 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 Community Edition 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;
5329 var to_addr = document.getElementById('addressTO'+idx);
5330 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
5332 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5333 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5336 // id is selected index of email template drop-down
5337 if(id == '' || id == "0") {
5338 YAHOO.SUGAR.MessageBox.show({
5343 if(btn=='no'){return;};
5344 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5351 YAHOO.SUGAR.MessageBox.show({
5356 if(btn=='no'){return;};
5357 SUGAR.email2.composeLayout.processResult(idx, id);},
5363 processNoneResult : function(idx, id) {
5364 var tiny = SE.util.getTiny('htmleditor' + idx);
5365 var tinyHTML = tiny.getContent();
5366 var openTag = '<div><span><span>';
5367 var htmllow = tinyHTML.toLowerCase();
5368 var start = htmllow.indexOf(openTag);
5370 tinyHTML = tinyHTML.substr(start);
5371 tiny.setContent(tinyHTML);
5373 tiny.setContent('');
5377 processResult : function(idx , id){
5378 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5380 // get attachments if any
5381 AjaxObject.target = '';
5382 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5385 appendEmailTemplateJSON : function() {
5386 var idx = SE.composeLayout.currentInstanceId; // post increment
5388 // query based on template, contact_id0,related_to
5389 //jchi 09/10/2008 refix #7743
5390 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5391 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5394 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,'"');
5396 // cn: bug 14361 - text-only templates don't fill compose screen
5398 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/>");
5401 var tiny = SE.util.getTiny('htmleditor' + idx);
5402 var tinyHTML = tiny.getContent();
5403 var openTag = '<div><span><span>';
5404 var closeTag = '</span></span></div>';
5405 var htmllow = tinyHTML.toLowerCase();
5406 var start = htmllow.indexOf(openTag);
5408 var htmlPart2 = tinyHTML.substr(start);
5409 tinyHTML = text + htmlPart2;
5410 tiny.setContent(tinyHTML);
5412 tiny.setContent(text);
5417 * Writes out the signature in the email editor
5419 setSignature : function(idx) {
5422 var hide = document.getElementById('setEditor' + idx).checked;
5423 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5424 //wait for signatures to load before trying to set them
5425 if (!SE.composeLayout.signatures) {
5426 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5431 var sel = document.getElementById('signatures' + idx);
5433 var sel = document.getElementById('signature_id');
5434 idx = SE.tinyInstances.currentHtmleditor;
5437 //Ensure that the tinyMCE html has been rendered.
5438 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5439 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5446 signature = sel.options[sel.selectedIndex].value;
5451 var openTag = '<div><span><span>';
5452 var closeTag = '</span></span></div>';
5453 var t = SE.util.getTiny('htmleditor' + idx);
5455 if(typeof(t) != 'undefined')
5457 t.contentDocument = t.contentWindow.document;
5458 var html = t.getContent();
5463 var htmllow = html.toLowerCase();
5464 var start = htmllow.indexOf(openTag);
5465 var end = htmllow.indexOf(closeTag) + closeTag.length;
5467 // selected "none" - remove signature from email
5468 if(signature == '') {
5470 var htmlPart1 = html.substr(0, start);
5471 var htmlPart2 = html.substr(end, html.length);
5473 html = htmlPart1 + htmlPart2;
5476 SE.signatures.lastAttemptedLoad = '';
5480 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5481 SE.signatures.lastAttemptedLoad = '';
5483 SE.signatures.lastAttemptedLoad = signature;
5485 if(typeof(SE.signatures[signature]) == 'undefined') {
5487 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5488 SE.signatures.targetInstance = (idx) ? idx : "";
5489 AjaxObject.target = '';
5490 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5492 var newSignature = this.prepareSignature(SE.signatures[signature]);
5494 // clear out old signature
5495 if(SE.signatures.lastAttemptedLoad && start > -1) {
5496 var htmlPart1 = html.substr(0, start);
5497 var htmlPart2 = html.substr(end, html.length);
5499 html = htmlPart1 + htmlPart2;
5503 start = html.indexOf('<div><hr></div>');
5504 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5505 var htmlPart1 = html.substr(0, start);
5506 var htmlPart2 = html.substr(start, html.length);
5507 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5508 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5509 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5511 var newHtml = html + openTag + newSignature + closeTag;
5513 //tinyMCE.setContent(newHtml);
5514 t.setContent(newHtml);
5518 prepareSignature : function(str) {
5519 var signature = new String(str);
5521 signature = signature.replace(/</gi, '<');
5522 signature = signature.replace(/>/gi, '>');
5528 showAttachmentPanel : function(idx) {
5529 var east = SE.composeLayout[idx].getUnitByPosition("right");
5530 var tabs = SE.composeLayout[idx].rightTabs;
5532 tabs.set("activeTab", tabs.getTab(0));
5536 * expands sidebar and displays options panel
5538 showOptionsPanel : function(idx) {
5539 var east = SE.composeLayout[idx].getUnitByPosition("right");
5540 var tabs = SE.composeLayout[idx].rightTabs;
5542 tabs.set("activeTab", tabs.getTab(1));
5546 * Selects the Contacts tab
5548 showContactsPanel : function() {
5549 SE.complexLayout.regions.west.showPanel("contactsTab");
5553 * Generates fields for Select Document
5555 addDocumentField : function(idx) {
5556 var basket = document.getElementById('addedDocuments' + idx);
5558 var index = (basket.childNodes.length / 7) - 1;
5565 var test = document.getElementById('documentId' + idx + index);
5567 while(test != null) {
5569 test = document.getElementById('documentId' + idx + index);
5572 var documentCup = document.createElement("div");
5573 documentCup.id = 'documentCup' + idx + index;
5574 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5575 // document id field
5576 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5577 // document name field
5578 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5580 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5581 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5582 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5584 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5585 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5586 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5589 basket.appendChild(documentCup);
5590 //basket.innerHTML += out;
5595 * Makes async call to save a draft of the email
5596 * @param int Instance index
5598 saveDraft : function(tinyInstance) {
5599 this.sendEmail(tinyInstance, true);
5602 selectDocument : function(target) {
5603 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5604 windowName = 'selectDocument';
5605 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5607 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5609 // put the focus on the popup if the browser supports the focus() method
5615 * Modal popup for file attachment dialogue
5617 addFileField : function() {
5618 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5619 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5623 constraintoviewport: true,
5625 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5626 fn:function(){SE.addFileDialog.hide();}
5629 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5630 SE.addFileDialog.render();
5631 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5633 Dom.removeClass("addFileDialog", "yui-hidden");
5635 SE.addFileDialog.show();
5639 * Async upload of file to temp dir
5641 uploadAttachment : function() {
5642 if(document.getElementById('email_attachment').value != "") {
5643 var formObject = document.getElementById('uploadAttachment');
5644 YAHOO.util.Connect.setForm(formObject, true, true);
5645 AjaxObject.target = '';
5646 AjaxObject.startRequest(callbackUploadAttachment, null);
5648 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5653 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5654 * @param string target in focus compose layout
5656 setDocument : function(idx, target, documentId, documentName, docRevId) {
5657 // fields are named/id'd [fieldName][instanceId][index]
5658 var addedDocs = document.getElementById("addedDocuments" + idx);
5659 var docId = document.getElementById('documentId' + idx + target);
5660 var docName = document.getElementById('documentName' + idx + target);
5661 var docRevisionId = document.getElementById('document' + idx + target);
5662 docId.value = documentId;
5663 docName.value = documentName;
5664 docRevisionId.value = docRevId;
5668 * Removes the bucket div containing the document input fields
5670 deleteDocumentField : function(documentCup) {
5671 var f0 = document.getElementById(documentCup);
5672 f0.parentNode.removeChild(f0);
5676 * Removes a Template Attachment field
5680 deleteTemplateAttachmentField : function(idx, index) {
5681 // create not-in-array values for removal filtering
5682 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5688 r += document.getElementById('templateAttachmentId' + idx + index).value;
5689 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5691 var target = 'templateAttachmentCup' + idx + index;
5692 d = document.getElementById(target);
5693 d.parentNode.removeChild(d);
5697 * Async removal of uploaded temp file
5698 * @param string index Should be a concatenation of idx and index
5701 deleteUploadAttachment : function(index, file) {
5702 var d = document.getElementById('email_attachment_bucket' + index);
5703 d.parentNode.removeChild(d);
5705 // make async call to delete cached file
5706 AjaxObject.target = '';
5707 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5711 * Attaches files coming from Email Templates
5713 addTemplateAttachmentField : function(idx) {
5715 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5717 var basket = document.getElementById('addedTemplateAttachments' + idx);
5720 var index = basket.childNodes.length;
5727 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5729 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5730 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5731 idx + "\",\"" + index + "\");'/>" +
5733 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5734 // templateAttachment field
5735 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5737 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5739 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5740 "<br id='br" + index + "></br>" +
5741 "<br id='brdoc" + index + "></br>" +
5743 basket.innerHTML = basket.innerHTML + out;
5749 * Sends one email via async call
5750 * @param int idx Editor instance ID
5751 * @param bool isDraft
5753 sendEmail : function(idx, isDraft) {
5755 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5756 var obAccountID = document.getElementById('addressFrom' + idx).value;
5758 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5760 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5765 var form = document.getElementById('emailCompose' + idx);
5766 var composeOptionsFormName = "composeOptionsForm" + idx;
5767 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5768 var html = t.getContent();
5769 var subj = document.getElementById('emailSubject' + idx).value;
5770 var to = trim(document.getElementById('addressTO' + idx).value);
5771 var cc = trim(document.getElementById('addressCC' + idx).value);
5772 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5773 var email_id = document.getElementById('email_id' + idx).value;
5774 var composeType = document.getElementById('composeType').value;
5775 var parent_type = document.getElementById("parent_type").value;
5776 var parent_id = document.getElementById("parent_id").value;
5778 var el_uid = document.getElementById("uid");
5779 var uid = (el_uid == null) ? '' : el_uid.value;
5781 var el_ieId = document.getElementById("ieId");
5782 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5784 var el_mbox = document.getElementById("mbox");
5785 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5787 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5788 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5792 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5795 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5796 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5797 parent_id = parentIdValue;
5798 parent_type = parentTypeValue;
5800 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5801 // baseline viability check
5803 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5804 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5806 } else if(subj == '' && !isDraft) {
5807 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5810 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5812 } else if(html == '' && !isDraft) {
5813 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5818 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5819 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5820 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5821 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5822 html = html.replace(/</ig, "sugarLessThan");
5823 html = html.replace(/>/ig, "sugarGreaterThan");
5825 form.sendDescription.value = html;
5826 form.sendSubject.value = subj;
5827 form.sendTo.value = to;
5828 form.sendCc.value = cc;
5829 form.sendBcc.value = bcc;
5830 form.email_id.value = email_id;
5831 form.composeType.value = composeType;
5832 form.composeLayoutId.value = 'composeLayout' + idx;
5833 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5834 form.saveToSugar.value = 1;
5835 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5836 form.parent_type.value = parent_type;
5837 form.parent_id.value = parent_id;
5838 form.uid.value = uid;
5839 form.ieId.value = ieId;
5840 form.mbox.value = mbox;
5842 // email attachments
5843 var addedFiles = document.getElementById('addedFiles' + idx);
5845 for(i=0; i<addedFiles.childNodes.length; i++) {
5846 var bucket = addedFiles.childNodes[i];
5848 for(j=0; j<bucket.childNodes.length; j++) {
5849 var node = bucket.childNodes[j];
5850 var nName = new String(node.name);
5852 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5853 if(form.attachments.value != '') {
5854 form.attachments.value += "::";
5856 form.attachments.value += node.value;
5863 var addedDocs = document.getElementById('addedDocuments' + idx);
5865 for(i=0; i<addedDocs.childNodes.length; i++) {
5866 var cNode = addedDocs.childNodes[i];
5867 for(j=0; j<cNode.childNodes.length; j++) {
5868 var node = cNode.childNodes[j];
5869 var nName = new String(node.name);
5870 if(node.type == 'hidden' && nName.match(/documentId/)) {
5871 if(form.documents.value != '') {
5872 form.documents.value += "::";
5874 form.documents.value += node.value;
5880 // template attachments
5881 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5882 if(addedTemplateAttachments) {
5883 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5884 var cNode = addedTemplateAttachments.childNodes[i];
5885 for(j=0; j<cNode.childNodes.length; j++) {
5886 var node = cNode.childNodes[j];
5887 var nName = new String(node.name);
5888 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5889 if(form.templateAttachments.value != "") {
5890 form.templateAttachments.value += "::";
5892 form.templateAttachments.value += node.value;
5898 // remove attachments
5899 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5901 YAHOO.util.Connect.setForm(form);
5903 AjaxObject.target = 'frameFlex';
5905 // sending a draft email
5906 if(!isDraft && in_draft) {
5908 SE.listView.removeRowByUid(email_id);
5911 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5912 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5914 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5918 * Handles clicking the email address link from a given view
5920 composePackage : function() {
5921 if(composePackage != null) {
5922 SE.composeLayout.c0_composeNewEmail();
5925 if(composePackage.to_email_addrs) {
5926 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5928 if (composePackage.subject != null && composePackage.subject.length > 0) {
5929 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5932 //If no parent fields are set in the composePackage, ensure they are cleared.
5933 var parentFields = ['parent_type','parent_name','parent_id'];
5934 for(var i=0;i<parentFields.length;i++)
5936 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5937 composePackage[parentFields[i]] = "";
5940 document.getElementById("parent_type").value = composePackage.parent_type;
5941 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5942 document.getElementById("parent_id").value = composePackage.parent_id;
5943 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5944 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5946 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5947 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5949 if (composePackage.body != null && composePackage.body.length > 0) {
5950 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5951 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5952 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5954 if (composePackage.attachments != null) {
5955 SE.composeLayout.loadAttachments(composePackage.attachments);
5958 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5959 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5960 SE.util.emptySelectOptions(addressFrom);
5961 var fromAccountOpts = composePackage.fromAccounts.data;
5962 for(i=0; i<fromAccountOpts.length; i++) {
5963 var key = fromAccountOpts[i].value;
5964 var display = fromAccountOpts[i].text;
5965 var opt = new Option(display, key);
5966 if (fromAccountOpts[i].selected) {
5967 opt.selected = true;
5969 addressFrom.options.add(opt);
5976 setContentOnThisTiny : function() {
5977 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5978 var tinyHTML = tiny.getContent();
5979 composePackage.body = decodeURI(encodeURI(composePackage.body));
5980 // cn: bug 14361 - text-only templates don't fill compose screen
5981 if(composePackage.body == '') {
5982 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
5984 //Flag determines if we should clear the tiny contents or just append
5985 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5986 SE.composeLayout.tinyHTML = '';
5988 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
5990 tiny.setContent(SE.composeLayout.tinyHTML);
5991 //Indicate that the contents has been loaded successfully.
5992 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5995 * Confirms closure of a compose screen if "x" is clicked
5997 confirmClose : function(panel) {
5998 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
5999 SE.composeLayout.closeCompose(panel.id);
6007 * forces close of a compose screen
6009 forceCloseCompose : function(id) {
6010 SE.composeLayout.closeCompose(id);
6012 // handle flow back to originating view
6013 if(composePackage) {
6014 // check if it's a module we need to return to
6015 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6016 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6017 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6018 window.location = url;
6025 * closes the editor that just sent email
6026 * @param string id ID of composeLayout tab
6028 closeCompose : function(id) {
6029 // destroy tinyMCE instance
6030 var idx = id.substr(13, id.length);
6031 var instanceId = "htmleditor" + idx;
6032 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6034 // nullify DOM and namespace values.
6036 SE.composeLayout[idx] = null;
6037 SE.tinyInstances[instanceId] = null;
6038 var tabsArray = SE.innerLayout.get("tabs");
6039 for (i = 0 ; i < tabsArray.length ; i++) {
6040 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6041 tabsArray[i].close();
6045 //SE.innerLayout.getTab(idx).close();
6049 * Enable the quick search for the compose relate field or search tab
6051 enableQuickSearchRelate: function(idx,overides){
6053 if(typeof overides != 'undefined')
6055 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6056 var newModule = document.getElementById(newModuleID).value;
6057 var formName = overides['formName'];
6058 var fieldName = overides['fieldName'];
6059 var fieldId = overides['fieldId'];
6060 var fullName = formName + "_" + fieldName;
6061 var postBlurFunction = null;
6065 var newModule = document.getElementById('data_parent_type'+idx).value;
6066 var formName = 'emailCompose'+idx;
6067 var fieldName = 'data_parent_name'+idx;
6068 var fieldId = 'data_parent_id'+idx;
6069 var fullName = formName + "_" + fieldName;
6070 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6073 if(typeof sqs_objects == 'undefined')
6074 window['sqs_objects'] = new Array;
6076 window['sqs_objects'][fullName] = {
6079 modules:[newModule],
6081 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6082 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6083 post_onblur_function: postBlurFunction,
6084 order:"name","limit":"30","no_match_text":"No Match"};
6087 if(typeof QSProcessedFieldsArray != 'undefined')
6088 QSProcessedFieldsArray[fullName] = false;
6089 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6090 QSFieldsArray[fullName].destroy();
6091 delete QSFieldsArray[fullName];
6093 if (Dom.get(fullName + "_results")) {
6094 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6100 qsAddAddress : function(o) {
6101 if (o.name != "" && o.email1 != "")
6103 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6104 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6108 * Returns a new instance ID, 0-index
6110 getNewInstanceId : function() {
6111 this.currentInstanceId = this.currentInstanceId + 1;
6112 return this.currentInstanceId;
6116 * 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.
6118 loadAttachments : function(result) {
6119 var idx = SE.composeLayout.currentInstanceId;
6121 if(typeof(result) == 'object') {
6122 //jchi #20680. Clean the former template attachments;
6123 var basket = document.getElementById('addedTemplateAttachments' + idx);
6124 if(basket.innerHTML != ''){
6125 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6127 basket.innerHTML = '';
6132 if(typeof result[i] == 'object') {
6133 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6134 var bean = result[i];
6135 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6136 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6143 * fills drop-down values for email templates and signatures
6145 setComposeOptions : function(idx) {
6146 // send from accounts
6147 var addressFrom = document.getElementById('addressFrom' + idx);
6149 if (addressFrom.options.length <= 0) {
6150 SE.util.emptySelectOptions(addressFrom);
6151 var fromAccountOpts = SE.composeLayout.fromAccounts;
6152 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6153 var key = fromAccountOpts[id].value;
6154 var display = fromAccountOpts[id].text;
6155 var is_default = false;
6156 if(key == SUGAR.default_inbound_accnt_id)
6158 var opt = new Option(display, key);
6159 addressFrom.options.add(opt);
6160 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6165 var et = document.getElementById('email_template' + idx);
6166 SE.util.emptySelectOptions(et);
6168 for(var key in this.emailTemplates) { // iterate through assoc array
6169 var display = this.emailTemplates[key];
6170 var opt = new Option(display, key);
6171 et.options.add(opt);
6175 var sigs = document.getElementById('signatures' + idx);
6176 SE.util.emptySelectOptions(sigs);
6178 for(var key in this.signatures) { // iterate through assoc array
6179 var display = this.signatures[key];
6180 var opt = new Option(display, key);
6182 if(key == SE.userPrefs.signatures.signature_default) {
6183 opt.selected = true;
6186 sigs.options.add(opt);
6189 // html/plain email?
6190 var htmlEmail = document.getElementById('setEditor' + idx);
6191 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6192 htmlEmail.checked = true;
6194 htmlEmail.checked = false;
6197 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6201 * After compose screen is rendered, async call to get email body from Sugar
6203 replyForwardEmailStage2 : function() {
6204 SE.util.clearHiddenFieldValues('emailUIForm');
6205 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6207 var ieId = SE.composeLayout.replyForwardObj.ieId;
6208 var uid = SE.composeLayout.replyForwardObj.uid;
6209 var mbox = SE.composeLayout.replyForwardObj.mbox;
6210 var type = SE.composeLayout.replyForwardObj.type;
6211 var idx = SE.composeLayout.currentInstanceId;
6213 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6215 document.getElementById('emailSubject' + idx).value = type;
6216 document.getElementById('emailUIAction').value = 'composeEmail';
6217 document.getElementById('composeType').value = type;
6218 document.getElementById('ieId').value = ieId;
6219 document.getElementById('uid').value = uid;
6220 document.getElementById('mbox').value = mbox;
6221 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6222 var formObject = document.getElementById('emailUIForm');
6223 YAHOO.util.Connect.setForm(formObject);
6225 var sendType = type;
6226 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6230 * Show the hidden cc or bcc fields
6232 showHiddenAddress: function(addrType,idx){
6234 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6235 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6236 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6237 this[addrType+'Hidden'+idx] = false;
6239 //After bcc or cc is added, move options below last addr field
6240 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6242 //If both cc and bcc hidden, remove the empty row containing text.
6243 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6244 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6245 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6247 SE.composeLayout.resizeEditor(idx);
6250 * Hide the cc and bcc fields if they were shown.
6252 hideHiddenAddresses: function(idx){
6254 var addrTypes = ['cc','bcc'];
6255 for(var i = 0;i<addrTypes.length;i++)
6257 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6258 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6259 this[addrTypes[i] + 'Hidden'+idx] = true
6262 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6263 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6264 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6268 //// END SE.composeLayout
6269 ///////////////////////////////////////////////////////////////////////////////
6270 ///////////////////////////////////////////////////////////////////////////////
6274 * Cleans serialized UID lists of duplicates
6278 cleanUids : function(str) {
6279 var seen = new Object();
6281 var arr = new String(str).split(",");
6283 for(var i=0; i<arr.length; i++) {
6288 clean += (clean != "") ? "," : "";
6290 seen[arr[i]] = true;
6297 * Clears hidden field values
6298 * @param string id ID of form element to clear
6300 clearHiddenFieldValues : function(id) {
6301 var form = document.getElementById(id);
6303 for(i=0; i<form.elements.length; i++) {
6304 if(form.elements[i].type == 'hidden') {
6305 var e = form.elements[i];
6306 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6314 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6316 emptySelectOptions : function(el) {
6318 for(i=el.childNodes.length - 1; i >= 0; i--) {
6319 if(el.childNodes[i]) {
6320 el.removeChild(el.childNodes[i]);
6327 * Returns the MBOX path in the manner php_imap expects:
6328 * ie: INBOX.DEBUG.test
6329 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6331 generateMboxPath : function(str) {
6332 var ex = str.split("::");
6334 /* we have a serialized MBOX path */
6338 for(var i=0; i<ex.length; i++) {
6339 if(ex[i] == 'INBOX') {
6351 /* we have a Sugar folder GUID - do nothing */
6359 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6360 * @param HTMLElement el
6361 * @return string GUID of found element or empty on failure
6363 getGuidFromElement : function(el) {
6369 for(var i=0; i<iterations; i++) {
6371 if(el.id.match(SE.reGUID)) {
6383 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6386 getPanelId : function() {
6387 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6391 * wrapper to handle weirdness with IE
6392 * @param string instanceId
6393 * @return tinyMCE Controller object
6395 getTiny : function(instanceId) {
6396 if(instanceId == '') {
6400 var t = tinyMCE.getInstanceById(instanceId);
6404 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6410 * Simple check for MSIE browser
6414 var nav = new String(navigator.appVersion);
6415 if(nav.match(/MSIE/)) {
6422 * Recursively removes an element from the DOM
6423 * @param HTMLElement
6425 removeElementRecursive : function(el) {
6426 this.emptySelectOptions(el);
6433 sleep : function(secs) {
6434 setTimeout("void(0);", secs);
6438 * Converts a <select> element to an Ext.form.combobox
6440 convertSelect : function(select) {
6441 alert('in convertSelect');
6442 if (typeof(select) == "string") {
6443 select = document.getElementById(select);
6447 findChildNode : function (parent, property, value) {
6448 for (i in parent.children) {
6449 var child = parent.children[i];
6450 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6452 var searchChild = SE.util.findChildNode(child, property, value);
6459 cascadeNodes : function (parent, fn, scope, args) {
6460 for (i in parent.children) {
6461 var child = parent.children[i];
6462 var s = scope ? scope : child;
6463 var a = args ? args : child;
6465 SE.util.cascadeNodes(child, fn, scope, args);
6472 ///////////////////////////////////////////////////////////////////////////////
6475 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6477 /*********************************************************************************
6478 * SugarCRM Community Edition is a customer relationship management program developed by
6479 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6481 * This program is free software; you can redistribute it and/or modify it under
6482 * the terms of the GNU Affero General Public License version 3 as published by the
6483 * Free Software Foundation with the addition of the following permission added
6484 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6485 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6486 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6488 * This program is distributed in the hope that it will be useful, but WITHOUT
6489 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6490 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6493 * You should have received a copy of the GNU Affero General Public License along with
6494 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6495 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6498 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6499 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6501 * The interactive user interfaces in modified source and object code versions
6502 * of this program must display Appropriate Legal Notices, as required under
6503 * Section 5 of the GNU Affero General Public License version 3.
6505 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6506 * these Appropriate Legal Notices must retain the display of the "Powered by
6507 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6508 * technical reasons, the Appropriate Legal Notices must display the words
6509 * "Powered by SugarCRM".
6510 ********************************************************************************/
6513 if (typeof console == "undefined")
6514 console = { log: function(o) {alert(o)} };
6518 currentRequestObject : null,
6519 //timeout : 30000, // 30 second timeout default
6520 timeout : 9999999999, // 30 second timeout default
6522 trail : new Array(),
6526 _reset : function() {
6527 this.timeout = 30000;
6528 this.forceAbort = false;
6531 folderRenameCleanup : function() {
6532 SUGAR.email2.folders.setSugarFolders();
6535 fullSyncCleanup : function(o) {
6536 this.folders.checkMailCleanup(o);
6537 SUGAR.email2.settings.settingsDialog.hide();
6542 composeCache : function(o) {
6543 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6544 // get email templates and user signatures
6545 var ret = JSON.parse(o.responseText);
6547 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6548 SUGAR.email2.composeLayout.signatures = ret.signatures;
6549 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6551 SUGAR.email2.composeLayout.setComposeOptions(idx);
6553 //Set the error array so we can notify the user when they try to hit send if any errors
6554 //are present. We will also notify them now (after hitting compose button).
6555 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6558 //if error element is returning an array, then check the length to make sure we have error messages
6559 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6560 //add error messages for display
6561 for(i in ret.errorArray)
6562 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6563 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6564 //if error element is returning an object, and the object value is not empty or null, then display error message
6565 for(i in ret.errorArray)
6566 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6569 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6571 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6573 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6579 handleDeleteSignature : function(o) {
6581 var ret = JSON.parse(o.responseText);
6582 SUGAR.email2.composeLayout.signatures = ret.signatures;
6583 var field = document.getElementById('signature_id');
6584 SUGAR.email2.util.emptySelectOptions(field);
6586 for(var i in ret.signatures) { // iterate through assoc array
6587 var opt = new Option(ret.signatures[i], i);
6588 field.options.add(opt);
6590 setSigEditButtonVisibility();
6595 handleDeleteReturn : function(o) {
6596 // force refresh ListView
6598 if(document.getElementById('focusEmailMbox')) {
6599 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6602 // need to display success message before calling next async call?
6603 document.getElementById(this.target).innerHTML = o.responseText;
6608 handleFailure : function(o) {
6610 overlay('Exception occurred...', o.statusText, 'alert');
6611 if(document.getElementById('saveButton')) {
6612 document.getElementById('saveButton').disabled = false;
6616 handleReplyForward : function(o) {
6617 var a = JSON.parse(o.responseText);
6619 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6621 document.getElementById('email_id' + idx).value = a.uid;
6622 document.getElementById('emailSubject' + idx).value = a.name;
6623 document.getElementById('addressTO' + idx).value = a.from;
6624 document.getElementById('uid' + idx).value = a.uid;
6626 document.getElementById('addressCC' + idx).value = a.cc;
6627 SE.composeLayout.showHiddenAddress('cc', idx);
6631 document.getElementById('type' + idx).value = a.type;
6634 // apply attachment values
6635 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6637 setTimeout("callbackReplyForward.finish(globalA);", 500);
6640 handleReplyForwardForDraft : function(o) {
6641 var a = JSON.parse(o.responseText);
6643 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6645 document.getElementById('email_id' + idx).value = a.uid;
6646 document.getElementById('emailSubject' + idx).value = a.name;
6647 document.getElementById('addressTO' + idx).value = a.to;
6650 document.getElementById('addressCC' + idx).value = a.cc;
6651 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6655 document.getElementById('addressBCC' + idx).value = a.bcc;
6656 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6661 document.getElementById('type' + idx).value = a.type;
6665 // apply attachment values
6666 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6668 setTimeout("callbackReplyForward.finish(globalA);", 500);
6673 handleSuccess : function(o) {
6674 document.getElementById(this.target).innerHTML = o.responseText;
6680 ieDeleteSuccess : function(o) {
6683 var ret = JSON.parse(o.responseText);
6685 SUGAR.email2.accounts.refreshInboundAccountTable();
6686 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6687 SUGAR.email2.accounts.rebuildFolderList();
6693 ieSaveSuccess : function(o) {
6694 document.getElementById('saveButton').disabled = false;
6695 var a = JSON.parse(o.responseText);
6698 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6699 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6701 resp = JSON.parse(o.responseText);
6702 SUGAR.email2.accounts.refreshInboundAccountTable();
6703 SUGAR.email2.accounts.refreshOuboundAccountTable();
6704 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6705 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6709 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6716 loadAttachments : function(o) {
6717 var result = JSON.parse(o.responseText);
6719 SUGAR.email2.composeLayout.loadAttachments(result);
6724 loadSignature : function(o) {
6725 var ret = JSON.parse(o.responseText);
6726 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6727 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6731 * Follow up to mark email read|unread|flagged
6733 markEmailCleanup : function(o) {
6734 var ret = JSON.parse(o.responseText);
6735 if (!ret['status']) {
6737 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6739 SUGAR.email2.contextMenus.markEmailCleanup();
6745 rebuildShowFolders : function(o) {
6746 var t = JSON.parse(o.responseText);
6747 var show = document.getElementById('ieAccountListShow');
6749 SUGAR.email2.util.emptySelectOptions(show);
6751 for(i=0; i<t.length; i++) { // iterate through assoc array
6752 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6753 opt.selected = t[i].selected;
6754 show.options.add(opt);
6757 SUGAR.email2.accounts.renderTree();
6761 saveListViewSortOrderPart2 : function() {
6762 // create the JSON string the func expects
6763 focusFolderPath = '[ "Home", "' + ieName + '"';
6765 var f = new String(focusFolder);
6766 var fEx = f.split('.');
6768 for(i=0; i<fEx.length; i++) {
6769 focusFolderPath += ', "' + fEx[i] +'"'
6772 focusFolderPath += ']';
6774 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6775 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6781 sendEmailCleanUp : function(o) {
6783 var ret = JSON.parse(o.responseText);
6785 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6786 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6787 } else if (o.responseText) {
6788 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6791 if (typeof(SE.grid) != 'undefined')
6792 SE.listView.refreshGrid();
6793 //Disabled while address book is disabled
6795 //If this call back was initiated by quick compose from a Detail View page, refresh the
6796 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6797 //close the shortcut bar menu
6798 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6799 if(action_sugar_grp1 == 'DetailView') {
6800 showSubPanel('history',null,true);
6801 } else if(action_sugar_grp1 == 'quickcreate') {
6802 closeEmailOverlay();
6808 ieSendSuccess : function(o) {
6810 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6815 settingsFolderRefresh : function(o) {
6816 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6817 var ret = JSON.parse(o.responseText);
6818 var user = document.getElementById('userFolders');
6820 SUGAR.email2.util.emptySelectOptions(user);
6822 for(i=0; i<ret.userFolders.length; i++) {
6823 var display = ret.userFolders[i].name;
6824 var value = ret.userFolders[i].id;
6825 var selected = (ret.userFolders[i].selected != "") ? true : false;
6826 var opt = new Option(display, value, selected);
6827 opt.selected = selected;
6828 user.options.add(opt);
6834 startRequest : function(callback, args, forceAbort) {
6835 if(this.currentRequestObject != null) {
6836 if(this.forceAbort == true) {
6837 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6840 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6844 requestInProgress : function() {
6845 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6850 updateFolderSubscriptions : function() {
6851 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6852 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6858 updateFrameFolder : function() {
6859 SUGAR.email2.folders.checkEmailAccounts();
6864 updateUserPrefs : function(o) {
6865 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6866 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6871 uploadAttachmentSuccessful : function(o) {
6873 document.getElementById('email_attachment').value = '';
6875 var ret = JSON.parse(o.responseText);
6876 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6877 var overall = document.getElementById('addedFiles' + idx);
6878 var index = overall.childNodes.length;
6880 "<div id='email_attachment_bucket" + idx + index + "'>" +
6882 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6883 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6884 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6886 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6887 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6889 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6891 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6894 overall.innerHTML += out;
6895 if(SUGAR.email2.util.isIe()) {
6896 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6900 SUGAR.email2.addFileDialog.hide();
6901 // focus attachments
6902 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6907 ///////////////////////////////////////////////////////////////////////////
6908 //// PER MODULE CALLBACK OBJECTS
6909 AjaxObject.accounts = {
6910 saveOutboundCleanup : function(o) {
6911 SUGAR.email2.accounts.refreshOuboundAccountTable();
6912 SUGAR.email2.accounts.outboundDialog.hide();
6913 var id = o.responseText;
6914 SUGAR.email2.accounts.newAddedOutboundId = id;
6916 saveDefaultOutboundCleanup: function(o){
6919 callbackEditOutbound : {
6920 success : function(o)
6922 var ret = JSON.parse(o.responseText);
6924 SUGAR.email2.accounts.showAddSmtp();
6927 document.getElementById("mail_id").value = ret.id;
6928 document.getElementById("type").value = ret.type;
6929 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6930 document.getElementById("mail_name").value = ret.name;
6931 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6932 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6933 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6934 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6935 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6936 SUGAR.email2.accounts.smtp_authenticate_field_display();
6937 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6939 if(ret.type == 'system-override') {
6940 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6941 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6944 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6945 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6947 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6950 failure : AjaxObject.handleFailure,
6951 timeout : AjaxObject.timeout,
6954 callbackDeleteOutbound : {
6955 success : function(o) {
6956 var ret = JSON.parse(o.responseText);
6959 if(confirm(ret.error_message))
6961 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6962 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6970 SUGAR.email2.accounts.refreshOuboundAccountTable();
6974 failure : AjaxObject.handleFailure,
6975 timeout : AjaxObject.timeout,
6979 callbackCheckMailProgress : {
6980 success : function(o) {
6981 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6982 SUGAR.email2.accounts.totalMsgCount = -1;
6985 //Check for server timeout / errors
6986 var ret = JSON.parse(o.responseText);
6989 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6991 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6992 SUGAR.email2.accounts.totalMsgCount = -1;
6993 //SUGAR.email2.folders.rebuildFolders();
6997 var currIeId = ret['ieid'];
7000 var serverCount = ret.count;
7002 if (ret['status'] == 'done') {
7003 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7004 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7008 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7009 //Go to next account
7010 currIeId = SUGAR.email2.accounts.ieIds[i+1];
7012 SUGAR.email2.accounts.totalMsgCount = -1;
7017 else if (ret.mbox && ret.totalcount && ret.count) {
7018 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7019 if (ret.count >= ret.totalcount) {
7022 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7023 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7026 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7027 SUGAR.email2.accounts.totalMsgCount = -1;
7032 SUGAR.email2.accounts.totalMsgCount = -1;
7034 SUGAR.email2.folders.rebuildFolders();
7035 SE.listView.refreshGrid();
7036 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7037 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7038 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7039 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7041 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7042 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7043 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7044 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7045 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7048 failure : AjaxObject.handleFailure,
7049 timeout : AjaxObject.timeout,
7054 ///////////////////////////////////////////////////////////////////////////////
7056 AjaxObject.composeLayout = {
7058 * Populates the record id
7060 saveDraftCleanup : function(o) {
7062 var ret = JSON.parse(o.responseText);
7064 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7065 else if (o.responseText)
7066 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7070 AjaxObject.composeLayout.callback = {
7072 success : AjaxObject.composeLayout.saveDraftCleanup,
7073 failure : AjaxObject.handleFailure,
7074 timeout : AjaxObject.timeout,
7079 AjaxObject.detailView = {
7081 * Pops-up a printable view of an email
7083 displayPrintable : function(o) {
7084 var ret = JSON.parse(o.responseText);
7085 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7086 // 2 below must be in global context
7088 meta['panelId'] = SUGAR.email2.util.getPanelId();
7089 email = ret.meta.email;
7090 if (typeof(email.cc) == 'undefined') {
7094 var out = displayTemplate.exec({
7095 'app_strings' : app_strings,
7099 'email' : meta.email
7102 // open popup window
7103 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7104 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7106 popup.document.write(out);
7107 popup.document.close();
7111 * Takes formatted response and creates a modal pop-over containing a title and content
7113 displayView : function(o) {
7114 var SED = SUGAR.email2.detailView;
7115 var ret = JSON.parse(o.responseText);
7117 if(!SED.viewDialog) {
7118 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7122 constraintoviewport: true,
7125 SED.viewDialog.renderEvent.subscribe(function() {
7126 var content = this.body.firstChild;
7127 var viewH = YAHOO.util.Dom.getViewportHeight();
7129 this.body.style.overflow = "auto";
7130 this.body.style.width = "800px";
7131 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7135 SED.viewDialog.setHeader(ret.title);
7136 SED.viewDialog.setBody(ret.html);
7137 SED.viewDialog.render();
7138 SED.viewDialog.show();
7142 * Generates a modal popup to populate with the contents of bean's full EditView
7144 showQuickCreateForm : function(o) {
7145 var SED = SUGAR.email2.detailView;
7146 var ret = JSON.parse(o.responseText);
7148 if(!SED.quickCreateDialog) {
7149 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7153 constraintoviewport: true,
7157 SED.quickCreateDialog.renderEvent.subscribe(function() {
7158 var viewH = YAHOO.util.Dom.getViewportHeight();
7160 for (var i in this.body.childNodes) {
7161 if (this.body.childNodes[i].clientHeight) {
7162 contH += this.body.childNodes[i].clientHeight;
7163 } else if (this.body.childNodes[i].offsetHeight) {
7164 contH += this.body.childNodes[i].offsetHeight;
7167 this.body.style.width = "800px";
7168 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7169 this.body.style.overflow = "auto";
7170 }, SED.quickCreateDialog);
7172 SED.quickCreateDialog.hideEvent.subscribe(function(){
7173 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7174 /*for(var qsField in qsFields){
7175 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7176 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7179 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7182 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7184 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7185 SED.quickCreateDialog.render();
7186 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7188 SED.quickCreateDialog.ieId = ret.ieId;
7189 SED.quickCreateDialog.uid = ret.uid;
7190 SED.quickCreateDialog.mbox = ret.mbox;
7191 SED.quickCreateDialog.qcmodule = ret.module;
7193 SED.quickCreateDialog.show();
7195 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7197 editForm.module.value = 'Emails';
7198 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7199 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7200 var instId = ret.module + count;
7201 SED.quickCreateEmailsToAdd = ret.emailAddress;
7202 SED.quickCreateEmailCallback = function(instId, tableId) {
7203 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7204 if (typeof(eaw) == "undefined")
7205 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7206 + instId + "','" + tableId + "');", 100);
7207 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7209 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7210 + instId + "','" + tableId + "');", 100);
7214 saveQuickCreateForm : function(o) {
7216 SUGAR.email2.detailView.quickCreateDialog.hide();
7217 validate['EditView'] = [ ];
7220 saveQuickCreateFormAndReply : function(o) {
7222 var ret = JSON.parse(o.responseText);
7223 SUGAR.email2.detailView.quickCreateDialog.hide();
7224 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7225 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7227 var emailID = ret.id;
7228 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7230 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7232 //Cean the validate cache to prevent errors on the next call
7233 validate['EditView'] = [ ];
7236 saveQuickCreateFormAndAddToAddressBook : function(o) {
7238 SUGAR.email2.detailView.quickCreateDialog.hide();
7239 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7240 validate['EditView'] = [ ];
7243 handleAssignmentDialogAssignAction : function() {
7246 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7248 var dist = 'direct';
7252 var found_teams = false;
7253 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7254 if(!found_teams && assign_user_id == '' )
7256 alert(warning_message);
7260 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7262 for(i=0; i<emailUids.length; i++) {
7264 uids += app_strings.LBL_EMAIL_DELIMITER;
7266 uids += emailUids[i];
7269 var row = SUGAR.email2.grid.getSelectedRows()[0];
7270 var data = SUGAR.email2.grid.getRecord(row).getData();
7271 var ieid = data.ieId;
7272 var mbox = data.mbox;
7273 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7274 SUGAR.email2.contextMenus.assignToDialogue.hide();
7275 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7279 handleAssignmentDialogDeleteAction : function() {
7280 // TO pass list of UIDS/emailIds
7281 var uids = SUGAR.email2.listView.getUidsFromSelection();
7282 var row = SUGAR.email2.grid.getSelections()[0];
7283 var ieid = row.data.ieId;
7284 var mbox = row.data.mbox;
7285 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7286 SUGAR.email2.contextMenus.assignmentDialog.hide();
7287 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7293 showEmailDetailView : function(o) {
7295 var SED = SUGAR.email2.detailView;
7296 var ret = JSON.parse(o.responseText);
7298 if(!SED.quickCreateDialog) {
7299 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7303 constraintoviewport: true,
7305 autofillheight: "body",
7308 SED.quickCreateDialog.renderEvent.subscribe(function() {
7309 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7311 for (var i in this.body.childNodes) {
7312 if (this.body.childNodes[i].offsetHeight)
7313 contH += this.body.childNodes[i].offsetHeight;
7315 this.body.style.overflow = "auto";
7316 this.body.style.width = "800px";
7317 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7319 }, SED.quickCreateDialog);
7321 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7322 SED.quickCreateDialog.setBody(ret.html);
7323 SED.quickCreateDialog.render();
7324 SUGAR.util.evalScript(ret.html);
7325 SED.quickCreateDialog.show();
7328 showAssignmentDialogWithData : function(o) {
7329 var SEC = SUGAR.email2.contextMenus;
7331 var ret = JSON.parse(o.responseText);
7332 if (!SEC.assignmentDialog) {
7333 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7336 constraintoviewport: true,
7339 SEC.assignmentDialog.setBody("");
7340 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7341 SEC.assignmentDialog.renderEvent.subscribe(function() {
7342 var iev = YAHOO.util.Dom.get("Distribute");
7344 this.body.style.width = "700px";
7346 }, SEC.assignmentDialog);
7347 SEC.assignmentDialog.render();
7349 SEC.assignmentDialog.setBody(ret);
7350 SEC.assignmentDialog.render();
7352 SEC.assignmentDialog.show();
7353 SUGAR.util.evalScript(ret);
7356 showImportForm : function(o) {
7357 var SED = SUGAR.email2.detailView;
7358 var ret = JSON.parse(o.responseText);
7360 document.getElementById('quickCreateContent').innerHTML = "";
7366 if(!SED.importDialog) {
7367 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7371 constraintoviewport: true,
7373 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7374 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7378 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7379 SED.importDialog.setBody("");
7380 SED.importDialog.hideEvent.subscribe(function(){
7381 for(var i in QSFieldsArray) {
7382 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7383 QSFieldsArray[i].destroy();
7384 delete QSFieldsArray[i];
7386 if (QSProcessedFieldsArray[i]) {
7387 QSProcessedFieldsArray[i] = false;
7391 SED.importDialog.renderEvent.subscribe(function() {
7392 var iev = YAHOO.util.Dom.get("ImportEditView");
7394 //this.body.style.height = (iev.clientHeight + 10) + "px";
7395 this.body.style.width = "600px";
7397 }, SED.importDialog);
7398 SED.importDialog.render();
7400 SED.importDialog.setBody(ret.html);
7401 SED.importDialog.ret = ret;
7402 SUGAR.util.evalScript(ret.html);
7403 SED.importDialog.render();
7405 SED.importDialog.show();
7406 SED.importDialog.focusFirstButton();
7408 getImportAction : function(ret) {
7409 if (!check_form('ImportEditView')) return false;
7410 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7411 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7415 var editView = document.getElementById('ImportEditView');
7416 if (editView.assigned_user_id != null) {
7417 get = get + "&user_id=" + editView.assigned_user_id.value
7418 //var user_id = editView.assigned_user_id.value;
7420 var parent_id = editView.parent_id.value;
7421 var parent_type = editView.parent_type.value;
7422 var row = SUGAR.email2.grid.getSelectedRows()[0];
7423 row = SUGAR.email2.grid.getRecord(row);
7424 var data = row.getData();
7425 var ieId = data.ieId;
7426 var mbox = data.mbox;
7427 var serverDelete = editView.serverDelete.checked;
7428 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7430 for(i=0; i<emailUids.length; i++) {
7432 uids += app_strings.LBL_EMAIL_DELIMITER;
7434 uids += emailUids[i];
7437 var action = 'importEmail&uid=';
7439 action = 'moveEmails';
7440 action = action + '&sourceFolder=' + ret['srcFolder'];
7441 action = action + '&sourceIeId=' + ret['srcIeId'];
7442 action = action + '&destinationFolder=' + ret['dstFolder'];
7443 action = action + '&destinationIeId=' + ret['dstIeId'];
7444 action = action + '&emailUids=';
7446 if (action.search(/importEmail/) != -1) {
7447 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7449 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7452 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7453 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7454 SUGAR.email2.detailView.importDialog.hide();
7455 document.getElementById('importDialogContent').innerHTML = "";
7458 showRelateForm : function(o) {
7459 var SED = SUGAR.email2.detailView;
7460 var ret = JSON.parse(o.responseText);
7461 document.getElementById('quickCreateContent').innerHTML = "";
7466 dialog_loaded = true;
7468 if(!SED.relateDialog) {
7469 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7474 constraintoviewport: true,
7476 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7477 if (!check_form('RelateEditView')) return false;
7479 var editView = document.getElementById('RelateEditView');
7480 var parent_id = editView.parent_id.value;
7481 var parent_type = editView.parent_type.value;
7482 var row = SUGAR.email2.grid.getSelectedRows()[0];
7483 row = SUGAR.email2.grid.getRecord(row);
7484 var ieId = row.getData().ieId;
7485 var mbox = row.getData().mbox;
7486 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7488 for(i=0; i<emailUids.length; i++) {
7490 uids += app_strings.LBL_EMAIL_DELIMITER;
7492 uids += emailUids[i];
7494 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7495 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7496 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7497 SED.relateDialog.hide();
7498 document.getElementById('relateDialogContent').innerHTML = "";
7503 SED.relateDialog.hideEvent.subscribe(function(){
7504 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7505 QSFieldsArray['ImportEditView_parent_name'].destroy();
7506 delete QSFieldsArray['ImportEditView_parent_name'];
7508 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7509 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7513 SED.relateDialog.renderEvent.subscribe(function() {
7514 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7516 for (var i in this.body.childNodes) {
7517 if (this.body.childNodes[i].clientHeight)
7518 contH += this.body.childNodes[i].clientHeight;
7520 }, SED.relateDialog);
7521 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7524 SED.relateDialog.setBody(ret.html);
7525 SED.relateDialog.render();
7526 SUGAR.util.evalScript(ret.html);
7527 SED.relateDialog.show();
7531 * DetailView callbacks
7533 AjaxObject.detailView.callback = {
7535 success : function(o) {
7537 var ret = JSON.parse(o.responseText);
7538 SUGAR.email2.detailView.consumeMetaDetail(ret);
7540 argument: [targetDiv],
7541 failure : AjaxObject.handleFailure,
7546 success : function(o) {
7548 var ret = JSON.parse(o.responseText);
7549 SUGAR.email2.detailView.consumeMetaPreview(ret);
7551 failure : AjaxObject.handleFailure,
7556 success : AjaxObject.detailView.displayPrintable,
7557 failure : AjaxObject.handleFailure,
7558 timeout : AjaxObject.timeout,
7562 success : AjaxObject.detailView.displayView,
7563 failure : AjaxObject.handleFailure,
7564 timeout : AjaxObject.timeout,
7573 AjaxObject.folders = {
7575 * check-mail post actions
7577 checkMailCleanup : function(o) {
7579 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7581 // refresh focus ListView
7582 SE.listView.refreshGrid();
7583 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7588 rebuildFolders : function(o) {
7591 var data = JSON.parse(o.responseText);
7593 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7594 SUGAR.email2.folders.setSugarFolders();
7597 AjaxObject.folders.callback = {
7599 success : AjaxObject.folders.checkMailCleanup,
7600 failure : AjaxObject.handleFailure,
7601 timeout : 600000, // 5 mins
7606 AjaxObject.rules = {
7607 loadRulesForSettings : function(o) {
7608 document.getElementById("rulesListCell").innerHTML = o.responseText;
7609 // assume we have the class we need
7610 SUGAR.routing.getStrings();
7611 SUGAR.routing.getDependentDropdowns();
7614 //// END PER MODULE CALLBACK OBJECTS
7615 ///////////////////////////////////////////////////////////////////////////
7619 success : AjaxObject.handleSuccess,
7620 failure : AjaxObject.handleFailure,
7621 timeout : AjaxObject.timeout,
7624 var callbackAccount = {
7625 success : AjaxObject.ieSaveSuccess,
7626 failure : AjaxObject.handleFailure,
7627 timeout : AjaxObject.timeout,
7630 var callbackAccountDelete = {
7631 success : AjaxObject.ieDeleteSuccess,
7632 failure : AjaxObject.handleFailure,
7633 timeout : AjaxObject.timeout,
7636 var callbackOutboundTest = {
7637 success : AjaxObject.ieSendSuccess,
7638 failure : AjaxObject.handleFailure,
7639 timeout : AjaxObject.timeout,
7645 var callbackTeamInfoForSettings = {
7646 success : function (o) {
7647 var data = JSON.parse(o.responseText);
7648 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7650 failure : AjaxObject.handleFailure,
7651 timeout : AjaxObject.timeout,
7656 var callbackStatusForImport = {
7657 success : function (o) {
7659 if (o.responseText != "") {
7660 var statusString = "";
7661 var data = JSON.parse(o.responseText);
7662 for(i=0; i<data.length; i++) {
7663 statusString = statusString + data[i] + '<br/>';
7665 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7667 SE.listView.refreshGrid();
7670 failure : AjaxObject.handleFailure,
7671 timeout : AjaxObject.timeout,
7675 var callbackComposeCache = {
7676 success : AjaxObject.composeCache,
7677 failure : AjaxObject.handleFailure,
7678 timeout : AjaxObject.timeout,
7681 var callbackDelete = {
7682 success : AjaxObject.handleDeleteReturn,
7683 failure : AjaxObject.handleFailure,
7684 timeout : AjaxObject.timeout,
7687 var callbackEmailDetailMultiple = {
7688 success : function(o) {
7690 var retMulti = JSON.parse(o.responseText);
7691 var ret = new Object();
7693 for(var i=0; i<retMulti.length; i++) {
7696 SUGAR.email2._setDetailCache(ret);
7697 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7700 failure : AjaxObject.handleFailure,
7704 var callbackListViewSortOrderChange = {
7705 success : AjaxObject.saveListViewSortOrderPart2,
7706 failure : AjaxObject.handleFailure,
7707 timeout : AjaxObject.timeout,
7709 argument : [ieId, ieName, focusFolder]
7711 var callbackEmptyTrash = {
7712 success : function(o) {
7714 AjaxObject.folderRenameCleanup;
7716 failure : AjaxObject.handleFailure,
7717 timeout : AjaxObject.timeout,
7720 var callbackClearCacheFiles = {
7721 success : function(o) {
7724 failure : AjaxObject.handleFailure,
7725 timeout : AjaxObject.timeout,
7728 var callbackFolderRename = {
7729 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7730 failure : AjaxObject.handleFailure,
7731 timeout : AjaxObject.timeout,
7734 var callbackFolderDelete = {
7735 success : function(o) {
7736 var ret = JSON.parse(o.responseText);
7738 if (ret.folder_id) {
7739 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7741 SUGAR.email2.tree.removeNode(node, true);
7742 } else if (ret.ieId && ret.mbox) {
7743 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7745 SUGAR.email2.tree.removeNode(node, true);
7748 //SUGAR.email2.folders.loadSettingFolder();
7751 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7754 failure : AjaxObject.handleFailure,
7755 timeout : AjaxObject.timeout,
7758 var callbackFolderSave = {
7759 success : function(o) {
7760 var ret = JSON.parse(o.responseText);
7762 switch(ret.action) {
7763 case 'newFolderSave':
7764 SUGAR.email2.folders.rebuildFolders();
7768 failure : AjaxObject.handleFailure,
7769 timeout : AjaxObject.timeout,
7772 var callbackFolderSubscriptions = {
7773 success : AjaxObject.updateFolderSubscriptions,
7774 failure : AjaxObject.handleFailure,
7775 timeout : AjaxObject.timeout,
7778 var callbackFolderUpdate = {
7779 success : AjaxObject.updateFrameFolder,
7780 failure : AjaxObject.handleFailure,
7781 timeout : AjaxObject.timeout,
7784 var callbackFolders = {
7785 success : AjaxObject.folders.rebuildFolders,
7786 //success : void(true),
7787 failure : AjaxObject.handleFailure,
7788 timeout : AjaxObject.timeout,
7791 var callbackFullSync = {
7792 success : AjaxObject.fullSyncCleanup,
7793 failure : AjaxObject.handleFailure,
7794 timeout : 9999999999999,
7797 var callbackGeneric = {
7798 success : function() {
7801 failure : AjaxObject.handleFailure,
7802 timeout : AjaxObject.timeout,
7805 var callbackIeAccountRetrieve = {
7806 success : function(o) {
7807 // return JSON encoding
7809 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7810 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7812 failure : AjaxObject.handleFailure,
7813 timeout : AjaxObject.timeout,
7816 var callbackImportOneEmail = {
7817 success : AjaxObject.detailView.showImportForm,
7818 failure : AjaxObject.handleFailure,
7819 timeout : AjaxObject.timeout,
7822 var callbackRelateEmail = {
7823 success : AjaxObject.detailView.showRelateForm,
7824 failure : AjaxObject.handleFailure,
7825 timeout : AjaxObject.timeout,
7828 var callbackEmailDetailView = {
7829 success : AjaxObject.detailView.showEmailDetailView,
7830 failure : AjaxObject.handleFailure,
7831 timeout : AjaxObject.timeout,
7834 var callbackAssignmentDialog = {
7835 success : AjaxObject.detailView.showAssignmentDialogWithData,
7836 failure : AjaxObject.handleFailure,
7837 timeout : AjaxObject.timeout,
7840 var callbackAssignmentAction = {
7841 success : function(o) {
7842 SE.listView.refreshGrid();
7844 if(o.responseText != '') {
7845 overlay('Assignment action result', o.responseText, 'alert');
7848 failure : AjaxObject.handleFailure,
7849 timeout : AjaxObject.timeout,
7852 var callbackMoveEmails = {
7853 success : function(o) {
7854 SE.listView.refreshGrid();
7856 if(o.responseText != '') {
7857 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7860 failure : AjaxObject.handleFailure,
7861 timeout : AjaxObject.timeout,
7864 var callbackLoadAttachments = {
7865 success : AjaxObject.loadAttachments,
7866 failure : AjaxObject.handleFailure,
7867 timeout : AjaxObject.timeout,
7870 var callbackLoadRules = {
7871 success : AjaxObject.rules.loadRulesForSettings,
7872 failure : AjaxObject.handleFailure,
7873 timeout : AjaxObject.timeout,
7876 var callbackLoadSignature = {
7877 success : AjaxObject.loadSignature,
7878 failure : AjaxObject.handleFailure,
7879 timeout : AjaxObject.timeout,
7882 var callbackDeleteSignature = {
7883 success : AjaxObject.handleDeleteSignature,
7884 failure : AjaxObject.handleFailure,
7885 timeout : AjaxObject.timeout,
7888 /*var callbackMoveEmails = {
7889 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7890 failure : AjaxObject.handleFailure,
7891 timeout : AjaxObject.timeout,
7894 var callbackOutboundSave = {
7895 success : AjaxObject.accounts.saveOutboundCleanup,
7896 failure : AjaxObject.handleFailure,
7897 timeout : AjaxObject.timeout,
7900 var callbackDefaultOutboundSave = {
7901 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7902 failure : AjaxObject.handleFailure,
7903 timeout : AjaxObject.timeout,
7906 var callbackQuickCreate = {
7907 success : AjaxObject.detailView.showQuickCreateForm,
7908 failure : AjaxObject.handleFailure,
7909 timeout : AjaxObject.timeout,
7912 var callbackQuickCreateSave = {
7913 success : AjaxObject.detailView.saveQuickCreateForm,
7914 failure : AjaxObject.handleFailure,
7915 timeout : AjaxObject.timeout,
7918 var callbackQuickCreateSaveAndAddToAddressBook = {
7919 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7920 failure : AjaxObject.handleFailure,
7921 timeout : AjaxObject.timeout,
7924 var callbackQuickCreateSaveAndReply = {
7925 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7926 failure : AjaxObject.handleFailure,
7927 timeout : AjaxObject.timeout,
7930 var callbackQuickCreateSaveAndReplyCase = {
7931 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7932 failure : AjaxObject.handleFailure,
7933 timeout : AjaxObject.timeout,
7936 var callbackRebuildShowAccountList = {
7937 success : AjaxObject.rebuildShowFolders,
7938 failure : AjaxObject.handleFailure,
7939 timeout : AjaxObject.timeout,
7943 var callbackRefreshSugarFolders = {
7944 success : function(o) {
7945 var t = JSON.parse(o.responseText);
7946 SUGAR.email2.folders.setSugarFoldersEnd(t);
7948 failure : AjaxObject.handleFailure,
7949 timeout : AjaxObject.timeout,
7952 var callbackReplyForward = {
7953 success : AjaxObject.handleReplyForward,
7954 finish : function(a, retryCount) {
7955 if (typeof(retryCount) == 'undefined') {
7960 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7961 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7963 var html = t.getContent();
7965 if (a.type != 'draft') {
7966 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7967 html += " <div><hr></div>" + a.description;
7969 html = " <div><hr></div>" + a.description + html;
7972 html = a.description;
7975 t.setContent(html);//
7978 if (retryCount < 5) {
7979 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7983 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7984 if (tabArray != null && tabArray.length > 0) {
7985 for (i = 0 ; i < tabArray.length ; i++) {
7986 var tabObject = tabArray[i];
7987 if (tabObject.get("id") == ("composeTab" + idx)) {
7988 var tabLabel = a.name;
7989 if (tabLabel != null && tabLabel.length > 25) {
7990 tabLabel = tabLabel.substring(0, 25) + "...";
7992 tabObject.get("labelEl").firstChild.data = tabLabel;
7998 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
7999 if (a.parent_name != null && a.parent_name != "") {
8000 document.getElementById('data_parent_name' + idx).value = a.parent_name;
8002 if (a.parent_type != null && a.parent_type != "") {
8003 document.getElementById('data_parent_type' + idx).value = a.parent_type;
8005 if (a.parent_id != null && a.parent_id != "") {
8006 document.getElementById('data_parent_id' + idx).value = a.parent_id;
8008 if (a.fromAccounts.status) {
8009 var addressFrom = document.getElementById('addressFrom' + idx);
8010 SUGAR.email2.util.emptySelectOptions(addressFrom);
8011 var fromAccountOpts = a.fromAccounts.data;
8012 for(i=0; i<fromAccountOpts.length; i++) {
8013 var key = fromAccountOpts[i].value;
8014 var display = fromAccountOpts[i].text;
8015 var opt = new Option(display, key);
8016 if (fromAccountOpts[i].selected) {
8017 opt.selected = true;
8019 addressFrom.options.add(opt);
8025 failure : AjaxObject.handleFailure,
8026 timeout : AjaxObject.timeout,
8028 argument : [sendType]
8030 var callbackSendEmail = {
8031 success : AjaxObject.sendEmailCleanUp,
8032 failure : AjaxObject.handleFailure,
8033 timeout : AjaxObject.timeout,
8036 var callbackSettings = {
8037 success : AjaxObject.updateUserPrefs,
8038 failure : AjaxObject.handleFailure,
8039 timeout : AjaxObject.timeout,
8042 var callbackSettingsFolderRefresh = {
8043 success : AjaxObject.settingsFolderRefresh,
8044 failure : AjaxObject.handleFailure,
8045 timeout : AjaxObject.timeout,
8048 var callbackLoadSettingFolder = {
8049 success : function(o) {
8050 AjaxObject.settingsFolderRefresh(o);
8051 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8053 failure : AjaxObject.handleFailure,
8054 timeout : AjaxObject.timeout,
8058 var callbackUploadAttachment = {
8059 success : AjaxObject.uploadAttachmentSuccessful,
8060 upload : AjaxObject.uploadAttachmentSuccessful,
8061 failure : AjaxObject.handleFailure,
8062 timeout : AjaxObject.timeout,
8065 var callbackUserPrefs = {
8066 success : function(o) {
8067 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8069 failure : AjaxObject.handleFailure,
8070 timeout : AjaxObject.timeout,
8074 var callbackContextmenus = {
8076 success : AjaxObject.markEmailCleanup,
8077 failure : AjaxObject.handleFailure,
8078 timeout : AjaxObject.timeout,
8083 var callbackCheckEmail2 = {
8084 success : function(o) {
8085 var ret = JSON.parse(o.responseText);
8086 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8090 failure : AjaxObject.handleFailure,
8091 timeout : AjaxObject.timeout,
8093 }// End of File modules/Emails/javascript/ajax.js
8095 /*********************************************************************************
8096 * SugarCRM Community Edition is a customer relationship management program developed by
8097 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8099 * This program is free software; you can redistribute it and/or modify it under
8100 * the terms of the GNU Affero General Public License version 3 as published by the
8101 * Free Software Foundation with the addition of the following permission added
8102 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8103 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8104 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8106 * This program is distributed in the hope that it will be useful, but WITHOUT
8107 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8108 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8111 * You should have received a copy of the GNU Affero General Public License along with
8112 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8113 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8116 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8117 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8119 * The interactive user interfaces in modified source and object code versions
8120 * of this program must display Appropriate Legal Notices, as required under
8121 * Section 5 of the GNU Affero General Public License version 3.
8123 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8124 * these Appropriate Legal Notices must retain the display of the "Powered by
8125 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8126 * technical reasons, the Appropriate Legal Notices must display the words
8127 * "Powered by SugarCRM".
8128 ********************************************************************************/
8130 function gridInit() {
8131 if(SUGAR.email2.grid) {
8132 SUGAR.email2.grid.destroy();
8138 var Ck = YAHOO.util.Cookie;
8139 var widths = [ 10, 10, 150, 250, 175, 125 ];
8141 if (Ck.get("EmailGridWidths")) {
8142 for (var i=0; i < widths.length; i++) {
8143 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8146 for (var i=0; i < widths.length; i++) {
8147 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8151 // changes "F" to an icon
8152 function flaggedIcon(cell, record, column, value) {
8154 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8157 // changes "A" to replied icon
8158 function repliedIcon(cell, record, column, value) {
8160 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8163 function attachIcon(cell, record, column, value) {
8165 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8172 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8177 formatter: attachIcon,
8181 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8186 formatter: flaggedIcon,
8190 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8195 formatter: repliedIcon,
8199 label: app_strings.LBL_EMAIL_FROM,
8206 label: app_strings.LBL_EMAIL_SUBJECT,
8213 label: mod_strings.LBL_LIST_DATE,
8220 label: app_strings.LBL_EMAIL_TO,
8256 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8257 responseType: YAHOO.util.DataSource.TYPE_JSON,
8259 resultsList: 'Email',
8260 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8261 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8267 action : "EmailUIAjax",
8268 emailUIAction : "getMessageList",
8271 forceRefresh : "false"
8273 if(lazyLoadFolder != null) {
8274 params['mbox'] = lazyLoadFolder.folder;
8275 params['ieId'] = lazyLoadFolder.ieId;
8276 //Check if the folder is a Sugar Folder
8277 var test = new String(lazyLoadFolder.folder);
8278 if(test.match(/SUGAR\./)) {
8279 params['emailUIAction'] = 'getMessageListSugarFolders';
8280 params['mbox'] = test.substr(6);
8283 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8286 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8287 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8289 paginator: new YAHOO.widget.Paginator({
8290 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8291 containers : ["dt-pag-nav"],
8292 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8293 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8294 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8295 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8296 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8298 initialRequest:SUGAR.util.paramsToUrl(params),
8305 //Override Paging request construction
8306 grid.set("generateRequest", function(oState, oSelf) {
8307 oState = oState || {pagination:null, sortedBy:null};
8308 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8309 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8310 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8311 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8312 // Build the request
8314 SUGAR.util.paramsToUrl(oSelf.params) +
8317 "&start=" + startIndex +
8318 ((results !== null) ? "&limit=" + results : "");
8323 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8324 oPayload = oPayload || { };
8326 oPayload.totalRecords = oResponse.meta.total;
8327 oPayload.unreadRecords = oResponse.meta.unread;
8329 var tabObject = SE.innerLayout.get("tabs")[0];
8331 if (this.params.mbox != null) {
8332 mboxTitle = this.params.mbox;
8334 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8335 tabObject.get("labelEl").firstChild.data = tabtext;
8338 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8340 node.data.unseen = oResponse.meta.unread;
8341 SE.accounts.renderTree();
8347 var resize = grid.resizeGrid = function () {
8348 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8349 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8351 grid.convertDDRows = function() {
8352 var rowEl = this.getFirstTrEl();
8353 while (rowEl != null) {
8354 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8355 rowEl = this.getNextTrEl(rowEl);
8360 grid.on("columnResizeEvent", function(o) {
8361 //Find the index of the column
8362 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8363 for (var i=0; i < colSet.length; i++) {
8364 if (o.column == colSet[i]) {
8365 //Store it in the cookie
8366 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8369 //this.resizeGrid();
8372 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8373 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8374 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8376 SUGAR.email2.listViewLayout.on("render", resize);
8379 //Setup the default load parameters
8380 SUGAR.email2.grid.params = params;
8382 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8383 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8384 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8391 function initRowDD() {
8392 var sg = SUGAR.email2.grid,
8393 Dom = YAHOO.util.Dom;
8394 sg.DDRow = function(oDataTable, oRecord, elTr) {
8395 if(oDataTable && oRecord && elTr) {
8396 this.ddtable = oDataTable;
8397 this.table = oDataTable.getTableEl();
8400 this.newIndex = null;
8402 this.initFrame(); // Needed for DDProxy
8403 this.invalidHandleTypes = {};
8407 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8408 _resizeProxy: function() {
8409 this.constructor.superclass._resizeProxy.apply(this, arguments);
8410 var dragEl = this.getDragEl(),
8412 var xy = Dom.getXY(el);
8414 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8415 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8416 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8417 Dom.setStyle(dragEl, 'display', "");
8420 startDrag: function(x, y) {
8421 //Check if we should be dragging a set of rows rather than just the one.
8422 var selectedRows = this.ddtable.getSelectedRows();
8423 var iSelected = false;
8424 for (var i in selectedRows) {
8425 if (this.rowEl.id == selectedRows[i]) {
8432 for (var i in selectedRows) {
8433 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8436 this.rows = [this.row];
8437 this.ddtable.unselectAllRows();
8438 this.ddtable.selectRow(this.row);
8441 //Initialize the dragable proxy
8442 var dragEl = this.getDragEl();
8443 var clickEl = this.getEl();
8444 Dom.setStyle(clickEl, "opacity", "0.25");
8445 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8446 Dom.addClass(dragEl, "yui-dt-liner");
8447 Dom.setStyle(dragEl, "opacity", "0.5");
8448 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8449 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8450 Dom.setStyle(dragEl, "border", "2px solid gray");
8453 clickValidator: function(e) {
8454 if (this.row.getData()[0] == " ")
8456 var target = YAHOO.util.Event.getTarget(e);
8457 return ( this.isValidHandleChild(target) &&
8458 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8461 * This funciton checks that the target of the drag is a table row in this
8462 * DDGroup and simply moves the sourceEL to that location as a preview.
8464 onDragOver: function(ev, id) {
8465 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8466 if (node && node != this.targetNode) {
8467 this.targetNode = node;
8468 SUGAR.email2.folders.unhighliteAll();
8473 onDragOut: function(e, id) {
8474 if (this.targetNode) {
8475 SUGAR.email2.folders.unhighliteAll();
8476 this.targetNode = false;
8479 endDrag: function() {
8480 Dom.setStyle(this.getEl(), "opacity", "");
8481 Dom.setStyle(this.getDragEl(), "display", "none");
8482 if (this.targetNode) {
8483 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8485 SUGAR.email2.folders.unhighliteAll();
8491 function AddressSearchGridInit() {
8492 function moduleIcon(elCell, oRecord, oColumn, oData) {
8493 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8495 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8496 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8498 var checkHeader = '<input type="checkbox" ';
8499 if (SUGAR.email2.util.isIe()) {
8500 checkHeader += 'style="top:-5px" ';
8502 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8507 formatter: selectionCheckBox,
8511 label: mod_strings.LBL_LIST_TYPE,
8513 formatter: moduleIcon,
8517 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8523 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8529 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8530 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8532 resultsList: 'Person',
8533 fields: ['name', 'email', 'bean_id', 'bean_module'],
8534 metaFields: {total: 'TotalCount'}
8536 //enable sorting on the server accross all data
8539 dataModel.params = {
8542 action : "EmailUIAjax",
8543 emailUIAction:"getAddressSearchResults"
8545 var rb = document.getElementById('hasRelatedBean').checked;
8547 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8548 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8549 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8550 dataModel.params['related_bean_id'] = relatedBeanId;
8551 dataModel.params['related_bean_type'] = relatedBeanType;
8552 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8554 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8556 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8557 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8559 paginator: new YAHOO.widget.Paginator({
8561 containers : ["dt-pag-nav-addressbook"],
8562 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8563 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8564 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8565 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8566 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8568 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8572 //Override Paging request construction
8573 grid.set("generateRequest", function(oState, oSelf) {
8574 oState = oState || {pagination:null, sortedBy:null};
8575 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8576 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8577 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8578 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8579 // Build the request
8581 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8582 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8583 ((results !== null) ? "&limit=" + results : "");
8587 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8588 oPayload = oPayload || { };
8589 oPayload.totalRecords = oResponse.meta.total;
8593 grid.clickToggleSelect= function(args) {
8594 var isIE = (args.event.target == null);
8595 var targetElement = isIE ? args.event.srcElement : args.event.target;
8596 if(targetElement.type == null || targetElement.type != 'checkbox') {
8597 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8601 grid.reSelectRowsOnRender = function (){
8602 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8603 for (var i = 0; i < rows.length; i++)
8605 var emailAddress = rows[i].getData("email");
8606 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8609 rows[i].setData("selected", true);
8610 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8614 rows[i].setData("selected", false);
8615 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8619 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8620 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8621 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8622 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8625 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8626 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8628 grid.toggleSelectCheckbox = function(id,checked){
8629 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8630 row.setData("checked",checked);
8632 grid.toggleSelect = function(id, checked) {
8633 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8634 checked = row.getData("selected");
8637 SUGAR.email2.addressBook.grid.selectRow(row);
8638 SE.addressBook.insertContactRowToResultTable(id,null)
8641 SUGAR.email2.addressBook.grid.unselectRow(row);
8642 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8644 row.setData("selected", !checked);
8647 grid.toggleSelectAll = function(checked) {
8648 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8649 for (var i = 0; i < rows.length; i++) {
8650 if (typeof(rows[i]) != "undefined")
8651 rows[i].setData("checked", checked);
8653 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8654 for (var i = 0; i < checkBoxes.length; i++) {
8655 checkBoxes[i].checked = checked;
8659 //Initialize the grid result table.
8660 AddressSearchResultsGridInit();
8666 * Initalize the results table for the address book selection.
8669 function AddressSearchResultsGridInit()
8672 /* Full name sort funciton to compare by last name if available */
8673 var fullNameSort = function(a, b, desc) {
8674 // Deal with empty values
8675 if(!YAHOO.lang.isValue(a))
8676 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8677 else if(!YAHOO.lang.isValue(b))
8680 var aNames = a.getData("name").split(' ');
8681 var bNames = b.getData("name").split(' ');
8683 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8684 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8686 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8690 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8691 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8692 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8694 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})},
8695 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8697 var myDataSource = new YAHOO.util.DataSource([]);
8698 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8699 myDataSource.responseSchema = {
8700 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8703 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8704 width: "350px",height: "250px", MSG_EMPTY: " "});
8706 var highlightEditableCell = function(oArgs) {
8707 var elCell = oArgs.target;
8708 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8709 this.highlightCell(elCell);
8713 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8714 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8715 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8716 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8717 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8719 //Setup the context menus
8720 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8721 var task = p_aArgs[1];
8724 var elRow = this.contextEventTarget;
8725 elRow = p_myDataTable.getTrEl(elRow);
8732 var oRecord = p_myDataTable.getRecord(elRow);
8733 p_myDataTable.deleteRow(elRow);
8734 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8739 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8740 {trigger:gridResults.getTbodyEl()});
8741 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8742 contextMenu.render("addrSearchResultGrid");
8743 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8745 // End of File modules/Emails/javascript/grid.js
8747 /*********************************************************************************
8748 * SugarCRM Community Edition is a customer relationship management program developed by
8749 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8751 * This program is free software; you can redistribute it and/or modify it under
8752 * the terms of the GNU Affero General Public License version 3 as published by the
8753 * Free Software Foundation with the addition of the following permission added
8754 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8755 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8756 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8758 * This program is distributed in the hope that it will be useful, but WITHOUT
8759 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8760 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8763 * You should have received a copy of the GNU Affero General Public License along with
8764 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8765 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8768 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8769 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8771 * The interactive user interfaces in modified source and object code versions
8772 * of this program must display Appropriate Legal Notices, as required under
8773 * Section 5 of the GNU Affero General Public License version 3.
8775 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8776 * these Appropriate Legal Notices must retain the display of the "Powered by
8777 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8778 * technical reasons, the Appropriate Legal Notices must display the words
8779 * "Powered by SugarCRM".
8780 ********************************************************************************/
8785 function complexLayoutInit() {
8786 var se = SUGAR.email2;
8787 var Dom = YAHOO.util.Dom;
8789 getInnerLayout : function(rows) {
8790 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8791 parent: se.complexLayout,
8797 scroll:false, // grid should autoScroll itself
8799 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8807 body: "<div id='listBottom' />"
8815 body: "<div id='listRight' />",
8816 titlebar: false //,header: "right"
8819 se.complexLayout.on("render", function(){
8820 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8821 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8822 SUGAR.email2.listViewLayout.set("height", height);
8823 SUGAR.email2.listViewLayout.render();
8825 se.listViewLayout.render();
8827 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8828 var rp = se.listViewLayout.resizePreview = function() {
8829 var pre = Dom.get("displayEmailFramePreview");
8831 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8832 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8835 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8836 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8837 se.e2Layout.setPreviewPanel(rows);
8838 se.previewLayout = se.listViewLayout;
8839 return se.listViewLayout;
8842 getInnerLayout2Rows : function() {
8843 return this.getInnerLayout(true);
8845 getInnerLayout2Columns : function() {
8846 return this.getInnerLayout(false);
8850 // initialize state manager, we will use cookies
8851 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8852 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8853 se.complexLayout = new YAHOO.widget.Layout("container", {
8856 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8857 width: Dom.getViewportWidth() - 40,
8861 body: "<div id='emailtabs'></div>"
8866 body: "<div id='lefttabs'></div>",
8876 header: Dom.get('footerLinks').innerHTML,
8883 se.complexLayout.render();
8884 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8885 tp.addTab(new YAHOO.widget.Tab({
8888 content : "<div id='listViewDiv'/>",
8892 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8893 tp.appendTo(centerEl);
8895 tp.get("element").style.borderRight = "1px solid #666"
8897 var listV = this.getInnerLayout2Rows();
8898 listV.set("height", tp.get("element").clientHeight - 25);
8901 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8902 var folderTab = new YAHOO.widget.Tab({
8903 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8905 content : "<div id='emailtree'/>",
8909 folderTab.on("activeChange", function(o){
8911 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8914 se.leftTabs.addTab(folderTab);
8916 var tabContent = SUGAR.util.getAndRemove("searchTab");
8917 var searchTab = new YAHOO.widget.Tab({
8918 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8920 content : tabContent.innerHTML,
8923 searchTab.on("activeChange", function(o){
8926 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8927 //Setup the calendars if needed
8928 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
8929 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
8931 //Initalize sqs object for assigned user name
8932 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
8934 //Attach event handler for when the relate module option is selected for the correct sqs object
8935 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8936 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8937 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
8938 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8940 //If enter key is pressed, perform search
8941 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8942 for(var i=0; i < addKeyPressFields.length;i++)
8944 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8945 if (e.keyCode == 13) {
8946 YAHOO.util.Event.stopEvent(e);
8947 SUGAR.email2.search.searchAdvanced();
8951 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
8953 //Clear parent values if selecting another parent type.
8954 YAHOO.util.Event.addListener('data_parent_type_search','change',
8956 document.getElementById('data_parent_id_search').value ='';
8957 document.getElementById('data_parent_name_search').value ='';
8962 se.leftTabs.addTab(searchTab);
8964 var resizeTabBody = function() {
8965 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8966 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8969 se.complexLayout.on("render", resizeTabBody);
8970 se.leftTabs.on("activeTabChange", resizeTabBody);
8971 //hack to allow left pane scroll bar to fully show
8972 var lefttabsDiv = document.getElementById('lefttabs');
8973 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8974 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8975 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8978 initSQSObject: function(formName,fieldName)
8980 var fullFieldName = formName + '_' + fieldName; //SQS Convention
8981 var resultName = fullFieldName + '_' + 'results';
8983 if (QSFieldsArray[fullFieldName] != null)
8985 QSFieldsArray[fullFieldName].destroy();
8986 delete QSFieldsArray[fullFieldName];
8988 if (QSProcessedFieldsArray[fullFieldName])
8989 QSProcessedFieldsArray[fullFieldName] = false;
8991 if( Dom.get(resultName) )
8993 var obj = document.getElementById(resultName);
8994 obj.parentNode.removeChild(obj);
8997 setPreviewPanel: function(rows) {
8999 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9000 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9001 Dom.get("listRight").innerHTML = "";
9002 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9004 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9005 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9006 Dom.get("listBottom").innerHTML = "";
9007 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9014 var myBufferedListenerObject = new Object();
9015 myBufferedListenerObject.refit = function() {
9016 if(SUGAR.email2.grid) {
9017 SUGAR.email2.grid.autoSize();
9020 // End of File modules/Emails/javascript/complexLayout.js
9022 /*********************************************************************************
9023 * SugarCRM Community Edition is a customer relationship management program developed by
9024 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9026 * This program is free software; you can redistribute it and/or modify it under
9027 * the terms of the GNU Affero General Public License version 3 as published by the
9028 * Free Software Foundation with the addition of the following permission added
9029 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9030 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9031 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9033 * This program is distributed in the hope that it will be useful, but WITHOUT
9034 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9035 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9038 * You should have received a copy of the GNU Affero General Public License along with
9039 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9040 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9043 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9044 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9046 * The interactive user interfaces in modified source and object code versions
9047 * of this program must display Appropriate Legal Notices, as required under
9048 * Section 5 of the GNU Affero General Public License version 3.
9050 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9051 * these Appropriate Legal Notices must retain the display of the "Powered by
9052 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9053 * technical reasons, the Appropriate Legal Notices must display the words
9054 * "Powered by SugarCRM".
9055 ********************************************************************************/
9058 /******************************************************************************
9059 * Initialize Email 2.0 Application
9062 //Override Sugar Languge so quick creates work properly
9065 function email2init() {
9068 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9069 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9070 if (!SUGAR.util.isTouchScreen()) {
9072 convert_urls : false,
9073 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9074 width: tinyConfig.width,
9075 theme: tinyConfig.theme,
9076 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9077 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9078 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9079 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9080 plugins : tinyConfig.plugins,
9081 elements : tinyConfig.elements,
9082 language : tinyConfig.language,
9083 extended_valid_elements : tinyConfig.extended_valid_elements,
9084 mode: tinyConfig.mode,
9085 strict_loading_mode : true,
9086 force_br_newlines : true,
9087 forced_root_block : '',
9088 directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
9092 // initialze message overlay
9093 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9103 if (SUGAR.themes.tempHideLeftCol)
9104 SUGAR.themes.tempHideLeftCol();
9106 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9107 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9109 // set defaults for YAHOO.util.DragDropManager
9110 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9112 SUGAR.email2.nextYear = new Date();
9113 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9116 // initialize and display UI framework (complexLayout.js)
9117 complexLayoutInit();
9119 // initialize and display grid (grid.js)
9122 // initialize treeview for folders
9124 SUGAR.email2.folders.rebuildFolders(true);
9127 //Setup the Message Box overlay
9128 /*Ext.MessageBox.maxWidth = 350;
9129 Ext.MessageBox.minProgressWidth = 350;
9131 ///////////////////////////////////////////////////////////////////////////
9134 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9136 var SEC = SUGAR.email2.contextMenus;
9139 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9140 trigger: SUGAR.email2.grid.get("element"),
9143 emailMenu.subscribe("beforeShow", function() {
9144 var oTarget = this.contextEventTarget;
9145 if (typeof(oTarget) == "undefined")
9147 var grid = SUGAR.email2.grid;
9148 var selectedRows = grid.getSelectedRows();
9149 var multipleSelected = (selectedRows.length > 1) ? true: false;
9150 if (!multipleSelected)
9152 grid.unselectAllRows();
9153 grid.selectRow(oTarget);
9154 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9156 else if(multipleSelected)
9158 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9162 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9163 //us to access individual elements easier by name rather than by index
9164 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
9165 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9166 emailMenu.addItems([
9168 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9169 id: 'showDetailView',
9170 onclick: { fn: SEC.showDetailView }
9173 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9174 onclick: { fn: SEC.openMultiple }
9177 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9178 onclick: { fn: SEC.archiveToSugar }
9181 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9183 onclick: { fn: SEC.replyForwardEmailContext }
9186 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9188 onclick: { fn: SEC.replyForwardEmailContext }
9191 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9193 onclick: { fn: SEC.replyForwardEmailContext }
9196 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9198 onclick: { fn: SEC.markDeleted }
9201 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9203 onclick: { fn: SEC.viewPrintable }
9207 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9209 id: "markEmailMenu",
9212 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9213 onclick: { fn: SEC.markUnread }
9216 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9217 onclick: { fn: SEC.markRead }
9220 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9221 onclick: { fn: SEC.markFlagged }
9224 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9225 onclick: { fn: SEC.markUnflagged }
9231 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9233 onclick: { fn: SEC.assignEmailsTo }
9236 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9238 onclick: { fn: SEC.relateTo }
9241 SEC.emailListContextMenu.render();
9243 //Handle the Tree folder menu trigger ourselves
9244 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9248 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9252 SEC.frameFoldersContextMenu.addItems([
9253 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9254 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9255 onclick: { fn: function() {
9256 var node = SUGAR.email2.clickedFolderNode;
9257 if (node.data.ieId) {
9258 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9261 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9262 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9263 onclick: { fn: function() {
9264 var node = SUGAR.email2.clickedFolderNode;
9265 if (node.data.ieId) {
9266 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9270 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9271 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9272 onclick: { fn: SUGAR.email2.folders.folderAdd }
9275 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9276 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9277 onclick: { fn: SUGAR.email2.folders.folderDelete }
9280 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9281 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9282 onclick: { fn: SUGAR.email2.folders.folderRename }
9285 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9286 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9287 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9290 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9291 onclick: { fn: function() {
9292 var node = SUGAR.email2.clickedFolderNode;
9293 if (node.data.ieId) {
9294 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9298 SEC.frameFoldersContextMenu.render();
9300 SEC.initContactsMenu = function() {
9302 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9303 trigger: "contacts",
9306 SEC.contactsContextMenu.addItems([
9308 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9309 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9312 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9313 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9316 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9317 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9318 if (oTarget && !grid.isSelected(oTarget)) {
9319 grid.unselectAllRows();
9320 grid.selectRow(oTarget);
9323 SEC.contactsContextMenu.render();
9327 // set auto-check timer
9328 SUGAR.email2.folders.startCheckTimer();
9329 // check if we're coming from an email-link click
9330 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9332 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9334 //Init fix for YUI 2.7.0 datatable sort.
9335 SUGAR.email2.addressBook.initFixForDatatableSort();
9338 function createTreePanel(treeData, params) {
9339 var tree = new YAHOO.widget.TreeView(params.id);
9340 var root = tree.getRoot();
9342 //if (treeData.nodes && treeData[0].id == "Home")
9343 // treeData = treeData[0];
9345 addChildNodes(root, treeData);
9350 function addChildNodes(parentNode, parentData) {
9351 var Ck = YAHOO.util.Cookie;
9352 var nextyear = SUGAR.email2.nextYear;
9353 var nodes = parentData.nodes || parentData.children;
9355 if (typeof(nodes[i]) == 'object') {
9356 if (nodes[i].data) {
9357 nodes[i].data.href = '#';
9358 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9359 node.action = nodes[i].data.action;
9361 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9362 addChildNodes(parentNode, nodes[i]);
9365 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9366 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9368 nodes[i].className = nodes[i].cls;
9370 nodes[i].href = "#";
9371 if (nodes[i].text) nodes[i].label = nodes[i].text;
9372 //Override YUI child node creation
9373 if (nodes[i].children) {
9374 nodes[i].nodes = nodes[i].children;
9375 nodes[i].children = [ ];
9377 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9380 if (typeof(nodes[i].nodes) == 'object') {
9381 addChildNodes(node, nodes[i]);
9388 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9390 function email2treeinit(tree, treedata, treediv, params) {
9391 //ensure the tree data is not corrupt
9395 if (SUGAR.email2.tree) {
9396 SUGAR.email2.tree.destroy();
9397 SUGAR.email2.tree = null;
9400 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9404 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9405 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9406 tree.subscribe("expandComplete", function(node){
9407 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9408 for (var i in node.children) {
9409 SE.accounts.setupDDTarget(node.children[i]);
9412 tree.setCollapseAnim("TVSlideOut");
9413 tree.setExpandAnim("TVSlideIn");
9414 var root = tree.root;
9415 while (root.hasChildren()) {
9416 var node = root.children[0];
9418 tree.removeNode(root.children[0], false);
9420 addChildNodes(root, treedata);
9422 SUGAR.email2.accounts.renderTree();
9425 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9426 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9430 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9431 startDrag: function(x, y) {
9432 var Dom = YAHOO.util.Dom;
9433 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9436 var dragEl = this.getDragEl();
9437 var clickEl = this.getEl();
9438 Dom.setStyle(clickEl, "color", "#AAA");
9439 Dom.setStyle(clickEl, "opacity", "0.25");
9440 dragEl.innerHTML = clickEl.innerHTML;
9442 Dom.addClass(dragEl, "ygtvcell");
9443 Dom.addClass(dragEl, "ygtvcontent");
9444 Dom.addClass(dragEl, "folderDragProxy");
9445 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9446 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9447 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9448 Dom.setStyle(dragEl, "opacity", "0.5");
9449 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9452 onDragOver: function(ev, id) {
9453 var Dom = YAHOO.util.Dom;
9454 if (id != this.dragId)
9456 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9457 if(node.data.cls != "sugarFolder") {
9458 SUGAR.email2.folders.unhighliteAll();
9462 this.targetNode = node;
9463 SUGAR.email2.folders.unhighliteAll();
9468 onDragOut: function(e, id) {
9469 if (this.targetNode) {
9470 SUGAR.email2.folders.unhighliteAll();
9471 this.targetNode = false;
9472 this.dragId = false;
9476 endDrag: function() {
9477 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9478 if (this.targetNode) {
9479 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9482 });// End of File modules/Emails/javascript/init.js
9484 /*********************************************************************************
9485 * SugarCRM Community Edition is a customer relationship management program developed by
9486 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9488 * This program is free software; you can redistribute it and/or modify it under
9489 * the terms of the GNU Affero General Public License version 3 as published by the
9490 * Free Software Foundation with the addition of the following permission added
9491 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9492 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9493 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9495 * This program is distributed in the hope that it will be useful, but WITHOUT
9496 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9497 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9500 * You should have received a copy of the GNU Affero General Public License along with
9501 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9502 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9505 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9506 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9508 * The interactive user interfaces in modified source and object code versions
9509 * of this program must display Appropriate Legal Notices, as required under
9510 * Section 5 of the GNU Affero General Public License version 3.
9512 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9513 * these Appropriate Legal Notices must retain the display of the "Powered by
9514 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9515 * technical reasons, the Appropriate Legal Notices must display the words
9516 * "Powered by SugarCRM".
9517 ********************************************************************************/
9519 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9520 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9521 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9522 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9523 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9524 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9525 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9526 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9527 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9528 ' <input type="hidden" id="composeType" name="composeType">' +
9529 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9530 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9531 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9532 ' <input type="hidden" id="sendTo" name="sendTo">' +
9533 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9534 ' <input type="hidden" id="sendCc" name="sendCc">' +
9535 ' <input type="hidden" id="setEditor" name="setEditor">' +
9536 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9537 ' <input type="hidden" id="parent_id" name="parent_id">' +
9538 ' <input type="hidden" id="parent_type" name="parent_type">' +
9539 ' <input type="hidden" id="attachments" name="attachments">' +
9540 ' <input type="hidden" id="documents" name="documents">' +
9541 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9542 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9543 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9544 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9546 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9547 ' <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>' +
9548 ' <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>' +
9549 ' <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>' +
9550 ' <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>' +
9551 '</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>' +
9552 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9553 '<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>' +
9554 ' </td></tr></tbody></table></th>' +
9558 ' <div style="margin:5px;">' +
9559 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9561 ' <td class="emailUILabel" NOWRAP >' +
9562 ' {app_strings.LBL_EMAIL_FROM}:' +
9564 ' <td class="emailUIField" NOWRAP>' +
9566 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9571 ' <td class="emailUILabel" NOWRAP>' +
9572 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9573 ' {app_strings.LBL_EMAIL_TO}:' +
9576 ' <td class="emailUIField" NOWRAP>' +
9577 ' <div class="ac_autocomplete">' +
9578 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9579 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9580 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9584 ' <tr id="add_addr_options_tr{idx}">' +
9585 ' <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>'+
9587 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9588 ' <td class="emailUILabel" NOWRAP>' +
9589 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9590 ' {app_strings.LBL_EMAIL_CC}:' +
9593 ' <td class="emailUIField" NOWRAP>' +
9594 ' <div class="ac_autocomplete">' +
9595 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9596 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9597 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9601 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9602 ' <td class="emailUILabel" NOWRAP>' +
9603 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9604 ' {app_strings.LBL_EMAIL_BCC}:' +
9607 ' <td class="emailUIField" NOWRAP>' +
9608 ' <div class="ac_autocomplete">' +
9609 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9610 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9611 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9616 ' <td class="emailUILabel" NOWRAP width="1%">' +
9617 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9619 ' <td class="emailUIField" NOWRAP width="99%">' +
9620 ' <div class="ac_autocomplete">' +
9621 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9630 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9631 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9632 ' <div style="padding:5px;">' +
9633 ' <table cellpadding="2" cellspacing="0" border="0">' +
9636 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9643 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9644 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9656 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9663 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9664 ' <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>' +
9676 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9683 ' <div id="addedTemplateAttachments{idx}"></div>' +
9690 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9691 ' <div style="padding:5px;">' +
9692 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9693 ' <table border="0" width="100%">' +
9695 ' <td NOWRAP style="padding:2px;">' +
9696 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9700 ' <td NOWRAP style="padding:2px;">' +
9701 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9706 ' <table border="0" width="100%">' +
9708 ' <td NOWRAP style="padding:2px;">' +
9709 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9713 ' <td NOWRAP style="padding:2px;">' +
9714 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9718 ' <table border="0" width="100%">' +
9720 ' <td NOWRAP style="padding:2px;">' +
9721 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9722 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9730 // End of File modules/Emails/javascript/composeEmailTemplate.js
9732 /*********************************************************************************
9733 * SugarCRM Community Edition is a customer relationship management program developed by
9734 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9736 * This program is free software; you can redistribute it and/or modify it under
9737 * the terms of the GNU Affero General Public License version 3 as published by the
9738 * Free Software Foundation with the addition of the following permission added
9739 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9740 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9741 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9743 * This program is distributed in the hope that it will be useful, but WITHOUT
9744 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9745 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9748 * You should have received a copy of the GNU Affero General Public License along with
9749 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9750 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9753 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9754 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9756 * The interactive user interfaces in modified source and object code versions
9757 * of this program must display Appropriate Legal Notices, as required under
9758 * Section 5 of the GNU Affero General Public License version 3.
9760 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9761 * these Appropriate Legal Notices must retain the display of the "Powered by
9762 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9763 * technical reasons, the Appropriate Legal Notices must display the words
9764 * "Powered by SugarCRM".
9765 ********************************************************************************/
9767 SUGAR.email2.templates['displayOneEmail'] =
9768 '<div class="emailDetailTable" style="height:100%">' +
9769 '<div id="viewMenuDiv{idx}"></div>' +
9770 '<div width="100%" class="displayEmailValue">' +
9771 ' <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>' +
9772 ' <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>' +
9773 ' <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>' +
9774 ' <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>' +
9775 ' <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>' +
9776 ' <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>' +
9777 ' <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>' +
9778 ' <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>' +
9779 ' <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>' +
9781 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9783 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9784 ' {app_strings.LBL_EMAIL_FROM}:' +
9786 ' <td width="99%" class="displayEmailValue">' +
9787 ' {email.from_addr}' +
9791 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9792 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9794 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9795 ' <b>{email.name}</b>' +
9799 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9800 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9802 ' <td class="displayEmailValue">' +
9803 ' {email.date_start} {email.time_start}' +
9807 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9808 ' {app_strings.LBL_EMAIL_TO}:' +
9810 ' <td class="displayEmailValue">' +
9811 ' {email.toaddrs}' +
9814 ' <tr>{meta.cc}</tr>' +
9815 ' <tr>{email.attachments}</tr>' +
9817 ' <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>' +
9818 //' {email.description}' +
9820 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9822 /*********************************************************************************
9823 * SugarCRM Community Edition is a customer relationship management program developed by
9824 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9826 * This program is free software; you can redistribute it and/or modify it under
9827 * the terms of the GNU Affero General Public License version 3 as published by the
9828 * Free Software Foundation with the addition of the following permission added
9829 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9830 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9831 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9833 * This program is distributed in the hope that it will be useful, but WITHOUT
9834 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9835 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9838 * You should have received a copy of the GNU Affero General Public License along with
9839 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9840 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9843 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9844 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9846 * The interactive user interfaces in modified source and object code versions
9847 * of this program must display Appropriate Legal Notices, as required under
9848 * Section 5 of the GNU Affero General Public License version 3.
9850 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9851 * these Appropriate Legal Notices must retain the display of the "Powered by
9852 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9853 * technical reasons, the Appropriate Legal Notices must display the words
9854 * "Powered by SugarCRM".
9855 ********************************************************************************/
9857 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9858 '<body onload="javascript:window.print();">' +
9862 ' font-family: helvetica, impact, sans-serif;' +
9863 ' font-size : 12pt;' +
9870 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9873 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9875 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9876 ' {app_strings.LBL_EMAIL_FROM}:' +
9878 ' <td width="99%" class="displayEmailValue">' +
9879 ' {email.from_name} <{email.from_addr}>' +
9883 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9884 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9886 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9887 ' <b>{email.name}</b>' +
9891 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9892 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9894 ' <td class="displayEmailValue">' +
9895 ' {email.date_start} {email.time_start}' +
9899 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9900 ' {app_strings.LBL_EMAIL_TO}:' +
9902 ' <td class="displayEmailValue">' +
9903 ' {email.toaddrs}' +
9907 ' {email.attachments}' +
9913 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9915 ' <td style="border-top: 1px solid #333;">' +
9916 ' <div style="padding:5px;">' +
9917 '{email.description}' +
9927 // End of File modules/Emails/javascript/viewPrintable.js
9929 /*********************************************************************************
9930 * SugarCRM Community Edition is a customer relationship management program developed by
9931 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9933 * This program is free software; you can redistribute it and/or modify it under
9934 * the terms of the GNU Affero General Public License version 3 as published by the
9935 * Free Software Foundation with the addition of the following permission added
9936 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9937 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9938 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9940 * This program is distributed in the hope that it will be useful, but WITHOUT
9941 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9942 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9945 * You should have received a copy of the GNU Affero General Public License along with
9946 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9947 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9950 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9951 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9953 * The interactive user interfaces in modified source and object code versions
9954 * of this program must display Appropriate Legal Notices, as required under
9955 * Section 5 of the GNU Affero General Public License version 3.
9957 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9958 * these Appropriate Legal Notices must retain the display of the "Powered by
9959 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9960 * technical reasons, the Appropriate Legal Notices must display the words
9961 * "Powered by SugarCRM".
9962 ********************************************************************************/
9963 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9964 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;}
9965 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');}
9966 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;}}
9967 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9968 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9969 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}
9970 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="";}}
9971 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
9972 {search.clearFields=function(){};search.setFields=function(data,filter)
9973 {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])
9974 {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';}}}}
9975 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))
9976 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
9977 {if(this.inputElement.id=='shipping_account_name')
9978 {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)/;}
9979 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
9980 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9981 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];}}}
9982 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]];}
9983 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;}}}}});}
9984 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9985 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js