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)};this.EmailAddressValidation(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},EmailAddressValidation:function(ev,fn,r,stR){YAHOO.util.Event.onContentReady(fn,function(){addToValidate(ev,fn,'email',r,stR);});},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
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.indexOf('DCQuickCreate')>0){DCMenu.save(theForm.id);}else if(this.emailView.indexOf('QuickCreate')>=0){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value+'_subpanel_save_button');}}}};emailAddressWidgetLoaded=true;})();
226 // End of File include/SugarEmailAddress/SugarEmailAddress.js
228 /*********************************************************************************
229 * SugarCRM Community Edition is a customer relationship management program developed by
230 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
232 * This program is free software; you can redistribute it and/or modify it under
233 * the terms of the GNU Affero General Public License version 3 as published by the
234 * Free Software Foundation with the addition of the following permission added
235 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
236 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
237 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
239 * This program is distributed in the hope that it will be useful, but WITHOUT
240 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
241 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
244 * You should have received a copy of the GNU Affero General Public License along with
245 * this program; if not, see http://www.gnu.org/licenses or write to the Free
246 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
249 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
250 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
252 * The interactive user interfaces in modified source and object code versions
253 * of this program must display Appropriate Legal Notices, as required under
254 * Section 5 of the GNU Affero General Public License version 3.
256 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
257 * these Appropriate Legal Notices must retain the display of the "Powered by
258 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
259 * technical reasons, the Appropriate Legal Notices must display the words
260 * "Powered by SugarCRM".
261 ********************************************************************************/
262 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)
263 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_","_")]);}
264 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
265 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;}
266 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();}
267 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';}
268 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='';}
269 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){var clone_id=this.form+'_'+this.field+'_collection_0';YAHOO.util.Event.onContentReady(clone_id,function(c){c.create_clone();enableQS();c.changePrimary(true);for(key in c.secondaries_values){if(isInteger(key)){c.add(c.secondaries_values[key]);}}
270 c.js_more();initEditView(document.forms[c.form]);},this);},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;var Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
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);var new_id=currentNode.id.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
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_id;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_id.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_id;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_id;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_id;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
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!='undefined'&&typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
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!='undefined'&&typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
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_element_name+"_collection_"+i);var id_field=document.getElementById("id_"+this.field_element_name+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].name==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
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=='';}
294 return false;}};SUGAR.collection.safe_clone=function(e,recursive)
295 {if(e.nodeName=="#text")
296 {return document.createTextNode(e.data);}
297 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];if(SUGAR.isIE7&&e.tagName.toLowerCase()=='input')
298 {var properties=['class','style','name','type','valign','border','width','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}else{var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}
299 for(var i in properties)
300 {if(e[properties[i]])
301 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
302 newNode[properties[i]]=e[properties[i]];}}
304 {for(var i in e.childNodes)
305 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
306 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
308 // End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
310 /*********************************************************************************
311 * SugarCRM Community Edition is a customer relationship management program developed by
312 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
314 * This program is free software; you can redistribute it and/or modify it under
315 * the terms of the GNU Affero General Public License version 3 as published by the
316 * Free Software Foundation with the addition of the following permission added
317 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
318 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
319 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
321 * This program is distributed in the hope that it will be useful, but WITHOUT
322 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
323 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
326 * You should have received a copy of the GNU Affero General Public License along with
327 * this program; if not, see http://www.gnu.org/licenses or write to the Free
328 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
331 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
332 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
334 * The interactive user interfaces in modified source and object code versions
335 * of this program must display Appropriate Legal Notices, as required under
336 * Section 5 of the GNU Affero General Public License version 3.
338 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
339 * these Appropriate Legal Notices must retain the display of the "Powered by
340 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
341 * technical reasons, the Appropriate Legal Notices must display the words
342 * "Powered by SugarCRM".
343 ********************************************************************************/
344 SUGAR.inboundEmail={};Rot13={map:null,convert:function(a){Rot13.init();var s="";for(i=0;i<a.length;i++){var b=a.charAt(i);s+=((b>='A'&&b<='Z')||(b>='a'&&b<='z')?Rot13.map[b]:b);}
345 return s;},init:function(){if(Rot13.map!=null)
346 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
347 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
348 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
349 function getEncryptedPassword(login,password,mailbox){var words=new Array(login,password,mailbox);for(i=0;i<3;i++){word=words[i];if(word.indexOf('&')>0){fragment1=word.substr(0,word.indexOf('&'));fragment2=word.substr(word.indexOf('&')+1,word.length);newWord=fragment1+'::amp::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
350 if(word.indexOf('+')>0){fragment1=word.substr(0,word.indexOf('+'));fragment2=word.substr(word.indexOf('+')+1,word.length);newWord=fragment1+'::plus::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
351 if(word.indexOf('%')>0){fragment1=word.substr(0,word.indexOf('%'));fragment2=word.substr(word.indexOf('%')+1,word.length);newWord=fragment1+'::percent::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}}
353 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName,ie_id)
354 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
355 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id:'';URL='index.php?'
356 +'module='+module_name
359 +'&target='+pageTarget
360 +'&target1='+pageTarget
361 +'&server_url='+mail_server
362 +'&email_user='+words[0]
363 +'&protocol='+protocol
365 +'&email_password='+words[1]
366 +'&mailbox='+words[2]
369 +'&personal='+isPersonal;var SI=SUGAR.inboundEmail;if(!SI.testDlg){SI.testDlg=new YAHOO.widget.SimpleDialog("testSettingsDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.testDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);if(this.evalJS)
370 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
371 this.body.style.width=w}}
372 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
373 title=SUGAR.language.get('InboundEmail','LBL_TEST_SETTINGS');SI.testDlg.setHeader(title);SI.testDlg.setBody(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.testDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.testDlg._updateContent,failure:SI.testDlg.hide,scope:SI.testDlg});SI.testDlg.show();}
374 function isDataValid(formName,validateMonitoredFolder){var formObject=document.getElementById(formName);var errors=new Array();var out=new String();if(trim(formObject.server_url.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_SERVER'));}
375 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
376 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
377 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
378 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
379 if(errors.length>0){out=SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_DESC');for(i=0;i<errors.length;i++){if(out!=""){out+="\n";}
381 alert(out);return false;}else{return true;}}
382 function getFoldersListForInboundAccount(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,searchFieldValue,formName){if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';URL='index.php?'
383 +'module='+module_name
386 +'&target='+pageTarget
387 +'&target1='+pageTarget
388 +'&server_url='+mail_server
389 +'&email_user='+words[0]
390 +'&protocol='+protocol
392 +'&email_password='+words[1]
393 +'&mailbox='+words[2]
395 +'&personal='+isPersonal
396 +'&searchField='+searchFieldValue;var SI=SUGAR.inboundEmail;if(!SI.listDlg){SI.listDlg=new YAHOO.widget.SimpleDialog("selectFoldersDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.listDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
397 this.body.style.width=w}}
398 SI.listDlg.setHeader(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.listDlg.setBody('');SI.listDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.listDlg._updateContent,failure:SI.listDlg.hide,scope:SI.listDlg});SI.listDlg.show();}
399 function setPortDefault(){var prot=document.getElementById('protocol');var ssl=document.getElementById('ssl');var port=document.getElementById('port');var stdPorts=new Array("110","143","993","995");var stdBool=new Boolean(false);if(port.value==''){stdBool.value=true;}else{for(i=0;i<stdPorts.length;i++){if(stdPorts[i]==port.value){stdBool.value=true;}}}
400 if(stdBool.value==true){if(prot.value=='imap'&&ssl.checked==false){port.value="143";}else if(prot.value=='imap'&&ssl.checked==true){port.value='993';}else if(prot.value=='pop3'&&ssl.checked==false){port.value='110';}else if(prot.value=='pop3'&&ssl.checked==true){port.value='995';}}}
401 function toggle_monitored_folder(field){var field1=document.getElementById('protocol');var mailbox=document.getElementById('mailbox');var label_inbox=document.getElementById('label_inbox');var subscribeFolderButton=document.getElementById('subscribeFolderButton');var trashFolderRow=document.getElementById('trashFolderRow');var trashFolderRow1=document.getElementById('trashFolderRow1');var sentFolderRow=document.getElementById('sentFolderRow');if(field1.value=='imap'){mailbox.disabled=false;try{mailbox.style.display='';trashFolderRow.style.display='';sentFolderRow.style.display='';trashFolderRow1.style.display='';subscribeFolderButton.style.display='';}catch(e){};label_inbox.style.display='';}
402 else{mailbox.value="INBOX";mailbox.disabled=false;try{mailbox.style.display="none";trashFolderRow.style.display="none";sentFolderRow.style.display="none";trashFolderRow1.style.display="none";subscribeFolderButton.style.display="none";}catch(e){};label_inbox.style.display="none";}}
403 // End of File modules/InboundEmail/InboundEmail.js
405 /*********************************************************************************
406 * SugarCRM Community Edition is a customer relationship management program developed by
407 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
409 * This program is free software; you can redistribute it and/or modify it under
410 * the terms of the GNU Affero General Public License version 3 as published by the
411 * Free Software Foundation with the addition of the following permission added
412 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
413 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
414 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
416 * This program is distributed in the hope that it will be useful, but WITHOUT
417 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
418 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
421 * You should have received a copy of the GNU Affero General Public License along with
422 * this program; if not, see http://www.gnu.org/licenses or write to the Free
423 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
426 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
427 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
429 * The interactive user interfaces in modified source and object code versions
430 * of this program must display Appropriate Legal Notices, as required under
431 * Section 5 of the GNU Affero General Public License version 3.
433 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
434 * these Appropriate Legal Notices must retain the display of the "Powered by
435 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
436 * technical reasons, the Appropriate Legal Notices must display the words
437 * "Powered by SugarCRM".
438 ********************************************************************************/
441 cache : new Object(),
442 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
443 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
446 currentHtmleditor : ''
450 * preserves hits from email server
452 _setDetailCache : function(ret) {
454 var compKey = ret.meta.mbox + ret.meta.uid;
456 if(!SUGAR.email2.cache[compKey]) {
457 SUGAR.email2.cache[compKey] = ret;
462 autoSetLayout : function() {
463 var c = document.getElementById('container');
464 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
465 //Ensure a minimum height.
466 tHeight = Math.max(tHeight, 550);
467 c.style.height = tHeight + "px";
468 SUGAR.email2.complexLayout.set('height', tHeight);
469 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
470 SUGAR.email2.complexLayout.render();
471 SUGAR.email2.listViewLayout.resizePreview();
477 * Shows overlay progress message
481 SUGAR.showMessageBoxModal = function(title, body) {
482 SUGAR.showMessageBox(title, body);
486 SUGAR.showMessageBox = function(reqtitle, body, type, additconfig) {
488 if (typeof(additconfig) == "object") {
489 var config = additconfig;
492 config.title = reqtitle;
494 YAHOO.SUGAR.MessageBox.show(config);
498 SUGAR.hideMessageBox = function() {
499 YAHOO.SUGAR.MessageBox.hide();
501 // End of File modules/Emails/javascript/EmailUIShared.js
503 /*********************************************************************************
504 * SugarCRM Community Edition is a customer relationship management program developed by
505 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
507 * This program is free software; you can redistribute it and/or modify it under
508 * the terms of the GNU Affero General Public License version 3 as published by the
509 * Free Software Foundation with the addition of the following permission added
510 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
511 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
512 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
514 * This program is distributed in the hope that it will be useful, but WITHOUT
515 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
516 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
519 * You should have received a copy of the GNU Affero General Public License along with
520 * this program; if not, see http://www.gnu.org/licenses or write to the Free
521 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
524 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
525 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
527 * The interactive user interfaces in modified source and object code versions
528 * of this program must display Appropriate Legal Notices, as required under
529 * Section 5 of the GNU Affero General Public License version 3.
531 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
532 * these Appropriate Legal Notices must retain the display of the "Powered by
533 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
534 * technical reasons, the Appropriate Legal Notices must display the words
535 * "Powered by SugarCRM".
536 ********************************************************************************/
540 var sw = YAHOO.SUGAR,
541 Event = YAHOO.util.Event,
542 Connect = YAHOO.util.Connect,
546 ///////////////////////////////////////////////////////////////////////////////
549 outboundDialog : null,
550 inboundAccountEditDialog : null,
551 inboundAccountsSettingsTable : null,
552 outboundAccountsSettingsTable : null,
553 testOutboundDialog : null,
554 errorStyle : 'input-error',
556 newAddedOutboundId : '',
559 * makes async call to retrieve an outbound instance for editting
562 editOutbound : function(obi) {
564 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
567 deleteOutbound : function(obi) {
569 if(obi.match(/^(add|line|sendmail)+/)) {
570 alert('Invalid Operation');
572 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
573 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
577 getReplyAddress : function() {
580 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
581 var addy = SE.userPrefs.current_user.emailAddresses[i];
583 if(addy.primary_address == "1") {
584 primary = addy.email_address;
587 if(addy.reply_to == "1") {
588 return addy.email_address;
596 * Called on "Accounts" tab activation event
598 lazyLoad : function() {
600 this._setupInboundAccountTable();
601 this._setupOutboundAccountTable();
605 _setupInboundAccountTable: function()
607 //Setup the inbound mail settings
608 if(!this.inboundAccountsSettingsTable)
610 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
611 var clckEvent = oColumn.key;
613 var is_group = oRecord.getData("is_group");
616 if(oColumn.key == 'edit')
618 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
619 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
621 else if(oColumn.key == 'delete')
623 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
624 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
626 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
630 this.showBoolean = function(el, oRecord, oColumn, oData)
632 var is_group = oRecord.getData("is_group");
633 var bChecked = oData;
634 bChecked = (bChecked) ? " checked" : "";
637 el.innerHTML = "<input type=\"radio\"" + bChecked +
638 " name=\"col" + oColumn.getId() + "-radio\"" +
639 " class=\"yui-dt-radio\">";
644 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
645 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
647 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
648 '<img border="0" src="themes/default/images/helpInline.gif">' +
649 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
652 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
653 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
654 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
655 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
656 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
657 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
658 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
659 this.ieDataSource = new YAHOO.util.DataSource(query);
660 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
661 this.ieDataSource.responseSchema = {
662 resultsList: "account_list",
663 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
665 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
666 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
668 var elCheckbox = oArgs.target;
669 var oColumn = this.getColumn(elCheckbox);
670 if(oColumn.key == 'is_active')
672 var oRecord = this.getRecord(elCheckbox);
673 oRecord.setData("is_active",elCheckbox.checked);
674 var t_id = oRecord.getData('id');
675 var isGroupFolder = oRecord.getData('has_groupfolder');
678 SUGAR.email2.folders.updateSubscriptions();
680 SUGAR.email2.folders.setFolderSelection();
684 var lastDefaultSelectedId = "";
685 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
687 var elRadio = oArgs.target;
688 var oColumn = this.getColumn(elRadio);
689 if(oColumn.key == 'is_default')
691 var oRecord = this.getRecord(elRadio);
692 var t_id = oRecord.getData('id');
693 var t_isGroup = oRecord.getData('is_group');
694 if(t_id != lastDefaultSelectedId && !t_isGroup)
696 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
697 lastDefaultSelectedId = t_id;
698 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
701 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
706 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
707 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
710 _setupOutboundAccountTable: function()
712 if(!this.outboundAccountsSettingsTable)
714 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
715 var clckEvent = oColumn.key;
717 var isEditable = oRecord.getData("is_editable");
718 var type = oRecord.getData("type");
721 if(oColumn.key == 'edit')
723 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
724 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
726 else if(oColumn.key == 'delete' && type == 'user')
728 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
729 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
732 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
736 //Custom formatter to display any error messages.
737 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
739 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
740 SUGAR.email2.composeLayout.outboundAccountErrors = {};
742 var id = oRecord.getData('id');
743 var message = oRecord.getData("errors");
746 elLiner.innerHTML = '<span class="required">' + message + '</span>';
747 //Add the id and message for all outbound accounts.
748 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
752 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
753 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
756 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
757 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
759 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
760 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
761 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
762 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
764 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
765 this.obDataSource = new YAHOO.util.DataSource(query);
766 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
767 this.obDataSource.responseSchema = {
769 resultsList: "outbound_account_list",
770 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
773 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
776 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
777 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
778 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
782 * Displays a modal diaglogue to edit outbound account settings
784 showEditInboundAccountDialogue : function(clear) {
786 if(!this.inboundAccountEditDialog) {
787 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
791 constraintoviewport: true,
795 EAD.showEvent.subscribe(function() {
796 var el = this.element;
797 var viewH = YAHOO.util.Dom.getViewportHeight();
798 if (this.header && el && viewH - 50 < el.clientHeight) {
799 var body = this.header.nextElementSibling;
800 body.style.overflow = "hidden";
801 body.style.height = "100%";
804 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
805 Dom.removeClass("editAccountDialogue", "yui-hidden");
809 if(clear == undefined || clear == true)
811 SE.accounts.clearInboundAccountEditScreen();
812 //Set default protocol to IMAP when creating new records
813 document.forms['ieAccount'].elements['protocol'].value = "imap";
814 SE.accounts.setPortDefault();
817 //Check if we should display username/password fields for outbound account if errors were detected.
818 this.checkOutBoundSelection();
820 this.inboundAccountEditDialog.render();
821 this.inboundAccountEditDialog.show();
822 SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
826 * Set all fields on the outbound edit form to either enabled/disabled
827 * except for the username/password.
830 toggleOutboundAccountDisabledFields: function(disable)
832 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
833 for(var i=0;i<fields.length;i++)
835 document.getElementById(fields[i]).disabled = disable;
838 Dom.addClass("mail_smtpssl_row", "yui-hidden");
840 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
844 * Refresh the inbound accounts table.
846 refreshInboundAccountTable : function()
848 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
850 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
851 scope: this.inboundAccountsSettingsTable }
855 * Refresh the outbound accounts table.
857 refreshOuboundAccountTable : function()
859 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
861 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
862 scope: this.outboundAccountsSettingsTable }
866 * Displays a modal diaglogue to add a SMTP server
868 showAddSmtp : function() {
869 // lazy load dialogue
870 if(!this.outboundDialog) {
871 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
875 constraintoviewport: true,
879 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
880 this.outboundDialog.hideEvent.subscribe(function(){
881 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
882 var out = Dom.get("outbound_email");
883 if (out && out.value == "SYSTEM_ADD")
885 out.value = out.options[0].value;
887 //Check if we should display username/password for system account.
888 SE.accounts.checkOutBoundSelection();
892 Dom.removeClass("outboundDialog", "yui-hidden");
896 var form = document.getElementById('outboundEmailForm');
897 for(i=0; i<form.elements.length; i++) {
898 if(form.elements[i].name == 'mail_smtpport') {
899 form.elements[i].value = 25;
900 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
901 form.elements[i].value = '';
902 } else if(form.elements[i].type == 'checkbox') {
903 form.elements[i].checked = false;
906 //Render the SMTP buttons
907 if ( !SUGAR.smtpButtonGroup ) {
908 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
909 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
911 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
912 document.getElementById('smtp_settings').style.display = '';
913 form.mail_smtptype.value = e.newValue.get('value');
915 YAHOO.widget.Button.addHiddenFieldsToForm(form);
917 //Hide Username/Password
918 SUGAR.email2.accounts.smtp_authenticate_field_display();
919 //Unset readonly fields
920 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
921 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
922 this.outboundDialog.render();
923 this.outboundDialog.show();
927 * Accounts' Advanced Settings view toggle
929 toggleAdv : function() {
930 var adv = document.getElementById("ie_adv");
931 if(adv.style.display == 'none') {
932 adv.style.display = "";
934 adv.style.display = 'none';
938 smtp_authenticate_field_display : function() {
939 var smtpauth_req = document.getElementById("mail_smtpauth_req");
940 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
941 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
944 smtp_setDefaultSMTPPort : function() {
945 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
947 if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
948 document.getElementById("mail_smtpport").value = '465';
950 if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
951 document.getElementById("mail_smtpport").value = '25';
956 * Changes the display used in the outbound email SMTP dialog to match the
958 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
960 document.getElementById("smtpButtonGroupTD").style.display = '';
961 document.getElementById("chooseEmailProviderTD").style.display = '';
962 document.getElementById("mailsettings1").style.display = '';
963 document.getElementById("mailsettings2").style.display = '';
964 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
965 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
966 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
967 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
971 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
972 document.getElementById("mail_smtpport").value = '465';
973 document.getElementById("mail_smtpauth_req").checked = true;
974 var ssl = document.getElementById("mail_smtpssl");
975 for(var j=0;j<ssl.options.length;j++) {
976 if(ssl.options[j].text == 'SSL') {
977 ssl.options[j].selected = true;
981 document.getElementById("mailsettings1").style.display = 'none';
982 document.getElementById("mailsettings2").style.display = 'none';
983 document.getElementById("mail_smtppass_label").innerHTML =
984 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
985 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
988 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
989 document.getElementById("mail_smtpport").value = '587';
990 document.getElementById("mail_smtpauth_req").checked = true;
991 var ssl = document.getElementById("mail_smtpssl");
992 for(var j=0;j<ssl.options.length;j++) {
993 if(ssl.options[j].text == 'TLS') {
994 ssl.options[j].selected = true;
998 document.getElementById("mailsettings1").style.display = 'none';
999 document.getElementById("mailsettings2").style.display = 'none';
1000 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
1001 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
1004 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
1005 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
1006 document.getElementById("mail_smtpserver").value = '';
1008 document.getElementById("mail_smtpport").value = '25';
1009 document.getElementById("mail_smtpauth_req").checked = true;
1010 document.getElementById("mailsettings1").style.display = '';
1011 document.getElementById("mailsettings2").style.display = '';
1012 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1013 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1014 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1015 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1018 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1020 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1021 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1022 document.getElementById("mailsettings2").style.display = 'none';
1025 SUGAR.email2.accounts.smtp_authenticate_field_display();
1026 SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1030 * Fill the gmail default values for inbound accounts.
1032 fillInboundGmailDefaults: function () {
1034 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1035 document.forms['ieAccount'].elements['ssl'].checked = true;
1036 document.forms['ieAccount'].elements['protocol'].value = "imap";
1037 SUGAR.email2.accounts.setPortDefault();
1038 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1041 * Sets Port field to selected protocol and SSL settings defaults
1043 setPortDefault : function() {
1044 var prot = document.getElementById('protocol');
1045 var ssl = document.getElementById('ssl');
1046 var port = document.getElementById('port');
1047 var stdPorts= new Array("110", "143", "993", "995");
1048 var stdBool = new Boolean(false);
1049 var mailboxdiv = document.getElementById("mailboxdiv");
1050 var trashFolderdiv = document.getElementById("trashFolderdiv");
1051 var sentFolderdiv = document.getElementById("sentFolderdiv");
1052 var monitoredFolder = document.getElementById("subscribeFolderButton");
1053 if(port.value == '') {
1054 stdBool.value = true;
1056 for(i=0; i<stdPorts.length; i++) {
1057 if(stdPorts[i] == port.value) {
1058 stdBool.value = true;
1063 if(stdBool.value == true) {
1064 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1066 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1068 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1070 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1075 if (prot.value == 'imap') {
1076 mailboxdiv.style.display = "";
1077 trashFolderdiv.style.display = "";
1078 sentFolderdiv.style.display = "";
1079 monitoredFolder.style.display = "";
1080 if (document.getElementById('mailbox').value == "") {
1081 document.getElementById('mailbox').value = "INBOX";
1084 mailboxdiv.style.display = "none";
1085 trashFolderdiv.style.display = "none";
1086 sentFolderdiv.style.display = "none";
1087 monitoredFolder.style.display = "none";
1088 document.getElementById('mailbox').value = "";
1093 * Draws/removes red boxes around required fields.
1095 ieAccountError : function(style) {
1096 document.getElementById('server_url').className = style;
1097 document.getElementById('email_user').className = style;
1098 document.getElementById('email_password').className = style;
1099 document.getElementById('protocol').className = style;
1100 document.getElementById('port').className = style;
1103 checkOutBoundSelection: function() {
1104 var select = Dom.get('outbound_email');
1105 if (!select || select.selectedIndex == -1) { return; }
1107 var v = select.options[select.selectedIndex].value;
1111 select.options[select.selectedIndex].selected = false;
1112 v = select.options[0].value;
1114 else if (v == 'SYSTEM_ADD')
1115 SUGAR.email2.accounts.showAddSmtp();
1117 var foundError = false;
1118 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1119 for(i in errorAccounts)
1128 //Should username/password fields for outbound account.
1130 this.toggleInboundOutboundFields(true);
1132 this.toggleInboundOutboundFields(false);
1137 toggleInboundOutboundFields : function (display)
1141 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1142 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1146 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1147 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1151 * rebuilds the select options for mailer options
1153 rebuildMailerOptions : function() {
1154 var select = document.forms['ieAccount'].elements['outbound_email'];
1155 SE.util.emptySelectOptions(select);
1157 //Get the available sugar mailers
1158 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1160 for(i=0;i<a_outbound.length;i++)
1162 var t_record = a_outbound[i];
1163 var key = t_record.getData('id');
1164 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1166 var opt = new Option(display, key);
1167 select.options.add(opt);
1168 if (key == SE.accounts.newAddedOutboundId) {
1169 select.options.selectedIndex = i;
1173 select.options.add(new Option('',''));
1174 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1175 //Hide/Show username password fields if necessary.
1176 SE.accounts.checkOutBoundSelection();
1179 * Empties all the fields in the accounts edit view
1181 clearInboundAccountEditScreen:function() {
1183 document.getElementById('ie_id').value = '';
1184 document.getElementById('ie_name').value = '';
1185 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1186 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1187 document.getElementById('reply_to_addr').value = '';
1188 document.getElementById('server_url').value = '';
1189 document.getElementById('email_user').value = '';
1190 document.getElementById('email_password').value = '';
1191 document.getElementById('port').value = '';
1192 document.getElementById('inbound_mail_smtpuser').value = '';
1193 document.getElementById('inbound_mail_smtppass').value = '';
1194 document.ieAccount.protocol.options[0].selected = true;
1196 document.getElementById('ssl').checked = false;
1197 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1201 * Populates an account's fields in Settings->Accounts
1203 fillIeAccount:function(jsonstr) {
1204 var o = YAHOO.lang.JSON.parse(jsonstr);
1206 document.getElementById('ie_id').value = o.id;
1207 document.getElementById('ie_name').value = o.name;
1208 if (o.stored_options != null) {
1209 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1210 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1211 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1212 if (o.stored_options.trashFolder != null) {
1213 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1215 if (o.stored_options.sentFolder != null) {
1216 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1219 document.getElementById('server_url').value = o.server_url;
1220 document.getElementById('email_user').value = o.email_user;
1221 document.getElementById('port').value = o.port;
1222 document.getElementById('group_id').value = o.group_id;
1223 document.getElementById('mailbox').value = o.mailbox;
1229 if(typeof(o.service[2]) != 'undefined') {
1230 document.getElementById('ssl').checked = true;
1234 if(document.getElementById('protocol').value != o.protocol) {
1235 var prot = document.getElementById('protocol');
1236 for(i=0; i<prot.options.length; i++) {
1237 if(prot.options[i].value == o.service[3]) {
1238 prot.options[i].selected = true;
1239 this.setPortDefault();
1243 // handle SMTP selection
1244 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1245 var opts = document.getElementById('outbound_email').options;
1246 for(i=0; i<opts.length; i++) {
1247 if(opts[i].value == o.stored_options.outbound_email) {
1248 opts[i].selected = true;
1254 deleteIeAccount : function(IeAccountID,IeGroupID) {
1255 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1257 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1259 AjaxObject.target = 'frameFlex';
1260 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1261 SUGAR.email2.accounts.refreshInboundAccountTable();
1265 // Null check for Outbound Settings.
1266 checkOutboundSettings: function() {
1267 var errorMessage = '';
1268 var isError = false;
1269 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1270 var mailName = document.getElementById('mail_name').value;
1271 var smtpServer = document.getElementById('mail_smtpserver').value;
1272 var smtpPort = document.getElementById('mail_smtpport').value;
1274 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1275 if(trim(mailName) == '') {
1277 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1279 if(trim(smtpServer) == '') {
1281 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1283 if(trim(smtpPort) == '') {
1285 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1287 if(mailsmtpauthreq.checked) {
1288 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1290 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1295 SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1302 testOutboundSettings: function() {
1303 var errorMessage = '';
1304 var isError = false;
1305 var fromAddress = document.getElementById("outboundtest_from_address").value;
1306 if (trim(fromAddress) == "") {
1307 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1308 SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1312 else if (!isValidEmail(fromAddress)) {
1313 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1314 SUGAR.showMessageBox(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1318 //Hide the dialogue and show an in progress indicator.
1319 SE.accounts.testOutboundDialog.hide();
1320 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1322 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1323 //nothing is sent in the request.
1324 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1325 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1327 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1328 if(outboundType == 'system-override')
1329 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1331 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1332 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1336 testOutboundSettingsDialog: function() {
1337 //Ensure that all settings are correct before proceeding to send test email.
1338 if(!SE.accounts.checkOutboundSettings())
1341 // lazy load dialogue
1342 if(!SE.accounts.testOutboundDialog) {
1343 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1347 constraintoviewport: true,
1351 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1352 Dom.removeClass("testOutboundDialog", "yui-hidden");
1354 SE.accounts.testOutboundDialog.render();
1355 SE.accounts.testOutboundDialog.show();
1359 * Saves Outbound email settings
1361 saveOutboundSettings : function() {
1362 if(SE.accounts.checkOutboundSettings()) {
1363 //Enable the form fields for the post.
1364 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1365 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1366 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1372 saveIeAccount : function() {
1374 //Before saving check if there are any error messages associated with the outbound account.
1375 var outboundID = document.getElementById('outbound_email').value;
1377 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1378 'validateSMTPCreds':true}) )
1380 document.getElementById('saveButton').disabled = true;
1382 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1384 var formObject = document.getElementById('ieAccount');
1385 YAHOO.util.Connect.setForm(formObject);
1387 AjaxObject._reset();
1388 AjaxObject.target = 'frameFlex';
1389 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1393 testSettings : function() {
1394 form = document.getElementById('ieAccount');
1396 if(SE.accounts.checkIeCreds()) {
1397 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);
1401 getFoldersListForInboundAccountForEmail2 : function() {
1402 form = document.getElementById('ieAccount');
1403 if(SE.accounts.checkIeCreds()) {
1404 var mailBoxValue = form.mailbox.value;
1405 if (form.searchField.value.length > 0) {
1408 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 );
1413 checkIeCreds : function(validateRules) {
1414 if(typeof(validateRules) == 'undefined')
1417 var errors = new Array();
1418 var out = new String();
1420 var ie_name = Dom.get('ie_name').value;
1421 var fromAddress = Dom.get('ie_from_addr').value;
1422 var server_url = Dom.get('server_url').value;
1423 var email_user = Dom.get('email_user').value;
1424 var email_password = Dom.get('email_password').value;
1425 var protocol = Dom.get('protocol').value;
1426 var port = Dom.get('port').value;
1427 var oe = Dom.get('outbound_email');
1429 // Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
1430 // other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
1431 // return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
1432 var oe_value = (typeof(oe.options[oe.selectedIndex]) === 'undefined' || typeof(oe.options[oe.selectedIndex]) === 'unknown' || typeof(oe.options[oe.selectedIndex]) === null) ? "" : oe.options[oe.selectedIndex].value;
1434 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1435 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1437 //If the username and password were provided then ignore the error messge
1439 var outboundCredentialsFound = false;
1441 if(outboundUserName != "" && outboundPass != "")
1442 outboundCredentialsFound = true;
1444 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1446 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1447 && validateSMTPCreds)
1449 if(trim(outboundUserName) == "") {
1450 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1452 if(trim(outboundPass) == "") {
1453 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1457 if(trim(ie_name) == "") {
1458 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1461 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1463 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1464 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1469 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1470 || trim(oe_value) == "SYSTEM_ADD") ) {
1471 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1473 if(trim(server_url) == "") {
1474 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1476 if(trim(email_user) == "") {
1477 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1479 if(protocol == "") {
1480 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1482 if (protocol == 'imap') {
1483 var mailbox = document.getElementById('mailbox').value;
1484 if (trim(mailbox) == "") {
1485 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1487 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1488 var trashFolder = document.getElementById('trashFolder').value;
1489 if (trim(trashFolder) == "") {
1490 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1495 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1498 if(errors.length > 0) {
1499 out = app_strings.LBL_EMAIL_ERROR_DESC;
1500 for(i=0; i<errors.length; i++) {
1515 getIeAccount : function(ieId) {
1519 SUGAR.showMessageBox(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1520 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1522 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1526 * Iterates through TreeView nodes to apply styles dependent nature of node
1528 renderTree:function() {
1529 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1533 //Sets the style for any nodes that need it.
1534 setNodeStyle : function(node) {
1535 if (!node.data.origText) {
1536 node.data.origText = node.data.text;
1539 if (typeof(node.data.unseen) != 'undefined') {
1540 if (node.data.unseen > 0) {
1541 node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
1542 // Add bold style to label, kinda hacky
1543 node.labelStyle += " ygtvlabelbold";
1546 node.setUpLabel(node.data.origText);
1549 node.setUpLabel(node.data.origText);
1551 SE.accounts.setupDDTarget(node);
1554 setupDDTarget : function(node) {
1555 if (node.ddTarget) {
1556 node.ddTarget.removeFromGroup();
1557 delete node.ddTarget;
1559 var id = node.getElId();
1560 var num = id.substring(4);
1561 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1562 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1563 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1565 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1567 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1568 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1573 * Async call to rebuild the folder list. After a folder delete or account delete
1575 rebuildFolderList : function() {
1576 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1577 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1581 * Returns the number of remote accounts the user has active.
1583 getAccountCount : function() {
1586 for(i=0; i<tree._nodes.length; i++) {
1587 var node = tree._nodes[i];
1589 if(typeof(node) != 'undefined' && node.data.ieId) {
1597 ///////////////////////////////////////////////////////////////////////////////
1602 ///////////////////////////////////////////////////////////////////////////////
1603 //// CONTEXT MENU CALLS
1606 assignToDialogue : null,
1608 * Archives from context menu
1610 * @param string ieId
1611 * @param string folder
1613 _archiveToSugar : function(uids, ieId, folder) {
1616 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1617 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1620 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1624 * Archives from context menu
1626 archiveToSugar : function(menuItem) {
1627 SE.contextMenus.emailListContextMenu.hide();
1629 var rows = SE.grid.getSelectedRows();
1631 /* iterate through available rows JIC a row is deleted - use first available */
1632 for(var i=0; i<rows.length; i++) {
1633 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1635 var data = SE.grid.getRecord(rows[0]).getData();
1636 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1640 * Popup the printable version and start system's print function.
1642 viewPrintable : function(menuItem) {
1643 var rows = SE.grid.getSelectedRows();
1644 var data = SE.grid.getRecord(rows[0]).getData();
1645 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1649 * Marks email flagged on mail server
1651 markRead : function(type, contextMenuId) {
1652 SE.contextMenus.markEmail('read');
1656 * Assign this emails to people based on assignment rules
1658 assignEmailsTo : function(type, contextMenuId) {
1659 if(!SE.contextMenus.assignToDialogue)
1661 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1665 constraintoviewport: true,
1669 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1673 Dom.removeClass("assignToDiv", "yui-hidden");
1674 SE.contextMenus.assignToDialogue.render();
1675 SE.contextMenus.assignToDialogue.show();
1679 * Marks email flagged on mail server
1681 markFlagged : function(contextMenuId) {
1682 SE.contextMenus.markEmail('flagged');
1686 * Marks email unflagged on mail server
1688 markUnflagged : function(contextMenuId) {
1689 SE.contextMenus.markEmail('unflagged');
1693 * Marks email unread on mail server
1695 markUnread : function() {
1696 SE.contextMenus.markEmail('unread');
1700 * Deletes an email from context menu
1702 markDeleted : function() {
1703 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1704 document.getElementById('_blank').innerHTML = "";
1705 SE.contextMenus.markEmail('deleted');
1710 * generic call API to apply a flag to emails on the server and on sugar
1711 * @param string type "read" | "unread" | "flagged" | "deleted"
1713 markEmail : function(type) {
1714 SE.contextMenus.emailListContextMenu.hide();
1716 //var dm = SE.grid.getStore();
1717 //var uids = SE.grid.getSelectedRowIds();
1718 //var indexes = SE.grid.getSelectedRowIndexes();
1719 var rows = SE.grid.getSelectedRows();
1720 if (rows.length == 0)
1721 rows = [SE.contextMenus.currentRow];
1724 for(var i=0; i<rows.length; i++) {
1725 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1728 ser = YAHOO.lang.JSON.stringify(ser);
1730 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1731 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1737 if(type == 'read' || type == 'deleted') {
1739 for(var j=0; j<rows.length; j++) {
1740 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1742 SE.grid.getRecord(rows[j]).setData("seen", "1");
1745 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1747 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1748 var unseenCount = node.data.unseen;
1749 if (isNaN(unseenCount)) {
1752 var finalCount = parseInt(unseenCount) - count;
1753 node.data.unseen = finalCount;
1755 SE.accounts.renderTree();
1757 } else if(type == 'unread') {
1759 for(var j=0; j<rows.length; j++) {
1760 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1765 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1766 var unseenCount = node.data.unseen;
1767 if (isNaN(unseenCount)) {
1770 var finalCount = parseInt(unseenCount) + count;
1771 node.data.unseen = finalCount;
1772 SE.accounts.renderTree();
1775 if (type == 'unread') {
1776 for(var i=0; i<rows.length; i++) {
1777 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1781 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1782 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1786 * refreshes the ListView to show changes to cache
1788 markEmailCleanup : function() {
1789 SE.accounts.renderTree();
1790 SUGAR.hideMessageBox();
1791 SE.listView.refreshGrid();
1794 showAssignmentDialog : function() {
1795 if (SE.contextMenus.assignmentDialog == null) {
1796 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1798 SE.contextMenus.assignmentDialog.show();
1803 * shows the import dialog with only relate visible.
1805 relateTo : function() {
1806 SE.contextMenus.emailListContextMenu.hide();
1808 var rows = SE.grid.getSelectedRows();
1809 var data = SE.grid.getRecord(rows[0]).getData();
1810 var ieId = data.ieId;
1811 var folder = data.mbox;
1813 /* iterate through available rows JIC a row is deleted - use first available */
1814 for(var i=0; i<rows.length; i++) {
1815 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1817 var ser = YAHOO.lang.JSON.stringify(uids);
1819 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1823 * shows the import dialog with only relate visible.
1825 showDetailView : function() {
1826 SE.contextMenus.emailListContextMenu.hide();
1827 var rows = SE.grid.getSelectedRows();
1828 if (rows.length > 1) {
1829 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1832 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1833 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1834 /* iterate through available rows JIC a row is deleted - use first available */
1835 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1836 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1842 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1843 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1844 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1848 * Opens multiple messages from ListView context click
1850 openMultiple : function() {
1851 SE.contextMenus.emailListContextMenu.hide();
1853 var rows = SE.grid.getSelectedRows();
1854 var uids = SE.listView.getUidsFromSelection();
1856 if(uids.length > 0) {
1857 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1858 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1859 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1864 * Replies/forwards email
1866 replyForwardEmailContext : function() {
1867 SE.contextMenus.emailListContextMenu.hide();
1869 var indexes = SE.grid.getSelectedRows();
1870 //var dm = SE.grid.getDataModel();
1873 for(var i=0; i<indexes.length; i++) {
1874 var row = SE.grid.getRecord(indexes[i]).getData();
1875 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1879 //show menu functions
1880 showEmailsListMenu : function(grid, row) {
1882 var data = row.getData();
1883 var draft = (data.type == "draft");
1884 var menu = SE.contextMenus.emailListContextMenu;
1889 if (data.mbox == 'sugar::Emails')
1890 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1892 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1894 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1895 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1896 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1897 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1899 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1902 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1904 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1905 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1906 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1907 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1908 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1911 if (data.mbox == "sugar::Emails")
1913 //Allow users to reassign imported emails
1914 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1915 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1916 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1917 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1921 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1922 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1926 showFolderMenu : function(grid, rowIndex, event) {
1928 var coords = event.getXY();
1929 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1933 SE.contextMenus.dv = {
1934 archiveToSugar : function(contextMenuId) {
1936 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1939 replyForwardEmailContext : function(all) {
1940 SE.contextMenus.detailViewContextMenu.hide();
1949 //// END SE.contextMenus
1950 ///////////////////////////////////////////////////////////////////////////////
1954 ///////////////////////////////////////////////////////////////////////////////
1957 consumeMetaDetail : function(ret) {
1958 // handling if the Email drafts
1959 if(ret.type == 'draft') {
1960 SE.composeLayout.c0_composeDraft();
1965 // cache contents browser-side
1966 SE._setDetailCache(ret);
1968 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1969 // 2 below must be in global context
1971 meta['panelId'] = SE.util.getPanelId();
1973 email = ret.meta.email;
1974 var out = displayTemplate.exec({
1975 'app_strings' : app_strings,
1977 'idx' : targetDiv.id,
1979 'email' : meta.email,
1980 'linkBeans' : linkBeans
1982 var tabLabel = meta.email.name;
1983 if (tabLabel != null && tabLabel.length > 25) {
1984 tabLabel = tabLabel.substring(0, 25) + "...";
1986 targetDiv.set("label", tabLabel);
1987 targetDiv.set("content", out);
1989 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1990 if (SUGAR.email2.util.isIe()) {
1991 displayEmailFrameDiv.style.height = "390px";
1993 displayEmailFrameDiv.style.height = "410px";
1996 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1997 displayFrame.contentWindow.document.write(email.description);
1998 displayFrame.contentWindow.document.close();
2000 // hide archive links
2001 if(ret.meta.is_sugarEmail) {
2002 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
2003 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
2005 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
2006 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
2011 consumeMetaPreview : function(ret) {
2012 // cache contents browser-side
2013 SE._setDetailCache(ret);
2017 var currrow = SE.grid.getLastSelectedRecord();
2018 currrow = SE.grid.getRecord(currrow);
2020 document.getElementById('_blank').innerHTML = '';
2023 // handling if the Email drafts
2024 if(ret.type == 'draft'){
2025 if (currrow.getData().uid == ret.uid) {
2026 SE.composeLayout.c0_composeDraft();
2031 if (currrow.getData().uid != ret.meta.uid) {
2035 // remove loading sprite
2036 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2037 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2039 meta['panelId'] = SE.util.getPanelId();
2040 email = ret.meta.email;
2042 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2043 'app_strings' : app_strings,
2047 'email' :meta.email,
2048 'linkBeans' : linkBeans
2050 // document.getElementById('_blank').innerHTML = meta.email;
2051 /* displayTemplate.append('_blank', {
2052 'app_strings' : app_strings,
2056 'email' :meta.email,
2057 'linkBeans' : linkBeans
2060 var displayFrame = document.getElementById('displayEmailFramePreview');
2061 displayFrame.contentWindow.document.write(email.description);
2062 displayFrame.contentWindow.document.close();
2064 SE.listViewLayout.resizePreview();
2066 // hide archive links
2067 if(ret.meta.is_sugarEmail) {
2068 document.getElementById("archiveEmailPreview").innerHTML = " ";
2069 document.getElementById("btnEmailViewPreview").style.display = "none";
2070 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2072 //hide view relationship link
2073 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2078 * wraps emailDelete() for single messages, comes from preview or tab
2080 emailDeleteSingle : function(ieId, uid, mbox) {
2081 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2082 // find active panel and close if the user double clicked the email to view.
2083 var activeTabId = SE.util.getPanelId();
2084 if(activeTabId != 'Preview')
2085 SE.innerLayout.get("activeTab").close();
2087 document.getElementById('_blank').innerHTML = "";
2090 uid = YAHOO.lang.JSON.stringify(ser);
2091 this.emailDelete(ieId, uid, mbox);
2096 * Sends async call to delete a given message
2099 emailDelete : function(ieId, uid, mbox) {
2100 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2101 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2102 uid + "&ieId=" + ieId + "&folder=" + mbox);
2106 * retrieves one email to display in the preview pane.
2108 getEmailPreview : function() {
2109 var row = SUGAR.email2.listView.currentRow;
2110 var data = row.getData();
2111 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2112 var setRead = (data['seen'] == 0) ? true : false;
2113 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2114 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2119 * Imports one email into Sugar
2121 importEmail : function(ieId, uid, mbox) {
2122 SE.util.clearHiddenFieldValues('emailUIForm');
2124 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2126 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2127 AjaxObject.target = '';
2128 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2132 * Populates the frameFlex div with the contents of an email
2134 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2135 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2137 var mboxStr = new String(mbox);
2138 var compKey = mbox + uid;
2140 if(setRead == true) {
2141 SE.listView.boldUnreadRows()
2142 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2145 if(destination == SE.innerLayout) {
2147 * loading email into a tab, peer with ListView
2148 * targetDiv must remain in the global namespace as it is used by AjaxObject
2150 //Check if we already have a tab of the email open
2151 var tabs = SE.innerLayout.get("tabs");
2152 for (var t in tabs) {
2153 if (tabs[t].id && tabs[t].id == uid) {
2154 SE.innerLayout.set("activeTab", tabs[t]);
2159 targetDiv = new YAHOO.SUGAR.ClosableTab({
2160 label: loadingSprite,
2166 SE.innerLayout.addTab(targetDiv);
2168 // use cache if available
2169 if(SE.cache[compKey]) {
2170 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2172 // open email as peer-tab to listView
2173 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2174 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2177 // loading email into preview pane
2178 document.getElementById('_blank').innerHTML = loadingSprite;
2180 // use cache if available
2181 if(SE.cache[compKey]) {
2182 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2184 AjaxObject.forceAbort = true;
2185 // open in preview window
2186 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2187 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2192 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2194 if(mboxStr.substring(0,7) == 'sugar::') {
2195 // display an email from Sugar
2196 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2198 // display an email from an email server
2199 document.getElementById('emailUIAction').value = 'getSingleMessage';
2201 document.getElementById('mbox').value = mbox;
2202 document.getElementById('ieId').value = ieId;
2203 document.getElementById('uid').value = uid;
2205 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2207 AjaxObject.forceAbort = true;
2208 AjaxObject.target = '_blank';
2209 AjaxObject.startRequest(callback, null);
2213 * Retrieves multiple emails for DetailView
2215 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2216 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2217 SE.util.clearHiddenFieldValues('emailUIForm');
2219 var mboxStr = new String(mbox);
2221 uids = SE.util.cleanUids(uids);
2223 if(mboxStr.substring(0,7) == 'sugar::') {
2224 // display an email from Sugar
2225 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2226 document.getElementById('uid').value = uids;
2228 // display an email from an email server
2229 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2230 document.getElementById('mbox').value = mbox;
2231 document.getElementById('ieId').value = ieId;
2232 document.getElementById('uid').value = uids;
2235 var formObject = document.getElementById('emailUIForm');
2236 YAHOO.util.Connect.setForm(formObject);
2238 AjaxObject.target = 'frameFlex';
2239 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2241 if(setRead == true) {
2242 var c = uids.split(",");
2243 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2248 * Makes async call to get QuickCreate form
2249 * Renders a modal edit view for a given module
2251 quickCreate : function(module, ieId, uid, mailbox) {
2252 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2254 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2255 get += "&sugarEmail=true";
2258 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2262 * Makes async call to save a quick create
2265 saveQuickCreate : function(action) {
2266 var qcd = SE.detailView.quickCreateDialog;
2267 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2268 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2269 var theCallback = callbackQuickCreateSave;
2270 var accountType = '&sugarEmail=true';
2271 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2272 accountType = '&ieId=' + qcd.ieId;
2275 if (action == 'reply') {
2276 theCallback = callbackQuickCreateSaveAndReply;
2277 } else if (action == true) {
2278 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2280 formObject.action.value = 'EmailUIAjax';
2281 YAHOO.util.Connect.setForm(formObject);
2282 SUGAR.showMessageBox('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2283 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2284 accountType + '&mbox=' + qcd.mbox);
2289 * Code to show/hide long list of email address in DetailView
2291 showCroppedEmailList : function(el) {
2292 el.style.display = 'none';
2293 el.previousSibling.style.display = 'inline'
2295 showFullEmailList : function(el) {
2296 el.style.display = 'none';
2297 el.nextSibling.style.display = 'inline';
2301 * Shows the QuickCreate overlay
2302 * @param string ieId
2304 * @param string mailbox
2306 showQuickCreate : function(ieId, uid, mailbox) {
2307 var panelId = SE.util.getPanelId();
2308 var context = document.getElementById("quickCreateSpan" + panelId);
2310 if (!SE.detailView.cqMenus)
2311 SE.detailView.cqMenus = {};
2313 if (SE.detailView.cqMenus[context])
2314 SE.detailView.cqMenus[context].destroy();
2316 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2318 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2321 for (var i=0; i < this.qcmodules.length; i++) {
2322 var module = this.qcmodules[i];
2324 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2327 onclick: { fn: function() {
2328 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2334 menu.render(document.body);
2339 * Displays the "View" submenu in the detailView
2340 * @param string ieId
2342 * @param string mailbox
2344 showViewMenu : function(ieId, uid, mailbox) {
2345 var panelId = SE.util.getPanelId();
2346 var context = "btnEmailView" + panelId;
2347 if (!SE.detailView.viewMenus)
2348 SE.detailView.viewMenus = {};
2350 if (SE.detailView.viewMenus[context])
2351 SE.detailView.viewMenus[context].destroy();
2353 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2355 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2359 (ieId == 'null' || ieId == null) ?
2360 //No ieId - Sugar Email
2362 text: app_strings.LBL_EMAIL_VIEW_RAW,
2363 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2366 //IeID exists, on a remote server
2368 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2369 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2371 text: app_strings.LBL_EMAIL_VIEW_RAW,
2372 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2375 menu.render(document.body);
2380 //#23108 jchi@07/17/2008
2381 menu.render('quickCreateSpan'+ panelId);*/
2382 //this.viewMenu = menu;
2383 //this.viewMenu.show(context);
2386 * Makes async call to get an email's headers
2388 viewHeaders : function(ieId, uid, mailbox) {
2389 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2390 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2394 * Makes async call to get a printable version
2396 viewPrintable : function(ieId, uid, mailbox) {
2397 if(mailbox == 'sugar::Emails') {
2398 // display an email from Sugar
2399 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2401 // display an email from an email server
2402 var emailUIAction = '&emailUIAction=getSingleMessage';
2405 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2406 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2410 * Makes async call to get an email's raw source
2412 viewRaw : function(ieId, uid, mailbox) {
2413 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2414 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2418 * Display all email addresses in detailview.
2420 displayAllAddrs : function(el) {
2421 el.style.display = 'none';
2422 Dom.getNextSibling(el).style.display = 'inline';
2425 //// END SE.detailView
2426 ///////////////////////////////////////////////////////////////////////////////
2430 ///////////////////////////////////////////////////////////////////////////////
2433 contextMenuFocus : new Object(),
2436 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2437 * SugarFolder ID - folder strings
2439 _createFolderId : function(node) {
2445 if(node.data.ieId) {
2446 /* we have a local Sugar folder */
2447 if(node.data.ieId == 'folder') {
2448 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2449 } else if(node.data.ieId.match(SE.reGUID)) {
2450 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2459 addChildNode : function(parentNode, childNode) {
2460 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2461 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2462 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2464 if(childNode.nodes) {
2465 if(childNode.nodes.length > 0) {
2466 for(j=0; j<childNode.nodes.length; j++) {
2467 var newChildNode = childNode.nodes[j];
2468 this.addChildNode(node, newChildNode);
2475 * Builds and returns a new TreeView Node
2476 * @param string name
2478 * @param int is_group
2481 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2482 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2484 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2485 node.expanded = expanded;
2486 node.data = new Object;
2487 node.data['id'] = id;
2488 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2489 node.data['label'] = name;
2490 node.data['ieId'] = 'folder';
2491 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2492 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2493 node.data['unseen'] = unseen;
2498 * ensures that a new folder has a valid name
2500 checkFolderName : function(name) {
2504 this.folderAdd(name);
2508 * Pings email servers for new email - forces refresh of folder pane
2510 checkEmailAccounts : function() {
2511 this.checkEmailAccountsSilent(true);
2514 checkEmailAccountsSilent : function(showOverlay) {
2515 if(typeof(SE.folders.checkingMail)) {
2516 clearTimeout(SE.folders.checkingMail);
2519 // don't stomp an on-going request
2520 if(AjaxObject.currentRequestObject.conn == null) {
2522 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW,
2523 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2525 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2527 // wait 5 secs before trying again.
2528 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2533 * Starts check of all email Accounts using a loading bar for large POP accounts
2535 startEmailAccountCheck : function() {
2536 // don't do two checks at the same time
2537 if(!AjaxObject.requestInProgress()) {
2538 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2539 SE.accounts.ieIds = SE.folders.getIeIds();
2540 if (SE.accounts.ieIds.length > 0) {
2541 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2542 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2544 SUGAR.hideMessageBox();
2547 // wait 5 secs before trying again.
2548 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2553 * Checks a single Account check based on passed ieId
2555 startEmailCheckOneAccount : function(ieId, synch) {
2562 var node = SE.clickedFolderNode;
2563 if (node && !synch) {
2564 mbox = node.data.mbox;
2566 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2567 SE.accounts.ieIds = [ieId];
2568 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2569 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2574 * Empties trash for subscribed accounts
2576 emptyTrash : function() {
2577 SE.contextMenus.frameFoldersContextMenu.hide();
2578 SUGAR.showMessageBox(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2579 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2583 * Clears Cache files of the inboundemail account
2585 clearCacheFiles : function(ieId) {
2586 SE.contextMenus.frameFoldersContextMenu.hide();
2587 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2588 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2593 * Returns an array of all the active accounts in the folder view
2595 getIeIds : function() {
2597 var root = SE.tree.getRoot();
2598 for(i=0; i < root.children.length; i++) {
2599 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2600 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2601 ieIds.push(root.children[i].children[0].data.ieId);
2608 * loads folder lists in Settings->Folders
2610 lazyLoadSettings : function() {
2611 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2612 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2616 * After the add new folder is done via folders tab on seetings, this function should get called
2617 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2619 loadSettingFolder : function() {
2620 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2621 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2625 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2627 removeSugarFolders : function() {
2629 var root = tree.getRoot();
2630 var folder = SE.util.findChildNode(root, "ieId", "folder");
2632 tree.removeNode(folder);
2633 folder = SE.util.findChildNode(root, "ieId", "folder");
2635 if (!root.childrenRendered) {
2636 root.childrenRendered = true;
2640 rebuildFolders : function(silent) {
2641 if (!silent) SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2642 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2648 * Updates TreeView with Sugar Folders
2650 setSugarFolders : function(delay) {
2651 this.removeSugarFolders();
2652 //AjaxObject.forceAbort = true;
2653 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2657 * Takes async data object and creates the sugar folders in TreeView
2659 setSugarFoldersEnd : function(o) {
2660 var root = SE.tree.getRoot();
2661 addChildNodes(root, {nodes: o});
2662 SE.accounts.renderTree();
2663 //If nothing is loaded in the grid, load "My Inbox"
2664 if (SE.grid.params.ieId == "undefined") {
2665 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2669 startCheckTimer : function() {
2670 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2671 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2673 if(typeof(SE.folders.checkTimer) != 'undefined') {
2674 clearTimeout(SE.folders.checkTimer);
2677 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2678 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2680 SE.userPrefs.emailSettings.firstAutoCheck = true;
2681 SE.folders.checkEmailAccountsSilent(false);
2687 * makes an async call to save user preference and refresh folder view
2688 * @param object SELECT list object
2690 setFolderSelection : function() {
2691 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2693 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2694 var a_active_accnts = "";
2695 for(i=0;i<a_rs.length;i++)
2697 var t_record = a_rs[i];
2698 var is_active = t_record.getData('is_active');
2700 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2703 if(a_active_accnts == "")
2704 a_active_accnts = "&ieIdShow[]=";
2706 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2708 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2712 * makes async call to save user preference for a given node's open state
2713 * @param object node YUI TextNode object
2715 setOpenState : function(node) {
2716 SE.util.clearHiddenFieldValues('emailUIForm');
2717 var nodePath = node.data.id;
2718 var nodeParent = node.parent;
2720 while(nodeParent != null) {
2721 // root node has no ID param
2722 if(nodeParent.data != null) {
2723 nodePath = nodeParent.data.id + "::" + nodePath;
2726 var nodeParent = nodeParent.parent;
2729 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2730 document.getElementById('focusFolder').value = nodePath;
2732 if(node.expanded == true) {
2733 document.getElementById('focusFolderOpen').value = 'open';
2735 document.getElementById('focusFolderOpen').value = 'closed';
2738 var formObject = document.getElementById('emailUIForm');
2739 YAHOO.util.Connect.setForm(formObject);
2741 AjaxObject.startRequest(null, null);
2744 getNodeFromMboxPath : function(path) {
2745 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2746 var a = YAHOO.lang.JSON.parse(path);
2748 var node = tree.getRoot();
2751 while(i < a.length) {
2752 node = this.getChildNodeFromLabel(node, a[i]);
2759 getChildNodeFromLabel : function(node, nodeLabel) {
2760 for(i=0; i<node.children.length; i++) {
2761 if(node.children[i].data.id == nodeLabel) {
2762 return node.children[i];
2768 * returns the node that presumably under the user's right-click
2770 getNodeFromContextMenuFocus : function() {
2771 //// get the target(parent) node
2772 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2774 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2776 // filter local folders
2777 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2778 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2779 if(target.id == '') {
2780 target = target.parentNode;
2787 var targetNode = document.getElementById(target.id);
2788 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2791 var matches = re.exec(targetNode.id);
2793 return document.getElementById(ygtvlabelel1);
2799 // usually parent node
2800 matches = re.exec(targetNode.parentNode.id);
2807 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2808 parentNode.expand();
2814 * Decrements the Unread Email count in folder text
2815 * @param string ieId ID to look for
2816 * @param string mailbox name
2817 * @param count how many to decrement
2819 decrementUnreadCount : function(ieId, mbox, count) {
2824 if(mbox.indexOf("sugar::") === 0) {
2825 var node = this.getNodeFromId(ieId);
2827 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2830 var unseen = node.data.unseen;
2832 var check = unseen - count;
2833 var finalCount = (check >= 0) ? check : 0;
2834 node.data.unseen = finalCount;
2836 SE.accounts.renderTree();
2841 * gets the TreeView node with a given ID/ieId
2842 * @param string id ID to look for
2843 * @return object Node
2845 getNodeFromId : function(id) {
2846 SE.folders.focusNode = null;
2847 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2848 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2849 SE.folders.focusNode = this;
2853 return SE.folders.focusNode;
2857 * Uses ieId and mailbox to try to find a node in the tree
2859 getNodeFromIeIdAndMailbox : function(id, mbox) {
2860 SE.folders.focusNode = null;
2861 if (mbox == "sugar::Emails") {
2865 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2866 if (varsarray instanceof Array) {
2867 if (this.data.ieId && this.data.ieId == varsarray[0]
2868 && this.data.mbox == varsarray[1]) {
2869 SE.folders.focusNode = this;
2873 if (this.data.ieId && this.data.ieId == varsarray) {
2874 SE.folders.focusNode = this;
2878 }, null, [id, mbox]);
2879 return SE.folders.focusNode;
2882 unhighliteAll : function() {
2883 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2887 * Displays a short form
2889 folderAdd : function() {
2890 SE.contextMenus.frameFoldersContextMenu.hide();
2892 var node = SE.clickedFolderNode;
2894 if(node != null && node.data) {
2895 SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2896 app_strings.LBL_EMAIL_SETTINGS_NAME,
2897 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2899 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2903 folderAddRegisterEnter : function() {
2904 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2905 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2906 this.buttons[1].handler);
2908 this.enterKeyListener.enable();
2911 folderRemoveRegisterEnter : function() {
2912 this.enterKeyListener.disable();
2915 folderAddXmlCall : function(name) {
2916 if (trim(name) == "") {
2917 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2920 name = escape(name);
2924 var parentNode = SE.clickedFolderNode;
2926 this.contextMenuFocus = parentNode;
2928 if(parentNode.data.ieId) {
2929 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2933 if(type == 'imap') {
2934 // make an IMAP folder
2935 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2936 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2937 } else if(type == 'sugar') {
2938 // make a Sugar folder
2939 if(SE.folders.isUniqueFolderName(name)) {
2940 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2941 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2943 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2944 SE.folders.folderAdd();
2948 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2951 // hide add-folder diaglogue
2952 SE.e2overlay.hide();
2956 * Removes either an IMAP folder or a Sugar Folder
2958 folderDelete : function() {
2959 SE.contextMenus.frameFoldersContextMenu.hide();
2961 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2963 var parentNode = SE.clickedFolderNode;
2965 if(parentNode != null && parentNode.data) {
2966 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2967 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2971 AjaxObject.target = 'frameFlex';
2973 if(parentNode.data.ieId != 'folder') {
2974 // delete an IMAP folder
2975 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2977 // delete a sugar folder
2978 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2980 SUGAR.showMessageBox("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2981 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2983 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2989 * Rename folder form
2992 folderRename : function() {
2993 SE.contextMenus.frameFoldersContextMenu.hide();
2994 var node = SE.clickedFolderNode;
2997 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2998 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
3002 SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
3003 app_strings.LBL_EMAIL_SETTINGS_NAME,
3005 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
3007 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
3012 * fills an Object with key-value pairs of available folders
3014 getAvailableFoldersObject : function() {
3015 var ret = new Object();
3016 var tree = SE.tree.root;
3019 for(var i=0; i<tree.children.length; i++) {
3020 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3023 ret['none'] = app_strings.LBL_NONE;
3030 * Fills in key-value pairs for dependent dropdowns
3031 * @param object ret Associative array
3032 * @param object node TreeView node in focus
3033 * @param string currentPath Built up path thus far
3034 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3036 getFolderFromChild : function(ret, node, currentPath, spacer) {
3037 if(node.data != null && node.depth > 0) {
3038 /* handle visual separtors differentiating b/t mailserver and local */
3039 if(node.data.ieId && node.data.ieId == 'folder') {
3040 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3044 ret['spacer0'] = spacer;
3045 } else if(ret.spacer0 != spacer) {
3046 ret['spacer1'] = spacer
3049 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3050 var depthMarker = currentPath;
3051 var retIndex = SE.folders._createFolderId(node);
3052 ret[retIndex] = depthMarker + theLabel;
3055 if(node.children != null) {
3057 currentPath += theLabel + "/";
3060 for(var i=0; i<node.children.length; i++) {
3061 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3069 * Wrapper to refresh folders tree
3071 getFolders : function() {
3072 SE.accounts.rebuildFolderList();
3076 * handles events around folder-rename input field changes
3077 * @param object YUI event object
3079 handleEnter : function(e) {
3080 switch(e.browserEvent.type) {
3082 e.preventDefault(); // click in text field
3086 SE.folders.submitFolderRename(e);
3090 var kc = e.browserEvent.keyCode;
3094 SE.folders.submitFolderRename(e);
3098 e.preventDefault(e);
3099 SE.folders.cancelFolderRename(e);
3106 * Called when a node is clicked on in the folder tree
3107 * @param node, The node clicked on
3108 * @param e, The click event
3110 handleClick : function(o) {
3112 //If the click was on a sugar folder
3113 if (node.data.ieId == "folder") {
3114 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3117 SE.listView.populateListFrame(node, node.data.ieId, false);
3119 //eval(node.data.click);
3124 * Called when a node is right-clicked on in the folder tree
3126 handleRightClick : function(e) {
3127 YAHOO.util.Event.preventDefault(e);
3129 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3130 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3132 //If the click was on a sugar folder
3133 SE.clickedFolderNode = node;
3134 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3135 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3136 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3137 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3138 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3139 menu.getItem(3).cfg.setProperty("disabled", false);
3140 menu.getItem(4).cfg.setProperty("disabled", false);
3141 menu.getItem(5).cfg.setProperty("disabled", false);
3142 menu.getItem(6).cfg.setProperty("disabled", true);
3144 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3145 menu.getItem(0).cfg.setProperty("disabled", true);
3146 menu.getItem(1).cfg.setProperty("disabled", true);
3147 menu.getItem(2).cfg.setProperty("disabled", true);
3148 menu.getItem(3).cfg.setProperty("disabled", true);
3149 menu.getItem(4).cfg.setProperty("disabled", true);
3151 if (node.data.protocol != null) {
3152 menu.getItem(6).cfg.setProperty("disabled", false);
3154 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3155 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3156 //Sent or Draft folders
3157 menu.getItem(3).cfg.setProperty("disabled", true);
3158 menu.getItem(4).cfg.setProperty("disabled", true);
3159 menu.getItem(5).cfg.setProperty("disabled", true);
3162 //For group with auto inbound, disable everything.
3163 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3165 menu.getItem(0).cfg.setProperty("disabled", true);
3166 menu.getItem(1).cfg.setProperty("disabled", true);
3167 menu.getItem(2).cfg.setProperty("disabled", true);
3168 menu.getItem(3).cfg.setProperty("disabled", true);
3169 menu.getItem(4).cfg.setProperty("disabled", true);
3170 menu.getItem(5).cfg.setProperty("disabled", true);
3171 menu.getItem(6).cfg.setProperty("disabled", true);
3174 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3179 * Called when a row is dropped on a node
3181 handleDrop : function(rows, targetFolder) {
3182 var rowData = rows[0].getData();
3183 if (rowData.mbox != targetFolder.data.mbox) {
3184 var srcIeId = rowData.ieId;
3185 var srcFolder = rowData.mbox;
3186 var destIeId = targetFolder.data.ieId;
3187 var destFolder = targetFolder.data.mbox;
3189 for(var i=0; i<rows.length; i++) {
3190 uids[i] = rows[i].getData().uid;
3192 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3197 * Called when something is dragged over a Folder Node
3199 dragOver : function(dragObject) {
3204 * Determines if a folder name is unique to the folder tree
3205 * @param string name
3207 isUniqueFolderName : function(name) {
3208 uniqueFolder = true;
3209 var root = SE.tree.getRoot();
3210 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3211 if (this.attributes && this.attributes.ieId == "folder") {
3212 if (this.attributes.text == name) {
3213 uniqueFolder = false;
3218 return uniqueFolder;
3222 * Makes async call to rename folder in focus
3223 * @param object e Event Object
3225 submitFolderRename : function(newName) {
3226 if (trim(newName) == "") {
3227 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3230 newName = escape(newName);
3231 var node = SE.clickedFolderNode;
3232 var origName = node.data.text
3234 if (newName == origName) {
3237 if(SE.folders.isUniqueFolderName(newName)) {
3238 SUGAR.showMessageBox(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3239 if (node.data.ieId == "folder") {
3241 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3244 //IMAP folder or POP mailbox
3245 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3246 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3247 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3251 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3256 moveFolder : function(folderId, parentFolderId) {
3257 if (folderId != parentFolderId)
3259 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3260 + folderId + "&newParentId=" + parentFolderId);
3265 * makes async call to do a full synchronization of all accounts
3267 synchronizeAccounts : function() {
3268 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3269 SUGAR.showMessageBoxModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3270 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3275 * Updates user's folder subscriptsion (Sugar only)
3276 * @param object SELECT DOM object in focus
3277 * @param string type of Folder selection
3279 updateSubscriptions : function() {
3280 SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3284 select = document.getElementById('userFolders');
3286 for(i=0; i<select.options.length; i++) {
3287 var opt = select.options[i];
3288 if(opt.selected && opt.value != "") {
3292 active += opt.value;
3296 //Add the group folder ids.
3297 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3298 for(i=0; i<group_folders.length; i++)
3300 active += ("::" + group_folders[i]);
3303 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3306 * Updates user's group folder subscriptsion (Sugar only)
3307 * @param ieID The group folder to add to the tree view
3309 retrieveGroupFolderSubscriptions : function() {
3311 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3312 var activeGroupFolders = "";
3313 var activeGroupIds = [];
3314 for(i=0;i<a_rs.length;i++)
3316 var t_record = a_rs[i];
3317 var is_active = t_record.getData('is_active');
3318 var isGroupFolder = t_record.getData('has_groupfolder');
3319 var ieID = t_record.getData('id');
3323 activeGroupIds.push(ieID);
3327 return activeGroupIds;
3332 SE.folders.checkEmail2 = function() {
3333 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3335 //// END FOLDERS OBJECT
3336 ///////////////////////////////////////////////////////////////////////////////
3339 ///////////////////////////////////////////////////////////////////////////////
3342 * Keypress Event capture and processing
3345 overall : function(e) {
3346 switch(e.charCode) {
3348 if(e.ctrlKey || e.altKey) {
3349 var focusRegion = SE.innerLayout.regions.center;
3350 if(focusRegion.activePanel.closable == true) {
3351 focusRegion.remove(focusRegion.activePanel);
3359 ///////////////////////////////////////////////////////////////////////////////
3362 ///////////////////////////////////////////////////////////////////////////////
3365 * ListView object methods and attributes
3371 * Fills the ListView pane with detected messages.
3373 populateListFrame : function(node, ieId, forceRefresh) {
3374 SE.innerLayout.selectTab(0);
3375 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3377 Dom.get('_blank').innerHTML = "";
3378 SE.grid.params['emailUIAction'] = 'getMessageList';
3379 SE.grid.params['mbox'] = node.data.mbox;
3380 SE.grid.params['ieId'] = ieId;
3381 forcePreview = true; // loads the preview pane with first item in grid
3382 SE.listView.refreshGrid();
3386 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3388 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3389 SE.innerLayout.selectTab(0);
3390 Dom.get('_blank').innerHTML = "";
3391 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3392 SE.grid.params['ieId'] = node.data.id;
3393 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3394 SE.listView.refreshGrid();
3398 * Sets sort order as user preference
3401 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3403 ieName = ieNamePassed;
3404 focusFolder = focusFolderPassed;
3406 SE.util.clearHiddenFieldValues('emailUIForm');
3407 var previousSort = document.getElementById('sortBy').value;
3409 document.getElementById('sortBy').value = sortBy;
3410 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3411 document.getElementById('focusFolder').value = focusFolder;
3412 document.getElementById('ieId').value = ieId;
3414 if(sortBy == previousSort) {
3415 document.getElementById('reverse').value = '1';
3418 var formObject = document.getElementById('emailUIForm');
3419 YAHOO.util.Connect.setForm(formObject);
3421 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3426 * Enables click/arrow select of grid items which then populate the preview pane.
3428 selectFirstRow : function() {
3429 SE.grid.selModel.selectFirstRow();
3432 selectLastRow : function() {
3433 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3436 setEmailListStyles : function() {
3437 SE.listView.boldUnreadRows();
3439 var ds = SE.grid.getStore();
3440 if (SE.grid.getSelections().length == 0) {
3441 document.getElementById('_blank').innerHTML = '';
3445 if(typeof(ds.baseParams.mbox) != 'undefined') {
3446 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3447 var cm = SE.grid.getColumnModel();
3448 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3449 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3451 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3452 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3456 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3457 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3459 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3460 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3461 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3462 if (node) node.data.unseen = unread;
3464 SE.accounts.renderTree();
3467 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3468 if(forcePreview && ds.totalCount > 0) {
3469 SE.detailView.getEmailPreview();
3470 forcePreview = false;
3475 * Removes a row if found via its UID
3477 removeRowByUid : function(uid) {
3478 uid = new String(uid);
3479 uids = uid.split(',');
3480 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3482 for(j=0; j<uids.length; j++) {
3483 var theUid = uids[j];
3484 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3485 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3486 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3492 displaySelectedEmails : function(rows) {
3493 var dm = SE.grid.getDataModel();
3496 for(i=0; i<rows.length; i++) {
3497 var rowIndex = rows[i].rowIndex;
3498 var metadata = dm.data[rowIndex];
3503 uids += metadata[5];
3505 // unbold unseen email
3506 this.unboldRow(rowIndex);
3509 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3513 * exception handler for data load failures
3515 loadException : function(dataModel, ex, response) {
3520 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3521 * @param string sourceIeId Email's source I-E id
3522 * @param string sourceFolder Email's current folder
3523 * @param destinationIeId Destination I-E id
3524 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3526 * @param array emailUids Array of email's UIDs
3528 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3529 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3530 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3532 SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3533 // remove rows from visibility
3534 for(row in selectedRows) {
3535 //SE.grid.getStore().remove(row);
3538 var baseUrl = '&sourceIeId=' + sourceIeId +
3539 '&sourceFolder=' + sourceFolder +
3540 '&destinationIeId=' + destinationIeId +
3541 '&destinationFolder=' + destinationFolder;
3544 for(i=0; i<emailUids.length; i++) {
3546 uids += app_strings.LBL_EMAIL_DELIMITER;
3548 uids += emailUids[i];
3550 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3551 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3553 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3559 * Unbolds text in the grid view to denote read status
3561 markRead : function(index, record) {
3562 // unbold unseen email
3563 var row = SE.grid.getRecord(record);
3564 row.getData().seen = 1;
3565 SE.grid.getTrEl(record).style.fontWeight = "normal";
3569 * grid row output, bolding unread emails
3571 boldUnreadRows : function() {
3572 // bold unread emails
3573 var trEl = SE.grid.getFirstTrEl();
3574 while(trEl != null) {
3575 if(SE.grid.getRecord(trEl).getData().seen == "0")
3576 trEl.style.fontWeight = "bold";
3578 trEl.style.fontWeight = "";
3579 trEl = SE.grid.getNextTrEl(trEl);
3584 * Show preview for an email if 1 and only 1 is selected
3585 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3587 handleRowSelect : function(e) {
3588 if(e.selectedRows.length == 1) {
3589 SE.detailView.getEmailPreview();
3593 handleDrop : function(e, dd, targetId, e2) {
3595 case 'htmleditordiv':
3596 var rows = SE.grid.getSelectedRows();
3597 if(rows.length > 0) {
3598 SE.listView.displaySelectedEmails(rows);
3603 var targetElId = new String(targetId);
3604 var targetIndex = targetElId.replace('ygtvlabelel',"");
3605 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3606 var dm = SE.grid.getDataModel();
3607 var emailUids = new Array();
3608 var destinationIeId = targetNode.data.ieId;
3609 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3612 var rows = SE.grid.getSelectedRows();
3613 // iterate through dragged rows
3614 for(i=0; i<rows.length; i++) {
3615 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3616 var rowIndex = rows[i].rowIndex;
3617 var dataModelRow = dm.data[rowIndex];
3618 var sourceIeId = dataModelRow[7];
3619 var sourceFolder = dataModelRow[6];
3620 emailUids[i] = dataModelRow[5];
3623 // event wrapped call - need FQ
3624 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3625 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3631 * Hack-around to get double-click and single clicks to work on the grid
3632 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3634 handleClick : function(o) {
3635 SUGAR.email2.grid.clearTextSelection();
3637 var el = SUGAR.email2.grid.getSelectedRows();
3639 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3640 if ( el.length == 1)
3643 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3644 SUGAR.email2.listView.currentRowIndex = rowId;
3645 clearTimeout(SUGAR.email2.detailView.previewTimer);
3646 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3651 * Custom handler for double-click/enter
3652 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3654 getEmail : function(e) {
3655 var rows = SE.grid.getSelectedRows();
3656 var row = SE.grid.getRecord(rows[0]).getData();
3658 clearTimeout(SE.detailView.previewTimer);
3659 document.getElementById("_blank").innerHTML = "";
3661 if(row.type != "draft") {
3662 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3664 // circumventing yui-ext tab generation, let callback handler build new view
3665 SE.util.clearHiddenFieldValues('emailUIForm');
3666 //function(uid, mbox, ieId, setRead, destination) {
3667 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3668 document.getElementById('uid').value = row.uid; // uid;
3669 document.getElementById('mbox').value = row.mbox; // mbox;
3670 document.getElementById('ieId').value = row.ieId; // ieId;
3672 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3673 AjaxObject.target = '_blank';
3674 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3679 * Retrieves a row if found via its UID
3683 getRowIndexByUid : function(uid) {
3684 uid = new String(uid);
3685 uids = uid.split(',');
3687 for(j=0; j<uids.length; j++) {
3688 var theUid = uids[j];
3690 for(i=0; i<SE.grid.getStore().data.length; i++) {
3691 if(SE.grid.getStore().data[i].id == theUid) {
3699 * Returns the UID's of the seleted rows
3702 getUidsFromSelection : function() {
3703 var rows = SE.grid.getSelectedRows();
3705 /* iterate through available rows JIC a row is deleted - use first available */
3706 for(var i=0; i<rows.length; i++) {
3707 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3712 refreshGrid : function() {
3713 SE.grid.getDataSource().sendRequest(
3714 SUGAR.util.paramsToUrl(SE.grid.params),
3715 SE.grid.onDataReturnInitializeTable,
3721 //// END SE.listView
3722 ///////////////////////////////////////////////////////////////////////////////
3724 ///////////////////////////////////////////////////////////////////////////////
3728 * sends search criteria
3729 * @param reference element search field
3731 search : function(el) {
3732 var searchCriteria = new String(el.value);
3734 if(searchCriteria == '') {
3735 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3739 var safeCriteria = escape(searchCriteria);
3741 var accountListSearch = document.getElementById('accountListSearch');
3743 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3744 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3745 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3746 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3747 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3752 * sends advanced search criteria
3754 searchAdvanced : function() {
3755 var formObject = document.getElementById('advancedSearchForm');
3758 //Set assigned user id to blank if name is not present.
3759 if (formObject.elements['assigned_user_name'].value == "")
3760 formObject.elements['assigned_user_id'].value = "";
3762 for(i=0; i<formObject.elements.length; i++) {
3763 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3766 if(formObject.elements[i].type == 'text') {
3767 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3769 if(formObject.elements[i].type == 'hidden') {
3770 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3772 if(formObject.elements[i].type == 'select-one') {
3773 var el = formObject.elements[i];
3774 var v = el.options[el.selectedIndex].value;
3777 SE.grid.params[el.name] = v;
3780 //Clear previous search results if necessary
3781 if(typeof( SE.grid.params[el.name]) != 'undefined')
3782 delete SE.grid.params[el.name]
3789 if(! this.validateSearchFormInput() )
3792 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3793 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3794 var accountListSearch = document.getElementById('accountListSearch');
3795 SE.listView.refreshGrid();
3797 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3802 * Validates the search form inputs to ensure all parameters are valid
3805 validateSearchFormInput: function()
3807 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3808 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3809 var dateCheck = check_form('advancedSearchForm');
3811 //If the parent type is selected ensure the user selected a parent_id.
3812 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3818 * Toggles the advanced options, either hidding or showing the selection.
3820 toggleAdvancedOptions: function()
3822 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3824 for(var i=0;i<el.length;i++)
3826 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3827 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3829 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3833 * clears adv search form fields
3835 searchClearAdvanced : function() {
3836 var form = document.getElementById('advancedSearchForm');
3838 for(i=0; i<form.elements.length; i++) {
3839 if(form.elements[i].type != 'button') {
3840 form.elements[i].value = '';
3846 //////////////////////////////////////////////////////////////////////////////
3849 //////////////////////////////////////////////////////////////////////////////
3852 /******************************************************************************
3853 * USER SIGNATURES calls stolen from Users module
3854 *****************************************************************************/
3855 createSignature : function(record, the_user_id) {
3856 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3858 URL += "&record="+record;
3860 if(the_user_id != "") {
3861 URL += "&the_user_id="+the_user_id;
3863 var windowName = 'email_signature';
3864 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3866 var win = window.open(URL, windowName, windowFeatures);
3867 if(win && win.focus) {
3868 // put the focus on the popup if the browser supports the focus() method
3873 deleteSignature : function() {
3874 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3875 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3876 var singature_id = document.getElementById('signature_id').value;
3877 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3881 saveOptionsGeneral : function(displayMessage) {
3882 var formObject = document.getElementById('formEmailSettingsGeneral');
3883 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3884 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3887 YAHOO.util.Connect.setForm(formObject);
3888 SE.composeLayout.emailTemplates = null;
3890 AjaxObject.target = 'frameFlex';
3891 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3894 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3896 SE.settings.settingsDialog.hide();
3900 * Shows settings container screen
3902 showSettings : function() {
3903 if(!SE.settings.settingsDialog) {
3904 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3910 constraintoviewport: true
3912 dlg.showEvent.subscribe( function (){
3913 var el = this.element;
3914 var viewH = YAHOO.util.Dom.getViewportHeight();
3915 if (this.header && el && viewH - 50 < el.clientHeight) {
3916 var body = this.header.nextElementSibling;
3917 body.style.overflow = "auto";
3918 body.style.height = (viewH - 50) + "px";
3921 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3922 dlg.setBody('<div id="settingsTabDiv"/>');
3923 dlg.beforeRenderEvent.subscribe(function() {
3924 var dd = new YAHOO.util.DDProxy(dlg.element);
3925 dd.setHandleElId(dlg.header);
3926 dd.on('endDragEvent', function() {
3932 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3933 var tabContent = Dom.get("tab_general");
3934 tp.addTab(new YAHOO.widget.Tab({
3935 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3937 content : tabContent.innerHTML,
3938 id : "generalSettings",
3941 tabContent.parentNode.removeChild(tabContent);
3942 tabContent = Dom.get("tab_accounts");
3943 var accountTab = new YAHOO.widget.Tab({
3944 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3946 content : tabContent.innerHTML,
3947 id : "accountSettings"
3949 tp.addTab(accountTab);
3950 tabContent.parentNode.removeChild(tabContent);
3952 tp.appendTo(dlg.body);
3955 SE.settings.settingsDialog.show();
3956 SE.folders.lazyLoadSettings();
3957 SE.accounts.lazyLoad();
3961 lazyLoadRules : function() {
3962 if(false/*!SE.settings.rules*/) {
3963 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3968 //// END SE.settings
3969 ///////////////////////////////////////////////////////////////////////////////
3972 /******************************************************************************
3974 *****************************************************************************/
3975 function removeHiddenNodes(nodes, grid) {
3977 for(var i = nodes.length - 1; i > -1; i--) {
3978 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3979 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3985 function strpad(val) {
3986 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3989 function refreshTodos() {
3990 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3991 AjaxObject.target = 'todo';
3992 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3995 /******************************************************************************
3996 * MUST STAY IN GLOBAL NAMESPACE
3997 *****************************************************************************/
3998 function refresh_signature_list(signature_id, signature_name) {
3999 var field=document.getElementById('signature_id');
4001 for (var i=0; i < field.options.length; i++) {
4002 if (field.options[i].value == signature_id) {
4003 if (field.options[i].selected==false) {
4004 field.options[i].selected=true;
4009 //add item to selection list.
4011 var newElement=document.createElement('option');
4012 newElement.text=signature_name;
4013 newElement.value=signature_id;
4014 field.options.add(newElement);
4015 newElement.selected=true;
4018 //enable the edit button.
4019 var field1=document.getElementById('edit_sig');
4020 field1.style.visibility="inherit";
4021 var deleteButt = document.getElementById('delete_sig');
4022 deleteButt.style.visibility="inherit";
4025 function setDefaultSigId(id) {
4026 var checkbox = document.getElementById("signature_default");
4027 var default_sig = document.getElementById("signatureDefault");
4029 if(checkbox.checked) {
4030 default_sig.value = id;
4032 default_sig.value = "";
4036 function setSigEditButtonVisibility() {
4037 var field = document.getElementById('signature_id');
4038 var editButt = document.getElementById('edit_sig');
4039 var deleteButt = document.getElementById('delete_sig');
4040 if(field.value != '') {
4041 editButt.style.visibility = "inherit";
4042 deleteButt.style.visibility = "inherit";
4044 editButt.style.visibility = "hidden";
4045 deleteButt.style.visibility = "hidden";
4047 }// End of File modules/Emails/javascript/EmailUI.js
4049 /*********************************************************************************
4050 * SugarCRM Community Edition is a customer relationship management program developed by
4051 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4053 * This program is free software; you can redistribute it and/or modify it under
4054 * the terms of the GNU Affero General Public License version 3 as published by the
4055 * Free Software Foundation with the addition of the following permission added
4056 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4057 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4058 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4060 * This program is distributed in the hope that it will be useful, but WITHOUT
4061 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4062 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4065 * You should have received a copy of the GNU Affero General Public License along with
4066 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4067 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4070 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4071 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4073 * The interactive user interfaces in modified source and object code versions
4074 * of this program must display Appropriate Legal Notices, as required under
4075 * Section 5 of the GNU Affero General Public License version 3.
4077 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4078 * these Appropriate Legal Notices must retain the display of the "Powered by
4079 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4080 * technical reasons, the Appropriate Legal Notices must display the words
4081 * "Powered by SugarCRM".
4082 ********************************************************************************/
4085 var sw = YAHOO.SUGAR,
4086 Event = YAHOO.util.Event,
4087 Connect = YAHOO.util.Connect,
4088 Dom = YAHOO.util.Dom
4091 ///////////////////////////////////////////////////////////////////////////////
4094 _contactCache : new Array(), // cache of contacts
4095 _dd : new Array(), // filtered list, same format as _contactCache
4096 _ddLists : new Array(), // list of Lists
4097 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4098 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4099 clickBubble : true, // hack to get around onclick event bubbling
4101 relatedBeanType : '',
4104 itemSpacing : 'white-space:nowrap; padding:2px;',
4110 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4112 initFixForDatatableSort: function () {
4113 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4114 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4115 var oColumn = this._oColumnSet.getColumn(column);
4118 // Validate TD element
4119 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4121 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4123 // Validate TH element
4125 elCell = this.getThEl(column);
4128 var allColumns = this._oColumnSet.flat;
4129 for(var i=0, len=allColumns.length; i<len; i++) {
4130 if(allColumns[i].getThEl().id === elCell.id) {
4131 oColumn = allColumns[i];
4142 cancelEdit : function() {
4143 if(this.editContactDialog)
4144 this.editContactDialog.hide();
4145 if(this.editMailingListDialog)
4146 this.editMailingListDialog.hide();
4150 * Clears filter form
4152 clear : function() {
4153 var t = document.getElementById('contactsFilter');
4159 * handle context-menu Compose-to call
4160 * @param string type 'contacts' or 'lists'
4162 composeTo : function(type, waited) {
4163 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4164 if (activePanel.substring(0, 10) != "composeTab") {
4165 SE.composeLayout.c0_composeNewEmail();
4166 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4167 SE.contextMenus.contactsContextMenu.hide();
4170 var idx = activePanel.substring(10);
4173 // determine if we have a selection to work with
4174 if(type == 'contacts') {
4175 var ids = SE.contactView.getSelectedRows();
4176 for (var i in ids) {
4177 rows[i] = SE.contactView.getRecord(ids[i]);
4179 removeHiddenNodes(rows, SE.contactView);
4183 if(rows.length > 0) {
4184 SE.composeLayout.handleDrop(
4185 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4186 null, rows, 'addressTO' + idx );
4188 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4192 editContact : function() {
4193 SE.contextMenus.contactsContextMenu.hide();
4194 var element = SE.contactView.getSelectedNodes()[0];
4196 if (element.className.indexOf('address-contact') > -1) {
4197 elementId = element.id;
4198 } else if (element.className.indexOf('address-exp-contact') > -1) {
4199 elementId = element.id.substring(2);
4205 * Filters contact entries based on user input
4207 filter : function(inputEl) {
4208 var ret = new Object();
4209 var re = new RegExp(inputEl.value, "gi");
4211 for(var i in this._contactCache) {
4212 if(this._contactCache[i].name.match(re)) {
4213 ret[i] = this._contactCache[i];
4217 this.buildContactList(ret);
4220 fullForm : function(id, module) {
4221 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4225 * returns a formatted email address from the addressBook cache
4227 getFormattedAddress : function(id) {
4228 var o = this._contactCache[id];
4229 var primaryEmail = '';
4231 for(var i=0; i<o.email.length; i++) {
4232 var currentEmail = o.email[i].email_address;
4234 if(o.email[i].primary_address == 1) {
4235 primaryEmail = o.email[i].email_address;
4239 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4240 var name = new String(o.name);
4241 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4242 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4248 * Sets up async call to query for matching contacts, users, etc.
4250 searchContacts : function() {
4251 var fn = document.getElementById('input_searchField').value;
4252 var pe = document.getElementById('input_searchPerson').value;
4254 var rb = document.getElementById('hasRelatedBean').checked;
4257 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4258 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4259 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4260 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4262 this.addressBookDataModel.params['related_bean_id'] = '';
4265 this.addressBookDataModel.params['search_field'] = fn;
4266 this.addressBookDataModel.params['person'] = pe;
4267 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4268 this.grid._oDataSource = this.addressBookDataModel;
4269 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4273 * Clear Search Crieteria For Addressbook
4275 clearAddressBookSearch : function() {
4276 document.getElementById('input_searchField').value = "";
4277 document.getElementById('input_searchPerson').selectedIndex = 0;
4281 * Opens modal select window to add contacts to addressbook
4283 selectContactsDialogue : function(destId) {
4284 if(!this.contactsDialogue) {
4285 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4289 constraintoviewport: true,
4291 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4292 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4294 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4296 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4297 dlg.setBody(body.innerHTML);
4298 dlg.renderEvent.subscribe(function() {
4299 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4300 if (iev && !SUGAR.isIE) {
4301 this.body.style.width = "950px";
4306 dlg.beforeRenderEvent.subscribe(function() {
4307 var dd = new YAHOO.util.DDProxy(dlg.element);
4308 dd.setHandleElId(dlg.header);
4309 dd.on('endDragEvent', function() {
4315 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4317 var tabContent = SUGAR.util.getAndRemove("searchForm");
4318 tp.addTab(new YAHOO.widget.Tab({
4319 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4321 content : tabContent.innerHTML,
4322 id : "addressSearchTab",
4326 var addListenerFields = ['input_searchPerson','input_searchField' ]
4327 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4328 if (e.keyCode == 13) {
4329 YAHOO.util.Event.stopEvent(e);
4330 SUGAR.email2.addressBook.searchContacts();
4334 this.contactsDialogue.render();
4337 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4338 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4342 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4343 var idx = activePanel.substring(10);
4345 SE.addressBook.idx = idx;
4348 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4349 document.getElementById('relatedBeanColumn').style.display = '';
4350 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4351 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4352 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4353 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4354 SE.addressBook.relatedBeanType = relatedBeanType;
4356 document.getElementById('relatedBeanColumn').style.display = 'none';
4357 document.getElementById('hasRelatedBean').checked = false;
4360 if (!SE.addressBook.grid)
4362 if (hasRelatedBeanId) {
4363 document.getElementById('hasRelatedBean').checked = true;
4365 AddressSearchGridInit();
4366 SE.addressBook.relatedBeanId = relatedBeanId;
4370 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4372 SE.addressBook.relatedBeanId = relatedBeanId;
4373 document.getElementById('hasRelatedBean').checked = true;
4375 if (document.getElementById('hasRelatedBean').checked == true)
4377 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4378 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4380 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4381 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4383 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4384 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4385 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4388 //Remove any lingering rows in the result set table if the module was closed.
4389 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4391 SE.addressBook.populateResulstTableEmailAddresses();
4393 this.contactsDialogue.show();
4396 * Clear all email addresses from result table.
4399 clearAllEmailAddressFieldsFromResultTable: function () {
4400 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4401 //Unhighlight any rows currently selected if the emails were cleared.
4402 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4403 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4406 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4407 * results table. This function is called when the address book is displayed.
4409 populateResulstTableEmailAddresses: function () {
4411 var idx = SE.addressBook.idx;
4412 var emailFields = ['to','cc','bcc'];
4414 for(var k=0;k<emailFields.length;k++)
4416 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4417 var allEmails = document.getElementById(elKey).value;
4421 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4423 for (var i=0; i<formatedEmails.length; i++)
4425 var t_name = formatedEmails[i].name;
4426 var t_emailAddr = formatedEmails[i].email_address;
4427 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4429 t_name = displayEmail = t_emailAddr;
4431 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4432 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4433 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4439 * Checks all entries in the result table against a particular email address, returning true
4440 * if the email address is found, false otherwise.
4442 doesEmailAdddressExistInResultTable: function(emailAddress)
4444 if(trim(emailAddress) == '')
4447 var emailAddressFound = false;
4448 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4449 for (var i=0; i < contacts.length; i++)
4451 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4452 //If we are adding to cc or bcc fields, make them visible.
4453 if(data.email_address == emailAddress)
4455 emailAddressFound = true;
4460 return emailAddressFound;
4463 * Takes all email addresses that the users wishes to add from the address book and populates the To
4464 * fields on the compose tab.
4466 populateEmailAddressFieldsFromResultTable: function()
4468 //Clear the fields first, all email addresses are stored in the address book
4469 var idx = SE.addressBook.idx;
4470 var emailFields = ['to','cc','bcc'];
4471 for(var k=0;k<emailFields.length;k++)
4473 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4474 document.getElementById(elKey).value = "";
4477 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4478 for (var i=0; i < contacts.length; i++)
4480 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4482 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4483 //If we are adding to cc or bcc fields, make them visible.
4484 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4485 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4486 //Construct the target id
4487 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4489 var target = document.getElementById(target_id);
4490 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4493 //Delete all rows from the result set table
4494 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4497 SE.addressBook.contactsDialogue.hide()
4500 * Insert contacts into the result table.
4502 insertContactToResultTable : function(event,address_type) {
4504 var contactsDialogue = SE.addressBook.contactsDialogue;
4505 var contacts = SE.addressBook.grid.getSelectedRows();
4507 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4508 for (var i = 0; i < rows.length; i++)
4510 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4512 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4513 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4514 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4515 rows[i].setData("selected",true);
4518 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4519 for (var i = 0; i < checkBoxes.length; i++) {
4520 checkBoxes[i].checked = false;
4526 insertContactRowToResultTable : function(rowId, addressType) {
4527 var data = SE.addressBook.grid.getRecord(rowId).getData();
4528 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4530 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4531 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4532 if(addressType == null)
4533 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4534 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});
4537 * Remove a row from the gridsResult table.
4539 removeRowFromGridResults : function(rowId,emailAddress)
4541 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4542 for (var i=0; i < contacts.length; i++)
4544 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4545 var data = rec.getData();
4546 if(data.email_address == emailAddress)
4548 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4553 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4556 * Translates between the addressType To|Cc|Bcc labels/keys.
4558 translateAddresType: function(addressType,fromKey)
4560 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4561 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4562 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4563 var mappingObject = {};
4566 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4569 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4570 mappingObject[displayCc] = 'cc';
4571 mappingObject[displayBcc] = 'bcc';
4574 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4580 toggleSearchRowIcon : function(rowId,show)
4584 var idToShow = rowId + '_add_img';
4585 var idToHide = rowId + '_rm_img';
4589 var idToShow = rowId + '_rm_img';
4590 var idToHide = rowId + '_add_img';
4594 Dom.addClass(idToHide, "yui-hidden");
4595 Dom.removeClass(idToShow, "yui-hidden");
4598 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4600 doesGridResultsEntryExist: function(emailAddrs)
4603 var contactExists = false;
4604 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4605 for (var i=0; i < contacts.length; i++)
4607 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4608 if(data.email_address == emailAddrs)
4610 contactExists = true;
4614 return contactExists;
4618 * adds an email address to a string, but first checks if it exists
4619 * @param string concat The string we are appending email addresses to
4620 * @param string addr Email address to add
4623 smartAddEmailAddressToComposeField : function(concat, addr) {
4624 var re = new RegExp(addr);
4626 if(!concat.match(re)) {
4628 concat += "; " + addr;
4637 //// END ADDRESS BOOK
4638 ///////////////////////////////////////////////////////////////////////////////
4642 ///////////////////////////////////////////////////////////////////////////////
4645 * Auto-complete object
4649 delimChar : [";", ","],
4653 prehighlightClassName : "yui-ac-prehighlight",
4656 instances : new Array(),
4659 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4660 * @param object Contact from AddressBook
4663 getPrimaryAddress : function(contact) {
4664 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4666 for(var eIndex in contact.email) {
4667 address = contact.email[eIndex].email_address;
4668 if(contact.email[eIndex].primary_address == 1) {
4669 return contact.email[eIndex].email_address;
4677 * initializes autocomplete widgets for a given compose view
4680 init : function(idx) {
4681 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4682 "queryMatchContains" : false,
4683 "queryMatchSubset" : true
4686 this.instances[idx] = {
4693 // instantiate the autoComplete widgets
4694 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4695 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4696 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4698 // enable hiding of interfering textareas
4699 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4700 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4701 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4703 // enable reshowing of hidden textareas
4704 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4705 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4706 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4708 // enable refreshes of contact lists
4709 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4710 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4711 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4714 refreshDataSource : function(sType, aArgs) {
4715 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4717 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4719 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4720 idx = textBoxId.substr(9);
4722 idx = textBoxId.substr(10);
4725 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4726 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4727 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4731 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4733 returnDataSource : function(contacts) {
4734 var ret = new Array();
4735 for(var id in contacts) {
4736 if (contacts[id].name) {
4737 var primary = this.getPrimaryAddress(contacts[id]);
4739 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4740 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4742 for(var emailIndex in contacts[id].email) {
4743 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4752 * Hides address textareas to prevent autocomplete dropdown from being obscured
4754 toggleTextareaHide : function(sType, aArgs) {
4755 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4759 if(textBoxId.indexOf("addressTO") > -1) {
4761 } else if(textBoxId.indexOf("addressCC") > -1) {
4764 idx = textBoxId.substr(9);
4766 // follow through if not BCC
4768 var cc = document.getElementById("addressCC" + idx);
4769 var bcc = document.getElementById("addressBCC" + idx);
4773 cc.style.visibility = 'hidden';
4775 bcc.style.visibility = 'hidden';
4782 * Redisplays the textareas after an address is commited
4784 toggleTextareaShow : function(sType, aArgs) {
4785 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4789 if(textBoxId.indexOf("addressTO") > -1) {
4791 } else if(textBoxId.indexOf("addressCC") > -1) {
4794 idx = textBoxId.substr(9);
4796 // follow through if not BCC
4798 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4799 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4804 //// END AUTOCOMPLETE
4805 ///////////////////////////////////////////////////////////////////////////////
4807 ///////////////////////////////////////////////////////////////////////////////
4810 * expands the options sidebar
4812 SE.composeLayout = {
4813 currentInstanceId : 0,
4816 outboundAccountErrors : null,
4817 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4819 showAddressDetails : function(e) {
4820 var linkElement = document.getElementById("More"+e.id);
4821 var spanElement = document.getElementById("Detail"+e.id);
4822 var emailAddressList = e.value;
4823 if(e.value.length > 96)
4825 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4826 var displayArray = [];
4827 for (var i=0; i<resultArray.length; i++)
4829 var t_name = resultArray[i].name;
4830 var t_emailAddr = resultArray[i].email_address;
4832 displayArray.push('<br/><' + t_emailAddr + '>');
4834 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4837 var result = displayArray.join('<br/>');
4839 linkElement.style.display = "inline";
4840 linkElement.style.height="10px";
4841 linkElement.style.overflow="visible";
4842 spanElement.innerHTML = result;
4845 linkElement.style.display = "none";
4850 * Given a string of email address, return an array containing the name portion (if available)
4851 * and email portion.
4853 _getEmailArrayFromString : function (emailAddressList){
4856 while ((results = reg.exec(emailAddressList)) != null)
4858 orignial = results[0];
4859 parsedResult = results[0].replace(';', ':::::');
4860 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4864 while ((results = reg.exec(emailAddressList)) != null)
4866 orignial = results[0];
4867 parsedResult = results[0].replace(',', ':::::');
4868 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4870 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4871 var emailArr = emailAddressList.split(":::::");
4872 var resultsArray = [];
4874 for (var i=0; i<emailArr.length; i++)
4876 var rposition = emailArr[i].indexOf('<');
4877 var lposition = emailArr[i].indexOf('>');
4879 if(trim(emailArr[i]) != '')
4881 if(rposition != -1 && lposition != -1)
4883 var t_name = emailArr[i].substr(0, rposition-1);
4884 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4885 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4889 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4893 return resultsArray;
4895 ///////////////////////////////////////////////////////////////////////////
4898 * Prepare bucket DIV and yui-ext tab panels
4900 _0_yui : function() {
4901 var idx = this.currentInstanceId;
4903 var composeTab = new YAHOO.SUGAR.ClosableTab({
4904 label: mod_strings.LNK_NEW_SEND_EMAIL,
4906 content : "<div id='htmleditordiv" + idx + "'/>",
4907 id : "composeTab" + idx,
4908 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4911 SE.innerLayout.addTab(composeTab);
4913 // get template engine with template
4914 if (!SE.composeLayout.composeTemplate) {
4915 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4918 // create Tab inner layout
4919 var composePanel = this.getComposeLayout();
4920 composePanel.getUnitByPosition("right").collapse();
4921 composePanel.autoSize();
4925 * Generate the quick compose layout
4926 * @method getQuickComposeLayout
4927 * @param {Pannel} parentPanel Parent pannel
4928 * @param {Object} o Options
4931 getQuickComposeLayout : function (parentPanel,o) {
4932 var idx = SE.composeLayout.currentInstanceId;
4934 //Before rendering the parent pannel we need to initalize the grid layout
4935 parentPanel.beforeRenderEvent.subscribe(function() {
4937 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4938 SE.composeLayout._createComposeLayout(idx);
4939 SE.composeLayout[idx].set('height', 350);
4940 SE.composeLayout[idx].render();
4944 //Wait until the Compose Layout has rendered, then add the
4945 //options tab and perform the tiny initialization.
4946 parentPanel.renderEvent.subscribe(function() {
4948 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4949 SE.composeLayout._initComposeOptionTabs(idx);
4950 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4951 //Initialize tinyMCE
4952 if (!SUGAR.util.isTouchScreen())
4953 SE.composeLayout._1_tiny(false);
4954 //Init templates and address book
4955 SE.composeLayout._2_final();
4957 SE.composeLayout.quickCreateComposePackage(o);
4962 //Check if we have the div override for the shortcut bar
4963 if(typeof o.menu_id != 'undefined') {
4964 parentPanel.render(o.menu_id);
4966 parentPanel.render(document.body);
4969 return SE.composeLayout[idx];
4972 * Fill in all fields into the quick compose layout.
4973 * @method quickCreateComposePackage
4974 * @param {Object} o Options
4977 quickCreateComposePackage: function(o)
4979 //If we have a compose package fill in defaults.
4980 if (typeof(o.composePackage) != 'undefined')
4982 composePackage = o.composePackage; //Set the compose data object
4983 //Hijack this method called by composePackage as it's not need for quick creates.
4984 SE.composeLayout.c0_composeNewEmail = function(){};
4985 SE.composeLayout.composePackage(); //Fill in defaults.
4988 getComposeLayout : function() {
4989 var idx = SE.composeLayout.currentInstanceId;
4991 this._createComposeLayout(idx);
4992 SE.composeLayout[idx].render();
4993 this._initComposeOptionTabs(idx);
4995 return SE.composeLayout[idx];
4999 * Create the layout manager for the compose window.
5001 _createComposeLayout : function(idx)
5003 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
5004 parent: SE.complexLayout,
5014 SE.composeLayout.composeTemplate.exec({
5015 'app_strings':app_strings,
5016 'mod_strings':mod_strings,
5017 'linkbeans_options' : linkBeans,
5018 'idx' : SE.composeLayout.currentInstanceId
5029 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5032 header: app_strings.LBL_EMAIL_OPTIONS
5038 * Create compose tab which will populate the 'right' container in the compose window.
5040 _initComposeOptionTabs : function(idx)
5042 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5043 var tab = new YAHOO.widget.Tab({
5044 label: app_strings.LBL_EMAIL_ATTACHMENT,
5046 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5047 id : "divAttachments" + idx,
5051 tab.layout = SE.composeLayout[idx];
5053 tab.on("activeChange", function(o){
5055 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5061 tab = new YAHOO.widget.Tab({
5062 label: app_strings.LBL_EMAIL_OPTIONS,
5064 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5065 id : "divOptions" + idx,
5069 tab.layout = SE.composeLayout[idx];
5070 tab.on("activeChange", function(o){
5072 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5077 SE.composeLayout[idx].autoSize = function() {
5078 var pEl = this.get("element").parentNode.parentNode.parentNode;
5079 this.set("height", pEl.clientHeight-30);
5083 SE.composeLayout[idx].rightTabs = cTabs;
5085 isParentTypeValid : function(idx) {
5086 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5087 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5088 if (trim(parentTypeValue) == ""){
5089 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5095 isParentTypeAndNameValid : function(idx) {
5096 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5097 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5098 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5099 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5100 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5101 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5107 callopenpopupForEmail2 : function(idx,options) {
5109 var formName = 'emailCompose' + idx;
5111 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5112 formName = options.form_name;
5114 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5115 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5116 if (!SE.composeLayout.isParentTypeValid(idx)) {
5119 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5121 call_back_function:"SE.composeLayout.popupAddEmail",
5123 field_to_name_array:{
5124 id:'data_parent_id' + idx,
5125 name:'data_parent_name' + idx,
5130 popupAddEmail : function(o)
5132 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5133 var data = o.name_to_value_array;
5134 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5135 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5137 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5138 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5145 _1_tiny : function(isReplyForward) {
5146 var idx = SE.composeLayout.currentInstanceId;
5147 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5148 SE.tinyInstances[elId] = { };
5149 SE.tinyInstances[elId].ready = false;
5150 var t = tinyMCE.getInstanceById(elId);
5152 if(typeof(t) == 'undefined') {
5153 tinyMCE.execCommand('mceAddControl', false, elId);
5154 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5155 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
5160 resizeEditorSetSignature : function(idx,setSignature)
5162 var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5164 if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
5165 setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+isReplyForward+"');",500);
5169 SE.composeLayout.resizeEditor(idx);
5171 setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
5176 resizeEditor : function(idx)
5178 var cof = Dom.get('composeOverFrame' + idx);
5179 var head = Dom.get('composeHeaderTable' + idx);
5180 var targetHeight = cof.clientHeight - head.clientHeight;
5181 var instance = SE.util.getTiny('htmleditor' + idx);
5184 var parentEl = Dom.get(instance.editorId + '_parent');
5185 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5186 var contentEl = instance.contentAreaContainer;
5187 var iFrame = contentEl.firstChild;
5188 var tinMceToolbarOffset = 18;
5189 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5192 setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
5197 * Initializes d&d, auto-complete, email templates
5199 _2_final : function() {
5200 var idx = SE.composeLayout.currentInstanceId;
5202 if(this.emailTemplates) {
5203 this.setComposeOptions(idx);
5205 //populate email template cache
5206 AjaxObject.target = '';
5207 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5210 // handle drop targets for addressBook
5211 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5212 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5213 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5214 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5216 // auto-complete setup
5217 SE.autoComplete.init(idx);
5220 document.getElementById("addressTO" + idx).focus();
5224 * hide tinyMCE tool bar if send email as plaintext is checked
5226 renderTinyMCEToolBar : function (idx, hide) {
5228 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5230 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5234 c1_composeEmail : function(isReplyForward, retry) {
5238 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5239 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5241 this._1_tiny(isReplyForward);
5244 if(isReplyForward) {
5245 this.replyForwardEmailStage2();
5251 * takes draft info and prepopulates
5253 c0_composeDraft : function() {
5254 this.getNewInstanceId();
5256 document.getElementById('_blank').innerHTML = '';
5257 var idx = SE.composeLayout.currentInstanceId;
5258 SE.composeLayout.draftObject = new Object();
5259 SE.composeLayout.draftObject.id = idx;
5260 SE.composeLayout.draftObject.isDraft = true;
5261 SE.composeLayout.currentInstanceId = idx;
5262 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5263 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5264 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5266 SE.composeLayout._0_yui();
5267 SE.composeLayout._1_tiny(true);
5270 SE.composeLayout._2_final();
5272 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5273 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5277 * Strip & Prep editor hidden fields
5279 c0_composeNewEmail : function() {
5280 this.getNewInstanceId();
5281 this.c1_composeEmail(false);
5285 * Sends async request to get the compose view.
5286 * Requests come from "reply" or "forwards"
5288 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5289 SE.composeLayout.replyForwardObj = new Object();
5290 SE.composeLayout.replyForwardObj.ieId = ieId;
5291 SE.composeLayout.replyForwardObj.uid = uid;
5292 SE.composeLayout.replyForwardObj.mbox = mbox;
5293 SE.composeLayout.replyForwardObj.type = type;
5295 if(mbox == 'sugar::Emails') {
5296 SE.composeLayout.replyForwardObj.sugarEmail = true;
5299 SE.composeLayout.getNewInstanceId();
5300 SE.composeLayout.c1_composeEmail(true);
5302 //// END COMPOSE FLOW
5303 ///////////////////////////////////////////////////////////////////////////
5306 * Called when a contact, email, or mailinglist is dropped
5307 * into one of the compose fields.
5309 handleDrop : function (source, event, data, target) {
5312 target = event.getTarget();
5314 data.nodes = [data.nodes];
5318 target = document.getElementById(target);
5322 if (target.id.indexOf('address') > -1) {
5323 // dropped onto email to/cc/bcc field
5324 for(var i in nodes) {
5325 var node = nodes[i].getData();
5327 if (node[1].indexOf('contact') > -1) {
5328 email = SE.addressBook.getFormattedAddress(node[0]);
5329 } else if (node[1].indexOf('address-email') > -1){
5330 email = node[3].replace(/ /gi, '');
5331 email = email.replace('<', '<').replace('>', '>');
5332 var tr = source.getTrEl(nodes[i]);
5333 while (tr && !Dom.hasClass(tr, "address-contact")) {
5334 tr = source.getPreviousTrEl(tr);
5336 var CID = source.getRecord(tr).getData()[0];
5337 var o = SE.addressBook._contactCache[CID];
5338 var name = new String(o.name);
5339 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5340 email = finalName + email;
5342 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5348 /*/////////////////////////////////////////////////////////////////////////////
5349 /// EMAIL TEMPLATE CODE
5351 applyEmailTemplate : function (idx, id) {
5354 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5355 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5356 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5359 var to_addr = document.getElementById('addressTO'+idx);
5360 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
5362 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5363 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5366 // id is selected index of email template drop-down
5367 if(id == '' || id == "0") {
5368 YAHOO.SUGAR.MessageBox.show({
5373 if(btn=='no'){return;};
5374 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5381 YAHOO.SUGAR.MessageBox.show({
5386 if(btn=='no'){return;};
5387 SUGAR.email2.composeLayout.processResult(idx, id);},
5393 processNoneResult : function(idx, id) {
5394 var tiny = SE.util.getTiny('htmleditor' + idx);
5395 var tinyHTML = tiny.getContent();
5396 var openTag = '<div><span><span>';
5397 var htmllow = tinyHTML.toLowerCase();
5398 var start = htmllow.indexOf(openTag);
5400 tinyHTML = tinyHTML.substr(start);
5401 tiny.setContent(tinyHTML);
5403 tiny.setContent('');
5407 processResult : function(idx , id){
5408 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5410 // get attachments if any
5411 AjaxObject.target = '';
5412 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5415 appendEmailTemplateJSON : function() {
5416 var idx = SE.composeLayout.currentInstanceId; // post increment
5418 // query based on template, contact_id0,related_to
5419 //jchi 09/10/2008 refix #7743
5420 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5421 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5424 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,'"');
5426 // cn: bug 14361 - text-only templates don't fill compose screen
5428 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/>");
5431 var tiny = SE.util.getTiny('htmleditor' + idx);
5432 var tinyHTML = tiny.getContent();
5433 var openTag = '<div><span><span>';
5434 var closeTag = '</span></span></div>';
5435 var htmllow = tinyHTML.toLowerCase();
5436 var start = htmllow.indexOf(openTag);
5438 var htmlPart2 = tinyHTML.substr(start);
5439 tinyHTML = text + htmlPart2;
5440 tiny.setContent(tinyHTML);
5442 tiny.setContent(text);
5447 * Writes out the signature in the email editor
5449 setSignature : function(idx) {
5452 var hide = document.getElementById('setEditor' + idx).checked;
5453 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5454 //wait for signatures to load before trying to set them
5455 if (!SE.composeLayout.signatures) {
5456 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5461 var sel = document.getElementById('signatures' + idx);
5463 var sel = document.getElementById('signature_id');
5464 idx = SE.tinyInstances.currentHtmleditor;
5467 //Ensure that the tinyMCE html has been rendered.
5468 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5469 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5476 signature = sel.options[sel.selectedIndex].value;
5481 var openTag = '<div><span><span>';
5482 var closeTag = '</span></span></div>';
5483 var t = tinyMCE.getInstanceById('htmleditor' + idx);
5485 if(typeof(t) != 'undefined')
5487 t.contentDocument = t.contentWindow.document;
5488 var html = t.getContent();
5495 var htmllow = html.toLowerCase();
5496 var start = htmllow.indexOf(openTag);
5497 var end = htmllow.indexOf(closeTag) + closeTag.length;
5499 // selected "none" - remove signature from email
5500 if(signature == '') {
5502 var htmlPart1 = html.substr(0, start);
5503 var htmlPart2 = html.substr(end, html.length);
5505 html = htmlPart1 + htmlPart2;
5508 SE.signatures.lastAttemptedLoad = '';
5512 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5513 SE.signatures.lastAttemptedLoad = '';
5515 SE.signatures.lastAttemptedLoad = signature;
5517 if(typeof(SE.signatures[signature]) == 'undefined') {
5519 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5520 SE.signatures.targetInstance = (idx) ? idx : "";
5521 AjaxObject.target = '';
5522 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5524 var newSignature = this.prepareSignature(SE.signatures[signature]);
5526 // clear out old signature
5527 if(SE.signatures.lastAttemptedLoad && start > -1) {
5528 var htmlPart1 = html.substr(0, start);
5529 var htmlPart2 = html.substr(end, html.length);
5531 html = htmlPart1 + htmlPart2;
5535 start = html.indexOf('<div><hr></div>');
5536 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5537 var htmlPart1 = html.substr(0, start);
5538 var htmlPart2 = html.substr(start, html.length);
5539 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5540 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5541 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5543 var newHtml = html + openTag + newSignature + closeTag;
5545 //tinyMCE.setContent(newHtml);
5546 t.setContent(newHtml);
5550 prepareSignature : function(str) {
5551 var signature = new String(str);
5553 signature = signature.replace(/</gi, '<');
5554 signature = signature.replace(/>/gi, '>');
5560 showAttachmentPanel : function(idx) {
5561 var east = SE.composeLayout[idx].getUnitByPosition("right");
5562 var tabs = SE.composeLayout[idx].rightTabs;
5564 tabs.set("activeTab", tabs.getTab(0));
5568 * expands sidebar and displays options panel
5570 showOptionsPanel : function(idx) {
5571 var east = SE.composeLayout[idx].getUnitByPosition("right");
5572 var tabs = SE.composeLayout[idx].rightTabs;
5574 tabs.set("activeTab", tabs.getTab(1));
5578 * Selects the Contacts tab
5580 showContactsPanel : function() {
5581 SE.complexLayout.regions.west.showPanel("contactsTab");
5585 * Generates fields for Select Document
5587 addDocumentField : function(idx) {
5588 var basket = document.getElementById('addedDocuments' + idx);
5590 var index = (basket.childNodes.length / 7) - 1;
5597 var test = document.getElementById('documentId' + idx + index);
5599 while(test != null) {
5601 test = document.getElementById('documentId' + idx + index);
5604 var documentCup = document.createElement("div");
5605 documentCup.id = 'documentCup' + idx + index;
5606 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5607 // document id field
5608 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5609 // document name field
5610 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5612 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5613 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5614 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5616 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5617 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5618 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5621 basket.appendChild(documentCup);
5622 //basket.innerHTML += out;
5627 * Makes async call to save a draft of the email
5628 * @param int Instance index
5630 saveDraft : function(tinyInstance) {
5631 this.sendEmail(tinyInstance, true);
5634 selectDocument : function(target) {
5635 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5636 windowName = 'selectDocument';
5637 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5639 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5641 // put the focus on the popup if the browser supports the focus() method
5647 * Modal popup for file attachment dialogue
5649 addFileField : function() {
5650 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5651 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5655 constraintoviewport: true,
5657 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5658 fn:function(){SE.addFileDialog.hide();}
5661 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5662 SE.addFileDialog.render();
5663 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5665 Dom.removeClass("addFileDialog", "yui-hidden");
5667 SE.addFileDialog.show();
5671 * Async upload of file to temp dir
5673 uploadAttachment : function() {
5674 if(document.getElementById('email_attachment').value != "") {
5675 var formObject = document.getElementById('uploadAttachment');
5676 YAHOO.util.Connect.setForm(formObject, true, true);
5677 AjaxObject.target = '';
5678 AjaxObject.startRequest(callbackUploadAttachment, null);
5680 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5685 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5686 * @param string target in focus compose layout
5688 setDocument : function(idx, target, documentId, documentName, docRevId) {
5689 // fields are named/id'd [fieldName][instanceId][index]
5690 var addedDocs = document.getElementById("addedDocuments" + idx);
5691 var docId = document.getElementById('documentId' + idx + target);
5692 var docName = document.getElementById('documentName' + idx + target);
5693 var docRevisionId = document.getElementById('document' + idx + target);
5694 docId.value = documentId;
5695 docName.value = documentName;
5696 docRevisionId.value = docRevId;
5700 * Removes the bucket div containing the document input fields
5702 deleteDocumentField : function(documentCup) {
5703 var f0 = document.getElementById(documentCup);
5704 f0.parentNode.removeChild(f0);
5708 * Removes a Template Attachment field
5712 deleteTemplateAttachmentField : function(idx, index) {
5713 // create not-in-array values for removal filtering
5714 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5720 r += document.getElementById('templateAttachmentId' + idx + index).value;
5721 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5723 var target = 'templateAttachmentCup' + idx + index;
5724 d = document.getElementById(target);
5725 d.parentNode.removeChild(d);
5729 * Async removal of uploaded temp file
5730 * @param string index Should be a concatenation of idx and index
5733 deleteUploadAttachment : function(index, file) {
5734 var d = document.getElementById('email_attachment_bucket' + index);
5735 d.parentNode.removeChild(d);
5737 // make async call to delete cached file
5738 AjaxObject.target = '';
5739 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5743 * Attaches files coming from Email Templates
5745 addTemplateAttachmentField : function(idx) {
5747 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5749 var basket = document.getElementById('addedTemplateAttachments' + idx);
5752 var index = basket.childNodes.length;
5759 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5761 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5762 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5763 idx + "\",\"" + index + "\");'/>" +
5765 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5766 // templateAttachment field
5767 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5769 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5771 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5772 "<br id='br" + index + "></br>" +
5773 "<br id='brdoc" + index + "></br>" +
5775 basket.innerHTML = basket.innerHTML + out;
5781 * Sends one email via async call
5782 * @param int idx Editor instance ID
5783 * @param bool isDraft
5785 sendEmail : function(idx, isDraft) {
5787 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5788 var obAccountID = document.getElementById('addressFrom' + idx).value;
5790 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5792 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5797 var form = document.getElementById('emailCompose' + idx);
5798 var composeOptionsFormName = "composeOptionsForm" + idx;
5799 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5800 var html = t.getContent();
5801 var subj = document.getElementById('emailSubject' + idx).value;
5802 var to = trim(document.getElementById('addressTO' + idx).value);
5803 var cc = trim(document.getElementById('addressCC' + idx).value);
5804 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5805 var email_id = document.getElementById('email_id' + idx).value;
5806 var composeType = document.getElementById('composeType').value;
5807 var parent_type = document.getElementById("parent_type").value;
5808 var parent_id = document.getElementById("parent_id").value;
5810 var el_uid = document.getElementById("uid");
5811 var uid = (el_uid == null) ? '' : el_uid.value;
5813 var el_ieId = document.getElementById("ieId");
5814 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5816 var el_mbox = document.getElementById("mbox");
5817 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5819 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5820 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5824 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5827 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5828 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5829 parent_id = parentIdValue;
5830 parent_type = parentTypeValue;
5832 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5833 // baseline viability check
5835 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5836 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5838 } else if(subj == '' && !isDraft) {
5839 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5842 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5844 } else if(html == '' && !isDraft) {
5845 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5850 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5851 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5852 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5853 SUGAR.showMessageBox(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5854 html = html.replace(/</ig, "sugarLessThan");
5855 html = html.replace(/>/ig, "sugarGreaterThan");
5857 form.sendDescription.value = html;
5858 form.sendSubject.value = subj;
5859 form.sendTo.value = to;
5860 form.sendCc.value = cc;
5861 form.sendBcc.value = bcc;
5862 form.email_id.value = email_id;
5863 form.composeType.value = composeType;
5864 form.composeLayoutId.value = 'composeLayout' + idx;
5865 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5866 form.saveToSugar.value = 1;
5867 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5868 form.parent_type.value = parent_type;
5869 form.parent_id.value = parent_id;
5870 form.uid.value = uid;
5871 form.ieId.value = ieId;
5872 form.mbox.value = mbox;
5874 // email attachments
5875 var addedFiles = document.getElementById('addedFiles' + idx);
5877 for(i=0; i<addedFiles.childNodes.length; i++) {
5878 var bucket = addedFiles.childNodes[i];
5880 for(j=0; j<bucket.childNodes.length; j++) {
5881 var node = bucket.childNodes[j];
5882 var nName = new String(node.name);
5884 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5885 if(form.attachments.value != '') {
5886 form.attachments.value += "::";
5888 form.attachments.value += node.value;
5895 var addedDocs = document.getElementById('addedDocuments' + idx);
5897 for(i=0; i<addedDocs.childNodes.length; i++) {
5898 var cNode = addedDocs.childNodes[i];
5899 for(j=0; j<cNode.childNodes.length; j++) {
5900 var node = cNode.childNodes[j];
5901 var nName = new String(node.name);
5902 if(node.type == 'hidden' && nName.match(/documentId/)) {
5903 if(form.documents.value != '') {
5904 form.documents.value += "::";
5906 form.documents.value += node.value;
5912 // template attachments
5913 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5914 if(addedTemplateAttachments) {
5915 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5916 var cNode = addedTemplateAttachments.childNodes[i];
5917 for(j=0; j<cNode.childNodes.length; j++) {
5918 var node = cNode.childNodes[j];
5919 var nName = new String(node.name);
5920 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5921 if(form.templateAttachments.value != "") {
5922 form.templateAttachments.value += "::";
5924 form.templateAttachments.value += node.value;
5930 // remove attachments
5931 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5933 YAHOO.util.Connect.setForm(form);
5935 AjaxObject.target = 'frameFlex';
5937 // sending a draft email
5938 if(!isDraft && in_draft) {
5940 SE.listView.removeRowByUid(email_id);
5943 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5944 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5946 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5950 * Handles clicking the email address link from a given view
5952 composePackage : function() {
5953 if(composePackage != null) {
5954 SE.composeLayout.c0_composeNewEmail();
5957 if(composePackage.to_email_addrs) {
5958 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5960 if (composePackage.subject != null && composePackage.subject.length > 0) {
5961 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5964 //If no parent fields are set in the composePackage, ensure they are cleared.
5965 var parentFields = ['parent_type','parent_name','parent_id'];
5966 for(var i=0;i<parentFields.length;i++)
5968 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5969 composePackage[parentFields[i]] = "";
5972 document.getElementById("parent_type").value = composePackage.parent_type;
5973 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5974 document.getElementById("parent_id").value = composePackage.parent_id;
5975 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5976 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5978 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5979 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5981 if (composePackage.body != null && composePackage.body.length > 0) {
5982 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5983 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5984 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5986 if (composePackage.attachments != null) {
5987 SE.composeLayout.loadAttachments(composePackage.attachments);
5990 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5991 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5992 SE.util.emptySelectOptions(addressFrom);
5993 var fromAccountOpts = composePackage.fromAccounts.data;
5994 for(i=0; i<fromAccountOpts.length; i++) {
5995 var key = fromAccountOpts[i].value;
5996 var display = fromAccountOpts[i].text;
5997 var opt = new Option(display, key);
5998 if (fromAccountOpts[i].selected) {
5999 opt.selected = true;
6001 addressFrom.options.add(opt);
6008 setContentOnThisTiny : function() {
6009 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6010 var tinyHTML = tiny.getContent();
6011 composePackage.body = decodeURI(encodeURI(composePackage.body));
6012 // cn: bug 14361 - text-only templates don't fill compose screen
6013 if(composePackage.body == '') {
6014 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
6016 //Flag determines if we should clear the tiny contents or just append
6017 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
6018 SE.composeLayout.tinyHTML = '';
6020 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
6022 tiny.setContent(SE.composeLayout.tinyHTML);
6023 //Indicate that the contents has been loaded successfully.
6024 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
6027 * Confirms closure of a compose screen if "x" is clicked
6029 confirmClose : function(panel) {
6030 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6031 SE.composeLayout.closeCompose(panel.id);
6039 * forces close of a compose screen
6041 forceCloseCompose : function(id) {
6042 SE.composeLayout.closeCompose(id);
6044 // handle flow back to originating view
6045 if(composePackage) {
6046 // check if it's a module we need to return to
6047 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6048 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6049 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6050 window.location = url;
6057 * closes the editor that just sent email
6058 * @param string id ID of composeLayout tab
6060 closeCompose : function(id) {
6061 // destroy tinyMCE instance
6062 var idx = id.substr(13, id.length);
6063 var instanceId = "htmleditor" + idx;
6064 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6066 // nullify DOM and namespace values.
6068 SE.composeLayout[idx] = null;
6069 SE.tinyInstances[instanceId] = null;
6070 var tabsArray = SE.innerLayout.get("tabs");
6071 for (i = 0 ; i < tabsArray.length ; i++) {
6072 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6073 tabsArray[i].close();
6077 //SE.innerLayout.getTab(idx).close();
6081 * Enable the quick search for the compose relate field or search tab
6083 enableQuickSearchRelate: function(idx,overides){
6085 if(typeof overides != 'undefined')
6087 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6088 var newModule = document.getElementById(newModuleID).value;
6089 var formName = overides['formName'];
6090 var fieldName = overides['fieldName'];
6091 var fieldId = overides['fieldId'];
6092 var fullName = formName + "_" + fieldName;
6093 var postBlurFunction = null;
6097 var newModule = document.getElementById('data_parent_type'+idx).value;
6098 var formName = 'emailCompose'+idx;
6099 var fieldName = 'data_parent_name'+idx;
6100 var fieldId = 'data_parent_id'+idx;
6101 var fullName = formName + "_" + fieldName;
6102 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6105 if(typeof sqs_objects == 'undefined')
6106 window['sqs_objects'] = new Array;
6108 window['sqs_objects'][fullName] = {
6111 modules:[newModule],
6113 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6114 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6115 post_onblur_function: postBlurFunction,
6116 order:"name","limit":"30","no_match_text":"No Match"};
6119 if(typeof QSProcessedFieldsArray != 'undefined')
6120 QSProcessedFieldsArray[fullName] = false;
6121 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6122 QSFieldsArray[fullName].destroy();
6123 delete QSFieldsArray[fullName];
6125 if (Dom.get(fullName + "_results")) {
6126 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6132 qsAddAddress : function(o) {
6133 if (o.name != "" && o.email1 != "")
6135 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6136 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6140 * Returns a new instance ID, 0-index
6142 getNewInstanceId : function() {
6143 this.currentInstanceId = this.currentInstanceId + 1;
6144 return this.currentInstanceId;
6148 * 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.
6150 loadAttachments : function(result) {
6151 var idx = SE.composeLayout.currentInstanceId;
6153 if(typeof(result) == 'object') {
6154 //jchi #20680. Clean the former template attachments;
6155 var basket = document.getElementById('addedTemplateAttachments' + idx);
6156 if(basket.innerHTML != ''){
6157 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6159 basket.innerHTML = '';
6164 if(typeof result[i] == 'object') {
6165 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6166 var bean = result[i];
6167 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6168 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6175 * fills drop-down values for email templates and signatures
6177 setComposeOptions : function(idx) {
6178 // send from accounts
6179 var addressFrom = document.getElementById('addressFrom' + idx);
6181 if (addressFrom.options.length <= 0) {
6182 SE.util.emptySelectOptions(addressFrom);
6183 var fromAccountOpts = SE.composeLayout.fromAccounts;
6184 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6185 var key = fromAccountOpts[id].value;
6186 var display = fromAccountOpts[id].text;
6187 var is_default = false;
6188 if(key == SUGAR.default_inbound_accnt_id)
6190 var opt = new Option(display, key);
6191 addressFrom.options.add(opt);
6192 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6197 var et = document.getElementById('email_template' + idx);
6198 SE.util.emptySelectOptions(et);
6200 for(var key in this.emailTemplates) { // iterate through assoc array
6201 var display = this.emailTemplates[key];
6202 var opt = new Option(display, key);
6203 et.options.add(opt);
6207 var sigs = document.getElementById('signatures' + idx);
6208 SE.util.emptySelectOptions(sigs);
6210 for(var key in this.signatures) { // iterate through assoc array
6211 var display = this.signatures[key];
6212 var opt = new Option(display, key);
6214 if(key == SE.userPrefs.signatures.signature_default) {
6215 opt.selected = true;
6218 sigs.options.add(opt);
6221 // html/plain email?
6222 var htmlEmail = document.getElementById('setEditor' + idx);
6223 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6224 htmlEmail.checked = true;
6226 htmlEmail.checked = false;
6229 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6233 * After compose screen is rendered, async call to get email body from Sugar
6235 replyForwardEmailStage2 : function() {
6236 SE.util.clearHiddenFieldValues('emailUIForm');
6237 SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6239 var ieId = SE.composeLayout.replyForwardObj.ieId;
6240 var uid = SE.composeLayout.replyForwardObj.uid;
6241 var mbox = SE.composeLayout.replyForwardObj.mbox;
6242 var type = SE.composeLayout.replyForwardObj.type;
6243 var idx = SE.composeLayout.currentInstanceId;
6245 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6247 document.getElementById('emailSubject' + idx).value = type;
6248 document.getElementById('emailUIAction').value = 'composeEmail';
6249 document.getElementById('composeType').value = type;
6250 document.getElementById('ieId').value = ieId;
6251 document.getElementById('uid').value = uid;
6252 document.getElementById('mbox').value = mbox;
6253 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6254 var formObject = document.getElementById('emailUIForm');
6255 YAHOO.util.Connect.setForm(formObject);
6257 var sendType = type;
6258 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6262 * Show the hidden cc or bcc fields
6264 showHiddenAddress: function(addrType,idx){
6266 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6267 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6268 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6269 this[addrType+'Hidden'+idx] = false;
6271 //After bcc or cc is added, move options below last addr field
6272 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6274 //If both cc and bcc hidden, remove the empty row containing text.
6275 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6276 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6277 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6279 // SE.composeLayout.resizeEditor(idx);
6282 * Hide the cc and bcc fields if they were shown.
6284 hideHiddenAddresses: function(idx){
6286 var addrTypes = ['cc','bcc'];
6287 for(var i = 0;i<addrTypes.length;i++)
6289 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6290 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6291 this[addrTypes[i] + 'Hidden'+idx] = true
6294 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6295 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6296 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6300 //// END SE.composeLayout
6301 ///////////////////////////////////////////////////////////////////////////////
6302 ///////////////////////////////////////////////////////////////////////////////
6306 * Cleans serialized UID lists of duplicates
6310 cleanUids : function(str) {
6311 var seen = new Object();
6313 var arr = new String(str).split(",");
6315 for(var i=0; i<arr.length; i++) {
6320 clean += (clean != "") ? "," : "";
6322 seen[arr[i]] = true;
6329 * Clears hidden field values
6330 * @param string id ID of form element to clear
6332 clearHiddenFieldValues : function(id) {
6333 var form = document.getElementById(id);
6335 for(i=0; i<form.elements.length; i++) {
6336 if(form.elements[i].type == 'hidden') {
6337 var e = form.elements[i];
6338 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6346 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6348 emptySelectOptions : function(el) {
6350 for(i=el.childNodes.length - 1; i >= 0; i--) {
6351 if(el.childNodes[i]) {
6352 el.removeChild(el.childNodes[i]);
6359 * Returns the MBOX path in the manner php_imap expects:
6360 * ie: INBOX.DEBUG.test
6361 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6363 generateMboxPath : function(str) {
6364 var ex = str.split("::");
6366 /* we have a serialized MBOX path */
6370 for(var i=0; i<ex.length; i++) {
6371 if(ex[i] == 'INBOX') {
6383 /* we have a Sugar folder GUID - do nothing */
6391 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6392 * @param HTMLElement el
6393 * @return string GUID of found element or empty on failure
6395 getGuidFromElement : function(el) {
6401 for(var i=0; i<iterations; i++) {
6403 if(el.id.match(SE.reGUID)) {
6415 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6418 getPanelId : function() {
6419 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6423 * wrapper to handle weirdness with IE
6424 * @param string instanceId
6425 * @return tinyMCE Controller object
6427 getTiny : function(instanceId) {
6428 if(instanceId == '') {
6432 var t = tinyMCE.getInstanceById(instanceId);
6436 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6442 * Simple check for MSIE browser
6446 var nav = new String(navigator.appVersion);
6447 if(nav.match(/MSIE/)) {
6454 * Recursively removes an element from the DOM
6455 * @param HTMLElement
6457 removeElementRecursive : function(el) {
6458 this.emptySelectOptions(el);
6465 sleep : function(secs) {
6466 setTimeout("void(0);", secs);
6470 * Converts a <select> element to an Ext.form.combobox
6472 convertSelect : function(select) {
6473 alert('in convertSelect');
6474 if (typeof(select) == "string") {
6475 select = document.getElementById(select);
6479 findChildNode : function (parent, property, value) {
6480 for (i in parent.children) {
6481 var child = parent.children[i];
6482 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6484 var searchChild = SE.util.findChildNode(child, property, value);
6491 cascadeNodes : function (parent, fn, scope, args) {
6492 for (i in parent.children) {
6493 var child = parent.children[i];
6494 var s = scope ? scope : child;
6495 var a = args ? args : child;
6497 SE.util.cascadeNodes(child, fn, scope, args);
6504 ///////////////////////////////////////////////////////////////////////////////
6507 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6509 /*********************************************************************************
6510 * SugarCRM Community Edition is a customer relationship management program developed by
6511 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6513 * This program is free software; you can redistribute it and/or modify it under
6514 * the terms of the GNU Affero General Public License version 3 as published by the
6515 * Free Software Foundation with the addition of the following permission added
6516 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6517 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6518 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6520 * This program is distributed in the hope that it will be useful, but WITHOUT
6521 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6522 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6525 * You should have received a copy of the GNU Affero General Public License along with
6526 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6527 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6530 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6531 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6533 * The interactive user interfaces in modified source and object code versions
6534 * of this program must display Appropriate Legal Notices, as required under
6535 * Section 5 of the GNU Affero General Public License version 3.
6537 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6538 * these Appropriate Legal Notices must retain the display of the "Powered by
6539 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6540 * technical reasons, the Appropriate Legal Notices must display the words
6541 * "Powered by SugarCRM".
6542 ********************************************************************************/
6545 if (typeof console == "undefined")
6546 console = { log: function(o) {alert(o)} };
6550 currentRequestObject : null,
6551 //timeout : 30000, // 30 second timeout default
6552 timeout : 9999999999, // 30 second timeout default
6554 trail : new Array(),
6558 _reset : function() {
6559 this.timeout = 30000;
6560 this.forceAbort = false;
6563 folderRenameCleanup : function() {
6564 SUGAR.email2.folders.setSugarFolders();
6567 fullSyncCleanup : function(o) {
6568 this.folders.checkMailCleanup(o);
6569 SUGAR.email2.settings.settingsDialog.hide();
6574 composeCache : function(o) {
6575 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6576 // get email templates and user signatures
6577 var ret = YAHOO.lang.JSON.parse(o.responseText);
6579 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6580 SUGAR.email2.composeLayout.signatures = ret.signatures;
6581 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6583 SUGAR.email2.composeLayout.setComposeOptions(idx);
6585 //Set the error array so we can notify the user when they try to hit send if any errors
6586 //are present. We will also notify them now (after hitting compose button).
6587 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6590 //if error element is returning an array, then check the length to make sure we have error messages
6591 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6592 //add error messages for display
6593 for(i in ret.errorArray)
6594 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6595 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6596 //if error element is returning an object, and the object value is not empty or null, then display error message
6597 for(i in ret.errorArray)
6598 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6601 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6603 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6605 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6611 handleDeleteSignature : function(o) {
6612 SUGAR.hideMessageBox();
6613 var ret = YAHOO.lang.JSON.parse(o.responseText);
6614 SUGAR.email2.composeLayout.signatures = ret.signatures;
6615 var field = document.getElementById('signature_id');
6616 SUGAR.email2.util.emptySelectOptions(field);
6618 for(var i in ret.signatures) { // iterate through assoc array
6619 var opt = new Option(ret.signatures[i], i);
6620 field.options.add(opt);
6622 setSigEditButtonVisibility();
6627 handleDeleteReturn : function(o) {
6628 // force refresh ListView
6629 SUGAR.hideMessageBox();
6630 if(document.getElementById('focusEmailMbox')) {
6631 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6634 // need to display success message before calling next async call?
6635 document.getElementById(this.target).innerHTML = o.responseText;
6640 handleFailure : function(o) {
6642 SUGAR.showMessageBox('Exception occurred...', o.statusText, 'alert');
6643 if(document.getElementById('saveButton')) {
6644 document.getElementById('saveButton').disabled = false;
6648 handleReplyForward : function(o) {
6649 var a = YAHOO.lang.JSON.parse(o.responseText);
6651 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6653 document.getElementById('email_id' + idx).value = a.uid;
6654 document.getElementById('emailSubject' + idx).value = a.name;
6655 document.getElementById('addressTO' + idx).value = a.from;
6656 document.getElementById('uid' + idx).value = a.uid;
6658 document.getElementById('addressCC' + idx).value = a.cc;
6659 SE.composeLayout.showHiddenAddress('cc', idx);
6663 document.getElementById('type' + idx).value = a.type;
6666 // apply attachment values
6667 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6669 setTimeout("callbackReplyForward.finish(globalA);", 500);
6672 handleReplyForwardForDraft : function(o) {
6673 var a = YAHOO.lang.JSON.parse(o.responseText);
6675 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6677 document.getElementById('email_id' + idx).value = a.uid;
6678 document.getElementById('emailSubject' + idx).value = a.name;
6679 document.getElementById('addressTO' + idx).value = a.to;
6682 document.getElementById('addressCC' + idx).value = a.cc;
6683 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6687 document.getElementById('addressBCC' + idx).value = a.bcc;
6688 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6693 document.getElementById('type' + idx).value = a.type;
6697 // apply attachment values
6698 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6700 setTimeout("callbackReplyForward.finish(globalA);", 500);
6705 handleSuccess : function(o) {
6706 document.getElementById(this.target).innerHTML = o.responseText;
6707 SUGAR.hideMessageBox();
6712 ieDeleteSuccess : function(o) {
6713 SUGAR.hideMessageBox();
6714 SUGAR.email2.accounts.refreshInboundAccountTable();
6715 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6716 SUGAR.email2.accounts.rebuildFolderList();
6721 ieSaveSuccess : function(o) {
6722 document.getElementById('saveButton').disabled = false;
6723 var a = YAHOO.lang.JSON.parse(o.responseText);
6726 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6727 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6729 resp = YAHOO.lang.JSON.parse(o.responseText);
6730 SUGAR.email2.accounts.refreshInboundAccountTable();
6731 SUGAR.email2.accounts.refreshOuboundAccountTable();
6732 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6733 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6736 SUGAR.hideMessageBox();
6737 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6744 loadAttachments : function(o) {
6745 var result = YAHOO.lang.JSON.parse(o.responseText);
6747 SUGAR.email2.composeLayout.loadAttachments(result);
6752 loadSignature : function(o) {
6753 var ret = YAHOO.lang.JSON.parse(o.responseText);
6754 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6755 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6759 * Follow up to mark email read|unread|flagged
6761 markEmailCleanup : function(o) {
6762 var ret = YAHOO.lang.JSON.parse(o.responseText);
6763 if (!ret['status']) {
6764 SUGAR.hideMessageBox();
6765 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6767 SUGAR.email2.contextMenus.markEmailCleanup();
6773 rebuildShowFolders : function(o) {
6774 var t = YAHOO.lang.JSON.parse(o.responseText);
6775 var show = document.getElementById('ieAccountListShow');
6777 SUGAR.email2.util.emptySelectOptions(show);
6779 for(i=0; i<t.length; i++) { // iterate through assoc array
6780 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6781 opt.selected = t[i].selected;
6782 show.options.add(opt);
6785 SUGAR.email2.accounts.renderTree();
6789 saveListViewSortOrderPart2 : function() {
6790 // create the JSON string the func expects
6791 focusFolderPath = '[ "Home", "' + ieName + '"';
6793 var f = new String(focusFolder);
6794 var fEx = f.split('.');
6796 for(i=0; i<fEx.length; i++) {
6797 focusFolderPath += ', "' + fEx[i] +'"'
6800 focusFolderPath += ']';
6802 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6803 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6809 sendEmailCleanUp : function(o) {
6811 SUGAR.hideMessageBox();
6814 ret = YAHOO.lang.JSON.parse(o.responseText);
6815 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6816 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6818 if (o.responseText) {
6819 SUGAR.showMessageBox(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6821 // Else we have an error here.
6824 if (typeof(SE.grid) != 'undefined')
6825 SE.listView.refreshGrid();
6826 //Disabled while address book is disabled
6828 //If this call back was initiated by quick compose from a Detail View page, refresh the
6829 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6830 //close the shortcut bar menu
6831 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6832 if(action_sugar_grp1 == 'DetailView') {
6833 showSubPanel('history',null,true);
6834 } else if(action_sugar_grp1 == 'quickcreate') {
6835 closeEmailOverlay();
6841 ieSendSuccess : function(o) {
6842 SUGAR.hideMessageBox();
6843 SUGAR.showMessageBox(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6848 settingsFolderRefresh : function(o) {
6849 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6850 var ret = YAHOO.lang.JSON.parse(o.responseText);
6851 var user = document.getElementById('userFolders');
6853 SUGAR.email2.util.emptySelectOptions(user);
6855 for(i=0; i<ret.userFolders.length; i++) {
6856 var display = ret.userFolders[i].name;
6857 var value = ret.userFolders[i].id;
6858 var selected = (ret.userFolders[i].selected != "") ? true : false;
6859 var opt = new Option(display, value, selected);
6860 opt.selected = selected;
6861 user.options.add(opt);
6867 startRequest : function(callback, args, forceAbort) {
6868 if(this.currentRequestObject != null) {
6869 if(this.forceAbort == true) {
6870 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6873 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6877 requestInProgress : function() {
6878 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6883 updateFolderSubscriptions : function() {
6884 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6885 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6886 SUGAR.hideMessageBox();
6891 updateFrameFolder : function() {
6892 SUGAR.email2.folders.checkEmailAccounts();
6897 updateUserPrefs : function(o) {
6898 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
6899 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6904 uploadAttachmentSuccessful : function(o) {
6906 document.getElementById('email_attachment').value = '';
6908 var ret = YAHOO.lang.JSON.parse(o.responseText);
6909 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6910 var overall = document.getElementById('addedFiles' + idx);
6911 var index = overall.childNodes.length;
6913 "<div id='email_attachment_bucket" + idx + index + "'>" +
6915 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6916 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6917 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6919 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6920 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6922 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6924 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6927 overall.innerHTML += out;
6928 if(SUGAR.email2.util.isIe()) {
6929 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6933 SUGAR.email2.addFileDialog.hide();
6934 // focus attachments
6935 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6940 ///////////////////////////////////////////////////////////////////////////
6941 //// PER MODULE CALLBACK OBJECTS
6942 AjaxObject.accounts = {
6943 saveOutboundCleanup : function(o) {
6944 SUGAR.email2.accounts.refreshOuboundAccountTable();
6945 SUGAR.email2.accounts.outboundDialog.hide();
6946 var id = o.responseText;
6947 SUGAR.email2.accounts.newAddedOutboundId = id;
6949 saveDefaultOutboundCleanup: function(o){
6952 callbackEditOutbound : {
6953 success : function(o)
6955 var ret = YAHOO.lang.JSON.parse(o.responseText);
6957 SUGAR.email2.accounts.showAddSmtp();
6960 document.getElementById("mail_id").value = ret.id;
6961 document.getElementById("type").value = ret.type;
6962 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6963 document.getElementById("mail_name").value = ret.name;
6964 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6965 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6966 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6967 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6968 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6969 SUGAR.email2.accounts.smtp_authenticate_field_display();
6970 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6972 if(ret.type == 'system-override') {
6973 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6974 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6977 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6978 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6980 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6983 failure : AjaxObject.handleFailure,
6984 timeout : AjaxObject.timeout,
6987 callbackDeleteOutbound : {
6988 success : function(o) {
6989 var ret = YAHOO.lang.JSON.parse(o.responseText);
6992 if(confirm(ret.error_message))
6994 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6995 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6998 SUGAR.hideMessageBox();
7002 SUGAR.hideMessageBox();
7003 SUGAR.email2.accounts.refreshOuboundAccountTable();
7007 failure : AjaxObject.handleFailure,
7008 timeout : AjaxObject.timeout,
7012 callbackCheckMailProgress : {
7013 success : function(o) {
7014 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
7015 SUGAR.email2.accounts.totalMsgCount = -1;
7018 //Check for server timeout / errors
7019 var ret = YAHOO.lang.JSON.parse(o.responseText);
7022 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
7023 SUGAR.hideMessageBox();
7024 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7025 SUGAR.email2.accounts.totalMsgCount = -1;
7026 //SUGAR.email2.folders.rebuildFolders();
7030 var currIeId = ret['ieid'];
7033 var serverCount = ret.count;
7035 if (ret['status'] == 'done') {
7036 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7037 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7041 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7042 //Go to next account
7043 currIeId = SUGAR.email2.accounts.ieIds[i+1];
7045 SUGAR.email2.accounts.totalMsgCount = -1;
7050 else if (ret.mbox && ret.totalcount && ret.count) {
7051 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7052 if (ret.count >= ret.totalcount) {
7055 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7056 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7058 SUGAR.hideMessageBox();
7059 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7060 SUGAR.email2.accounts.totalMsgCount = -1;
7065 SUGAR.email2.accounts.totalMsgCount = -1;
7066 SUGAR.hideMessageBox();
7067 SUGAR.email2.folders.rebuildFolders();
7068 SE.listView.refreshGrid();
7069 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7070 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7071 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7072 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7074 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7075 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7076 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7077 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7078 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7081 failure : AjaxObject.handleFailure,
7082 timeout : AjaxObject.timeout,
7087 ///////////////////////////////////////////////////////////////////////////////
7089 AjaxObject.composeLayout = {
7091 * Populates the record id
7093 saveDraftCleanup : function(o) {
7095 SUGAR.hideMessageBox();
7098 ret = YAHOO.lang.JSON.parse(o.responseText);
7099 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7101 if (o.responseText) {
7102 SUGAR.showMessageBox(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7108 AjaxObject.composeLayout.callback = {
7110 success : AjaxObject.composeLayout.saveDraftCleanup,
7111 failure : AjaxObject.handleFailure,
7112 timeout : AjaxObject.timeout,
7117 AjaxObject.detailView = {
7119 * Pops-up a printable view of an email
7121 displayPrintable : function(o) {
7122 var ret = YAHOO.lang.JSON.parse(o.responseText);
7123 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7124 // 2 below must be in global context
7126 meta['panelId'] = SUGAR.email2.util.getPanelId();
7127 email = ret.meta.email;
7128 if (typeof(email.cc) == 'undefined') {
7132 var out = displayTemplate.exec({
7133 'app_strings' : app_strings,
7137 'email' : meta.email
7140 // open popup window
7141 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7142 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7144 popup.document.write(out);
7145 popup.document.close();
7149 * Takes formatted response and creates a modal pop-over containing a title and content
7151 displayView : function(o) {
7152 var SED = SUGAR.email2.detailView;
7153 var ret = YAHOO.lang.JSON.parse(o.responseText);
7155 if(!SED.viewDialog) {
7156 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7160 constraintoviewport: true,
7163 SED.viewDialog.renderEvent.subscribe(function() {
7164 var content = this.body.firstChild;
7165 var viewH = YAHOO.util.Dom.getViewportHeight();
7167 this.body.style.overflow = "auto";
7168 this.body.style.width = "800px";
7169 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7173 SED.viewDialog.setHeader(ret.title);
7174 SED.viewDialog.setBody(ret.html);
7175 SED.viewDialog.render();
7176 SED.viewDialog.show();
7180 * Generates a modal popup to populate with the contents of bean's full EditView
7182 showQuickCreateForm : function(o) {
7183 var SED = SUGAR.email2.detailView;
7184 var ret = YAHOO.lang.JSON.parse(o.responseText);
7186 if(!SED.quickCreateDialog) {
7187 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7191 constraintoviewport: true,
7195 SED.quickCreateDialog.renderEvent.subscribe(function() {
7196 var viewH = YAHOO.util.Dom.getViewportHeight();
7198 for (var i in this.body.childNodes) {
7199 if (this.body.childNodes[i].clientHeight) {
7200 contH += this.body.childNodes[i].clientHeight;
7201 } else if (this.body.childNodes[i].offsetHeight) {
7202 contH += this.body.childNodes[i].offsetHeight;
7205 this.body.style.width = "800px";
7206 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7207 this.body.style.overflow = "auto";
7208 }, SED.quickCreateDialog);
7210 SED.quickCreateDialog.hideEvent.subscribe(function(){
7211 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7212 /*for(var qsField in qsFields){
7213 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7214 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7217 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7220 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7222 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7223 SED.quickCreateDialog.render();
7224 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7226 SED.quickCreateDialog.ieId = ret.ieId;
7227 SED.quickCreateDialog.uid = ret.uid;
7228 SED.quickCreateDialog.mbox = ret.mbox;
7229 SED.quickCreateDialog.qcmodule = ret.module;
7231 SED.quickCreateDialog.show();
7233 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7235 editForm.module.value = 'Emails';
7236 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7237 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7238 var instId = ret.module + count;
7239 SED.quickCreateEmailsToAdd = ret.emailAddress;
7240 SED.quickCreateEmailCallback = function(instId, tableId) {
7241 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7242 if (typeof(eaw) == "undefined")
7243 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7244 + instId + "','" + tableId + "');", 100);
7245 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7247 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7248 + instId + "','" + tableId + "');", 100);
7252 saveQuickCreateForm : function(o) {
7253 SUGAR.hideMessageBox();
7254 SUGAR.email2.detailView.quickCreateDialog.hide();
7255 validate['EditView'] = [ ];
7258 saveQuickCreateFormAndReply : function(o) {
7259 SUGAR.hideMessageBox();
7260 var ret = YAHOO.lang.JSON.parse(o.responseText);
7261 SUGAR.email2.detailView.quickCreateDialog.hide();
7262 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7263 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7265 var emailID = ret.id;
7266 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7268 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7270 //Cean the validate cache to prevent errors on the next call
7271 validate['EditView'] = [ ];
7274 saveQuickCreateFormAndAddToAddressBook : function(o) {
7275 SUGAR.hideMessageBox();
7276 SUGAR.email2.detailView.quickCreateDialog.hide();
7277 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7278 validate['EditView'] = [ ];
7281 handleAssignmentDialogAssignAction : function() {
7284 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7286 var dist = 'direct';
7290 var found_teams = false;
7291 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7292 if(!found_teams && assign_user_id == '' )
7294 alert(warning_message);
7298 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7300 for(i=0; i<emailUids.length; i++) {
7302 uids += app_strings.LBL_EMAIL_DELIMITER;
7304 uids += emailUids[i];
7307 var row = SUGAR.email2.grid.getSelectedRows()[0];
7308 var data = SUGAR.email2.grid.getRecord(row).getData();
7309 var ieid = data.ieId;
7310 var mbox = data.mbox;
7311 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7312 SUGAR.email2.contextMenus.assignToDialogue.hide();
7313 SUGAR.showMessageBox('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7317 handleAssignmentDialogDeleteAction : function() {
7318 // TO pass list of UIDS/emailIds
7319 var uids = SUGAR.email2.listView.getUidsFromSelection();
7320 var row = SUGAR.email2.grid.getSelections()[0];
7321 var ieid = row.data.ieId;
7322 var mbox = row.data.mbox;
7323 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7324 SUGAR.email2.contextMenus.assignmentDialog.hide();
7325 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7331 showEmailDetailView : function(o) {
7332 SUGAR.hideMessageBox();
7333 var SED = SUGAR.email2.detailView;
7334 var ret = YAHOO.lang.JSON.parse(o.responseText);
7336 if(!SED.quickCreateDialog) {
7337 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7341 constraintoviewport: true,
7343 autofillheight: "body",
7346 SED.quickCreateDialog.renderEvent.subscribe(function() {
7347 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7349 for (var i in this.body.childNodes) {
7350 if (this.body.childNodes[i].offsetHeight)
7351 contH += this.body.childNodes[i].offsetHeight;
7353 this.body.style.overflow = "auto";
7354 this.body.style.width = "800px";
7355 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7357 }, SED.quickCreateDialog);
7359 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7360 SED.quickCreateDialog.setBody(ret.html);
7361 SED.quickCreateDialog.render();
7362 SUGAR.util.evalScript(ret.html);
7363 SED.quickCreateDialog.show();
7366 showAssignmentDialogWithData : function(o) {
7367 var SEC = SUGAR.email2.contextMenus;
7368 SUGAR.hideMessageBox();
7369 var ret = YAHOO.lang.JSON.parse(o.responseText);
7370 if (!SEC.assignmentDialog) {
7371 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7374 constraintoviewport: true,
7377 SEC.assignmentDialog.setBody("");
7378 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7379 SEC.assignmentDialog.renderEvent.subscribe(function() {
7380 var iev = YAHOO.util.Dom.get("Distribute");
7382 this.body.style.width = "700px";
7384 }, SEC.assignmentDialog);
7385 SEC.assignmentDialog.render();
7387 SEC.assignmentDialog.setBody(ret);
7388 SEC.assignmentDialog.render();
7390 SEC.assignmentDialog.show();
7391 SUGAR.util.evalScript(ret);
7394 showImportForm : function(o) {
7395 var SED = SUGAR.email2.detailView;
7396 var ret = YAHOO.lang.JSON.parse(o.responseText);
7398 document.getElementById('quickCreateContent').innerHTML = "";
7399 SUGAR.hideMessageBox();
7404 if(!SED.importDialog) {
7405 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7409 constraintoviewport: true,
7411 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7412 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7416 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7417 SED.importDialog.setBody("");
7418 SED.importDialog.hideEvent.subscribe(function(){
7419 for(var i in QSFieldsArray) {
7420 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7421 QSFieldsArray[i].destroy();
7422 delete QSFieldsArray[i];
7424 if (QSProcessedFieldsArray[i]) {
7425 QSProcessedFieldsArray[i] = false;
7429 SED.importDialog.renderEvent.subscribe(function() {
7430 var iev = YAHOO.util.Dom.get("ImportEditView");
7432 //this.body.style.height = (iev.clientHeight + 10) + "px";
7433 this.body.style.width = "600px";
7435 }, SED.importDialog);
7436 SED.importDialog.render();
7438 SED.importDialog.setBody(ret.html);
7439 SED.importDialog.ret = ret;
7440 SUGAR.util.evalScript(ret.html);
7441 SED.importDialog.render();
7443 SED.importDialog.show();
7444 SED.importDialog.focusFirstButton();
7446 getImportAction : function(ret) {
7447 if (!check_form('ImportEditView')) return false;
7448 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7449 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7453 var editView = document.getElementById('ImportEditView');
7454 if (editView.assigned_user_id != null) {
7455 get = get + "&user_id=" + editView.assigned_user_id.value
7456 //var user_id = editView.assigned_user_id.value;
7458 var parent_id = editView.parent_id.value;
7459 var parent_type = editView.parent_type.value;
7460 var row = SUGAR.email2.grid.getSelectedRows()[0];
7461 row = SUGAR.email2.grid.getRecord(row);
7462 var data = row.getData();
7463 var ieId = data.ieId;
7464 var mbox = data.mbox;
7465 var serverDelete = editView.serverDelete.checked;
7466 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7468 for(i=0; i<emailUids.length; i++) {
7470 uids += app_strings.LBL_EMAIL_DELIMITER;
7472 uids += emailUids[i];
7475 var action = 'importEmail&uid=';
7477 action = 'moveEmails';
7478 action = action + '&sourceFolder=' + ret['srcFolder'];
7479 action = action + '&sourceIeId=' + ret['srcIeId'];
7480 action = action + '&destinationFolder=' + ret['dstFolder'];
7481 action = action + '&destinationIeId=' + ret['dstIeId'];
7482 action = action + '&emailUids=';
7484 if (action.search(/importEmail/) != -1) {
7485 SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7487 SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7490 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7491 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7492 SUGAR.email2.detailView.importDialog.hide();
7493 document.getElementById('importDialogContent').innerHTML = "";
7496 showRelateForm : function(o) {
7497 var SED = SUGAR.email2.detailView;
7498 var ret = YAHOO.lang.JSON.parse(o.responseText);
7499 document.getElementById('quickCreateContent').innerHTML = "";
7500 SUGAR.hideMessageBox();
7504 dialog_loaded = true;
7506 if(!SED.relateDialog) {
7507 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7512 constraintoviewport: true,
7514 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7515 if (!check_form('RelateEditView')) return false;
7517 var editView = document.getElementById('RelateEditView');
7518 var parent_id = editView.parent_id.value;
7519 var parent_type = editView.parent_type.value;
7520 var row = SUGAR.email2.grid.getSelectedRows()[0];
7521 row = SUGAR.email2.grid.getRecord(row);
7522 var ieId = row.getData().ieId;
7523 var mbox = row.getData().mbox;
7524 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7526 for(i=0; i<emailUids.length; i++) {
7528 uids += app_strings.LBL_EMAIL_DELIMITER;
7530 uids += emailUids[i];
7532 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7533 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7534 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7535 SED.relateDialog.hide();
7536 document.getElementById('relateDialogContent').innerHTML = "";
7541 SED.relateDialog.hideEvent.subscribe(function(){
7542 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7543 QSFieldsArray['ImportEditView_parent_name'].destroy();
7544 delete QSFieldsArray['ImportEditView_parent_name'];
7546 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7547 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7551 SED.relateDialog.renderEvent.subscribe(function() {
7552 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7554 for (var i in this.body.childNodes) {
7555 if (this.body.childNodes[i].clientHeight)
7556 contH += this.body.childNodes[i].clientHeight;
7558 }, SED.relateDialog);
7559 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7562 SED.relateDialog.setBody(ret.html);
7563 SED.relateDialog.render();
7564 SUGAR.util.evalScript(ret.html);
7565 SED.relateDialog.show();
7569 * DetailView callbacks
7571 AjaxObject.detailView.callback = {
7573 success : function(o) {
7575 var ret = YAHOO.lang.JSON.parse(o.responseText);
7576 SUGAR.email2.detailView.consumeMetaDetail(ret);
7578 argument: [targetDiv],
7579 failure : AjaxObject.handleFailure,
7584 success : function(o) {
7586 var ret = YAHOO.lang.JSON.parse(o.responseText);
7587 SUGAR.email2.detailView.consumeMetaPreview(ret);
7589 failure : AjaxObject.handleFailure,
7594 success : AjaxObject.detailView.displayPrintable,
7595 failure : AjaxObject.handleFailure,
7596 timeout : AjaxObject.timeout,
7600 success : AjaxObject.detailView.displayView,
7601 failure : AjaxObject.handleFailure,
7602 timeout : AjaxObject.timeout,
7611 AjaxObject.folders = {
7613 * check-mail post actions
7615 checkMailCleanup : function(o) {
7616 SUGAR.hideMessageBox();
7617 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7619 // refresh focus ListView
7620 SE.listView.refreshGrid();
7621 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7626 rebuildFolders : function(o) {
7627 SUGAR.hideMessageBox();
7629 var data = YAHOO.lang.JSON.parse(o.responseText);
7631 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7632 SUGAR.email2.folders.setSugarFolders();
7635 AjaxObject.folders.callback = {
7637 success : AjaxObject.folders.checkMailCleanup,
7638 failure : AjaxObject.handleFailure,
7639 timeout : 600000, // 5 mins
7644 AjaxObject.rules = {
7645 loadRulesForSettings : function(o) {
7646 document.getElementById("rulesListCell").innerHTML = o.responseText;
7647 // assume we have the class we need
7648 SUGAR.routing.getStrings();
7649 SUGAR.routing.getDependentDropdowns();
7652 //// END PER MODULE CALLBACK OBJECTS
7653 ///////////////////////////////////////////////////////////////////////////
7657 success : AjaxObject.handleSuccess,
7658 failure : AjaxObject.handleFailure,
7659 timeout : AjaxObject.timeout,
7662 var callbackAccount = {
7663 success : AjaxObject.ieSaveSuccess,
7664 failure : AjaxObject.handleFailure,
7665 timeout : AjaxObject.timeout,
7668 var callbackAccountDelete = {
7669 success : AjaxObject.ieDeleteSuccess,
7670 failure : AjaxObject.handleFailure,
7671 timeout : AjaxObject.timeout,
7674 var callbackOutboundTest = {
7675 success : AjaxObject.ieSendSuccess,
7676 failure : AjaxObject.handleFailure,
7677 timeout : AjaxObject.timeout,
7683 var callbackTeamInfoForSettings = {
7684 success : function (o) {
7685 var data = YAHOO.lang.JSON.parse(o.responseText);
7686 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7688 failure : AjaxObject.handleFailure,
7689 timeout : AjaxObject.timeout,
7694 var callbackStatusForImport = {
7695 success : function (o) {
7696 SUGAR.hideMessageBox();
7697 if (o.responseText != "") {
7698 var statusString = "";
7699 var data = YAHOO.lang.JSON.parse(o.responseText);
7700 for(i=0; i<data.length; i++) {
7701 statusString = statusString + data[i] + '<br/>';
7703 SUGAR.showMessageBox(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7705 SE.listView.refreshGrid();
7708 failure : AjaxObject.handleFailure,
7709 timeout : AjaxObject.timeout,
7713 var callbackComposeCache = {
7714 success : AjaxObject.composeCache,
7715 failure : AjaxObject.handleFailure,
7716 timeout : AjaxObject.timeout,
7719 var callbackDelete = {
7720 success : AjaxObject.handleDeleteReturn,
7721 failure : AjaxObject.handleFailure,
7722 timeout : AjaxObject.timeout,
7725 var callbackEmailDetailMultiple = {
7726 success : function(o) {
7727 SUGAR.hideMessageBox();
7728 var retMulti = YAHOO.lang.JSON.parse(o.responseText);
7729 var ret = new Object();
7731 for(var i=0; i<retMulti.length; i++) {
7734 SUGAR.email2._setDetailCache(ret);
7735 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7738 failure : AjaxObject.handleFailure,
7742 var callbackListViewSortOrderChange = {
7743 success : AjaxObject.saveListViewSortOrderPart2,
7744 failure : AjaxObject.handleFailure,
7745 timeout : AjaxObject.timeout,
7747 argument : [ieId, ieName, focusFolder]
7749 var callbackEmptyTrash = {
7750 success : function(o) {
7751 SUGAR.hideMessageBox();
7752 AjaxObject.folderRenameCleanup;
7754 failure : AjaxObject.handleFailure,
7755 timeout : AjaxObject.timeout,
7758 var callbackClearCacheFiles = {
7759 success : function(o) {
7760 SUGAR.hideMessageBox();
7762 failure : AjaxObject.handleFailure,
7763 timeout : AjaxObject.timeout,
7766 var callbackFolderRename = {
7767 success : function(o) {SUGAR.hideMessageBox();SUGAR.email2.folders.rebuildFolders();},
7768 failure : AjaxObject.handleFailure,
7769 timeout : AjaxObject.timeout,
7772 var callbackFolderDelete = {
7773 success : function(o) {
7774 var ret = YAHOO.lang.JSON.parse(o.responseText);
7776 if (ret.folder_id) {
7777 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7779 SUGAR.email2.tree.removeNode(node, true);
7780 } else if (ret.ieId && ret.mbox) {
7781 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7783 SUGAR.email2.tree.removeNode(node, true);
7785 SUGAR.hideMessageBox();
7786 //SUGAR.email2.folders.loadSettingFolder();
7788 SUGAR.hideMessageBox();
7789 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7792 failure : AjaxObject.handleFailure,
7793 timeout : AjaxObject.timeout,
7796 var callbackFolderSave = {
7797 success : function(o) {
7798 var ret = YAHOO.lang.JSON.parse(o.responseText);
7800 switch(ret.action) {
7801 case 'newFolderSave':
7802 SUGAR.email2.folders.rebuildFolders();
7806 failure : AjaxObject.handleFailure,
7807 timeout : AjaxObject.timeout,
7810 var callbackFolderSubscriptions = {
7811 success : AjaxObject.updateFolderSubscriptions,
7812 failure : AjaxObject.handleFailure,
7813 timeout : AjaxObject.timeout,
7816 var callbackFolderUpdate = {
7817 success : AjaxObject.updateFrameFolder,
7818 failure : AjaxObject.handleFailure,
7819 timeout : AjaxObject.timeout,
7822 var callbackFolders = {
7823 success : AjaxObject.folders.rebuildFolders,
7824 //success : void(true),
7825 failure : AjaxObject.handleFailure,
7826 timeout : AjaxObject.timeout,
7829 var callbackFullSync = {
7830 success : AjaxObject.fullSyncCleanup,
7831 failure : AjaxObject.handleFailure,
7832 timeout : 9999999999999,
7835 var callbackGeneric = {
7836 success : function() {
7837 SUGAR.hideMessageBox();
7839 failure : AjaxObject.handleFailure,
7840 timeout : AjaxObject.timeout,
7843 var callbackIeAccountRetrieve = {
7844 success : function(o) {
7845 // return JSON encoding
7846 SUGAR.hideMessageBox();
7847 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7848 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7850 failure : AjaxObject.handleFailure,
7851 timeout : AjaxObject.timeout,
7854 var callbackImportOneEmail = {
7855 success : AjaxObject.detailView.showImportForm,
7856 failure : AjaxObject.handleFailure,
7857 timeout : AjaxObject.timeout,
7860 var callbackRelateEmail = {
7861 success : AjaxObject.detailView.showRelateForm,
7862 failure : AjaxObject.handleFailure,
7863 timeout : AjaxObject.timeout,
7866 var callbackEmailDetailView = {
7867 success : AjaxObject.detailView.showEmailDetailView,
7868 failure : AjaxObject.handleFailure,
7869 timeout : AjaxObject.timeout,
7872 var callbackAssignmentDialog = {
7873 success : AjaxObject.detailView.showAssignmentDialogWithData,
7874 failure : AjaxObject.handleFailure,
7875 timeout : AjaxObject.timeout,
7878 var callbackAssignmentAction = {
7879 success : function(o) {
7880 SE.listView.refreshGrid();
7881 SUGAR.hideMessageBox();
7882 if(o.responseText != '') {
7883 SUGAR.showMessageBox('Assignment action result', o.responseText, 'alert');
7886 failure : AjaxObject.handleFailure,
7887 timeout : AjaxObject.timeout,
7890 var callbackMoveEmails = {
7891 success : function(o) {
7892 SE.listView.refreshGrid();
7893 SUGAR.hideMessageBox();
7894 if(o.responseText != '') {
7895 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7898 failure : AjaxObject.handleFailure,
7899 timeout : AjaxObject.timeout,
7902 var callbackLoadAttachments = {
7903 success : AjaxObject.loadAttachments,
7904 failure : AjaxObject.handleFailure,
7905 timeout : AjaxObject.timeout,
7908 var callbackLoadRules = {
7909 success : AjaxObject.rules.loadRulesForSettings,
7910 failure : AjaxObject.handleFailure,
7911 timeout : AjaxObject.timeout,
7914 var callbackLoadSignature = {
7915 success : AjaxObject.loadSignature,
7916 failure : AjaxObject.handleFailure,
7917 timeout : AjaxObject.timeout,
7920 var callbackDeleteSignature = {
7921 success : AjaxObject.handleDeleteSignature,
7922 failure : AjaxObject.handleFailure,
7923 timeout : AjaxObject.timeout,
7926 /*var callbackMoveEmails = {
7927 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7928 failure : AjaxObject.handleFailure,
7929 timeout : AjaxObject.timeout,
7932 var callbackOutboundSave = {
7933 success : AjaxObject.accounts.saveOutboundCleanup,
7934 failure : AjaxObject.handleFailure,
7935 timeout : AjaxObject.timeout,
7938 var callbackDefaultOutboundSave = {
7939 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7940 failure : AjaxObject.handleFailure,
7941 timeout : AjaxObject.timeout,
7944 var callbackQuickCreate = {
7945 success : AjaxObject.detailView.showQuickCreateForm,
7946 failure : AjaxObject.handleFailure,
7947 timeout : AjaxObject.timeout,
7950 var callbackQuickCreateSave = {
7951 success : AjaxObject.detailView.saveQuickCreateForm,
7952 failure : AjaxObject.handleFailure,
7953 timeout : AjaxObject.timeout,
7956 var callbackQuickCreateSaveAndAddToAddressBook = {
7957 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7958 failure : AjaxObject.handleFailure,
7959 timeout : AjaxObject.timeout,
7962 var callbackQuickCreateSaveAndReply = {
7963 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7964 failure : AjaxObject.handleFailure,
7965 timeout : AjaxObject.timeout,
7968 var callbackQuickCreateSaveAndReplyCase = {
7969 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7970 failure : AjaxObject.handleFailure,
7971 timeout : AjaxObject.timeout,
7974 var callbackRebuildShowAccountList = {
7975 success : AjaxObject.rebuildShowFolders,
7976 failure : AjaxObject.handleFailure,
7977 timeout : AjaxObject.timeout,
7981 var callbackRefreshSugarFolders = {
7982 success : function(o) {
7983 var t = YAHOO.lang.JSON.parse(o.responseText);
7984 SUGAR.email2.folders.setSugarFoldersEnd(t);
7986 failure : AjaxObject.handleFailure,
7987 timeout : AjaxObject.timeout,
7990 var callbackReplyForward = {
7991 success : AjaxObject.handleReplyForward,
7992 finish : function(a, retryCount) {
7993 if (typeof(retryCount) == 'undefined') {
7998 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7999 var t = tinyMCE.getInstanceById('htmleditor' + idx);
8001 var html = t.getContent();
8003 html = " <div><hr></div>" + a.description;
8005 t.setContent(html);//
8007 if (a.type != 'draft') {
8008 // Next step, attach signature
8009 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
8013 if (retryCount < 5) {
8014 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
8018 var tabArray = SUGAR.email2.innerLayout.get("tabs");
8019 if (tabArray != null && tabArray.length > 0) {
8020 for (i = 0 ; i < tabArray.length ; i++) {
8021 var tabObject = tabArray[i];
8022 if (tabObject.get("id") == ("composeTab" + idx)) {
8023 var tabLabel = a.name;
8024 if (tabLabel != null && tabLabel.length > 25) {
8025 tabLabel = tabLabel.substring(0, 25) + "...";
8027 tabObject.get("labelEl").firstChild.data = tabLabel;
8033 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8034 if (a.parent_name != null && a.parent_name != "") {
8035 document.getElementById('data_parent_name' + idx).value = a.parent_name;
8037 if (a.parent_type != null && a.parent_type != "") {
8038 document.getElementById('data_parent_type' + idx).value = a.parent_type;
8040 if (a.parent_id != null && a.parent_id != "") {
8041 document.getElementById('data_parent_id' + idx).value = a.parent_id;
8043 if (a.fromAccounts.status) {
8044 var addressFrom = document.getElementById('addressFrom' + idx);
8045 SUGAR.email2.util.emptySelectOptions(addressFrom);
8046 var fromAccountOpts = a.fromAccounts.data;
8047 for(i=0; i<fromAccountOpts.length; i++) {
8048 var key = fromAccountOpts[i].value;
8049 var display = fromAccountOpts[i].text;
8050 var opt = new Option(display, key);
8051 if (fromAccountOpts[i].selected) {
8052 opt.selected = true;
8054 addressFrom.options.add(opt);
8057 SUGAR.hideMessageBox();
8060 failure : AjaxObject.handleFailure,
8061 timeout : AjaxObject.timeout,
8063 argument : [sendType]
8065 var callbackSendEmail = {
8066 success : AjaxObject.sendEmailCleanUp,
8067 failure : AjaxObject.handleFailure,
8068 timeout : AjaxObject.timeout,
8071 var callbackSettings = {
8072 success : AjaxObject.updateUserPrefs,
8073 failure : AjaxObject.handleFailure,
8074 timeout : AjaxObject.timeout,
8077 var callbackSettingsFolderRefresh = {
8078 success : AjaxObject.settingsFolderRefresh,
8079 failure : AjaxObject.handleFailure,
8080 timeout : AjaxObject.timeout,
8083 var callbackLoadSettingFolder = {
8084 success : function(o) {
8085 AjaxObject.settingsFolderRefresh(o);
8086 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8088 failure : AjaxObject.handleFailure,
8089 timeout : AjaxObject.timeout,
8093 var callbackUploadAttachment = {
8094 success : AjaxObject.uploadAttachmentSuccessful,
8095 upload : AjaxObject.uploadAttachmentSuccessful,
8096 failure : AjaxObject.handleFailure,
8097 timeout : AjaxObject.timeout,
8100 var callbackUserPrefs = {
8101 success : function(o) {
8102 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
8104 failure : AjaxObject.handleFailure,
8105 timeout : AjaxObject.timeout,
8109 var callbackContextmenus = {
8111 success : AjaxObject.markEmailCleanup,
8112 failure : AjaxObject.handleFailure,
8113 timeout : AjaxObject.timeout,
8118 var callbackCheckEmail2 = {
8119 success : function(o) {
8120 var ret = YAHOO.lang.JSON.parse(o.responseText);
8121 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8125 failure : AjaxObject.handleFailure,
8126 timeout : AjaxObject.timeout,
8128 }// End of File modules/Emails/javascript/ajax.js
8130 /*********************************************************************************
8131 * SugarCRM Community Edition is a customer relationship management program developed by
8132 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8134 * This program is free software; you can redistribute it and/or modify it under
8135 * the terms of the GNU Affero General Public License version 3 as published by the
8136 * Free Software Foundation with the addition of the following permission added
8137 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8138 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8139 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8141 * This program is distributed in the hope that it will be useful, but WITHOUT
8142 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8143 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8146 * You should have received a copy of the GNU Affero General Public License along with
8147 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8148 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8151 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8152 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8154 * The interactive user interfaces in modified source and object code versions
8155 * of this program must display Appropriate Legal Notices, as required under
8156 * Section 5 of the GNU Affero General Public License version 3.
8158 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8159 * these Appropriate Legal Notices must retain the display of the "Powered by
8160 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8161 * technical reasons, the Appropriate Legal Notices must display the words
8162 * "Powered by SugarCRM".
8163 ********************************************************************************/
8165 function gridInit() {
8166 if(SUGAR.email2.grid) {
8167 SUGAR.email2.grid.destroy();
8173 var Ck = YAHOO.util.Cookie;
8174 var widths = [ 10, 10, 150, 250, 175, 125 ];
8176 if (Ck.get("EmailGridWidths")) {
8177 for (var i=0; i < widths.length; i++) {
8178 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8181 for (var i=0; i < widths.length; i++) {
8182 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8186 // changes "F" to an icon
8187 function flaggedIcon(cell, record, column, value) {
8189 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8192 // changes "A" to replied icon
8193 function repliedIcon(cell, record, column, value) {
8195 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8198 function attachIcon(cell, record, column, value) {
8200 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8207 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8212 formatter: attachIcon,
8216 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8221 formatter: flaggedIcon,
8225 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8230 formatter: repliedIcon,
8234 label: app_strings.LBL_EMAIL_FROM,
8241 label: app_strings.LBL_EMAIL_SUBJECT,
8248 label: mod_strings.LBL_LIST_DATE,
8255 label: app_strings.LBL_EMAIL_TO,
8291 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8292 responseType: YAHOO.util.DataSource.TYPE_JSON,
8294 resultsList: 'Email',
8295 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8296 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8302 action : "EmailUIAjax",
8303 emailUIAction : "getMessageList",
8306 forceRefresh : "false"
8308 if(lazyLoadFolder != null) {
8309 params['mbox'] = lazyLoadFolder.folder;
8310 params['ieId'] = lazyLoadFolder.ieId;
8311 //Check if the folder is a Sugar Folder
8312 var test = new String(lazyLoadFolder.folder);
8313 if(test.match(/SUGAR\./)) {
8314 params['emailUIAction'] = 'getMessageListSugarFolders';
8315 params['mbox'] = test.substr(6);
8318 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8321 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8322 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8324 paginator: new YAHOO.widget.Paginator({
8325 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8326 containers : ["dt-pag-nav"],
8327 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8328 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8329 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8330 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8331 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8333 initialRequest:SUGAR.util.paramsToUrl(params),
8340 //Override Paging request construction
8341 grid.set("generateRequest", function(oState, oSelf) {
8342 oState = oState || {pagination:null, sortedBy:null};
8343 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8344 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8345 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8346 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8347 // Build the request
8349 SUGAR.util.paramsToUrl(oSelf.params) +
8352 "&start=" + startIndex +
8353 ((results !== null) ? "&limit=" + results : "");
8358 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8359 oPayload = oPayload || { };
8361 oPayload.totalRecords = oResponse.meta.total;
8362 oPayload.unreadRecords = oResponse.meta.unread;
8364 var tabObject = SE.innerLayout.get("tabs")[0];
8366 if (this.params.mbox != null) {
8367 mboxTitle = this.params.mbox;
8369 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8370 tabObject.get("labelEl").firstChild.data = tabtext;
8373 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8375 node.data.unseen = oResponse.meta.unread;
8376 SE.accounts.renderTree();
8382 var resize = grid.resizeGrid = function () {
8383 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8384 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8386 grid.convertDDRows = function() {
8387 var rowEl = this.getFirstTrEl();
8388 while (rowEl != null) {
8389 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8390 rowEl = this.getNextTrEl(rowEl);
8395 grid.on("columnResizeEvent", function(o) {
8396 //Find the index of the column
8397 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8398 for (var i=0; i < colSet.length; i++) {
8399 if (o.column == colSet[i]) {
8400 //Store it in the cookie
8401 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8404 //this.resizeGrid();
8407 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8408 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8409 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8411 SUGAR.email2.listViewLayout.on("render", resize);
8414 //Setup the default load parameters
8415 SUGAR.email2.grid.params = params;
8417 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8418 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8419 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8426 function initRowDD() {
8427 var sg = SUGAR.email2.grid,
8428 Dom = YAHOO.util.Dom;
8429 sg.DDRow = function(oDataTable, oRecord, elTr) {
8430 if(oDataTable && oRecord && elTr) {
8431 this.ddtable = oDataTable;
8432 this.table = oDataTable.getTableEl();
8435 this.newIndex = null;
8437 this.initFrame(); // Needed for DDProxy
8438 this.invalidHandleTypes = {};
8442 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8443 _resizeProxy: function() {
8444 this.constructor.superclass._resizeProxy.apply(this, arguments);
8445 var dragEl = this.getDragEl(),
8447 var xy = Dom.getXY(el);
8449 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8450 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8451 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8452 Dom.setStyle(dragEl, 'display', "");
8455 startDrag: function(x, y) {
8456 //Check if we should be dragging a set of rows rather than just the one.
8457 var selectedRows = this.ddtable.getSelectedRows();
8458 var iSelected = false;
8459 for (var i in selectedRows) {
8460 if (this.rowEl.id == selectedRows[i]) {
8467 for (var i in selectedRows) {
8468 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8471 this.rows = [this.row];
8472 this.ddtable.unselectAllRows();
8473 this.ddtable.selectRow(this.row);
8476 //Initialize the dragable proxy
8477 var dragEl = this.getDragEl();
8478 var clickEl = this.getEl();
8479 Dom.setStyle(clickEl, "opacity", "0.25");
8480 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8481 Dom.addClass(dragEl, "yui-dt-liner");
8482 Dom.setStyle(dragEl, "opacity", "0.5");
8483 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8484 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8485 Dom.setStyle(dragEl, "border", "2px solid gray");
8488 clickValidator: function(e) {
8489 if (this.row.getData()[0] == " ")
8491 var target = YAHOO.util.Event.getTarget(e);
8492 return ( this.isValidHandleChild(target) &&
8493 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8496 * This funciton checks that the target of the drag is a table row in this
8497 * DDGroup and simply moves the sourceEL to that location as a preview.
8499 onDragOver: function(ev, id) {
8500 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8501 if (node && node != this.targetNode) {
8502 this.targetNode = node;
8503 SUGAR.email2.folders.unhighliteAll();
8508 onDragOut: function(e, id) {
8509 if (this.targetNode) {
8510 SUGAR.email2.folders.unhighliteAll();
8511 this.targetNode = false;
8514 endDrag: function() {
8515 Dom.setStyle(this.getEl(), "opacity", "");
8516 Dom.setStyle(this.getDragEl(), "display", "none");
8517 if (this.targetNode) {
8518 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8520 SUGAR.email2.folders.unhighliteAll();
8526 function AddressSearchGridInit() {
8527 function moduleIcon(elCell, oRecord, oColumn, oData) {
8528 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8530 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8531 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8533 var checkHeader = '<input type="checkbox" ';
8534 if (SUGAR.email2.util.isIe()) {
8535 checkHeader += 'style="top:-5px" ';
8537 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8542 formatter: selectionCheckBox,
8546 label: mod_strings.LBL_LIST_TYPE,
8548 formatter: moduleIcon,
8552 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8558 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8564 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8565 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8567 resultsList: 'Person',
8568 fields: ['name', 'email', 'bean_id', 'bean_module'],
8569 metaFields: {total: 'TotalCount'}
8571 //enable sorting on the server accross all data
8574 dataModel.params = {
8577 action : "EmailUIAjax",
8578 emailUIAction:"getAddressSearchResults"
8580 var rb = document.getElementById('hasRelatedBean').checked;
8582 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8583 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8584 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8585 dataModel.params['related_bean_id'] = relatedBeanId;
8586 dataModel.params['related_bean_type'] = relatedBeanType;
8587 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8589 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8591 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8592 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8594 paginator: new YAHOO.widget.Paginator({
8596 containers : ["dt-pag-nav-addressbook"],
8597 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8598 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8599 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8600 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8601 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8603 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8607 //Override Paging request construction
8608 grid.set("generateRequest", function(oState, oSelf) {
8609 oState = oState || {pagination:null, sortedBy:null};
8610 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8611 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8612 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8613 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8614 // Build the request
8616 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8617 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8618 ((results !== null) ? "&limit=" + results : "");
8622 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8623 oPayload = oPayload || { };
8624 oPayload.totalRecords = oResponse.meta.total;
8628 grid.clickToggleSelect= function(args) {
8629 var isIE = (args.event.target == null);
8630 var targetElement = isIE ? args.event.srcElement : args.event.target;
8631 if(targetElement.type == null || targetElement.type != 'checkbox') {
8632 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8636 grid.reSelectRowsOnRender = function (){
8637 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8638 for (var i = 0; i < rows.length; i++)
8640 var emailAddress = rows[i].getData("email");
8641 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8644 rows[i].setData("selected", true);
8645 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8649 rows[i].setData("selected", false);
8650 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8654 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8655 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8656 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8657 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8660 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8661 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8663 grid.toggleSelectCheckbox = function(id,checked){
8664 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8665 row.setData("checked",checked);
8667 grid.toggleSelect = function(id, checked) {
8668 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8669 checked = row.getData("selected");
8672 SUGAR.email2.addressBook.grid.selectRow(row);
8673 SE.addressBook.insertContactRowToResultTable(id,null)
8676 SUGAR.email2.addressBook.grid.unselectRow(row);
8677 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8679 row.setData("selected", !checked);
8682 grid.toggleSelectAll = function(checked) {
8683 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8684 for (var i = 0; i < rows.length; i++) {
8685 if (typeof(rows[i]) != "undefined")
8686 rows[i].setData("checked", checked);
8688 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8689 for (var i = 0; i < checkBoxes.length; i++) {
8690 checkBoxes[i].checked = checked;
8694 //Initialize the grid result table.
8695 AddressSearchResultsGridInit();
8701 * Initalize the results table for the address book selection.
8704 function AddressSearchResultsGridInit()
8707 /* Full name sort funciton to compare by last name if available */
8708 var fullNameSort = function(a, b, desc) {
8709 // Deal with empty values
8710 if(!YAHOO.lang.isValue(a))
8711 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8712 else if(!YAHOO.lang.isValue(b))
8715 var aNames = a.getData("name").split(' ');
8716 var bNames = b.getData("name").split(' ');
8718 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8719 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8721 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8725 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8726 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8727 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8729 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})},
8730 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8732 var myDataSource = new YAHOO.util.DataSource([]);
8733 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8734 myDataSource.responseSchema = {
8735 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8738 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8739 width: "350px",height: "250px", MSG_EMPTY: " "});
8741 var highlightEditableCell = function(oArgs) {
8742 var elCell = oArgs.target;
8743 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8744 this.highlightCell(elCell);
8748 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8749 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8750 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8751 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8752 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8754 //Setup the context menus
8755 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8756 var task = p_aArgs[1];
8759 var elRow = this.contextEventTarget;
8760 elRow = p_myDataTable.getTrEl(elRow);
8767 var oRecord = p_myDataTable.getRecord(elRow);
8768 p_myDataTable.deleteRow(elRow);
8769 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8774 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8775 {trigger:gridResults.getTbodyEl()});
8776 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8777 contextMenu.render("addrSearchResultGrid");
8778 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8780 // End of File modules/Emails/javascript/grid.js
8782 /*********************************************************************************
8783 * SugarCRM Community Edition is a customer relationship management program developed by
8784 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8786 * This program is free software; you can redistribute it and/or modify it under
8787 * the terms of the GNU Affero General Public License version 3 as published by the
8788 * Free Software Foundation with the addition of the following permission added
8789 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8790 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8791 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8793 * This program is distributed in the hope that it will be useful, but WITHOUT
8794 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8795 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8798 * You should have received a copy of the GNU Affero General Public License along with
8799 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8800 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8803 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8804 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8806 * The interactive user interfaces in modified source and object code versions
8807 * of this program must display Appropriate Legal Notices, as required under
8808 * Section 5 of the GNU Affero General Public License version 3.
8810 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8811 * these Appropriate Legal Notices must retain the display of the "Powered by
8812 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8813 * technical reasons, the Appropriate Legal Notices must display the words
8814 * "Powered by SugarCRM".
8815 ********************************************************************************/
8818 /******************************************************************************
8819 * Initialize Email 2.0 Application
8822 //Override Sugar Languge so quick creates work properly
8825 function email2init() {
8828 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
8829 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
8830 if (!SUGAR.util.isTouchScreen()) {
8832 convert_urls : false,
8833 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
8834 width: tinyConfig.width,
8835 theme: tinyConfig.theme,
8836 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
8837 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
8838 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
8839 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
8840 plugins : tinyConfig.plugins,
8841 elements : tinyConfig.elements,
8842 language : tinyConfig.language,
8843 extended_valid_elements : tinyConfig.extended_valid_elements,
8844 mode: tinyConfig.mode,
8845 strict_loading_mode : true,
8846 force_br_newlines : true,
8847 forced_root_block : '',
8848 directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
8852 // initialze message overlay
8853 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
8863 if (SUGAR.themes.tempHideLeftCol)
8864 SUGAR.themes.tempHideLeftCol();
8866 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
8867 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
8869 // set defaults for YAHOO.util.DragDropManager
8870 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
8872 SUGAR.email2.nextYear = new Date();
8873 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
8876 // initialize and display UI framework (complexLayout.js)
8877 complexLayoutInit();
8879 // initialize and display grid (grid.js)
8882 // initialize treeview for folders
8884 SUGAR.email2.folders.rebuildFolders(true);
8887 //Setup the Message Box overlay
8888 /*Ext.MessageBox.maxWidth = 350;
8889 Ext.MessageBox.minProgressWidth = 350;
8891 ///////////////////////////////////////////////////////////////////////////
8894 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
8896 var SEC = SUGAR.email2.contextMenus;
8899 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
8900 trigger: SUGAR.email2.grid.get("element"),
8903 emailMenu.subscribe("beforeShow", function() {
8904 var oTarget = this.contextEventTarget;
8905 if (typeof(oTarget) == "undefined")
8907 var grid = SUGAR.email2.grid;
8908 var selectedRows = grid.getSelectedRows();
8909 var multipleSelected = (selectedRows.length > 1) ? true: false;
8910 if (!multipleSelected)
8912 grid.unselectAllRows();
8913 grid.selectRow(oTarget);
8914 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8916 else if(multipleSelected)
8918 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8922 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
8923 //us to access individual elements easier by name rather than by index
8924 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
8925 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
8926 emailMenu.addItems([
8928 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
8929 id: 'showDetailView',
8930 onclick: { fn: SEC.showDetailView }
8933 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
8934 onclick: { fn: SEC.openMultiple }
8937 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
8938 onclick: { fn: SEC.archiveToSugar }
8941 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
8943 onclick: { fn: SEC.replyForwardEmailContext }
8946 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
8948 onclick: { fn: SEC.replyForwardEmailContext }
8951 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
8953 onclick: { fn: SEC.replyForwardEmailContext }
8956 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
8958 onclick: { fn: SEC.markDeleted }
8961 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
8963 onclick: { fn: SEC.viewPrintable }
8967 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
8969 id: "markEmailMenu",
8972 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
8973 onclick: { fn: SEC.markUnread }
8976 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
8977 onclick: { fn: SEC.markRead }
8980 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
8981 onclick: { fn: SEC.markFlagged }
8984 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
8985 onclick: { fn: SEC.markUnflagged }
8991 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
8993 onclick: { fn: SEC.assignEmailsTo }
8996 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
8998 onclick: { fn: SEC.relateTo }
9001 SEC.emailListContextMenu.render();
9003 //Handle the Tree folder menu trigger ourselves
9004 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9008 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9012 SEC.frameFoldersContextMenu.addItems([
9013 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9014 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9015 onclick: { fn: function() {
9016 var node = SUGAR.email2.clickedFolderNode;
9017 if (node.data.ieId) {
9018 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9021 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9022 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9023 onclick: { fn: function() {
9024 var node = SUGAR.email2.clickedFolderNode;
9025 if (node.data.ieId) {
9026 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9030 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9031 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9032 onclick: { fn: SUGAR.email2.folders.folderAdd }
9035 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9036 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9037 onclick: { fn: SUGAR.email2.folders.folderDelete }
9040 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9041 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9042 onclick: { fn: SUGAR.email2.folders.folderRename }
9045 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9046 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9047 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9050 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9051 onclick: { fn: function() {
9052 var node = SUGAR.email2.clickedFolderNode;
9053 if (node.data.ieId) {
9054 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9058 SEC.frameFoldersContextMenu.render();
9060 SEC.initContactsMenu = function() {
9062 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9063 trigger: "contacts",
9066 SEC.contactsContextMenu.addItems([
9068 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9069 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9072 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9073 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9076 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9077 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9078 if (oTarget && !grid.isSelected(oTarget)) {
9079 grid.unselectAllRows();
9080 grid.selectRow(oTarget);
9083 SEC.contactsContextMenu.render();
9087 // set auto-check timer
9088 SUGAR.email2.folders.startCheckTimer();
9089 // check if we're coming from an email-link click
9090 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9092 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9094 //Init fix for YUI 2.7.0 datatable sort.
9095 SUGAR.email2.addressBook.initFixForDatatableSort();
9098 function createTreePanel(treeData, params) {
9099 var tree = new YAHOO.widget.TreeView(params.id);
9100 var root = tree.getRoot();
9102 //if (treeData.nodes && treeData[0].id == "Home")
9103 // treeData = treeData[0];
9107 function addChildNodes(parentNode, parentData) {
9108 var Ck = YAHOO.util.Cookie;
9109 var nextyear = SUGAR.email2.nextYear;
9110 var nodes = parentData.nodes || parentData.children;
9112 if (typeof(nodes[i]) == 'object') {
9113 if (nodes[i].data) {
9114 // See comment about href below.
9115 // nodes[i].data.href = '#';
9116 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode);
9117 node.action = nodes[i].data.action;
9119 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9120 addChildNodes(parentNode, nodes[i]);
9123 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9124 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9126 nodes[i].className = nodes[i].cls;
9128 // Previously, span was added in the label so it was rendering in the tree.
9129 // Default behavior is to wrap in span if no href property, and since this href
9130 // doesn't do anything, remove it so that it will be wrapped in spans.
9131 // nodes[i].href = "#";
9132 if (nodes[i].text) nodes[i].label = nodes[i].text;
9133 //Override YUI child node creation
9134 if (nodes[i].children) {
9135 nodes[i].nodes = nodes[i].children;
9136 nodes[i].children = [ ];
9138 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9141 if (typeof(nodes[i].nodes) == 'object') {
9142 addChildNodes(node, nodes[i]);
9149 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9151 function email2treeinit(tree, treedata, treediv, params) {
9152 //ensure the tree data is not corrupt
9156 if (SUGAR.email2.tree) {
9157 SUGAR.email2.tree.destroy();
9158 SUGAR.email2.tree = null;
9161 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9165 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9166 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9167 tree.subscribe("expandComplete", function(node){
9168 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9169 for (var i in node.children) {
9170 SE.accounts.setupDDTarget(node.children[i]);
9173 tree.setCollapseAnim("TVSlideOut");
9174 tree.setExpandAnim("TVSlideIn");
9175 var root = tree.root;
9176 while (root.hasChildren()) {
9177 var node = root.children[0];
9179 tree.removeNode(root.children[0], false);
9181 addChildNodes(root, treedata);
9183 SUGAR.email2.accounts.renderTree();
9186 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9187 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9191 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9192 startDrag: function(x, y) {
9193 var Dom = YAHOO.util.Dom;
9194 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9197 var dragEl = this.getDragEl();
9198 var clickEl = this.getEl();
9199 Dom.setStyle(clickEl, "color", "#AAA");
9200 Dom.setStyle(clickEl, "opacity", "0.25");
9201 dragEl.innerHTML = clickEl.innerHTML;
9203 Dom.addClass(dragEl, "ygtvcell");
9204 Dom.addClass(dragEl, "ygtvcontent");
9205 Dom.addClass(dragEl, "folderDragProxy");
9206 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9207 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9208 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9209 Dom.setStyle(dragEl, "opacity", "0.5");
9210 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9213 onDragOver: function(ev, id) {
9214 var Dom = YAHOO.util.Dom;
9215 if (id != this.dragId)
9217 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9218 if(node.data.cls != "sugarFolder") {
9219 SUGAR.email2.folders.unhighliteAll();
9223 this.targetNode = node;
9224 SUGAR.email2.folders.unhighliteAll();
9229 onDragOut: function(e, id) {
9230 if (this.targetNode) {
9231 SUGAR.email2.folders.unhighliteAll();
9232 this.targetNode = false;
9233 this.dragId = false;
9237 endDrag: function() {
9238 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9239 if (this.targetNode) {
9240 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9243 });// End of File modules/Emails/javascript/init.js
9245 /*********************************************************************************
9246 * SugarCRM Community Edition is a customer relationship management program developed by
9247 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9249 * This program is free software; you can redistribute it and/or modify it under
9250 * the terms of the GNU Affero General Public License version 3 as published by the
9251 * Free Software Foundation with the addition of the following permission added
9252 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9253 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9254 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9256 * This program is distributed in the hope that it will be useful, but WITHOUT
9257 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9258 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9261 * You should have received a copy of the GNU Affero General Public License along with
9262 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9263 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9266 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9267 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9269 * The interactive user interfaces in modified source and object code versions
9270 * of this program must display Appropriate Legal Notices, as required under
9271 * Section 5 of the GNU Affero General Public License version 3.
9273 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9274 * these Appropriate Legal Notices must retain the display of the "Powered by
9275 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9276 * technical reasons, the Appropriate Legal Notices must display the words
9277 * "Powered by SugarCRM".
9278 ********************************************************************************/
9283 function complexLayoutInit() {
9284 var se = SUGAR.email2;
9285 var Dom = YAHOO.util.Dom;
9287 getInnerLayout : function(rows) {
9288 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
9289 parent: se.complexLayout,
9295 scroll:false, // grid should autoScroll itself
9297 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
9305 body: "<div id='listBottom' />"
9313 body: "<div id='listRight' />",
9314 titlebar: false //,header: "right"
9317 se.complexLayout.on("render", function(){
9318 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
9319 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9320 SUGAR.email2.listViewLayout.set("height", height);
9321 SUGAR.email2.listViewLayout.render();
9323 se.listViewLayout.render();
9325 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
9326 var rp = se.listViewLayout.resizePreview = function() {
9327 var pre = Dom.get("displayEmailFramePreview");
9329 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
9330 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
9333 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
9334 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
9335 se.e2Layout.setPreviewPanel(rows);
9336 se.previewLayout = se.listViewLayout;
9337 return se.listViewLayout;
9340 getInnerLayout2Rows : function() {
9341 return this.getInnerLayout(true);
9343 getInnerLayout2Columns : function() {
9344 return this.getInnerLayout(false);
9348 // initialize state manager, we will use cookies
9349 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
9350 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
9351 se.complexLayout = new YAHOO.widget.Layout("container", {
9354 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
9355 width: Dom.getViewportWidth() - 40,
9359 body: "<div id='emailtabs'></div>"
9364 body: "<div id='lefttabs'></div>",
9374 header: Dom.get('footerLinks').innerHTML,
9381 se.complexLayout.render();
9382 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
9383 tp.addTab(new YAHOO.widget.Tab({
9386 content : "<div id='listViewDiv'/>",
9390 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
9391 tp.appendTo(centerEl);
9393 tp.get("element").style.borderRight = "1px solid #666"
9395 var listV = this.getInnerLayout2Rows();
9396 listV.set("height", tp.get("element").clientHeight - 25);
9399 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
9400 var folderTab = new YAHOO.widget.Tab({
9401 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
9403 content : "<div id='emailtree'/>",
9407 folderTab.on("activeChange", function(o){
9409 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
9412 se.leftTabs.addTab(folderTab);
9414 var tabContent = SUGAR.util.getAndRemove("searchTab");
9415 var searchTab = new YAHOO.widget.Tab({
9416 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
9418 content : tabContent.innerHTML,
9421 searchTab.on("activeChange", function(o){
9424 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
9425 //Setup the calendars if needed
9426 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
9427 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
9429 //Initalize sqs object for assigned user name
9430 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
9432 //Attach event handler for when the relate module option is selected for the correct sqs object
9433 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
9434 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
9435 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
9436 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
9438 //If enter key is pressed, perform search
9439 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
9440 for(var i=0; i < addKeyPressFields.length;i++)
9442 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
9443 if (e.keyCode == 13) {
9444 YAHOO.util.Event.stopEvent(e);
9445 SUGAR.email2.search.searchAdvanced();
9449 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
9451 //Clear parent values if selecting another parent type.
9452 YAHOO.util.Event.addListener('data_parent_type_search','change',
9454 document.getElementById('data_parent_id_search').value ='';
9455 document.getElementById('data_parent_name_search').value ='';
9460 se.leftTabs.addTab(searchTab);
9462 var resizeTabBody = function() {
9463 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
9464 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9467 se.complexLayout.on("render", resizeTabBody);
9468 se.leftTabs.on("activeTabChange", resizeTabBody);
9469 //hack to allow left pane scroll bar to fully show
9470 var lefttabsDiv = document.getElementById('lefttabs');
9471 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
9472 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
9473 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
9476 initSQSObject: function(formName,fieldName)
9478 var fullFieldName = formName + '_' + fieldName; //SQS Convention
9479 var resultName = fullFieldName + '_' + 'results';
9481 if (QSFieldsArray[fullFieldName] != null)
9483 QSFieldsArray[fullFieldName].destroy();
9484 delete QSFieldsArray[fullFieldName];
9486 if (QSProcessedFieldsArray[fullFieldName])
9487 QSProcessedFieldsArray[fullFieldName] = false;
9489 if( Dom.get(resultName) )
9491 var obj = document.getElementById(resultName);
9492 obj.parentNode.removeChild(obj);
9495 setPreviewPanel: function(rows) {
9497 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9498 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9499 Dom.get("listRight").innerHTML = "";
9500 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9502 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9503 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9504 Dom.get("listBottom").innerHTML = "";
9505 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9512 var myBufferedListenerObject = new Object();
9513 myBufferedListenerObject.refit = function() {
9514 if(SUGAR.email2.grid) {
9515 SUGAR.email2.grid.autoSize();
9518 // End of File modules/Emails/javascript/complexLayout.js
9520 /*********************************************************************************
9521 * SugarCRM Community Edition is a customer relationship management program developed by
9522 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9524 * This program is free software; you can redistribute it and/or modify it under
9525 * the terms of the GNU Affero General Public License version 3 as published by the
9526 * Free Software Foundation with the addition of the following permission added
9527 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9528 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9529 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9531 * This program is distributed in the hope that it will be useful, but WITHOUT
9532 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9533 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9536 * You should have received a copy of the GNU Affero General Public License along with
9537 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9538 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9541 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9542 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9544 * The interactive user interfaces in modified source and object code versions
9545 * of this program must display Appropriate Legal Notices, as required under
9546 * Section 5 of the GNU Affero General Public License version 3.
9548 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9549 * these Appropriate Legal Notices must retain the display of the "Powered by
9550 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9551 * technical reasons, the Appropriate Legal Notices must display the words
9552 * "Powered by SugarCRM".
9553 ********************************************************************************/
9555 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9556 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9557 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9558 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9559 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9560 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9561 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9562 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9563 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9564 ' <input type="hidden" id="composeType" name="composeType">' +
9565 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9566 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9567 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9568 ' <input type="hidden" id="sendTo" name="sendTo">' +
9569 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9570 ' <input type="hidden" id="sendCc" name="sendCc">' +
9571 ' <input type="hidden" id="setEditor" name="setEditor">' +
9572 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9573 ' <input type="hidden" id="parent_id" name="parent_id">' +
9574 ' <input type="hidden" id="parent_type" name="parent_type">' +
9575 ' <input type="hidden" id="attachments" name="attachments">' +
9576 ' <input type="hidden" id="documents" name="documents">' +
9577 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9578 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9579 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9580 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9582 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9583 ' <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>' +
9584 ' <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>' +
9585 ' <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>' +
9586 ' <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>' +
9587 '</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>' +
9588 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9589 '<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>' +
9590 ' </td></tr></tbody></table></th>' +
9594 ' <div style="margin:5px;">' +
9595 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9597 ' <td class="emailUILabel" NOWRAP >' +
9598 ' {app_strings.LBL_EMAIL_FROM}:' +
9600 ' <td class="emailUIField" NOWRAP>' +
9602 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9607 ' <td class="emailUILabel" NOWRAP>' +
9608 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9609 ' {app_strings.LBL_EMAIL_TO}:' +
9612 ' <td class="emailUIField" NOWRAP>' +
9613 ' <div class="ac_autocomplete">' +
9614 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9615 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9616 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9620 ' <tr id="add_addr_options_tr{idx}">' +
9621 ' <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>'+
9623 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9624 ' <td class="emailUILabel" NOWRAP>' +
9625 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9626 ' {app_strings.LBL_EMAIL_CC}:' +
9629 ' <td class="emailUIField" NOWRAP>' +
9630 ' <div class="ac_autocomplete">' +
9631 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9632 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9633 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9637 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9638 ' <td class="emailUILabel" NOWRAP>' +
9639 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9640 ' {app_strings.LBL_EMAIL_BCC}:' +
9643 ' <td class="emailUIField" NOWRAP>' +
9644 ' <div class="ac_autocomplete">' +
9645 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9646 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9647 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9652 ' <td class="emailUILabel" NOWRAP width="1%">' +
9653 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9655 ' <td class="emailUIField" NOWRAP width="99%">' +
9656 ' <div class="ac_autocomplete">' +
9657 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9666 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9667 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9668 ' <div style="padding:5px;">' +
9669 ' <table cellpadding="2" cellspacing="0" border="0">' +
9672 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9679 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9680 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9692 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9699 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9700 ' <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>' +
9712 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9719 ' <div id="addedTemplateAttachments{idx}"></div>' +
9726 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9727 ' <div style="padding:5px;">' +
9728 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9729 ' <table border="0" width="100%">' +
9731 ' <td NOWRAP style="padding:2px;">' +
9732 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9736 ' <td NOWRAP style="padding:2px;">' +
9737 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9742 ' <table border="0" width="100%">' +
9744 ' <td NOWRAP style="padding:2px;">' +
9745 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9749 ' <td NOWRAP style="padding:2px;">' +
9750 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9754 ' <table border="0" width="100%">' +
9756 ' <td NOWRAP style="padding:2px;">' +
9757 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9758 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9766 // End of File modules/Emails/javascript/composeEmailTemplate.js
9768 /*********************************************************************************
9769 * SugarCRM Community Edition is a customer relationship management program developed by
9770 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9772 * This program is free software; you can redistribute it and/or modify it under
9773 * the terms of the GNU Affero General Public License version 3 as published by the
9774 * Free Software Foundation with the addition of the following permission added
9775 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9776 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9777 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9779 * This program is distributed in the hope that it will be useful, but WITHOUT
9780 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9781 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9784 * You should have received a copy of the GNU Affero General Public License along with
9785 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9786 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9789 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9790 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9792 * The interactive user interfaces in modified source and object code versions
9793 * of this program must display Appropriate Legal Notices, as required under
9794 * Section 5 of the GNU Affero General Public License version 3.
9796 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9797 * these Appropriate Legal Notices must retain the display of the "Powered by
9798 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9799 * technical reasons, the Appropriate Legal Notices must display the words
9800 * "Powered by SugarCRM".
9801 ********************************************************************************/
9803 SUGAR.email2.templates['displayOneEmail'] =
9804 '<div class="emailDetailTable" style="height:100%">' +
9805 '<div id="viewMenuDiv{idx}"></div>' +
9806 '<div width="100%" class="displayEmailValue">' +
9807 ' <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>' +
9808 ' <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>' +
9809 ' <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>' +
9810 ' <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>' +
9811 ' <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>' +
9812 ' <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>' +
9813 ' <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>' +
9814 ' <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>' +
9815 ' <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>' +
9817 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9819 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9820 ' {app_strings.LBL_EMAIL_FROM}:' +
9822 ' <td width="99%" class="displayEmailValue">' +
9823 ' {email.from_addr}' +
9827 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9828 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9830 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9831 ' <b>{email.name}</b>' +
9835 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9836 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9838 ' <td class="displayEmailValue">' +
9839 ' {email.date_start} {email.time_start}' +
9843 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9844 ' {app_strings.LBL_EMAIL_TO}:' +
9846 ' <td class="displayEmailValue">' +
9847 ' {email.toaddrs}' +
9850 ' <tr>{meta.cc}</tr>' +
9851 ' <tr>{email.attachments}</tr>' +
9853 ' <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>' +
9854 //' {email.description}' +
9856 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9858 /*********************************************************************************
9859 * SugarCRM Community Edition is a customer relationship management program developed by
9860 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9862 * This program is free software; you can redistribute it and/or modify it under
9863 * the terms of the GNU Affero General Public License version 3 as published by the
9864 * Free Software Foundation with the addition of the following permission added
9865 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9866 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9867 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9869 * This program is distributed in the hope that it will be useful, but WITHOUT
9870 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9871 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9874 * You should have received a copy of the GNU Affero General Public License along with
9875 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9876 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9879 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9880 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9882 * The interactive user interfaces in modified source and object code versions
9883 * of this program must display Appropriate Legal Notices, as required under
9884 * Section 5 of the GNU Affero General Public License version 3.
9886 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9887 * these Appropriate Legal Notices must retain the display of the "Powered by
9888 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9889 * technical reasons, the Appropriate Legal Notices must display the words
9890 * "Powered by SugarCRM".
9891 ********************************************************************************/
9893 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9894 '<body onload="javascript:window.print();">' +
9898 ' font-family: helvetica, impact, sans-serif;' +
9899 ' font-size : 12pt;' +
9906 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9909 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9911 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9912 ' {app_strings.LBL_EMAIL_FROM}:' +
9914 ' <td width="99%" class="displayEmailValue">' +
9915 ' {email.from_name} <{email.from_addr}>' +
9919 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9920 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9922 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9923 ' <b>{email.name}</b>' +
9927 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9928 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9930 ' <td class="displayEmailValue">' +
9931 ' {email.date_start} {email.time_start}' +
9935 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9936 ' {app_strings.LBL_EMAIL_TO}:' +
9938 ' <td class="displayEmailValue">' +
9939 ' {email.toaddrs}' +
9943 ' {email.attachments}' +
9949 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9951 ' <td style="border-top: 1px solid #333;">' +
9952 ' <div style="padding:5px;">' +
9953 '{email.description}' +
9963 // End of File modules/Emails/javascript/viewPrintable.js
9965 /*********************************************************************************
9966 * SugarCRM Community Edition is a customer relationship management program developed by
9967 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9969 * This program is free software; you can redistribute it and/or modify it under
9970 * the terms of the GNU Affero General Public License version 3 as published by the
9971 * Free Software Foundation with the addition of the following permission added
9972 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9973 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9974 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9976 * This program is distributed in the hope that it will be useful, but WITHOUT
9977 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9978 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9981 * You should have received a copy of the GNU Affero General Public License along with
9982 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9983 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9986 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9987 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9989 * The interactive user interfaces in modified source and object code versions
9990 * of this program must display Appropriate Legal Notices, as required under
9991 * Section 5 of the GNU Affero General Public License version 3.
9993 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9994 * these Appropriate Legal Notices must retain the display of the "Powered by
9995 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9996 * technical reasons, the Appropriate Legal Notices must display the words
9997 * "Powered by SugarCRM".
9998 ********************************************************************************/
9999 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
10000 var Dom=YAHOO.util.Dom;var qsFields=Dom.getElementsByClassName('sqsEnabled');for(var qsField in qsFields){if(typeof qsFields[qsField]=='function'||typeof qsFields[qsField].id=='undefined'){continue;}
10001 var form_id=qsFields[qsField].form.getAttribute('id');if(typeof form_id=='object'&&qsFields[qsField].form.getAttribute('real_id')){form_id=qsFields[qsField].form.getAttribute('real_id');}
10002 var qs_index_id=form_id+'_'+qsFields[qsField].name;if(typeof sqs_objects[qs_index_id]=='undefined'){qs_index_id=qsFields[qsField].name;if(typeof sqs_objects[qs_index_id]=='undefined'){continue;}}
10003 if(QSProcessedFieldsArray[qs_index_id]){continue;}
10004 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
10005 if(!document.forms[qs_obj.form].elements[qsFields[qsField].id].readOnly&&qs_obj['disable']!=true){var combo_id=qs_obj.form+'_'+qsFields[qsField].id;if(Dom.get(combo_id+"_results")){loaded=true}
10006 if(!loaded){QSProcessedFieldsArray[qs_index_id]=true;qsFields[qsField].form_id=form_id;var sqs=sqs_objects[qs_index_id];var resultDiv=document.createElement('div');resultDiv.id=combo_id+"_results";Dom.insertAfter(resultDiv,qsFields[qsField]);var fields=qs_obj.field_list.slice();fields[fields.length]="module";var ds=new YAHOO.util.DataSource("index.php?",{responseType:YAHOO.util.XHRDataSource.TYPE_JSON,responseSchema:{resultsList:'fields',total:'totalCount',fields:fields,metaNode:"fields",metaFields:{total:'totalCount',fields:"fields"}},connMethodPost:true});var forceSelect=!((qsFields[qsField].form&&typeof(qsFields[qsField].form)=='object'&&qsFields[qsField].form.name=='search_form')||qsFields[qsField].className.match('sqsNoAutofill')!=null);var search=new YAHOO.widget.AutoComplete(qsFields[qsField],resultDiv,ds,{typeAhead:forceSelect,forceSelection:forceSelect,fields:fields,sqs:sqs,animSpeed:0.25,qs_obj:qs_obj,inputElement:qsFields[qsField],generateRequest:function(sQuery){var out=SUGAR.util.paramsToUrl({to_pdf:'true',module:'Home',action:'quicksearchQuery',data:encodeURIComponent(YAHOO.lang.JSON.stringify(this.sqs)),query:sQuery});return out;},setFields:function(data,filter){this.updateFields(data,filter);},updateFields:function(data,filter){for(var i in this.fields){for(var key in this.qs_obj.field_list){if(this.fields[i]==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&this.qs_obj.populate_list[key].match(filter)){var displayValue=data[i].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value=displayValue;SUGAR.util.callOnChangeListers(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]);}}}
10007 SUGAR.util.callOnChangeListers(this._elTextbox);},clearFields:function(){for(var key in this.qs_obj.field_list){if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]){document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";SUGAR.util.callOnChangeListers(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]);}}
10008 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
10009 {search.clearFields=function(){for(var i in{name:0,id:1}){for(var key in this.qs_obj.field_list){if(i==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]])
10010 {document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";}}}};search.setFields=function(data,filter)
10011 {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])
10012 {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';}}}}
10013 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))
10014 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
10015 {if(this.inputElement.id=='shipping_account_name')
10016 {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)/;}
10017 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
10018 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
10019 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];}}}
10020 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]];}
10021 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;}}}}});}
10022 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
10023 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}
10024 // End of File include/javascript/quicksearch.js