2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
5 * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6 * dragged element is inserted before the dragged-over element.
8 * @extends YAHOO.util.DDProxy
10 * @param {String} id the id of the linked element
11 * @param {String} sGroup the group of related DragDrop objects
13 function ygDDList(id, sGroup) {
16 this.init(id, sGroup);
18 //this.logger = new ygLogger("ygDDList");
21 var s = this.getDragEl().style;
22 s.borderColor = "transparent";
23 s.backgroundColor = "#f6f5e5";
25 s.filter = "alpha(opacity=76)";
28 ygDDList.prototype = new YAHOO.util.DDProxy();
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
33 ygDDList.prototype.startDrag = function(x, y) {
34 //this.logger.debug(this.id + " startDrag");
36 var dragEl = this.getDragEl();
37 var clickEl = this.getEl();
39 dragEl.innerHTML = clickEl.innerHTML;
40 dragElObjects = dragEl.getElementsByTagName('object');
43 dragEl.className = clickEl.className;
44 dragEl.style.color = clickEl.style.color;
45 dragEl.style.border = "1px solid #aaa";
47 // save the style of the object
48 clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
50 this.borderDiv = document.createElement('div'); // create a div to display border
51 this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52 this.borderDiv.style.border = '2px dashed #cccccc';
54 for(i in clickEl.childNodes) { // hide contents of the target elements contents
55 if(typeof clickEl.childNodes[i].style != 'undefined') {
56 this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57 clickEl.childNodes[i].style.display = 'none';
61 clickEl.appendChild(this.borderDiv);
64 ygDDList.prototype.endDrag = function(e) {
65 // disable moving the linked element
66 var clickEl = this.getEl();
68 clickEl.removeChild(this.borderDiv); // remove border div
70 for(i in clickEl.childNodes) { // show target elements contents
71 if(typeof clickEl.childNodes[i].style != 'undefined') {
72 clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
77 clickEl.style.height = this.clickHeight;
79 clickEl.style.height = '';
82 clickEl.style.border = this.clickBorder;
84 clickEl.style.border = '';
86 dragEl = this.getDragEl();
87 dragEl.innerHTML = '';
92 ygDDList.prototype.afterEndDrag = function(e) {
96 ygDDList.prototype.onDrag = function(e, id) {
100 ygDDList.prototype.onDragOver = function(e, id) {
101 // this.logger.debug(this.id.toString() + " onDragOver " + id);
104 if ("string" == typeof id) {
105 el = YAHOO.util.DDM.getElement(id);
107 el = YAHOO.util.DDM.getBestMatch(id).getEl();
110 dragEl = this.getDragEl();
111 elRegion = YAHOO.util.Dom.getRegion(el);
113 // this.logger.debug('id: ' + el.id);
114 // this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 // this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116 var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 // this.logger.debug('mid: ' + mid);
119 // this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " < " + mid);
120 // this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
122 if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123 var el2 = this.getEl();
124 var p = el.parentNode;
125 p.insertBefore(el2, el);
127 if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128 var el2 = this.getEl();
129 var p = el.parentNode;
130 p.insertBefore(el2, el.nextSibling);
134 ygDDList.prototype.onDragEnter = function(e, id) {
135 // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136 // this.getDragEl().style.border = "1px solid #449629";
139 ygDDList.prototype.onDragOut = function(e, id) {
140 // I need to know when we are over nothing
141 // this.getDragEl().style.border = "1px solid #964428";
144 /////////////////////////////////////////////////////////////////////////////
146 function ygDDListBoundary(id, sGroup) {
148 this.init(id, sGroup);
149 //this.logger = new ygLogger("ygDDListBoundary");
150 this.isBoundary = true;
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
157 /*********************************************************************************
158 * SugarCRM is a customer relationship management program developed by
159 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
161 * This program is free software; you can redistribute it and/or modify it under
162 * the terms of the GNU Affero General Public License version 3 as published by the
163 * Free Software Foundation with the addition of the following permission added
164 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
168 * This program is distributed in the hope that it will be useful, but WITHOUT
169 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
173 * You should have received a copy of the GNU Affero General Public License along with
174 * this program; if not, see http://www.gnu.org/licenses or write to the Free
175 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
178 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
181 * The interactive user interfaces in modified source and object code versions
182 * of this program must display Appropriate Legal Notices, as required under
183 * Section 5 of the GNU Affero General Public License version 3.
185 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186 * these Appropriate Legal Notices must retain the display of the "Powered by
187 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188 * technical reasons, the Appropriate Legal Notices must display the words
189 * "Powered by SugarCRM".
190 ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span> </span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&themeName=Sugar&imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace(''',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML=' ';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};addToValidate(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,'email',this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
216 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
217 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
218 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
219 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
220 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
221 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
222 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
223 if(SUGAR.isIE){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
224 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
225 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();// End of File include/SugarEmailAddress/SugarEmailAddress.js
227 /*********************************************************************************
228 * SugarCRM is a customer relationship management program developed by
229 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
231 * This program is free software; you can redistribute it and/or modify it under
232 * the terms of the GNU Affero General Public License version 3 as published by the
233 * Free Software Foundation with the addition of the following permission added
234 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
235 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
236 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
238 * This program is distributed in the hope that it will be useful, but WITHOUT
239 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
240 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
243 * You should have received a copy of the GNU Affero General Public License along with
244 * this program; if not, see http://www.gnu.org/licenses or write to the Free
245 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
248 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
249 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
251 * The interactive user interfaces in modified source and object code versions
252 * of this program must display Appropriate Legal Notices, as required under
253 * Section 5 of the GNU Affero General Public License version 3.
255 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
256 * these Appropriate Legal Notices must retain the display of the "Powered by
257 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
258 * technical reasons, the Appropriate Legal Notices must display the words
259 * "Powered by SugarCRM".
260 ********************************************************************************/
261 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
262 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
263 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
264 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
265 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
266 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
267 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
268 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
269 this.js_more();this.js_more();}
270 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
271 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
272 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
273 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
274 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&¤tNode.tagName=='SPAN'){currentNode.id=/_input/.test(currentNode.id)?this.field_element_name+'_input_div_'+this.fields_count:this.field_element_name+'_radio_div_'+this.fields_count;if(/_input/.test(currentNode.id)){currentNode.name='teamset_div';}
275 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
276 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
277 currentNode.name=new_name;currentNode.id=new_name;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_name;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
278 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
279 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
281 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
283 if(!has_primary){return false;}
285 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
286 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
287 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
288 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
289 if(noAdd){enableQS(false);}
290 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_collection_"+i);var id_field=document.getElementById("id_"+this.field+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].id==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
292 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
293 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
295 SUGAR.collection.safe_clone=function(e,recursive)
296 {if(e.nodeName=="#text")
297 {return document.createTextNode(e.data);}
298 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];for(var i in properties)
299 {if(e[properties[i]])
300 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
301 newNode[properties[i]]=e[properties[i]];}}
303 {for(var i in e.childNodes)
304 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
305 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
306 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
308 /*********************************************************************************
309 * SugarCRM is a customer relationship management program developed by
310 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
312 * This program is free software; you can redistribute it and/or modify it under
313 * the terms of the GNU Affero General Public License version 3 as published by the
314 * Free Software Foundation with the addition of the following permission added
315 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
316 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
317 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
319 * This program is distributed in the hope that it will be useful, but WITHOUT
320 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
321 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
324 * You should have received a copy of the GNU Affero General Public License along with
325 * this program; if not, see http://www.gnu.org/licenses or write to the Free
326 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
329 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
330 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
332 * The interactive user interfaces in modified source and object code versions
333 * of this program must display Appropriate Legal Notices, as required under
334 * Section 5 of the GNU Affero General Public License version 3.
336 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
337 * these Appropriate Legal Notices must retain the display of the "Powered by
338 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
339 * technical reasons, the Appropriate Legal Notices must display the words
340 * "Powered by SugarCRM".
341 ********************************************************************************/
342 SUGAR.inboundEmail={};Rot13={map:null,convert:function(a){Rot13.init();var s="";for(i=0;i<a.length;i++){var b=a.charAt(i);s+=((b>='A'&&b<='Z')||(b>='a'&&b<='z')?Rot13.map[b]:b);}
343 return s;},init:function(){if(Rot13.map!=null)
344 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
345 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
346 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
347 function getEncryptedPassword(login,password,mailbox){var words=new Array(login,password,mailbox);for(i=0;i<3;i++){word=words[i];if(word.indexOf('&')>0){fragment1=word.substr(0,word.indexOf('&'));fragment2=word.substr(word.indexOf('&')+1,word.length);newWord=fragment1+'::amp::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
348 if(word.indexOf('+')>0){fragment1=word.substr(0,word.indexOf('+'));fragment2=word.substr(word.indexOf('+')+1,word.length);newWord=fragment1+'::plus::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
349 if(word.indexOf('%')>0){fragment1=word.substr(0,word.indexOf('%'));fragment2=word.substr(word.indexOf('%')+1,word.length);newWord=fragment1+'::percent::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}}
351 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName)
352 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
354 +'module='+module_name
357 +'&target='+pageTarget
358 +'&target1='+pageTarget
359 +'&server_url='+mail_server
360 +'&email_user='+words[0]
361 +'&protocol='+protocol
363 +'&email_password='+words[1]
364 +'&mailbox='+words[2]
366 +'&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)
367 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
368 this.body.style.width=w}}
369 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
370 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();}
371 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'));}
372 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
373 if(trim(formObject.email_password.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PASSWORD'));}
374 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
375 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
376 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
377 if(errors.length>0){out=SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_DESC');for(i=0;i<errors.length;i++){if(out!=""){out+="\n";}
379 alert(out);return false;}else{return true;}}
380 function getFoldersListForInboundAccount(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,searchFieldValue,formName){if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';URL='index.php?'
381 +'module='+module_name
384 +'&target='+pageTarget
385 +'&target1='+pageTarget
386 +'&server_url='+mail_server
387 +'&email_user='+words[0]
388 +'&protocol='+protocol
390 +'&email_password='+words[1]
391 +'&mailbox='+words[2]
393 +'&personal='+isPersonal
394 +'&searchField='+searchFieldValue;var SI=SUGAR.inboundEmail;if(!SI.listDlg){SI.listDlg=new YAHOO.widget.SimpleDialog("selectFoldersDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.listDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
395 this.body.style.width=w}}
396 SI.listDlg.setHeader(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.listDlg.setBody('');SI.listDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.listDlg._updateContent,failure:SI.listDlg.hide,scope:SI.listDlg});SI.listDlg.show();}
397 function setPortDefault(){var prot=document.getElementById('protocol');var ssl=document.getElementById('ssl');var port=document.getElementById('port');var stdPorts=new Array("110","143","993","995");var stdBool=new Boolean(false);if(port.value==''){stdBool.value=true;}else{for(i=0;i<stdPorts.length;i++){if(stdPorts[i]==port.value){stdBool.value=true;}}}
398 if(stdBool.value==true){if(prot.value=='imap'&&ssl.checked==false){port.value="143";}else if(prot.value=='imap'&&ssl.checked==true){port.value='993';}else if(prot.value=='pop3'&&ssl.checked==false){port.value='110';}else if(prot.value=='pop3'&&ssl.checked==true){port.value='995';}}}
399 function toggle_monitored_folder(field){var field1=document.getElementById('protocol');var mailbox=document.getElementById('mailbox');var label_inbox=document.getElementById('label_inbox');var subscribeFolderButton=document.getElementById('subscribeFolderButton');var trashFolderRow=document.getElementById('trashFolderRow');var trashFolderRow1=document.getElementById('trashFolderRow1');var sentFolderRow=document.getElementById('sentFolderRow');if(field1.value=='imap'){mailbox.disabled=false;try{mailbox.style.display='';trashFolderRow.style.display='';sentFolderRow.style.display='';trashFolderRow1.style.display='';subscribeFolderButton.style.display='';}catch(e){};label_inbox.style.display='';}
400 else{mailbox.value="INBOX";mailbox.disabled=false;try{mailbox.style.display="none";trashFolderRow.style.display="none";sentFolderRow.style.display="none";trashFolderRow1.style.display="none";subscribeFolderButton.style.display="none";}catch(e){};label_inbox.style.display="none";}}// End of File modules/InboundEmail/InboundEmail.js
402 /*********************************************************************************
403 * SugarCRM is a customer relationship management program developed by
404 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
406 * This program is free software; you can redistribute it and/or modify it under
407 * the terms of the GNU Affero General Public License version 3 as published by the
408 * Free Software Foundation with the addition of the following permission added
409 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
410 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
411 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
413 * This program is distributed in the hope that it will be useful, but WITHOUT
414 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
415 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
418 * You should have received a copy of the GNU Affero General Public License along with
419 * this program; if not, see http://www.gnu.org/licenses or write to the Free
420 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
423 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
424 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
426 * The interactive user interfaces in modified source and object code versions
427 * of this program must display Appropriate Legal Notices, as required under
428 * Section 5 of the GNU Affero General Public License version 3.
430 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
431 * these Appropriate Legal Notices must retain the display of the "Powered by
432 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
433 * technical reasons, the Appropriate Legal Notices must display the words
434 * "Powered by SugarCRM".
435 ********************************************************************************/
438 cache : new Object(),
439 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
440 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
443 currentHtmleditor : ''
447 * preserves hits from email server
449 _setDetailCache : function(ret) {
451 var compKey = ret.meta.mbox + ret.meta.uid;
453 if(!SUGAR.email2.cache[compKey]) {
454 SUGAR.email2.cache[compKey] = ret;
459 autoSetLayout : function() {
460 var c = document.getElementById('container');
461 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
462 //Ensure a minimum height.
463 tHeight = Math.max(tHeight, 550);
464 c.style.height = tHeight + "px";
465 SUGAR.email2.complexLayout.set('height', tHeight);
466 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
467 SUGAR.email2.complexLayout.render();
468 SUGAR.email2.listViewLayout.resizePreview();
473 * Shows overlay progress message
475 function overlayModal(title, body) {
476 overlay(title, body);
478 function overlay(reqtitle, body, type, additconfig) {
480 if (typeof(additconfig) == "object") {
481 var config = additconfig;
484 config.title = reqtitle;
486 YAHOO.SUGAR.MessageBox.show(config);
489 function hideOverlay() {
490 YAHOO.SUGAR.MessageBox.hide();
492 // End of File modules/Emails/javascript/EmailUIShared.js
494 /*********************************************************************************
495 * SugarCRM is a customer relationship management program developed by
496 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
498 * This program is free software; you can redistribute it and/or modify it under
499 * the terms of the GNU Affero General Public License version 3 as published by the
500 * Free Software Foundation with the addition of the following permission added
501 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
502 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
503 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
505 * This program is distributed in the hope that it will be useful, but WITHOUT
506 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
507 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
510 * You should have received a copy of the GNU Affero General Public License along with
511 * this program; if not, see http://www.gnu.org/licenses or write to the Free
512 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
515 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
516 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
518 * The interactive user interfaces in modified source and object code versions
519 * of this program must display Appropriate Legal Notices, as required under
520 * Section 5 of the GNU Affero General Public License version 3.
522 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
523 * these Appropriate Legal Notices must retain the display of the "Powered by
524 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
525 * technical reasons, the Appropriate Legal Notices must display the words
526 * "Powered by SugarCRM".
527 ********************************************************************************/
531 var sw = YAHOO.SUGAR,
532 Event = YAHOO.util.Event,
533 Connect = YAHOO.util.Connect,
537 ///////////////////////////////////////////////////////////////////////////////
540 outboundDialog : null,
541 inboundAccountEditDialog : null,
542 inboundAccountsSettingsTable : null,
543 outboundAccountsSettingsTable : null,
544 testOutboundDialog : null,
545 errorStyle : 'input-error',
547 newAddedOutboundId : '',
550 * makes async call to retrieve an outbound instance for editting
553 editOutbound : function(obi) {
555 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
558 deleteOutbound : function(obi) {
560 if(obi.match(/^(add|line|sendmail)+/)) {
561 alert('Invalid Operation');
563 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
564 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
568 getReplyAddress : function() {
571 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
572 var addy = SE.userPrefs.current_user.emailAddresses[i];
574 if(addy.primary_address == "1") {
575 primary = addy.email_address;
578 if(addy.reply_to == "1") {
579 return addy.email_address;
587 * Called on "Accounts" tab activation event
589 lazyLoad : function() {
591 this._setupInboundAccountTable();
592 this._setupOutboundAccountTable();
596 _setupInboundAccountTable: function()
598 //Setup the inbound mail settings
599 if(!this.inboundAccountsSettingsTable)
601 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
602 var clckEvent = oColumn.key;
604 var is_group = oRecord.getData("is_group");
607 if(oColumn.key == 'edit')
609 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
610 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
612 else if(oColumn.key == 'delete')
614 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
615 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
617 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
621 this.showBoolean = function(el, oRecord, oColumn, oData)
623 var is_group = oRecord.getData("is_group");
624 var bChecked = oData;
625 bChecked = (bChecked) ? " checked" : "";
628 el.innerHTML = "<input type=\"radio\"" + bChecked +
629 " name=\"col" + oColumn.getId() + "-radio\"" +
630 " class=\"yui-dt-radio\">";
635 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
636 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
638 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
639 '<img border="0" src="themes/default/images/helpInline.gif">' +
640 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
643 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
644 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
645 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
646 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
647 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
648 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
649 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
650 this.ieDataSource = new YAHOO.util.DataSource(query);
651 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
652 this.ieDataSource.responseSchema = {
653 resultsList: "account_list",
654 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
656 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
657 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
659 var elCheckbox = oArgs.target;
660 var oColumn = this.getColumn(elCheckbox);
661 if(oColumn.key == 'is_active')
663 var oRecord = this.getRecord(elCheckbox);
664 oRecord.setData("is_active",elCheckbox.checked);
665 var t_id = oRecord.getData('id');
666 var isGroupFolder = oRecord.getData('has_groupfolder');
669 SUGAR.email2.folders.updateSubscriptions();
671 SUGAR.email2.folders.setFolderSelection();
675 var lastDefaultSelectedId = "";
676 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
678 var elRadio = oArgs.target;
679 var oColumn = this.getColumn(elRadio);
680 if(oColumn.key == 'is_default')
682 var oRecord = this.getRecord(elRadio);
683 var t_id = oRecord.getData('id');
684 var t_isGroup = oRecord.getData('is_group');
685 if(t_id != lastDefaultSelectedId && !t_isGroup)
687 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
688 lastDefaultSelectedId = t_id;
689 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
692 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
697 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
698 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
701 _setupOutboundAccountTable: function()
703 if(!this.outboundAccountsSettingsTable)
705 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
706 var clckEvent = oColumn.key;
708 var isEditable = oRecord.getData("is_editable");
709 var type = oRecord.getData("type");
712 if(oColumn.key == 'edit')
714 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
715 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
717 else if(oColumn.key == 'delete' && type == 'user')
719 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
720 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
723 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
727 //Custom formatter to display any error messages.
728 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
730 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
731 SUGAR.email2.composeLayout.outboundAccountErrors = {};
733 var id = oRecord.getData('id');
734 var message = oRecord.getData("errors");
737 elLiner.innerHTML = '<span class="required">' + message + '</span>';
738 //Add the id and message for all outbound accounts.
739 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
743 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
744 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
747 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
748 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
750 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
751 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
752 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
753 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
755 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
756 this.obDataSource = new YAHOO.util.DataSource(query);
757 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
758 this.obDataSource.responseSchema = {
760 resultsList: "outbound_account_list",
761 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
764 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
767 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
768 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
769 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
773 * Displays a modal diaglogue to edit outbound account settings
775 showEditInboundAccountDialogue : function(clear) {
777 if(!this.inboundAccountEditDialog) {
778 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
782 constraintoviewport: true,
786 EAD.showEvent.subscribe(function() {
787 var el = this.element;
788 var viewH = YAHOO.util.Dom.getViewportHeight();
789 if (this.header && el && viewH - 50 < el.clientHeight) {
790 var body = this.header.nextElementSibling;
791 body.style.overflow = "auto";
792 body.style.height = (viewH - 50) + "px";
795 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
796 Dom.removeClass("editAccountDialogue", "yui-hidden");
800 if(clear == undefined || clear == true)
802 SE.accounts.clearInboundAccountEditScreen();
803 //Set default protocol to IMAP when creating new records
804 document.forms['ieAccount'].elements['protocol'].value = "imap";
805 SE.accounts.setPortDefault();
808 //Check if we should display username/password fields for outbound account if errors were detected.
809 this.checkOutBoundSelection();
811 this.inboundAccountEditDialog.render();
812 this.inboundAccountEditDialog.show();
816 * Set all fields on the outbound edit form to either enabled/disabled
817 * except for the username/password.
820 toggleOutboundAccountDisabledFields: function(disable)
822 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
823 for(var i=0;i<fields.length;i++)
825 document.getElementById(fields[i]).disabled = disable;
828 Dom.addClass("mail_smtpssl_row", "yui-hidden");
830 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
834 * Refresh the inbound accounts table.
836 refreshInboundAccountTable : function()
838 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
840 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
841 scope: this.inboundAccountsSettingsTable }
845 * Refresh the outbound accounts table.
847 refreshOuboundAccountTable : function()
849 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
851 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
852 scope: this.outboundAccountsSettingsTable }
856 * Displays a modal diaglogue to add a SMTP server
858 showAddSmtp : function() {
859 // lazy load dialogue
860 if(!this.outboundDialog) {
861 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
865 constraintoviewport: true,
869 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
870 this.outboundDialog.hideEvent.subscribe(function(){
871 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
872 var out = Dom.get("outbound_email");
873 if (out && out.value == "SYSTEM_ADD")
875 out.value = out.options[0].value;
877 //Check if we should display username/password for system account.
878 SE.accounts.checkOutBoundSelection();
882 Dom.removeClass("outboundDialog", "yui-hidden");
886 var form = document.getElementById('outboundEmailForm');
887 for(i=0; i<form.elements.length; i++) {
888 if(form.elements[i].name == 'mail_smtpport') {
889 form.elements[i].value = 25;
890 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
891 form.elements[i].value = '';
892 } else if(form.elements[i].type == 'checkbox') {
893 form.elements[i].checked = false;
896 //Render the SMTP buttons
897 if ( !SUGAR.smtpButtonGroup ) {
898 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
899 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
901 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
902 document.getElementById('smtp_settings').style.display = '';
903 form.mail_smtptype.value = e.newValue.get('value');
905 YAHOO.widget.Button.addHiddenFieldsToForm(form);
907 //Hide Username/Password
908 SUGAR.email2.accounts.smtp_authenticate_field_display();
909 //Unset readonly fields
910 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
911 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
912 this.outboundDialog.render();
913 this.outboundDialog.show();
917 * Accounts' Advanced Settings view toggle
919 toggleAdv : function() {
920 var adv = document.getElementById("ie_adv");
921 if(adv.style.display == 'none') {
922 adv.style.display = "";
924 adv.style.display = 'none';
928 smtp_authenticate_field_display : function() {
929 var smtpauth_req = document.getElementById("mail_smtpauth_req");
930 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
931 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
935 * Changes the display used in the outbound email SMTP dialog to match the
937 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
939 document.getElementById("smtpButtonGroupTD").style.display = '';
940 document.getElementById("chooseEmailProviderTD").style.display = '';
941 document.getElementById("mailsettings1").style.display = '';
942 document.getElementById("mailsettings2").style.display = '';
943 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
944 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
945 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
946 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
950 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
951 document.getElementById("mail_smtpport").value = '465';
952 document.getElementById("mail_smtpauth_req").checked = true;
953 var ssl = document.getElementById("mail_smtpssl");
954 for(var j=0;j<ssl.options.length;j++) {
955 if(ssl.options[j].text == 'SSL') {
956 ssl.options[j].selected = true;
960 document.getElementById("mailsettings1").style.display = 'none';
961 document.getElementById("mailsettings2").style.display = 'none';
962 document.getElementById("mail_smtppass_label").innerHTML =
963 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
964 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
967 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
968 document.getElementById("mail_smtpport").value = '587';
969 document.getElementById("mail_smtpauth_req").checked = true;
970 var ssl = document.getElementById("mail_smtpssl");
971 for(var j=0;j<ssl.options.length;j++) {
972 if(ssl.options[j].text == 'TLS') {
973 ssl.options[j].selected = true;
977 document.getElementById("mailsettings1").style.display = 'none';
978 document.getElementById("mailsettings2").style.display = 'none';
979 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
980 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
983 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
984 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
985 document.getElementById("mail_smtpserver").value = '';
987 document.getElementById("mail_smtpport").value = '25';
988 document.getElementById("mail_smtpauth_req").checked = true;
989 document.getElementById("mailsettings1").style.display = '';
990 document.getElementById("mailsettings2").style.display = '';
991 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
992 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
993 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
994 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
997 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
999 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1000 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1001 document.getElementById("mailsettings2").style.display = 'none';
1004 SUGAR.email2.accounts.smtp_authenticate_field_display();
1008 * Fill the gmail default values for inbound accounts.
1010 fillInboundGmailDefaults: function () {
1012 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1013 document.forms['ieAccount'].elements['ssl'].checked = true;
1014 document.forms['ieAccount'].elements['protocol'].value = "imap";
1015 SUGAR.email2.accounts.setPortDefault();
1018 * Sets Port field to selected protocol and SSL settings defaults
1020 setPortDefault : function() {
1021 var prot = document.getElementById('protocol');
1022 var ssl = document.getElementById('ssl');
1023 var port = document.getElementById('port');
1024 var stdPorts= new Array("110", "143", "993", "995");
1025 var stdBool = new Boolean(false);
1026 var mailboxdiv = document.getElementById("mailboxdiv");
1027 var trashFolderdiv = document.getElementById("trashFolderdiv");
1028 var sentFolderdiv = document.getElementById("sentFolderdiv");
1029 var monitoredFolder = document.getElementById("subscribeFolderButton");
1030 if(port.value == '') {
1031 stdBool.value = true;
1033 for(i=0; i<stdPorts.length; i++) {
1034 if(stdPorts[i] == port.value) {
1035 stdBool.value = true;
1040 if(stdBool.value == true) {
1041 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1043 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1045 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1047 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1052 if (prot.value == 'imap') {
1053 mailboxdiv.style.display = "";
1054 trashFolderdiv.style.display = "";
1055 sentFolderdiv.style.display = "";
1056 monitoredFolder.style.display = "";
1057 if (document.getElementById('mailbox').value == "") {
1058 document.getElementById('mailbox').value = "INBOX";
1061 mailboxdiv.style.display = "none";
1062 trashFolderdiv.style.display = "none";
1063 sentFolderdiv.style.display = "none";
1064 monitoredFolder.style.display = "none";
1065 document.getElementById('mailbox').value = "";
1070 * Draws/removes red boxes around required fields.
1072 ieAccountError : function(style) {
1073 document.getElementById('server_url').className = style;
1074 document.getElementById('email_user').className = style;
1075 document.getElementById('email_password').className = style;
1076 document.getElementById('protocol').className = style;
1077 document.getElementById('port').className = style;
1080 checkOutBoundSelection: function() {
1081 var select = Dom.get('outbound_email');
1082 if (!select || select.selectedIndex == -1) { return; }
1084 var v = select.options[select.selectedIndex].value;
1088 select.options[select.selectedIndex].selected = false;
1089 v = select.options[0].value;
1091 else if (v == 'SYSTEM_ADD')
1092 SUGAR.email2.accounts.showAddSmtp();
1094 var foundError = false;
1095 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1096 for(i in errorAccounts)
1105 //Should username/password fields for outbound account.
1107 this.toggleInboundOutboundFields(true);
1109 this.toggleInboundOutboundFields(false);
1114 toggleInboundOutboundFields : function (display)
1118 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1119 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1123 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1124 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1128 * rebuilds the select options for mailer options
1130 rebuildMailerOptions : function() {
1131 var select = document.forms['ieAccount'].elements['outbound_email'];
1132 SE.util.emptySelectOptions(select);
1134 //Get the available sugar mailers
1135 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1137 for(i=0;i<a_outbound.length;i++)
1139 var t_record = a_outbound[i];
1140 var key = t_record.getData('id');
1141 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1143 var opt = new Option(display, key);
1144 select.options.add(opt);
1145 if (key == SE.accounts.newAddedOutboundId) {
1146 select.options.selectedIndex = i;
1150 select.options.add(new Option('',''));
1151 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1152 //Hide/Show username password fields if necessary.
1153 SE.accounts.checkOutBoundSelection();
1156 * Empties all the fields in the accounts edit view
1158 clearInboundAccountEditScreen:function() {
1160 document.getElementById('ie_id').value = '';
1161 document.getElementById('ie_name').value = '';
1162 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1163 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1164 document.getElementById('reply_to_addr').value = '';
1165 document.getElementById('server_url').value = '';
1166 document.getElementById('email_user').value = '';
1167 document.getElementById('email_password').value = '';
1168 document.getElementById('port').value = '';
1169 document.getElementById('inbound_mail_smtpuser').value = '';
1170 document.getElementById('inbound_mail_smtppass').value = '';
1171 document.ieAccount.protocol.options[0].selected = true;
1173 document.getElementById('ssl').checked = false;
1178 * Populates an account's fields in Settings->Accounts
1180 fillIeAccount:function(jsonstr) {
1181 var o = JSON.parse(jsonstr);
1183 document.getElementById('ie_id').value = o.id;
1184 document.getElementById('ie_name').value = o.name;
1185 if (o.stored_options != null) {
1186 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1187 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1188 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1189 if (o.stored_options.trashFolder != null) {
1190 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1192 if (o.stored_options.sentFolder != null) {
1193 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1196 document.getElementById('server_url').value = o.server_url;
1197 document.getElementById('email_user').value = o.email_user;
1198 document.getElementById('email_password').value = o.email_password;
1199 document.getElementById('port').value = o.port;
1200 document.getElementById('group_id').value = o.group_id;
1201 document.getElementById('mailbox').value = o.mailbox;
1207 if(typeof(o.service[2]) != 'undefined') {
1208 document.getElementById('ssl').checked = true;
1212 if(document.getElementById('protocol').value != o.protocol) {
1213 var prot = document.getElementById('protocol');
1214 for(i=0; i<prot.options.length; i++) {
1215 if(prot.options[i].value == o.service[3]) {
1216 prot.options[i].selected = true;
1217 this.setPortDefault();
1221 // handle SMTP selection
1222 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1223 var opts = document.getElementById('outbound_email').options;
1224 for(i=0; i<opts.length; i++) {
1225 if(opts[i].value == o.stored_options.outbound_email) {
1226 opts[i].selected = true;
1232 deleteIeAccount : function(IeAccountID,IeGroupID) {
1233 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1235 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1237 AjaxObject.target = 'frameFlex';
1238 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1239 SUGAR.email2.accounts.refreshInboundAccountTable();
1243 // Null check for Outbound Settings.
1244 checkOutboundSettings: function() {
1245 var errorMessage = '';
1246 var isError = false;
1247 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1248 var mailName = document.getElementById('mail_name').value;
1249 var smtpServer = document.getElementById('mail_smtpserver').value;
1250 var smtpPort = document.getElementById('mail_smtpport').value;
1252 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1253 if(trim(mailName) == '') {
1255 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1257 if(trim(smtpServer) == '') {
1259 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1261 if(trim(smtpPort) == '') {
1263 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1265 if(mailsmtpauthreq.checked) {
1266 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1268 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1270 if(trim(document.getElementById('mail_smtppass').value) == '') {
1272 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS + "<br/>";
1277 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1284 testOutboundSettings: function() {
1285 var errorMessage = '';
1286 var isError = false;
1287 var fromAddress = document.getElementById("outboundtest_from_address").value;
1288 if (trim(fromAddress) == "") {
1289 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1290 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1294 else if (!isValidEmail(fromAddress)) {
1295 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1296 overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1300 //Hide the dialogue and show an in progress indicator.
1301 SE.accounts.testOutboundDialog.hide();
1302 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1304 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1305 //nothing is sent in the request.
1306 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1307 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1309 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1310 if(outboundType == 'system-override')
1311 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1313 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1314 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1318 testOutboundSettingsDialog: function() {
1319 //Ensure that all settings are correct before proceeding to send test email.
1320 if(!SE.accounts.checkOutboundSettings())
1323 // lazy load dialogue
1324 if(!SE.accounts.testOutboundDialog) {
1325 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1329 constraintoviewport: true,
1333 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1334 Dom.removeClass("testOutboundDialog", "yui-hidden");
1336 SE.accounts.testOutboundDialog.render();
1337 SE.accounts.testOutboundDialog.show();
1341 * Saves Outbound email settings
1343 saveOutboundSettings : function() {
1344 if(SE.accounts.checkOutboundSettings()) {
1345 //Enable the form fields for the post.
1346 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1347 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1348 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1354 saveIeAccount : function() {
1356 //Before saving check if there are any error messages associated with the outbound account.
1357 var outboundID = document.getElementById('outbound_email').value;
1359 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1360 'validateSMTPCreds':true}) )
1362 document.getElementById('saveButton').disabled = true;
1364 overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1366 var formObject = document.getElementById('ieAccount');
1367 YAHOO.util.Connect.setForm(formObject);
1369 AjaxObject._reset();
1370 AjaxObject.target = 'frameFlex';
1371 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1375 testSettings : function() {
1376 form = document.getElementById('ieAccount');
1378 if(SE.accounts.checkIeCreds()) {
1379 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");
1383 getFoldersListForInboundAccountForEmail2 : function() {
1384 form = document.getElementById('ieAccount');
1385 if(SE.accounts.checkIeCreds()) {
1386 var mailBoxValue = form.mailbox.value;
1387 if (form.searchField.value.length > 0) {
1390 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 );
1395 checkIeCreds : function(validateRules) {
1396 if(typeof(validateRules) == 'undefined')
1399 var errors = new Array();
1400 var out = new String();
1402 var ie_name = Dom.get('ie_name').value;
1403 var fromAddress = Dom.get('ie_from_addr').value;
1404 var server_url = Dom.get('server_url').value;
1405 var email_user = Dom.get('email_user').value;
1406 var email_password = Dom.get('email_password').value;
1407 var protocol = Dom.get('protocol').value;
1408 var port = Dom.get('port').value;
1409 var oe = Dom.get('outbound_email');
1410 var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1412 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1413 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1415 //If the username and password were provided then ignore the error messge
1417 var outboundCredentialsFound = false;
1419 if(outboundUserName != "" && outboundPass != "")
1420 outboundCredentialsFound = true;
1422 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1424 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1425 && validateSMTPCreds)
1427 if(trim(outboundUserName) == "") {
1428 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1430 if(trim(outboundPass) == "") {
1431 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1435 if(trim(ie_name) == "") {
1436 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1439 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1441 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1442 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1447 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1448 || trim(oe_value) == "SYSTEM_ADD") ) {
1449 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1451 if(trim(server_url) == "") {
1452 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1454 if(trim(email_user) == "") {
1455 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1457 if(trim(email_password) == "") {
1458 errors.push(app_strings.LBL_EMAIL_ERROR_PASSWORD);
1460 if(protocol == "") {
1461 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1463 if (protocol == 'imap') {
1464 var mailbox = document.getElementById('mailbox').value;
1465 if (trim(mailbox) == "") {
1466 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1468 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1469 var trashFolder = document.getElementById('trashFolder').value;
1470 if (trim(trashFolder) == "") {
1471 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1476 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1479 if(errors.length > 0) {
1480 out = app_strings.LBL_EMAIL_ERROR_DESC;
1481 for(i=0; i<errors.length; i++) {
1496 getIeAccount : function(ieId) {
1500 overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1501 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1503 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1507 * Iterates through TreeView nodes to apply styles dependent nature of node
1509 renderTree:function() {
1510 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1514 //Sets the style for any nodes that need it.
1515 setNodeStyle : function(node) {
1516 if (!node.data.origText) {
1517 node.data.origText = node.data.text;
1520 if (typeof(node.data.unseen) != 'undefined') {
1521 if (node.data.unseen > 0) {
1522 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1525 node.setUpLabel(node.data.origText);
1528 node.setUpLabel('<span>' + node.data.origText + '</span>');
1530 SE.accounts.setupDDTarget(node);
1533 setupDDTarget : function(node) {
1534 if (node.ddTarget) {
1535 node.ddTarget.removeFromGroup();
1536 delete node.ddTarget;
1538 var id = node.getElId();
1539 var num = id.substring(4);
1540 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1541 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1542 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1544 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1546 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1547 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1552 * Async call to rebuild the folder list. After a folder delete or account delete
1554 rebuildFolderList : function() {
1555 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1556 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1560 * Returns the number of remote accounts the user has active.
1562 getAccountCount : function() {
1565 for(i=0; i<tree._nodes.length; i++) {
1566 var node = tree._nodes[i];
1568 if(typeof(node) != 'undefined' && node.data.ieId) {
1576 ///////////////////////////////////////////////////////////////////////////////
1581 ///////////////////////////////////////////////////////////////////////////////
1582 //// CONTEXT MENU CALLS
1585 assignToDialogue : null,
1587 * Archives from context menu
1589 * @param string ieId
1590 * @param string folder
1592 _archiveToSugar : function(uids, ieId, folder) {
1595 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1596 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1599 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1603 * Archives from context menu
1605 archiveToSugar : function(menuItem) {
1606 SE.contextMenus.emailListContextMenu.hide();
1608 var rows = SE.grid.getSelectedRows();
1610 /* iterate through available rows JIC a row is deleted - use first available */
1611 for(var i=0; i<rows.length; i++) {
1612 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1614 var data = SE.grid.getRecord(rows[0]).getData();
1615 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1619 * Popup the printable version and start system's print function.
1621 viewPrintable : function(menuItem) {
1622 var rows = SE.grid.getSelectedRows();
1623 var data = SE.grid.getRecord(rows[0]).getData();
1624 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1628 * Marks email flagged on mail server
1630 markRead : function(type, contextMenuId) {
1631 SE.contextMenus.markEmail('read');
1635 * Assign this emails to people based on assignment rules
1637 assignEmailsTo : function(type, contextMenuId) {
1638 if(!SE.contextMenus.assignToDialogue)
1640 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1644 constraintoviewport: true,
1648 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1652 Dom.removeClass("assignToDiv", "yui-hidden");
1653 SE.contextMenus.assignToDialogue.render();
1654 SE.contextMenus.assignToDialogue.show();
1658 * Marks email flagged on mail server
1660 markFlagged : function(contextMenuId) {
1661 SE.contextMenus.markEmail('flagged');
1665 * Marks email unflagged on mail server
1667 markUnflagged : function(contextMenuId) {
1668 SE.contextMenus.markEmail('unflagged');
1672 * Marks email unread on mail server
1674 markUnread : function() {
1675 SE.contextMenus.markEmail('unread');
1679 * Deletes an email from context menu
1681 markDeleted : function() {
1682 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1683 document.getElementById('_blank').innerHTML = "";
1684 SE.contextMenus.markEmail('deleted');
1689 * generic call API to apply a flag to emails on the server and on sugar
1690 * @param string type "read" | "unread" | "flagged" | "deleted"
1692 markEmail : function(type) {
1693 SE.contextMenus.emailListContextMenu.hide();
1695 //var dm = SE.grid.getStore();
1696 //var uids = SE.grid.getSelectedRowIds();
1697 //var indexes = SE.grid.getSelectedRowIndexes();
1698 var rows = SE.grid.getSelectedRows();
1699 if (rows.length == 0)
1700 rows = [SE.contextMenus.currentRow];
1703 for(var i=0; i<rows.length; i++) {
1704 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1707 ser = YAHOO.lang.JSON.stringify(ser);
1709 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1710 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1716 if(type == 'read' || type == 'deleted') {
1718 for(var j=0; j<rows.length; j++) {
1719 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1721 SE.grid.getRecord(rows[j]).setData("seen", "1");
1724 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1726 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1727 var unseenCount = node.data.unseen;
1728 if (isNaN(unseenCount)) {
1731 var finalCount = parseInt(unseenCount) - count;
1732 node.data.unseen = finalCount;
1734 SE.accounts.renderTree();
1736 } else if(type == 'unread') {
1738 for(var j=0; j<rows.length; j++) {
1739 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1744 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1745 var unseenCount = node.data.unseen;
1746 if (isNaN(unseenCount)) {
1749 var finalCount = parseInt(unseenCount) + count;
1750 node.data.unseen = finalCount;
1751 SE.accounts.renderTree();
1754 if (type == 'unread') {
1755 for(var i=0; i<rows.length; i++) {
1756 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1760 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1761 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1765 * refreshes the ListView to show changes to cache
1767 markEmailCleanup : function() {
1768 SE.accounts.renderTree();
1770 SE.listView.refreshGrid();
1773 showAssignmentDialog : function() {
1774 if (SE.contextMenus.assignmentDialog == null) {
1775 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1777 SE.contextMenus.assignmentDialog.show();
1782 * shows the import dialog with only relate visible.
1784 relateTo : function() {
1785 SE.contextMenus.emailListContextMenu.hide();
1787 var rows = SE.grid.getSelectedRows();
1788 var data = SE.grid.getRecord(rows[0]).getData();
1789 var ieId = data.ieId;
1790 var folder = data.mbox;
1792 /* iterate through available rows JIC a row is deleted - use first available */
1793 for(var i=0; i<rows.length; i++) {
1794 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1796 var ser = JSON.stringifyNoSecurity(uids);
1798 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1802 * shows the import dialog with only relate visible.
1804 showDetailView : function() {
1805 SE.contextMenus.emailListContextMenu.hide();
1806 var rows = SE.grid.getSelectedRows();
1807 if (rows.length > 1) {
1808 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1811 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1812 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1813 /* iterate through available rows JIC a row is deleted - use first available */
1814 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1815 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1821 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1822 overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1823 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1827 * Opens multiple messages from ListView context click
1829 openMultiple : function() {
1830 SE.contextMenus.emailListContextMenu.hide();
1832 var rows = SE.grid.getSelectedRows();
1833 var uids = SE.listView.getUidsFromSelection();
1835 if(uids.length > 0) {
1836 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1837 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1838 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1843 * Replies/forwards email
1845 replyForwardEmailContext : function() {
1846 SE.contextMenus.emailListContextMenu.hide();
1848 var indexes = SE.grid.getSelectedRows();
1849 //var dm = SE.grid.getDataModel();
1852 for(var i=0; i<indexes.length; i++) {
1853 var row = SE.grid.getRecord(indexes[i]).getData();
1854 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1858 //show menu functions
1859 showEmailsListMenu : function(grid, row) {
1861 var data = row.getData();
1862 var draft = (data.type == "draft");
1863 var menu = SE.contextMenus.emailListContextMenu;
1868 if (data.mbox == 'sugar::Emails')
1869 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1871 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1873 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1874 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1875 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1876 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1878 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1881 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1883 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1884 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1885 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1886 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1887 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1890 if (data.mbox == "sugar::Emails")
1892 //Allow users to reassign imported emails
1893 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1894 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1895 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1896 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1900 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1901 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1905 showFolderMenu : function(grid, rowIndex, event) {
1907 var coords = event.getXY();
1908 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1912 SE.contextMenus.dv = {
1913 archiveToSugar : function(contextMenuId) {
1915 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1918 replyForwardEmailContext : function(all) {
1919 SE.contextMenus.detailViewContextMenu.hide();
1928 //// END SE.contextMenus
1929 ///////////////////////////////////////////////////////////////////////////////
1933 ///////////////////////////////////////////////////////////////////////////////
1936 consumeMetaDetail : function(ret) {
1937 // handling if the Email drafts
1938 if(ret.type == 'draft') {
1939 SE.composeLayout.c0_composeDraft();
1944 // cache contents browser-side
1945 SE._setDetailCache(ret);
1947 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1948 // 2 below must be in global context
1950 meta['panelId'] = SE.util.getPanelId();
1952 email = ret.meta.email;
1953 var out = displayTemplate.exec({
1954 'app_strings' : app_strings,
1956 'idx' : targetDiv.id,
1958 'email' : meta.email,
1959 'linkBeans' : linkBeans
1961 var tabLabel = meta.email.name;
1962 if (tabLabel != null && tabLabel.length > 25) {
1963 tabLabel = tabLabel.substring(0, 25) + "...";
1965 targetDiv.set("label", tabLabel);
1966 targetDiv.set("content", out);
1968 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1969 if (SUGAR.email2.util.isIe()) {
1970 displayEmailFrameDiv.style.height = "390px";
1972 displayEmailFrameDiv.style.height = "410px";
1975 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1976 displayFrame.contentWindow.document.write(email.description);
1977 displayFrame.contentWindow.document.close();
1979 // hide archive links
1980 if(ret.meta.is_sugarEmail) {
1981 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1982 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1984 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1985 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1990 consumeMetaPreview : function(ret) {
1991 // cache contents browser-side
1992 SE._setDetailCache(ret);
1996 var currrow = SE.grid.getLastSelectedRecord();
1997 currrow = SE.grid.getRecord(currrow);
1999 document.getElementById('_blank').innerHTML = '';
2002 // handling if the Email drafts
2003 if(ret.type == 'draft'){
2004 if (currrow.getData().uid == ret.uid) {
2005 SE.composeLayout.c0_composeDraft();
2010 if (currrow.getData().uid != ret.meta.uid) {
2014 // remove loading sprite
2015 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2016 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2018 meta['panelId'] = SE.util.getPanelId();
2019 email = ret.meta.email;
2021 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2022 'app_strings' : app_strings,
2026 'email' :meta.email,
2027 'linkBeans' : linkBeans
2029 // document.getElementById('_blank').innerHTML = meta.email;
2030 /* displayTemplate.append('_blank', {
2031 'app_strings' : app_strings,
2035 'email' :meta.email,
2036 'linkBeans' : linkBeans
2039 var displayFrame = document.getElementById('displayEmailFramePreview');
2040 displayFrame.contentWindow.document.write(email.description);
2041 displayFrame.contentWindow.document.close();
2043 SE.listViewLayout.resizePreview();
2045 // hide archive links
2046 if(ret.meta.is_sugarEmail) {
2047 document.getElementById("archiveEmailPreview").innerHTML = " ";
2048 document.getElementById("btnEmailViewPreview").style.display = "none";
2049 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2051 //hide view relationship link
2052 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2057 * wraps emailDelete() for single messages, comes from preview or tab
2059 emailDeleteSingle : function(ieId, uid, mbox) {
2060 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2061 // find active panel and close if the user double clicked the email to view.
2062 var activeTabId = SE.util.getPanelId();
2063 if(activeTabId != 'Preview')
2064 SE.innerLayout.get("activeTab").close();
2066 document.getElementById('_blank').innerHTML = "";
2069 uid = JSON.stringifyNoSecurity(ser);
2070 this.emailDelete(ieId, uid, mbox);
2075 * Sends async call to delete a given message
2078 emailDelete : function(ieId, uid, mbox) {
2079 overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2080 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2081 uid + "&ieId=" + ieId + "&folder=" + mbox);
2085 * retrieves one email to display in the preview pane.
2087 getEmailPreview : function() {
2088 var row = SUGAR.email2.listView.currentRow;
2089 var data = row.getData();
2090 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2091 var setRead = (data['seen'] == 0) ? true : false;
2092 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2093 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2098 * Imports one email into Sugar
2100 importEmail : function(ieId, uid, mbox) {
2101 SE.util.clearHiddenFieldValues('emailUIForm');
2103 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2105 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2106 AjaxObject.target = '';
2107 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2111 * Populates the frameFlex div with the contents of an email
2113 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2114 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2116 var mboxStr = new String(mbox);
2117 var compKey = mbox + uid;
2119 if(setRead == true) {
2120 SE.listView.boldUnreadRows()
2121 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2124 if(destination == SE.innerLayout) {
2126 * loading email into a tab, peer with ListView
2127 * targetDiv must remain in the global namespace as it is used by AjaxObject
2129 //Check if we already have a tab of the email open
2130 var tabs = SE.innerLayout.get("tabs");
2131 for (var t in tabs) {
2132 if (tabs[t].id && tabs[t].id == uid) {
2133 SE.innerLayout.set("activeTab", tabs[t]);
2138 targetDiv = new YAHOO.SUGAR.ClosableTab({
2139 label: loadingSprite,
2145 SE.innerLayout.addTab(targetDiv);
2147 // use cache if available
2148 if(SE.cache[compKey]) {
2149 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2151 // open email as peer-tab to listView
2152 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2153 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2156 // loading email into preview pane
2157 document.getElementById('_blank').innerHTML = loadingSprite;
2159 // use cache if available
2160 if(SE.cache[compKey]) {
2161 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2163 AjaxObject.forceAbort = true;
2164 // open in preview window
2165 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2166 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2171 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2173 if(mboxStr.substring(0,7) == 'sugar::') {
2174 // display an email from Sugar
2175 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2177 // display an email from an email server
2178 document.getElementById('emailUIAction').value = 'getSingleMessage';
2180 document.getElementById('mbox').value = mbox;
2181 document.getElementById('ieId').value = ieId;
2182 document.getElementById('uid').value = uid;
2184 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2186 AjaxObject.forceAbort = true;
2187 AjaxObject.target = '_blank';
2188 AjaxObject.startRequest(callback, null);
2192 * Retrieves multiple emails for DetailView
2194 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2195 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2196 SE.util.clearHiddenFieldValues('emailUIForm');
2198 var mboxStr = new String(mbox);
2200 uids = SE.util.cleanUids(uids);
2202 if(mboxStr.substring(0,7) == 'sugar::') {
2203 // display an email from Sugar
2204 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2205 document.getElementById('uid').value = uids;
2207 // display an email from an email server
2208 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2209 document.getElementById('mbox').value = mbox;
2210 document.getElementById('ieId').value = ieId;
2211 document.getElementById('uid').value = uids;
2214 var formObject = document.getElementById('emailUIForm');
2215 YAHOO.util.Connect.setForm(formObject);
2217 AjaxObject.target = 'frameFlex';
2218 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2220 if(setRead == true) {
2221 var c = uids.split(",");
2222 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2227 * Makes async call to get QuickCreate form
2228 * Renders a modal edit view for a given module
2230 quickCreate : function(module, ieId, uid, mailbox) {
2231 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2233 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2234 get += "&sugarEmail=true";
2237 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2241 * Makes async call to save a quick create
2244 saveQuickCreate : function(action) {
2245 var qcd = SE.detailView.quickCreateDialog;
2246 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2247 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2248 var theCallback = callbackQuickCreateSave;
2249 var accountType = '&sugarEmail=true';
2250 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2251 accountType = '&ieId=' + qcd.ieId;
2254 if (action == 'reply') {
2255 theCallback = callbackQuickCreateSaveAndReply;
2256 } else if (action == true) {
2257 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2259 formObject.action.value = 'EmailUIAjax';
2260 YAHOO.util.Connect.setForm(formObject);
2261 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2262 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2263 accountType + '&mbox=' + qcd.mbox);
2268 * Code to show/hide long list of email address in DetailView
2270 showCroppedEmailList : function(el) {
2271 el.style.display = 'none';
2272 el.previousSibling.style.display = 'inline'
2274 showFullEmailList : function(el) {
2275 el.style.display = 'none';
2276 el.nextSibling.style.display = 'inline';
2280 * Shows the QuickCreate overlay
2281 * @param string ieId
2283 * @param string mailbox
2285 showQuickCreate : function(ieId, uid, mailbox) {
2286 var panelId = SE.util.getPanelId();
2287 var context = document.getElementById("quickCreateSpan" + panelId);
2289 if (!SE.detailView.cqMenus)
2290 SE.detailView.cqMenus = {};
2292 if (SE.detailView.cqMenus[context])
2293 SE.detailView.cqMenus[context].destroy();
2295 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2297 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2300 for (var i=0; i < this.qcmodules.length; i++) {
2301 var module = this.qcmodules[i];
2303 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2306 onclick: { fn: function() {
2307 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2313 menu.render(document.body);
2318 * Displays the "View" submenu in the detailView
2319 * @param string ieId
2321 * @param string mailbox
2323 showViewMenu : function(ieId, uid, mailbox) {
2324 var panelId = SE.util.getPanelId();
2325 var context = "btnEmailView" + panelId;
2326 if (!SE.detailView.viewMenus)
2327 SE.detailView.viewMenus = {};
2329 if (SE.detailView.viewMenus[context])
2330 SE.detailView.viewMenus[context].destroy();
2332 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2334 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2338 (ieId == 'null' || ieId == null) ?
2339 //No ieId - Sugar Email
2341 text: app_strings.LBL_EMAIL_VIEW_RAW,
2342 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2345 //IeID exists, on a remote server
2347 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2348 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2350 text: app_strings.LBL_EMAIL_VIEW_RAW,
2351 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2354 menu.render(document.body);
2359 //#23108 jchi@07/17/2008
2360 menu.render('quickCreateSpan'+ panelId);*/
2361 //this.viewMenu = menu;
2362 //this.viewMenu.show(context);
2365 * Makes async call to get an email's headers
2367 viewHeaders : function(ieId, uid, mailbox) {
2368 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2369 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2373 * Makes async call to get a printable version
2375 viewPrintable : function(ieId, uid, mailbox) {
2376 if(mailbox == 'sugar::Emails') {
2377 // display an email from Sugar
2378 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2380 // display an email from an email server
2381 var emailUIAction = '&emailUIAction=getSingleMessage';
2384 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2385 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2389 * Makes async call to get an email's raw source
2391 viewRaw : function(ieId, uid, mailbox) {
2392 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2393 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2397 * Display all email addresses in detailview.
2399 displayAllAddrs : function(el) {
2400 el.style.display = 'none';
2401 Dom.getNextSibling(el).style.display = 'inline';
2404 //// END SE.detailView
2405 ///////////////////////////////////////////////////////////////////////////////
2409 ///////////////////////////////////////////////////////////////////////////////
2412 contextMenuFocus : new Object(),
2415 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2416 * SugarFolder ID - folder strings
2418 _createFolderId : function(node) {
2424 if(node.data.ieId) {
2425 /* we have a local Sugar folder */
2426 if(node.data.ieId == 'folder') {
2427 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2428 } else if(node.data.ieId.match(SE.reGUID)) {
2429 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2438 addChildNode : function(parentNode, childNode) {
2439 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2440 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2441 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2443 if(childNode.nodes) {
2444 if(childNode.nodes.length > 0) {
2445 for(j=0; j<childNode.nodes.length; j++) {
2446 var newChildNode = childNode.nodes[j];
2447 this.addChildNode(node, newChildNode);
2454 * Builds and returns a new TreeView Node
2455 * @param string name
2457 * @param int is_group
2460 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2461 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2463 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2464 node.expanded = expanded;
2465 node.data = new Object;
2466 node.data['id'] = id;
2467 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2468 node.data['label'] = name;
2469 node.data['ieId'] = 'folder';
2470 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2471 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2472 node.data['unseen'] = unseen;
2477 * ensures that a new folder has a valid name
2479 checkFolderName : function(name) {
2483 this.folderAdd(name);
2487 * Pings email servers for new email - forces refresh of folder pane
2489 checkEmailAccounts : function() {
2490 this.checkEmailAccountsSilent(true);
2493 checkEmailAccountsSilent : function(showOverlay) {
2494 if(typeof(SE.folders.checkingMail)) {
2495 clearTimeout(SE.folders.checkingMail);
2498 // don't stomp an on-going request
2499 if(AjaxObject.currentRequestObject.conn == null) {
2501 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2502 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2504 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2506 // wait 5 secs before trying again.
2507 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2512 * Starts check of all email Accounts using a loading bar for large POP accounts
2514 startEmailAccountCheck : function() {
2515 // don't do two checks at the same time
2516 if(!AjaxObject.requestInProgress()) {
2517 overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2518 SE.accounts.ieIds = SE.folders.getIeIds();
2519 if (SE.accounts.ieIds.length > 0) {
2520 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2521 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2526 // wait 5 secs before trying again.
2527 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2532 * Checks a single Account check based on passed ieId
2534 startEmailCheckOneAccount : function(ieId, synch) {
2541 var node = SE.clickedFolderNode;
2542 if (node && !synch) {
2543 mbox = node.data.mbox;
2545 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2546 SE.accounts.ieIds = [ieId];
2547 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2548 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2553 * Empties trash for subscribed accounts
2555 emptyTrash : function() {
2556 SE.contextMenus.frameFoldersContextMenu.hide();
2557 overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2558 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2562 * Clears Cache files of the inboundemail account
2564 clearCacheFiles : function(ieId) {
2565 SE.contextMenus.frameFoldersContextMenu.hide();
2566 overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2567 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2572 * Returns an array of all the active accounts in the folder view
2574 getIeIds : function() {
2576 var root = SE.tree.getRoot();
2577 for(i=0; i < root.children.length; i++) {
2578 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2579 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2580 ieIds.push(root.children[i].children[0].data.ieId);
2587 * loads folder lists in Settings->Folders
2589 lazyLoadSettings : function() {
2590 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2591 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2595 * After the add new folder is done via folders tab on seetings, this function should get called
2596 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2598 loadSettingFolder : function() {
2599 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2600 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2604 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2606 removeSugarFolders : function() {
2608 var root = tree.getRoot();
2609 var folder = SE.util.findChildNode(root, "ieId", "folder");
2611 tree.removeNode(folder);
2612 folder = SE.util.findChildNode(root, "ieId", "folder");
2614 if (!root.childrenRendered) {
2615 root.childrenRendered = true;
2619 rebuildFolders : function(silent) {
2620 if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2621 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2627 * Updates TreeView with Sugar Folders
2629 setSugarFolders : function(delay) {
2630 this.removeSugarFolders();
2631 //AjaxObject.forceAbort = true;
2632 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2636 * Takes async data object and creates the sugar folders in TreeView
2638 setSugarFoldersEnd : function(o) {
2639 var root = SE.tree.getRoot();
2640 addChildNodes(root, {nodes: o});
2641 SE.accounts.renderTree();
2642 //If nothing is loaded in the grid, load "My Inbox"
2643 if (SE.grid.params.ieId == "undefined") {
2644 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2648 startCheckTimer : function() {
2649 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2650 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2652 if(typeof(SE.folders.checkTimer) != 'undefined') {
2653 clearTimeout(SE.folders.checkTimer);
2656 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2657 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2659 SE.userPrefs.emailSettings.firstAutoCheck = true;
2660 SE.folders.checkEmailAccountsSilent(false);
2666 * makes an async call to save user preference and refresh folder view
2667 * @param object SELECT list object
2669 setFolderSelection : function() {
2670 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2672 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2673 var a_active_accnts = "";
2674 for(i=0;i<a_rs.length;i++)
2676 var t_record = a_rs[i];
2677 var is_active = t_record.getData('is_active');
2679 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2682 if(a_active_accnts == "")
2683 a_active_accnts = "&ieIdShow[]=";
2685 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2687 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2691 * makes async call to save user preference for a given node's open state
2692 * @param object node YUI TextNode object
2694 setOpenState : function(node) {
2695 SE.util.clearHiddenFieldValues('emailUIForm');
2696 var nodePath = node.data.id;
2697 var nodeParent = node.parent;
2699 while(nodeParent != null) {
2700 // root node has no ID param
2701 if(nodeParent.data != null) {
2702 nodePath = nodeParent.data.id + "::" + nodePath;
2705 var nodeParent = nodeParent.parent;
2708 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2709 document.getElementById('focusFolder').value = nodePath;
2711 if(node.expanded == true) {
2712 document.getElementById('focusFolderOpen').value = 'open';
2714 document.getElementById('focusFolderOpen').value = 'closed';
2717 var formObject = document.getElementById('emailUIForm');
2718 YAHOO.util.Connect.setForm(formObject);
2720 AjaxObject.startRequest(null, null);
2723 getNodeFromMboxPath : function(path) {
2724 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2725 var a = JSON.parse(path);
2727 var node = tree.getRoot();
2730 while(i < a.length) {
2731 node = this.getChildNodeFromLabel(node, a[i]);
2738 getChildNodeFromLabel : function(node, nodeLabel) {
2739 for(i=0; i<node.children.length; i++) {
2740 if(node.children[i].data.id == nodeLabel) {
2741 return node.children[i];
2747 * returns the node that presumably under the user's right-click
2749 getNodeFromContextMenuFocus : function() {
2750 //// get the target(parent) node
2751 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2753 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2755 // filter local folders
2756 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2757 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2758 if(target.id == '') {
2759 target = target.parentNode;
2766 var targetNode = document.getElementById(target.id);
2767 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2770 var matches = re.exec(targetNode.id);
2772 return document.getElementById(ygtvlabelel1);
2778 // usually parent node
2779 matches = re.exec(targetNode.parentNode.id);
2786 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2787 parentNode.expand();
2793 * Decrements the Unread Email count in folder text
2794 * @param string ieId ID to look for
2795 * @param string mailbox name
2796 * @param count how many to decrement
2798 decrementUnreadCount : function(ieId, mbox, count) {
2803 if(mbox.indexOf("sugar::") === 0) {
2804 var node = this.getNodeFromId(ieId);
2806 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2809 var unseen = node.data.unseen;
2811 var check = unseen - count;
2812 var finalCount = (check >= 0) ? check : 0;
2813 node.data.unseen = finalCount;
2815 SE.accounts.renderTree();
2820 * gets the TreeView node with a given ID/ieId
2821 * @param string id ID to look for
2822 * @return object Node
2824 getNodeFromId : function(id) {
2825 SE.folders.focusNode = null;
2826 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2827 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2828 SE.folders.focusNode = this;
2832 return SE.folders.focusNode;
2836 * Uses ieId and mailbox to try to find a node in the tree
2838 getNodeFromIeIdAndMailbox : function(id, mbox) {
2839 SE.folders.focusNode = null;
2840 if (mbox == "sugar::Emails") {
2844 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2845 if (varsarray instanceof Array) {
2846 if (this.data.ieId && this.data.ieId == varsarray[0]
2847 && this.data.mbox == varsarray[1]) {
2848 SE.folders.focusNode = this;
2852 if (this.data.ieId && this.data.ieId == varsarray) {
2853 SE.folders.focusNode = this;
2857 }, null, [id, mbox]);
2858 return SE.folders.focusNode;
2861 unhighliteAll : function() {
2862 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2866 * Displays a short form
2868 folderAdd : function() {
2869 SE.contextMenus.frameFoldersContextMenu.hide();
2871 var node = SE.clickedFolderNode;
2873 if(node != null && node.data) {
2874 overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2875 app_strings.LBL_EMAIL_SETTINGS_NAME,
2876 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2878 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2882 folderAddRegisterEnter : function() {
2883 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2884 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2885 this.buttons[1].handler);
2887 this.enterKeyListener.enable();
2890 folderRemoveRegisterEnter : function() {
2891 this.enterKeyListener.disable();
2894 folderAddXmlCall : function(name) {
2895 if (trim(name) == "") {
2896 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2899 name = escape(name);
2903 var parentNode = SE.clickedFolderNode;
2905 this.contextMenuFocus = parentNode;
2907 if(parentNode.data.ieId) {
2908 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2912 if(type == 'imap') {
2913 // make an IMAP folder
2914 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2915 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2916 } else if(type == 'sugar') {
2917 // make a Sugar folder
2918 if(SE.folders.isUniqueFolderName(name)) {
2919 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2920 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2922 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2923 SE.folders.folderAdd();
2927 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2930 // hide add-folder diaglogue
2931 SE.e2overlay.hide();
2935 * Removes either an IMAP folder or a Sugar Folder
2937 folderDelete : function() {
2938 SE.contextMenus.frameFoldersContextMenu.hide();
2940 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2942 var parentNode = SE.clickedFolderNode;
2944 if(parentNode != null && parentNode.data) {
2945 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2946 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2950 AjaxObject.target = 'frameFlex';
2952 if(parentNode.data.ieId != 'folder') {
2953 // delete an IMAP folder
2954 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2956 // delete a sugar folder
2957 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2959 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2960 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2962 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2968 * Rename folder form
2971 folderRename : function() {
2972 SE.contextMenus.frameFoldersContextMenu.hide();
2973 var node = SE.clickedFolderNode;
2976 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2977 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2981 overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2982 app_strings.LBL_EMAIL_SETTINGS_NAME,
2984 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2986 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2991 * fills an Object with key-value pairs of available folders
2993 getAvailableFoldersObject : function() {
2994 var ret = new Object();
2995 var tree = SE.tree.root;
2998 for(var i=0; i<tree.children.length; i++) {
2999 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3002 ret['none'] = app_strings.LBL_NONE;
3009 * Fills in key-value pairs for dependent dropdowns
3010 * @param object ret Associative array
3011 * @param object node TreeView node in focus
3012 * @param string currentPath Built up path thus far
3013 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3015 getFolderFromChild : function(ret, node, currentPath, spacer) {
3016 if(node.data != null && node.depth > 0) {
3017 /* handle visual separtors differentiating b/t mailserver and local */
3018 if(node.data.ieId && node.data.ieId == 'folder') {
3019 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3023 ret['spacer0'] = spacer;
3024 } else if(ret.spacer0 != spacer) {
3025 ret['spacer1'] = spacer
3028 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3029 var depthMarker = currentPath;
3030 var retIndex = SE.folders._createFolderId(node);
3031 ret[retIndex] = depthMarker + theLabel;
3034 if(node.children != null) {
3036 currentPath += theLabel + "/";
3039 for(var i=0; i<node.children.length; i++) {
3040 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3048 * Wrapper to refresh folders tree
3050 getFolders : function() {
3051 SE.accounts.rebuildFolderList();
3055 * handles events around folder-rename input field changes
3056 * @param object YUI event object
3058 handleEnter : function(e) {
3059 switch(e.browserEvent.type) {
3061 e.preventDefault(); // click in text field
3065 SE.folders.submitFolderRename(e);
3069 var kc = e.browserEvent.keyCode;
3073 SE.folders.submitFolderRename(e);
3077 e.preventDefault(e);
3078 SE.folders.cancelFolderRename(e);
3085 * Called when a node is clicked on in the folder tree
3086 * @param node, The node clicked on
3087 * @param e, The click event
3089 handleClick : function(o) {
3091 //If the click was on a sugar folder
3092 if (node.data.ieId == "folder") {
3093 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3096 SE.listView.populateListFrame(node, node.data.ieId, false);
3098 //eval(node.data.click);
3103 * Called when a node is right-clicked on in the folder tree
3105 handleRightClick : function(e) {
3106 YAHOO.util.Event.preventDefault(e);
3108 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3109 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3111 //If the click was on a sugar folder
3112 SE.clickedFolderNode = node;
3113 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3114 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3115 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3116 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3117 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3118 menu.getItem(3).cfg.setProperty("disabled", false);
3119 menu.getItem(4).cfg.setProperty("disabled", false);
3120 menu.getItem(5).cfg.setProperty("disabled", false);
3121 menu.getItem(6).cfg.setProperty("disabled", true);
3123 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3124 menu.getItem(0).cfg.setProperty("disabled", true);
3125 menu.getItem(1).cfg.setProperty("disabled", true);
3126 menu.getItem(2).cfg.setProperty("disabled", true);
3127 menu.getItem(3).cfg.setProperty("disabled", true);
3128 menu.getItem(4).cfg.setProperty("disabled", true);
3130 if (node.data.protocol != null) {
3131 menu.getItem(6).cfg.setProperty("disabled", false);
3133 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3134 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3135 //Sent or Draft folders
3136 menu.getItem(3).cfg.setProperty("disabled", true);
3137 menu.getItem(4).cfg.setProperty("disabled", true);
3138 menu.getItem(5).cfg.setProperty("disabled", true);
3141 //For group with auto inbound, disable everything.
3142 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3144 menu.getItem(0).cfg.setProperty("disabled", true);
3145 menu.getItem(1).cfg.setProperty("disabled", true);
3146 menu.getItem(2).cfg.setProperty("disabled", true);
3147 menu.getItem(3).cfg.setProperty("disabled", true);
3148 menu.getItem(4).cfg.setProperty("disabled", true);
3149 menu.getItem(5).cfg.setProperty("disabled", true);
3150 menu.getItem(6).cfg.setProperty("disabled", true);
3153 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3158 * Called when a row is dropped on a node
3160 handleDrop : function(rows, targetFolder) {
3161 var rowData = rows[0].getData();
3162 if (rowData.mbox != targetFolder.data.mbox) {
3163 var srcIeId = rowData.ieId;
3164 var srcFolder = rowData.mbox;
3165 var destIeId = targetFolder.data.ieId;
3166 var destFolder = targetFolder.data.mbox;
3168 for(var i=0; i<rows.length; i++) {
3169 uids[i] = rows[i].getData().uid;
3171 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3176 * Called when something is dragged over a Folder Node
3178 dragOver : function(dragObject) {
3183 * Determines if a folder name is unique to the folder tree
3184 * @param string name
3186 isUniqueFolderName : function(name) {
3187 uniqueFolder = true;
3188 var root = SE.tree.getRoot();
3189 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3190 if (this.attributes && this.attributes.ieId == "folder") {
3191 if (this.attributes.text == name) {
3192 uniqueFolder = false;
3197 return uniqueFolder;
3201 * Makes async call to rename folder in focus
3202 * @param object e Event Object
3204 submitFolderRename : function(newName) {
3205 if (trim(newName) == "") {
3206 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3209 newName = escape(newName);
3210 var node = SE.clickedFolderNode;
3211 var origName = node.data.text
3213 if (newName == origName) {
3216 if(SE.folders.isUniqueFolderName(newName)) {
3217 overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3218 if (node.data.ieId == "folder") {
3220 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3223 //IMAP folder or POP mailbox
3224 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3225 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3226 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3230 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3235 moveFolder : function(folderId, parentFolderId) {
3236 if (folderId != parentFolderId)
3238 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3239 + folderId + "&newParentId=" + parentFolderId);
3244 * makes async call to do a full synchronization of all accounts
3246 synchronizeAccounts : function() {
3247 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3248 overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3249 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3254 * Updates user's folder subscriptsion (Sugar only)
3255 * @param object SELECT DOM object in focus
3256 * @param string type of Folder selection
3258 updateSubscriptions : function() {
3259 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3263 select = document.getElementById('userFolders');
3265 for(i=0; i<select.options.length; i++) {
3266 var opt = select.options[i];
3267 if(opt.selected && opt.value != "") {
3271 active += opt.value;
3275 //Add the group folder ids.
3276 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3277 for(i=0; i<group_folders.length; i++)
3279 active += ("::" + group_folders[i]);
3282 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3285 * Updates user's group folder subscriptsion (Sugar only)
3286 * @param ieID The group folder to add to the tree view
3288 retrieveGroupFolderSubscriptions : function() {
3290 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3291 var activeGroupFolders = "";
3292 var activeGroupIds = [];
3293 for(i=0;i<a_rs.length;i++)
3295 var t_record = a_rs[i];
3296 var is_active = t_record.getData('is_active');
3297 var isGroupFolder = t_record.getData('has_groupfolder');
3298 var ieID = t_record.getData('id');
3302 activeGroupIds.push(ieID);
3306 return activeGroupIds;
3311 SE.folders.checkEmail2 = function() {
3312 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3314 //// END FOLDERS OBJECT
3315 ///////////////////////////////////////////////////////////////////////////////
3318 ///////////////////////////////////////////////////////////////////////////////
3321 * Keypress Event capture and processing
3324 overall : function(e) {
3325 switch(e.charCode) {
3327 if(e.ctrlKey || e.altKey) {
3328 var focusRegion = SE.innerLayout.regions.center;
3329 if(focusRegion.activePanel.closable == true) {
3330 focusRegion.remove(focusRegion.activePanel);
3338 ///////////////////////////////////////////////////////////////////////////////
3341 ///////////////////////////////////////////////////////////////////////////////
3344 * ListView object methods and attributes
3350 * Fills the ListView pane with detected messages.
3352 populateListFrame : function(node, ieId, forceRefresh) {
3353 SE.innerLayout.selectTab(0);
3354 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3356 Dom.get('_blank').innerHTML = "";
3357 SE.grid.params['emailUIAction'] = 'getMessageList';
3358 SE.grid.params['mbox'] = node.data.mbox;
3359 SE.grid.params['ieId'] = ieId;
3360 forcePreview = true; // loads the preview pane with first item in grid
3361 SE.listView.refreshGrid();
3365 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3367 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3368 SE.innerLayout.selectTab(0);
3369 Dom.get('_blank').innerHTML = "";
3370 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3371 SE.grid.params['ieId'] = node.data.id;
3372 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3373 SE.listView.refreshGrid();
3377 * Sets sort order as user preference
3380 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3382 ieName = ieNamePassed;
3383 focusFolder = focusFolderPassed;
3385 SE.util.clearHiddenFieldValues('emailUIForm');
3386 var previousSort = document.getElementById('sortBy').value;
3388 document.getElementById('sortBy').value = sortBy;
3389 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3390 document.getElementById('focusFolder').value = focusFolder;
3391 document.getElementById('ieId').value = ieId;
3393 if(sortBy == previousSort) {
3394 document.getElementById('reverse').value = '1';
3397 var formObject = document.getElementById('emailUIForm');
3398 YAHOO.util.Connect.setForm(formObject);
3400 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3405 * Enables click/arrow select of grid items which then populate the preview pane.
3407 selectFirstRow : function() {
3408 SE.grid.selModel.selectFirstRow();
3411 selectLastRow : function() {
3412 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3415 setEmailListStyles : function() {
3416 SE.listView.boldUnreadRows();
3418 var ds = SE.grid.getStore();
3419 if (SE.grid.getSelections().length == 0) {
3420 document.getElementById('_blank').innerHTML = '';
3424 if(typeof(ds.baseParams.mbox) != 'undefined') {
3425 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3426 var cm = SE.grid.getColumnModel();
3427 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3428 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3430 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3431 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3435 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3436 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3439 // 4/20/2007 added to hide overlay after search
3441 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3442 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3443 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3444 if (node) node.data.unseen = unread;
3446 SE.accounts.renderTree();
3449 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3450 if(forcePreview && ds.totalCount > 0) {
3451 SE.detailView.getEmailPreview();
3452 forcePreview = false;
3457 * Removes a row if found via its UID
3459 removeRowByUid : function(uid) {
3460 uid = new String(uid);
3461 uids = uid.split(',');
3462 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3464 for(j=0; j<uids.length; j++) {
3465 var theUid = uids[j];
3466 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3467 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3468 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3474 displaySelectedEmails : function(rows) {
3475 var dm = SE.grid.getDataModel();
3478 for(i=0; i<rows.length; i++) {
3479 var rowIndex = rows[i].rowIndex;
3480 var metadata = dm.data[rowIndex];
3485 uids += metadata[5];
3487 // unbold unseen email
3488 this.unboldRow(rowIndex);
3491 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3495 * exception handler for data load failures
3497 loadException : function(dataModel, ex, response) {
3502 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3503 * @param string sourceIeId Email's source I-E id
3504 * @param string sourceFolder Email's current folder
3505 * @param destinationIeId Destination I-E id
3506 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3508 * @param array emailUids Array of email's UIDs
3510 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3511 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3512 overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3514 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3515 // remove rows from visibility
3516 for(row in selectedRows) {
3517 //SE.grid.getStore().remove(row);
3520 var baseUrl = '&sourceIeId=' + sourceIeId +
3521 '&sourceFolder=' + sourceFolder +
3522 '&destinationIeId=' + destinationIeId +
3523 '&destinationFolder=' + destinationFolder;
3526 for(i=0; i<emailUids.length; i++) {
3528 uids += app_strings.LBL_EMAIL_DELIMITER;
3530 uids += emailUids[i];
3532 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3533 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3535 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3541 * Unbolds text in the grid view to denote read status
3543 markRead : function(index, record) {
3544 // unbold unseen email
3545 var row = SE.grid.getRecord(record);
3546 row.getData().seen = 1;
3547 SE.grid.getTrEl(record).style.fontWeight = "normal";
3551 * grid row output, bolding unread emails
3553 boldUnreadRows : function() {
3554 // bold unread emails
3555 var trEl = SE.grid.getFirstTrEl();
3556 while(trEl != null) {
3557 if(SE.grid.getRecord(trEl).getData().seen == "0")
3558 trEl.style.fontWeight = "bold";
3560 trEl.style.fontWeight = "";
3561 trEl = SE.grid.getNextTrEl(trEl);
3566 * Show preview for an email if 1 and only 1 is selected
3567 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3569 handleRowSelect : function(e) {
3570 if(e.selectedRows.length == 1) {
3571 SE.detailView.getEmailPreview();
3575 handleDrop : function(e, dd, targetId, e2) {
3577 case 'htmleditordiv':
3578 var rows = SE.grid.getSelectedRows();
3579 if(rows.length > 0) {
3580 SE.listView.displaySelectedEmails(rows);
3585 var targetElId = new String(targetId);
3586 var targetIndex = targetElId.replace('ygtvlabelel',"");
3587 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3588 var dm = SE.grid.getDataModel();
3589 var emailUids = new Array();
3590 var destinationIeId = targetNode.data.ieId;
3591 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3594 var rows = SE.grid.getSelectedRows();
3595 // iterate through dragged rows
3596 for(i=0; i<rows.length; i++) {
3597 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3598 var rowIndex = rows[i].rowIndex;
3599 var dataModelRow = dm.data[rowIndex];
3600 var sourceIeId = dataModelRow[7];
3601 var sourceFolder = dataModelRow[6];
3602 emailUids[i] = dataModelRow[5];
3605 // event wrapped call - need FQ
3606 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3607 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3613 * Hack-around to get double-click and single clicks to work on the grid
3614 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3616 handleClick : function(o) {
3617 SUGAR.email2.grid.clearTextSelection();
3619 var el = SUGAR.email2.grid.getSelectedRows();
3621 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3622 if ( el.length == 1)
3625 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3626 SUGAR.email2.listView.currentRowIndex = rowId;
3627 clearTimeout(SUGAR.email2.detailView.previewTimer);
3628 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3633 * Custom handler for double-click/enter
3634 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3636 getEmail : function(e) {
3637 var rows = SE.grid.getSelectedRows();
3638 var row = SE.grid.getRecord(rows[0]).getData();
3640 clearTimeout(SE.detailView.previewTimer);
3641 document.getElementById("_blank").innerHTML = "";
3643 if(row.type != "draft") {
3644 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3646 // circumventing yui-ext tab generation, let callback handler build new view
3647 SE.util.clearHiddenFieldValues('emailUIForm');
3648 //function(uid, mbox, ieId, setRead, destination) {
3649 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3650 document.getElementById('uid').value = row.uid; // uid;
3651 document.getElementById('mbox').value = row.mbox; // mbox;
3652 document.getElementById('ieId').value = row.ieId; // ieId;
3654 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3655 AjaxObject.target = '_blank';
3656 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3661 * Retrieves a row if found via its UID
3665 getRowIndexByUid : function(uid) {
3666 uid = new String(uid);
3667 uids = uid.split(',');
3669 for(j=0; j<uids.length; j++) {
3670 var theUid = uids[j];
3672 for(i=0; i<SE.grid.getStore().data.length; i++) {
3673 if(SE.grid.getStore().data[i].id == theUid) {
3681 * Returns the UID's of the seleted rows
3684 getUidsFromSelection : function() {
3685 var rows = SE.grid.getSelectedRows();
3687 /* iterate through available rows JIC a row is deleted - use first available */
3688 for(var i=0; i<rows.length; i++) {
3689 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3694 refreshGrid : function() {
3695 SE.grid.getDataSource().sendRequest(
3696 SUGAR.util.paramsToUrl(SE.grid.params),
3697 SE.grid.onDataReturnInitializeTable,
3703 //// END SE.listView
3704 ///////////////////////////////////////////////////////////////////////////////
3706 ///////////////////////////////////////////////////////////////////////////////
3710 * sends search criteria
3711 * @param reference element search field
3713 search : function(el) {
3714 var searchCriteria = new String(el.value);
3716 if(searchCriteria == '') {
3717 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3721 var safeCriteria = escape(searchCriteria);
3723 var accountListSearch = document.getElementById('accountListSearch');
3724 //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3726 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3727 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3728 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3729 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3730 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3735 * sends advanced search criteria
3737 searchAdvanced : function() {
3738 var formObject = document.getElementById('advancedSearchForm');
3741 //Set assigned user id to blank if name is not present.
3742 if (formObject.elements['assigned_user_name'].value == "")
3743 formObject.elements['assigned_user_id'].value = "";
3745 for(i=0; i<formObject.elements.length; i++) {
3746 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3749 if(formObject.elements[i].type == 'text') {
3750 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3752 if(formObject.elements[i].type == 'hidden') {
3753 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3755 if(formObject.elements[i].type == 'select-one') {
3756 var el = formObject.elements[i];
3757 var v = el.options[el.selectedIndex].value;
3760 SE.grid.params[el.name] = v;
3763 //Clear previous search results if necessary
3764 if(typeof( SE.grid.params[el.name]) != 'undefined')
3765 delete SE.grid.params[el.name]
3772 if(! this.validateSearchFormInput() )
3775 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3776 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3777 var accountListSearch = document.getElementById('accountListSearch');
3778 SE.listView.refreshGrid();
3780 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3785 * Validates the search form inputs to ensure all parameters are valid
3788 validateSearchFormInput: function()
3790 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3791 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3792 var dateCheck = check_form('advancedSearchForm');
3794 //If the parent type is selected ensure the user selected a parent_id.
3795 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3801 * Toggles the advanced options, either hidding or showing the selection.
3803 toggleAdvancedOptions: function()
3805 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3807 for(var i=0;i<el.length;i++)
3809 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3810 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3812 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3816 * clears adv search form fields
3818 searchClearAdvanced : function() {
3819 var form = document.getElementById('advancedSearchForm');
3821 for(i=0; i<form.elements.length; i++) {
3822 if(form.elements[i].type != 'button') {
3823 form.elements[i].value = '';
3829 //////////////////////////////////////////////////////////////////////////////
3832 //////////////////////////////////////////////////////////////////////////////
3835 /******************************************************************************
3836 * USER SIGNATURES calls stolen from Users module
3837 *****************************************************************************/
3838 createSignature : function(record, the_user_id) {
3839 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3841 URL += "&record="+record;
3843 if(the_user_id != "") {
3844 URL += "&the_user_id="+the_user_id;
3846 var windowName = 'email_signature';
3847 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3849 var win = window.open(URL, windowName, windowFeatures);
3850 if(win && win.focus) {
3851 // put the focus on the popup if the browser supports the focus() method
3856 deleteSignature : function() {
3857 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3858 overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3859 var singature_id = document.getElementById('signature_id').value;
3860 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3864 saveOptionsGeneral : function(displayMessage) {
3865 var formObject = document.getElementById('formEmailSettingsGeneral');
3866 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3867 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3870 YAHOO.util.Connect.setForm(formObject);
3871 SE.composeLayout.emailTemplates = null;
3873 AjaxObject.target = 'frameFlex';
3874 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3877 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3879 SE.settings.settingsDialog.hide();
3883 * Shows settings container screen
3885 showSettings : function() {
3886 if(!SE.settings.settingsDialog) {
3887 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3893 constraintoviewport: true
3895 dlg.showEvent.subscribe( function (){
3896 var el = this.element;
3897 var viewH = YAHOO.util.Dom.getViewportHeight();
3898 if (this.header && el && viewH - 50 < el.clientHeight) {
3899 var body = this.header.nextElementSibling;
3900 body.style.overflow = "auto";
3901 body.style.height = (viewH - 50) + "px";
3904 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3905 dlg.setBody('<div id="settingsTabDiv"/>');
3906 dlg.beforeRenderEvent.subscribe(function() {
3907 var dd = new YAHOO.util.DDProxy(dlg.element);
3908 dd.setHandleElId(dlg.header);
3909 dd.on('endDragEvent', function() {
3915 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3916 var tabContent = Dom.get("tab_general");
3917 tp.addTab(new YAHOO.widget.Tab({
3918 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3920 content : tabContent.innerHTML,
3921 id : "generalSettings",
3924 tabContent.parentNode.removeChild(tabContent);
3925 tabContent = Dom.get("tab_accounts");
3926 var accountTab = new YAHOO.widget.Tab({
3927 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3929 content : tabContent.innerHTML,
3930 id : "accountSettings"
3932 tp.addTab(accountTab);
3933 tabContent.parentNode.removeChild(tabContent);
3935 tp.appendTo(dlg.body);
3938 SE.settings.settingsDialog.show();
3939 SE.folders.lazyLoadSettings();
3940 SE.accounts.lazyLoad();
3944 lazyLoadRules : function() {
3945 if(false/*!SE.settings.rules*/) {
3946 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3952 //// END SE.settings
3953 ///////////////////////////////////////////////////////////////////////////////
3956 /******************************************************************************
3958 *****************************************************************************/
3959 function removeHiddenNodes(nodes, grid) {
3961 for(var i = nodes.length - 1; i > -1; i--) {
3962 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3963 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3969 function strpad(val) {
3970 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3973 function refreshTodos() {
3974 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3975 AjaxObject.target = 'todo';
3976 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3979 /******************************************************************************
3980 * MUST STAY IN GLOBAL NAMESPACE
3981 *****************************************************************************/
3982 function refresh_signature_list(signature_id, signature_name) {
3983 var field=document.getElementById('signature_id');
3985 for (var i=0; i < field.options.length; i++) {
3986 if (field.options[i].value == signature_id) {
3987 if (field.options[i].selected==false) {
3988 field.options[i].selected=true;
3993 //add item to selection list.
3995 var newElement=document.createElement('option');
3996 newElement.text=signature_name;
3997 newElement.value=signature_id;
3998 field.options.add(newElement);
3999 newElement.selected=true;
4002 //enable the edit button.
4003 var field1=document.getElementById('edit_sig');
4004 field1.style.visibility="inherit";
4005 var deleteButt = document.getElementById('delete_sig');
4006 deleteButt.style.visibility="inherit";
4009 function setDefaultSigId(id) {
4010 var checkbox = document.getElementById("signature_default");
4011 var default_sig = document.getElementById("signatureDefault");
4013 if(checkbox.checked) {
4014 default_sig.value = id;
4016 default_sig.value = "";
4020 function setSigEditButtonVisibility() {
4021 var field = document.getElementById('signature_id');
4022 var editButt = document.getElementById('edit_sig');
4023 var deleteButt = document.getElementById('delete_sig');
4024 if(field.value != '') {
4025 editButt.style.visibility = "inherit";
4026 deleteButt.style.visibility = "inherit";
4028 editButt.style.visibility = "hidden";
4029 deleteButt.style.visibility = "hidden";
4031 }// End of File modules/Emails/javascript/EmailUI.js
4033 /*********************************************************************************
4034 * SugarCRM is a customer relationship management program developed by
4035 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4037 * This program is free software; you can redistribute it and/or modify it under
4038 * the terms of the GNU Affero General Public License version 3 as published by the
4039 * Free Software Foundation with the addition of the following permission added
4040 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4041 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4042 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4044 * This program is distributed in the hope that it will be useful, but WITHOUT
4045 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4046 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4049 * You should have received a copy of the GNU Affero General Public License along with
4050 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4051 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4054 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4055 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4057 * The interactive user interfaces in modified source and object code versions
4058 * of this program must display Appropriate Legal Notices, as required under
4059 * Section 5 of the GNU Affero General Public License version 3.
4061 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4062 * these Appropriate Legal Notices must retain the display of the "Powered by
4063 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4064 * technical reasons, the Appropriate Legal Notices must display the words
4065 * "Powered by SugarCRM".
4066 ********************************************************************************/
4069 var sw = YAHOO.SUGAR,
4070 Event = YAHOO.util.Event,
4071 Connect = YAHOO.util.Connect,
4072 Dom = YAHOO.util.Dom
4075 ///////////////////////////////////////////////////////////////////////////////
4078 _contactCache : new Array(), // cache of contacts
4079 _dd : new Array(), // filtered list, same format as _contactCache
4080 _ddLists : new Array(), // list of Lists
4081 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4082 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4083 clickBubble : true, // hack to get around onclick event bubbling
4085 relatedBeanType : '',
4088 itemSpacing : 'white-space:nowrap; padding:2px;',
4094 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4096 initFixForDatatableSort: function () {
4097 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4098 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4099 var oColumn = this._oColumnSet.getColumn(column);
4102 // Validate TD element
4103 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4105 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4107 // Validate TH element
4109 elCell = this.getThEl(column);
4112 var allColumns = this._oColumnSet.flat;
4113 for(var i=0, len=allColumns.length; i<len; i++) {
4114 if(allColumns[i].getThEl().id === elCell.id) {
4115 oColumn = allColumns[i];
4126 cancelEdit : function() {
4127 if(this.editContactDialog)
4128 this.editContactDialog.hide();
4129 if(this.editMailingListDialog)
4130 this.editMailingListDialog.hide();
4134 * Clears filter form
4136 clear : function() {
4137 var t = document.getElementById('contactsFilter');
4143 * handle context-menu Compose-to call
4144 * @param string type 'contacts' or 'lists'
4146 composeTo : function(type, waited) {
4147 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4148 if (activePanel.substring(0, 10) != "composeTab") {
4149 SE.composeLayout.c0_composeNewEmail();
4150 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4151 SE.contextMenus.contactsContextMenu.hide();
4154 var idx = activePanel.substring(10);
4157 // determine if we have a selection to work with
4158 if(type == 'contacts') {
4159 var ids = SE.contactView.getSelectedRows();
4160 for (var i in ids) {
4161 rows[i] = SE.contactView.getRecord(ids[i]);
4163 removeHiddenNodes(rows, SE.contactView);
4167 if(rows.length > 0) {
4168 SE.composeLayout.handleDrop(
4169 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4170 null, rows, 'addressTO' + idx );
4172 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4176 editContact : function() {
4177 SE.contextMenus.contactsContextMenu.hide();
4178 var element = SE.contactView.getSelectedNodes()[0];
4180 if (element.className.indexOf('address-contact') > -1) {
4181 elementId = element.id;
4182 } else if (element.className.indexOf('address-exp-contact') > -1) {
4183 elementId = element.id.substring(2);
4189 * Filters contact entries based on user input
4191 filter : function(inputEl) {
4192 var ret = new Object();
4193 var re = new RegExp(inputEl.value, "gi");
4195 for(var i in this._contactCache) {
4196 if(this._contactCache[i].name.match(re)) {
4197 ret[i] = this._contactCache[i];
4201 this.buildContactList(ret);
4204 fullForm : function(id, module) {
4205 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4209 * returns a formatted email address from the addressBook cache
4211 getFormattedAddress : function(id) {
4212 var o = this._contactCache[id];
4213 var primaryEmail = '';
4215 for(var i=0; i<o.email.length; i++) {
4216 var currentEmail = o.email[i].email_address;
4218 if(o.email[i].primary_address == 1) {
4219 primaryEmail = o.email[i].email_address;
4223 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4224 var name = new String(o.name);
4225 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4226 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4232 * Sets up async call to query for matching contacts, users, etc.
4234 searchContacts : function() {
4235 var fn = document.getElementById('input_searchField').value;
4236 var pe = document.getElementById('input_searchPerson').value;
4238 var rb = document.getElementById('hasRelatedBean').checked;
4241 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4242 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4243 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4244 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4246 this.addressBookDataModel.params['related_bean_id'] = '';
4249 this.addressBookDataModel.params['search_field'] = fn;
4250 this.addressBookDataModel.params['person'] = pe;
4251 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4252 this.grid._oDataSource = this.addressBookDataModel;
4253 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4257 * Clear Search Crieteria For Addressbook
4259 clearAddressBookSearch : function() {
4260 document.getElementById('input_searchField').value = "";
4261 document.getElementById('input_searchPerson').selectedIndex = 0;
4265 * Opens modal select window to add contacts to addressbook
4267 selectContactsDialogue : function(destId) {
4268 if(!this.contactsDialogue) {
4269 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4273 constraintoviewport: true,
4275 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4276 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4278 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4280 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4281 dlg.setBody(body.innerHTML);
4282 dlg.renderEvent.subscribe(function() {
4283 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4284 if (iev && !SUGAR.isIE) {
4285 this.body.style.width = "950px";
4290 dlg.beforeRenderEvent.subscribe(function() {
4291 var dd = new YAHOO.util.DDProxy(dlg.element);
4292 dd.setHandleElId(dlg.header);
4293 dd.on('endDragEvent', function() {
4299 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4301 var tabContent = SUGAR.util.getAndRemove("searchForm");
4302 tp.addTab(new YAHOO.widget.Tab({
4303 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4305 content : tabContent.innerHTML,
4306 id : "addressSearchTab",
4310 var addListenerFields = ['input_searchPerson','input_searchField' ]
4311 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4312 if (e.keyCode == 13) {
4313 YAHOO.util.Event.stopEvent(e);
4314 SUGAR.email2.addressBook.searchContacts();
4318 this.contactsDialogue.render();
4321 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4322 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4326 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4327 var idx = activePanel.substring(10);
4329 SE.addressBook.idx = idx;
4332 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4333 document.getElementById('relatedBeanColumn').style.display = '';
4334 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4335 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4336 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4337 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4338 SE.addressBook.relatedBeanType = relatedBeanType;
4340 document.getElementById('relatedBeanColumn').style.display = 'none';
4341 document.getElementById('hasRelatedBean').checked = false;
4344 if (!SE.addressBook.grid)
4346 if (hasRelatedBeanId) {
4347 document.getElementById('hasRelatedBean').checked = true;
4349 AddressSearchGridInit();
4350 SE.addressBook.relatedBeanId = relatedBeanId;
4354 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4356 SE.addressBook.relatedBeanId = relatedBeanId;
4357 document.getElementById('hasRelatedBean').checked = true;
4359 if (document.getElementById('hasRelatedBean').checked == true)
4361 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4362 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4364 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4365 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4367 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4368 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4369 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4372 //Remove any lingering rows in the result set table if the module was closed.
4373 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4375 SE.addressBook.populateResulstTableEmailAddresses();
4377 this.contactsDialogue.show();
4380 * Clear all email addresses from result table.
4383 clearAllEmailAddressFieldsFromResultTable: function () {
4384 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4385 //Unhighlight any rows currently selected if the emails were cleared.
4386 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4387 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4390 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4391 * results table. This function is called when the address book is displayed.
4393 populateResulstTableEmailAddresses: function () {
4395 var idx = SE.addressBook.idx;
4396 var emailFields = ['to','cc','bcc'];
4398 for(var k=0;k<emailFields.length;k++)
4400 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4401 var allEmails = document.getElementById(elKey).value;
4405 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4407 for (var i=0; i<formatedEmails.length; i++)
4409 var t_name = formatedEmails[i].name;
4410 var t_emailAddr = formatedEmails[i].email_address;
4411 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4413 t_name = displayEmail = t_emailAddr;
4415 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4416 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4417 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4423 * Checks all entries in the result table against a particular email address, returning true
4424 * if the email address is found, false otherwise.
4426 doesEmailAdddressExistInResultTable: function(emailAddress)
4428 if(trim(emailAddress) == '')
4431 var emailAddressFound = false;
4432 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4433 for (var i=0; i < contacts.length; i++)
4435 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4436 //If we are adding to cc or bcc fields, make them visible.
4437 if(data.email_address == emailAddress)
4439 emailAddressFound = true;
4444 return emailAddressFound;
4447 * Takes all email addresses that the users wishes to add from the address book and populates the To
4448 * fields on the compose tab.
4450 populateEmailAddressFieldsFromResultTable: function()
4452 //Clear the fields first, all email addresses are stored in the address book
4453 var idx = SE.addressBook.idx;
4454 var emailFields = ['to','cc','bcc'];
4455 for(var k=0;k<emailFields.length;k++)
4457 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4458 document.getElementById(elKey).value = "";
4461 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4462 for (var i=0; i < contacts.length; i++)
4464 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4466 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4467 //If we are adding to cc or bcc fields, make them visible.
4468 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4469 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4470 //Construct the target id
4471 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4473 var target = document.getElementById(target_id);
4474 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4477 //Delete all rows from the result set table
4478 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4481 SE.addressBook.contactsDialogue.hide()
4484 * Insert contacts into the result table.
4486 insertContactToResultTable : function(event,address_type) {
4488 var contactsDialogue = SE.addressBook.contactsDialogue;
4489 var contacts = SE.addressBook.grid.getSelectedRows();
4491 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4492 for (var i = 0; i < rows.length; i++)
4494 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4496 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4497 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4498 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4499 rows[i].setData("selected",true);
4502 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4503 for (var i = 0; i < checkBoxes.length; i++) {
4504 checkBoxes[i].checked = false;
4510 insertContactRowToResultTable : function(rowId, addressType) {
4511 var data = SE.addressBook.grid.getRecord(rowId).getData();
4512 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4514 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4515 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4516 if(addressType == null)
4517 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4518 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});
4521 * Remove a row from the gridsResult table.
4523 removeRowFromGridResults : function(rowId,emailAddress)
4525 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4526 for (var i=0; i < contacts.length; i++)
4528 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4529 var data = rec.getData();
4530 if(data.email_address == emailAddress)
4532 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4537 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4540 * Translates between the addressType To|Cc|Bcc labels/keys.
4542 translateAddresType: function(addressType,fromKey)
4544 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4545 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4546 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4547 var mappingObject = {};
4550 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4553 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4554 mappingObject[displayCc] = 'cc';
4555 mappingObject[displayBcc] = 'bcc';
4558 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4564 toggleSearchRowIcon : function(rowId,show)
4568 var idToShow = rowId + '_add_img';
4569 var idToHide = rowId + '_rm_img';
4573 var idToShow = rowId + '_rm_img';
4574 var idToHide = rowId + '_add_img';
4578 Dom.addClass(idToHide, "yui-hidden");
4579 Dom.removeClass(idToShow, "yui-hidden");
4582 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4584 doesGridResultsEntryExist: function(emailAddrs)
4587 var contactExists = false;
4588 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4589 for (var i=0; i < contacts.length; i++)
4591 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4592 if(data.email_address == emailAddrs)
4594 contactExists = true;
4598 return contactExists;
4602 * adds an email address to a string, but first checks if it exists
4603 * @param string concat The string we are appending email addresses to
4604 * @param string addr Email address to add
4607 smartAddEmailAddressToComposeField : function(concat, addr) {
4608 var re = new RegExp(addr);
4610 if(!concat.match(re)) {
4612 concat += "; " + addr;
4621 //// END ADDRESS BOOK
4622 ///////////////////////////////////////////////////////////////////////////////
4626 ///////////////////////////////////////////////////////////////////////////////
4629 * Auto-complete object
4633 delimChar : [";", ","],
4637 prehighlightClassName : "yui-ac-prehighlight",
4640 instances : new Array(),
4643 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4644 * @param object Contact from AddressBook
4647 getPrimaryAddress : function(contact) {
4648 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4650 for(var eIndex in contact.email) {
4651 address = contact.email[eIndex].email_address;
4652 if(contact.email[eIndex].primary_address == 1) {
4653 return contact.email[eIndex].email_address;
4661 * initializes autocomplete widgets for a given compose view
4664 init : function(idx) {
4665 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4666 "queryMatchContains" : false,
4667 "queryMatchSubset" : true
4670 this.instances[idx] = {
4677 // instantiate the autoComplete widgets
4678 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4679 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4680 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4682 // enable hiding of interfering textareas
4683 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4684 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4685 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4687 // enable reshowing of hidden textareas
4688 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4689 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4690 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4692 // enable refreshes of contact lists
4693 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4694 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4695 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4698 refreshDataSource : function(sType, aArgs) {
4699 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4701 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4703 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4704 idx = textBoxId.substr(9);
4706 idx = textBoxId.substr(10);
4709 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4710 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4711 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4715 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4717 returnDataSource : function(contacts) {
4718 var ret = new Array();
4719 for(var id in contacts) {
4720 if (contacts[id].name) {
4721 var primary = this.getPrimaryAddress(contacts[id]);
4723 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4724 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4726 for(var emailIndex in contacts[id].email) {
4727 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4736 * Hides address textareas to prevent autocomplete dropdown from being obscured
4738 toggleTextareaHide : function(sType, aArgs) {
4739 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4743 if(textBoxId.indexOf("addressTO") > -1) {
4745 } else if(textBoxId.indexOf("addressCC") > -1) {
4748 idx = textBoxId.substr(9);
4750 // follow through if not BCC
4752 var cc = document.getElementById("addressCC" + idx);
4753 var bcc = document.getElementById("addressBCC" + idx);
4757 cc.style.visibility = 'hidden';
4759 bcc.style.visibility = 'hidden';
4766 * Redisplays the textareas after an address is commited
4768 toggleTextareaShow : function(sType, aArgs) {
4769 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4773 if(textBoxId.indexOf("addressTO") > -1) {
4775 } else if(textBoxId.indexOf("addressCC") > -1) {
4778 idx = textBoxId.substr(9);
4780 // follow through if not BCC
4782 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4783 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4788 //// END AUTOCOMPLETE
4789 ///////////////////////////////////////////////////////////////////////////////
4791 ///////////////////////////////////////////////////////////////////////////////
4794 * expands the options sidebar
4796 SE.composeLayout = {
4797 currentInstanceId : 0,
4800 outboundAccountErrors : null,
4801 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4803 showAddressDetails : function(e) {
4804 var linkElement = document.getElementById("More"+e.id);
4805 var spanElement = document.getElementById("Detail"+e.id);
4806 var emailAddressList = e.value;
4807 if(e.value.length > 96)
4809 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4810 var displayArray = [];
4811 for (var i=0; i<resultArray.length; i++)
4813 var t_name = resultArray[i].name;
4814 var t_emailAddr = resultArray[i].email_address;
4816 displayArray.push('<br/><' + t_emailAddr + '>');
4818 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4821 var result = displayArray.join('<br/>');
4823 linkElement.style.display = "inline";
4824 linkElement.style.height="10px";
4825 linkElement.style.overflow="visible";
4826 spanElement.innerHTML = result;
4829 linkElement.style.display = "none";
4834 * Given a string of email address, return an array containing the name portion (if available)
4835 * and email portion.
4837 _getEmailArrayFromString : function (emailAddressList){
4840 while ((results = reg.exec(emailAddressList)) != null)
4842 orignial = results[0];
4843 parsedResult = results[0].replace(';', ':::::');
4844 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4848 while ((results = reg.exec(emailAddressList)) != null)
4850 orignial = results[0];
4851 parsedResult = results[0].replace(',', ':::::');
4852 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4854 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4855 var emailArr = emailAddressList.split(":::::");
4856 var resultsArray = [];
4858 for (var i=0; i<emailArr.length; i++)
4860 var rposition = emailArr[i].indexOf('<');
4861 var lposition = emailArr[i].indexOf('>');
4863 if(trim(emailArr[i]) != '')
4865 if(rposition != -1 && lposition != -1)
4867 var t_name = emailArr[i].substr(0, rposition-1);
4868 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4869 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4873 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4877 return resultsArray;
4879 ///////////////////////////////////////////////////////////////////////////
4882 * Prepare bucket DIV and yui-ext tab panels
4884 _0_yui : function() {
4885 var idx = this.currentInstanceId;
4887 var composeTab = new YAHOO.SUGAR.ClosableTab({
4888 label: mod_strings.LNK_NEW_SEND_EMAIL,
4890 content : "<div id='htmleditordiv" + idx + "'/>",
4891 id : "composeTab" + idx,
4892 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4895 SE.innerLayout.addTab(composeTab);
4897 // get template engine with template
4898 if (!SE.composeLayout.composeTemplate) {
4899 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4902 // create Tab inner layout
4903 var composePanel = this.getComposeLayout();
4904 composePanel.getUnitByPosition("right").collapse();
4905 composePanel.autoSize();
4909 * Generate the quick compose layout
4910 * @method getQuickComposeLayout
4911 * @param {Pannel} parentPanel Parent pannel
4912 * @param {Object} o Options
4915 getQuickComposeLayout : function (parentPanel,o) {
4916 var idx = SE.composeLayout.currentInstanceId;
4918 //Before rendering the parent pannel we need to initalize the grid layout
4919 parentPanel.beforeRenderEvent.subscribe(function() {
4921 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4922 SE.composeLayout._createComposeLayout(idx);
4923 SE.composeLayout[idx].set('height', 350);
4924 SE.composeLayout[idx].render();
4928 //Wait until the Compose Layout has rendered, then add the
4929 //options tab and perform the tiny initialization.
4930 parentPanel.renderEvent.subscribe(function() {
4932 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4933 SE.composeLayout._initComposeOptionTabs(idx);
4934 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4935 //Initialize tinyMCE
4936 if (!SUGAR.util.isTouchScreen())
4937 SE.composeLayout._1_tiny();
4938 //Init templates and address book
4939 SE.composeLayout._2_final();
4941 SE.composeLayout.quickCreateComposePackage(o);
4946 //Check if we have the div override for the shortcut bar
4947 if(typeof o.menu_id != 'undefined') {
4948 parentPanel.render(o.menu_id);
4950 parentPanel.render(document.body);
4953 return SE.composeLayout[idx];
4956 * Fill in all fields into the quick compose layout.
4957 * @method quickCreateComposePackage
4958 * @param {Object} o Options
4961 quickCreateComposePackage: function(o)
4963 //If we have a compose package fill in defaults.
4964 if (typeof(o.composePackage) != 'undefined')
4966 composePackage = o.composePackage; //Set the compose data object
4967 //Hijack this method called by composePackage as it's not need for quick creates.
4968 SE.composeLayout.c0_composeNewEmail = function(){};
4969 SE.composeLayout.composePackage(); //Fill in defaults.
4972 getComposeLayout : function() {
4973 var idx = SE.composeLayout.currentInstanceId;
4975 this._createComposeLayout(idx);
4976 SE.composeLayout[idx].render();
4977 this._initComposeOptionTabs(idx);
4979 return SE.composeLayout[idx];
4983 * Create the layout manager for the compose window.
4985 _createComposeLayout : function(idx)
4987 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
4988 parent: SE.complexLayout,
4998 SE.composeLayout.composeTemplate.exec({
4999 'app_strings':app_strings,
5000 'mod_strings':mod_strings,
5002 'linkbeans_options' : linkBeans,
5003 'idx' : SE.composeLayout.currentInstanceId
5014 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5017 header: app_strings.LBL_EMAIL_OPTIONS
5023 * Create compose tab which will populate the 'right' container in the compose window.
5025 _initComposeOptionTabs : function(idx)
5027 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5028 var tab = new YAHOO.widget.Tab({
5029 label: app_strings.LBL_EMAIL_ATTACHMENT,
5031 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5032 id : "divAttachments" + idx,
5036 tab.layout = SE.composeLayout[idx];
5038 tab.on("activeChange", function(o){
5040 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5046 tab = new YAHOO.widget.Tab({
5047 label: app_strings.LBL_EMAIL_OPTIONS,
5049 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5050 id : "divOptions" + idx,
5054 tab.layout = SE.composeLayout[idx];
5055 tab.on("activeChange", function(o){
5057 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5062 SE.composeLayout[idx].autoSize = function() {
5063 var pEl = this.get("element").parentNode.parentNode.parentNode;
5064 this.set("height", pEl.clientHeight-30);
5068 SE.composeLayout[idx].rightTabs = cTabs;
5070 isParentTypeValid : function(idx) {
5071 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5072 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5073 if (trim(parentTypeValue) == ""){
5074 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5080 isParentTypeAndNameValid : function(idx) {
5081 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5082 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5083 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5084 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5085 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5086 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5092 callopenpopupForEmail2 : function(idx,options) {
5094 var formName = 'emailCompose' + idx;
5096 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5097 formName = options.form_name;
5099 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5100 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5101 if (!SE.composeLayout.isParentTypeValid(idx)) {
5104 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5106 call_back_function:"SE.composeLayout.popupAddEmail",
5108 field_to_name_array:{
5109 id:'data_parent_id' + idx,
5110 name:'data_parent_name' + idx,
5115 popupAddEmail : function(o)
5117 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5118 var data = o.name_to_value_array;
5119 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5120 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5122 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5123 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5130 _1_tiny : function() {
5131 var idx = SE.composeLayout.currentInstanceId;
5132 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5133 SE.tinyInstances[elId] = { };
5134 SE.tinyInstances[elId].ready = false;
5135 var t = tinyMCE.getInstanceById(elId);
5137 if(typeof(t) == 'undefined') {
5138 tinyMCE.execCommand('mceAddControl', false, elId);
5139 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5140 SE.composeLayout.resizeEditor(idx);
5141 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
5146 resizeEditor : function(idx)
5148 var cof = Dom.get('composeOverFrame' + idx);
5149 var head = Dom.get('composeHeaderTable' + idx);
5150 var targetHeight = cof.clientHeight - head.clientHeight;
5151 var instance = tinyMCE.get(SE.tinyInstances.currentHtmleditor);
5153 var parentEl = Dom.get(instance.editorId + '_parent');
5154 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5155 var contentEl = instance.contentAreaContainer;
5156 var iFrame = contentEl.firstChild;
5157 var tinMceToolbarOffset = 18;
5158 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5162 * Initializes d&d, auto-complete, email templates
5164 _2_final : function() {
5165 var idx = SE.composeLayout.currentInstanceId;
5167 if(this.emailTemplates) {
5168 this.setComposeOptions(idx);
5170 //populate email template cache
5171 AjaxObject.target = '';
5172 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5175 // handle drop targets for addressBook
5176 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5177 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5178 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5179 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5181 // auto-complete setup
5182 SE.autoComplete.init(idx);
5185 document.getElementById("addressTO" + idx).focus();
5189 * hide tinyMCE tool bar if send email as plaintext is checked
5191 renderTinyMCEToolBar : function (idx, hide) {
5193 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5195 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5199 c1_composeEmail : function(isReplyForward, retry) {
5203 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5204 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5209 if(isReplyForward) {
5210 this.replyForwardEmailStage2();
5216 * takes draft info and prepopulates
5218 c0_composeDraft : function() {
5219 this.getNewInstanceId();
5221 document.getElementById('_blank').innerHTML = '';
5222 var idx = SE.composeLayout.currentInstanceId;
5223 SE.composeLayout.draftObject = new Object();
5224 SE.composeLayout.draftObject.id = idx;
5225 SE.composeLayout.draftObject.isDraft = true;
5226 SE.composeLayout.currentInstanceId = idx;
5227 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5228 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5229 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5231 SE.composeLayout._0_yui();
5232 SE.composeLayout._1_tiny();
5235 SE.composeLayout._2_final();
5237 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5238 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5242 * Strip & Prep editor hidden fields
5244 c0_composeNewEmail : function() {
5245 this.getNewInstanceId();
5246 this.c1_composeEmail(false);
5250 * Sends async request to get the compose view.
5251 * Requests come from "reply" or "forwards"
5253 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5254 SE.composeLayout.replyForwardObj = new Object();
5255 SE.composeLayout.replyForwardObj.ieId = ieId;
5256 SE.composeLayout.replyForwardObj.uid = uid;
5257 SE.composeLayout.replyForwardObj.mbox = mbox;
5258 SE.composeLayout.replyForwardObj.type = type;
5260 if(mbox == 'sugar::Emails') {
5261 SE.composeLayout.replyForwardObj.sugarEmail = true;
5264 SE.composeLayout.getNewInstanceId();
5265 SE.composeLayout.c1_composeEmail(true);
5267 //// END COMPOSE FLOW
5268 ///////////////////////////////////////////////////////////////////////////
5271 * Called when a contact, email, or mailinglist is dropped
5272 * into one of the compose fields.
5274 handleDrop : function (source, event, data, target) {
5277 target = event.getTarget();
5279 data.nodes = [data.nodes];
5283 target = document.getElementById(target);
5287 if (target.id.indexOf('address') > -1) {
5288 // dropped onto email to/cc/bcc field
5289 for(var i in nodes) {
5290 var node = nodes[i].getData();
5292 if (node[1].indexOf('contact') > -1) {
5293 email = SE.addressBook.getFormattedAddress(node[0]);
5294 } else if (node[1].indexOf('address-email') > -1){
5295 email = node[3].replace(/ /gi, '');
5296 email = email.replace('<', '<').replace('>', '>');
5297 var tr = source.getTrEl(nodes[i]);
5298 while (tr && !Dom.hasClass(tr, "address-contact")) {
5299 tr = source.getPreviousTrEl(tr);
5301 var CID = source.getRecord(tr).getData()[0];
5302 var o = SE.addressBook._contactCache[CID];
5303 var name = new String(o.name);
5304 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5305 email = finalName + email;
5307 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5313 /*/////////////////////////////////////////////////////////////////////////////
5314 /// EMAIL TEMPLATE CODE
5316 applyEmailTemplate : function (idx, id) {
5319 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5320 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5321 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5323 // id is selected index of email template drop-down
5324 if(id == '' || id == "0") {
5325 YAHOO.SUGAR.MessageBox.show({
5330 if(btn=='no'){return;};
5331 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5338 YAHOO.SUGAR.MessageBox.show({
5343 if(btn=='no'){return;};
5344 SUGAR.email2.composeLayout.processResult(idx, id);},
5350 processNoneResult : function(idx, id) {
5351 var tiny = SE.util.getTiny('htmleditor' + idx);
5352 var tinyHTML = tiny.getContent();
5353 var openTag = '<div><span><span>';
5354 var htmllow = tinyHTML.toLowerCase();
5355 var start = htmllow.indexOf(openTag);
5357 tinyHTML = tinyHTML.substr(start);
5358 tiny.setContent(tinyHTML);
5360 tiny.setContent('');
5364 processResult : function(idx , id){
5365 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5367 // get attachments if any
5368 AjaxObject.target = '';
5369 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5372 appendEmailTemplateJSON : function() {
5373 var idx = SE.composeLayout.currentInstanceId; // post increment
5375 // query based on template, contact_id0,related_to
5376 //jchi 09/10/2008 refix #7743
5377 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5378 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5381 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,'"');
5383 // cn: bug 14361 - text-only templates don't fill compose screen
5385 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/>");
5388 var tiny = SE.util.getTiny('htmleditor' + idx);
5389 var tinyHTML = tiny.getContent();
5390 var openTag = '<div><span><span>';
5391 var closeTag = '</span></span></div>';
5392 var htmllow = tinyHTML.toLowerCase();
5393 var start = htmllow.indexOf(openTag);
5395 var htmlPart2 = tinyHTML.substr(start);
5396 tinyHTML = text + htmlPart2;
5397 tiny.setContent(tinyHTML);
5399 tiny.setContent(text);
5404 * Writes out the signature in the email editor
5406 setSignature : function(idx) {
5409 var hide = document.getElementById('setEditor' + idx).checked;
5410 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5411 //wait for signatures to load before trying to set them
5412 if (!SE.composeLayout.signatures) {
5413 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5418 var sel = document.getElementById('signatures' + idx);
5420 var sel = document.getElementById('signature_id');
5421 idx = SE.tinyInstances.currentHtmleditor;
5424 //Ensure that the tinyMCE html has been rendered.
5425 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5426 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5433 signature = sel.options[sel.selectedIndex].value;
5438 var openTag = '<div><span><span>';
5439 var closeTag = '</span></span></div>';
5440 var t = SE.util.getTiny('htmleditor' + idx);
5442 if(typeof(t) != 'undefined')
5444 t.contentDocument = t.contentWindow.document;
5445 var html = t.getContent();
5450 var htmllow = html.toLowerCase();
5451 var start = htmllow.indexOf(openTag);
5452 var end = htmllow.indexOf(closeTag) + closeTag.length;
5454 // selected "none" - remove signature from email
5455 if(signature == '') {
5457 var htmlPart1 = html.substr(0, start);
5458 var htmlPart2 = html.substr(end, html.length);
5460 html = htmlPart1 + htmlPart2;
5463 SE.signatures.lastAttemptedLoad = '';
5467 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5468 SE.signatures.lastAttemptedLoad = '';
5470 SE.signatures.lastAttemptedLoad = signature;
5472 if(typeof(SE.signatures[signature]) == 'undefined') {
5474 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5475 SE.signatures.targetInstance = (idx) ? idx : "";
5476 AjaxObject.target = '';
5477 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5479 var newSignature = this.prepareSignature(SE.signatures[signature]);
5481 // clear out old signature
5482 if(SE.signatures.lastAttemptedLoad && start > -1) {
5483 var htmlPart1 = html.substr(0, start);
5484 var htmlPart2 = html.substr(end, html.length);
5486 html = htmlPart1 + htmlPart2;
5490 start = html.indexOf('<div><hr></div>');
5491 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5492 var htmlPart1 = html.substr(0, start);
5493 var htmlPart2 = html.substr(start, html.length);
5494 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5495 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5496 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5498 var newHtml = html + openTag + newSignature + closeTag;
5500 //tinyMCE.setContent(newHtml);
5501 t.setContent(newHtml);
5505 prepareSignature : function(str) {
5506 var signature = new String(str);
5508 signature = signature.replace(/</gi, '<');
5509 signature = signature.replace(/>/gi, '>');
5515 showAttachmentPanel : function(idx) {
5516 var east = SE.composeLayout[idx].getUnitByPosition("right");
5517 var tabs = SE.composeLayout[idx].rightTabs;
5519 tabs.set("activeTab", tabs.getTab(0));
5523 * expands sidebar and displays options panel
5525 showOptionsPanel : function(idx) {
5526 var east = SE.composeLayout[idx].getUnitByPosition("right");
5527 var tabs = SE.composeLayout[idx].rightTabs;
5529 tabs.set("activeTab", tabs.getTab(1));
5533 * Selects the Contacts tab
5535 showContactsPanel : function() {
5536 SE.complexLayout.regions.west.showPanel("contactsTab");
5540 * Generates fields for Select Document
5542 addDocumentField : function(idx) {
5543 var basket = document.getElementById('addedDocuments' + idx);
5545 var index = (basket.childNodes.length / 7) - 1;
5552 var test = document.getElementById('documentId' + idx + index);
5554 while(test != null) {
5556 test = document.getElementById('documentId' + idx + index);
5559 var documentCup = document.createElement("div");
5560 documentCup.id = 'documentCup' + idx + index;
5561 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5562 // document id field
5563 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5564 // document name field
5565 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5567 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5568 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5569 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5571 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5572 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5573 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5576 basket.appendChild(documentCup);
5577 //basket.innerHTML += out;
5582 * Makes async call to save a draft of the email
5583 * @param int Instance index
5585 saveDraft : function(tinyInstance) {
5586 this.sendEmail(tinyInstance, true);
5589 selectDocument : function(target) {
5590 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5591 windowName = 'selectDocument';
5592 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5594 win = window.open(URL, windowName, windowFeatures);
5596 // put the focus on the popup if the browser supports the focus() method
5602 * Modal popup for file attachment dialogue
5604 addFileField : function() {
5605 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5606 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5610 constraintoviewport: true,
5612 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5613 fn:function(){SE.addFileDialog.hide();}
5616 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5617 SE.addFileDialog.render();
5618 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5620 Dom.removeClass("addFileDialog", "yui-hidden");
5622 SE.addFileDialog.show();
5626 * Async upload of file to temp dir
5628 uploadAttachment : function() {
5629 if(document.getElementById('email_attachment').value != "") {
5630 var formObject = document.getElementById('uploadAttachment');
5631 YAHOO.util.Connect.setForm(formObject, true, true);
5632 AjaxObject.target = '';
5633 AjaxObject.startRequest(callbackUploadAttachment, null);
5635 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5640 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5641 * @param string target in focus compose layout
5643 setDocument : function(idx, target, documentId, documentName, docRevId) {
5644 // fields are named/id'd [fieldName][instanceId][index]
5645 var addedDocs = document.getElementById("addedDocuments" + idx);
5646 var docId = document.getElementById('documentId' + idx + target);
5647 var docName = document.getElementById('documentName' + idx + target);
5648 var docRevisionId = document.getElementById('document' + idx + target);
5649 docId.value = documentId;
5650 docName.value = documentName;
5651 docRevisionId.value = docRevId;
5655 * Removes the bucket div containing the document input fields
5657 deleteDocumentField : function(documentCup) {
5658 var f0 = document.getElementById(documentCup);
5659 f0.parentNode.removeChild(f0);
5663 * Removes a Template Attachment field
5667 deleteTemplateAttachmentField : function(idx, index) {
5668 // create not-in-array values for removal filtering
5669 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5675 r += document.getElementById('templateAttachmentId' + idx + index).value;
5676 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5678 var target = 'templateAttachmentCup' + idx + index;
5679 d = document.getElementById(target);
5680 d.parentNode.removeChild(d);
5684 * Async removal of uploaded temp file
5685 * @param string index Should be a concatenation of idx and index
5688 deleteUploadAttachment : function(index, file) {
5689 var d = document.getElementById('email_attachment_bucket' + index);
5690 d.parentNode.removeChild(d);
5692 // make async call to delete cached file
5693 AjaxObject.target = '';
5694 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5698 * Attaches files coming from Email Templates
5700 addTemplateAttachmentField : function(idx) {
5702 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5704 var basket = document.getElementById('addedTemplateAttachments' + idx);
5707 var index = basket.childNodes.length;
5714 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5716 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5717 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5718 idx + "\",\"" + index + "\");'/>" +
5720 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5721 // templateAttachment field
5722 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5724 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5726 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5727 "<br id='br" + index + "></br>" +
5728 "<br id='brdoc" + index + "></br>" +
5730 basket.innerHTML = basket.innerHTML + out;
5736 * Sends one email via async call
5737 * @param int idx Editor instance ID
5738 * @param bool isDraft
5740 sendEmail : function(idx, isDraft) {
5742 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5743 var obAccountID = document.getElementById('addressFrom' + idx).value;
5745 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5747 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5752 var form = document.getElementById('emailCompose' + idx);
5753 var composeOptionsFormName = "composeOptionsForm" + idx;
5754 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5755 var html = t.getContent();
5756 var subj = document.getElementById('emailSubject' + idx).value;
5757 var to = trim(document.getElementById('addressTO' + idx).value);
5758 var cc = trim(document.getElementById('addressCC' + idx).value);
5759 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5760 var email_id = document.getElementById('email_id' + idx).value;
5761 var composeType = document.getElementById('composeType').value;
5762 var parent_type = document.getElementById("parent_type").value;
5763 var parent_id = document.getElementById("parent_id").value;
5765 var el_uid = document.getElementById("uid");
5766 var uid = (el_uid == null) ? '' : el_uid.value;
5768 var el_ieId = document.getElementById("ieId");
5769 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5771 var el_mbox = document.getElementById("mbox");
5772 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5774 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5775 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5779 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5782 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5783 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5784 parent_id = parentIdValue;
5785 parent_type = parentTypeValue;
5787 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5788 // baseline viability check
5790 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5791 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5793 } else if(subj == '' && !isDraft) {
5794 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5797 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5799 } else if(html == '' && !isDraft) {
5800 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5805 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5806 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5807 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5808 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5809 html = html.replace(/</ig, "sugarLessThan");
5810 html = html.replace(/>/ig, "sugarGreaterThan");
5812 form.sendDescription.value = html;
5813 form.sendSubject.value = subj;
5814 form.sendTo.value = to;
5815 form.sendCc.value = cc;
5816 form.sendBcc.value = bcc;
5817 form.email_id.value = email_id;
5818 form.composeType.value = composeType;
5819 form.composeLayoutId.value = 'composeLayout' + idx;
5820 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5821 form.saveToSugar.value = 1;
5822 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5823 form.parent_type.value = parent_type;
5824 form.parent_id.value = parent_id;
5825 form.uid.value = uid;
5826 form.ieId.value = ieId;
5827 form.mbox.value = mbox;
5829 // email attachments
5830 var addedFiles = document.getElementById('addedFiles' + idx);
5832 for(i=0; i<addedFiles.childNodes.length; i++) {
5833 var bucket = addedFiles.childNodes[i];
5835 for(j=0; j<bucket.childNodes.length; j++) {
5836 var node = bucket.childNodes[j];
5837 var nName = new String(node.name);
5839 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5840 if(form.attachments.value != '') {
5841 form.attachments.value += "::";
5843 form.attachments.value += node.value;
5850 var addedDocs = document.getElementById('addedDocuments' + idx);
5852 for(i=0; i<addedDocs.childNodes.length; i++) {
5853 var cNode = addedDocs.childNodes[i];
5854 for(j=0; j<cNode.childNodes.length; j++) {
5855 var node = cNode.childNodes[j];
5856 var nName = new String(node.name);
5857 if(node.type == 'hidden' && nName.match(/documentId/)) {
5858 if(form.documents.value != '') {
5859 form.documents.value += "::";
5861 form.documents.value += node.value;
5867 // template attachments
5868 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5869 if(addedTemplateAttachments) {
5870 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5871 var cNode = addedTemplateAttachments.childNodes[i];
5872 for(j=0; j<cNode.childNodes.length; j++) {
5873 var node = cNode.childNodes[j];
5874 var nName = new String(node.name);
5875 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5876 if(form.templateAttachments.value != "") {
5877 form.templateAttachments.value += "::";
5879 form.templateAttachments.value += node.value;
5885 // remove attachments
5886 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5888 YAHOO.util.Connect.setForm(form);
5890 AjaxObject.target = 'frameFlex';
5892 // sending a draft email
5893 if(!isDraft && in_draft) {
5895 SE.listView.removeRowByUid(email_id);
5898 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5899 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5901 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5905 * Handles clicking the email address link from a given view
5907 composePackage : function() {
5908 if(composePackage != null) {
5909 SE.composeLayout.c0_composeNewEmail();
5912 if(composePackage.to_email_addrs) {
5913 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5915 if (composePackage.subject != null && composePackage.subject.length > 0) {
5916 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5919 //If no parent fields are set in the composePackage, ensure they are cleared.
5920 var parentFields = ['parent_type','parent_name','parent_id'];
5921 for(var i=0;i<parentFields.length;i++)
5923 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5924 composePackage[parentFields[i]] = "";
5927 document.getElementById("parent_type").value = composePackage.parent_type;
5928 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5929 document.getElementById("parent_id").value = composePackage.parent_id;
5930 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5931 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5933 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5934 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5936 if (composePackage.body != null && composePackage.body.length > 0) {
5937 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5938 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5939 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5941 if (composePackage.attachments != null) {
5942 SE.composeLayout.loadAttachments(composePackage.attachments);
5945 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5946 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5947 SE.util.emptySelectOptions(addressFrom);
5948 var fromAccountOpts = composePackage.fromAccounts.data;
5949 for(i=0; i<fromAccountOpts.length; i++) {
5950 var key = fromAccountOpts[i].value;
5951 var display = fromAccountOpts[i].text;
5952 var opt = new Option(display, key);
5953 if (fromAccountOpts[i].selected) {
5954 opt.selected = true;
5956 addressFrom.options.add(opt);
5963 setContentOnThisTiny : function() {
5964 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5965 var tinyHTML = tiny.getContent();
5966 composePackage.body = decodeURI(encodeURI(composePackage.body));
5967 // cn: bug 14361 - text-only templates don't fill compose screen
5968 if(composePackage.body == '') {
5969 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
5971 //Flag determines if we should clear the tiny contents or just append
5972 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5973 SE.composeLayout.tinyHTML = '';
5975 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
5977 tiny.setContent(SE.composeLayout.tinyHTML);
5978 //Indicate that the contents has been loaded successfully.
5979 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5982 * Confirms closure of a compose screen if "x" is clicked
5984 confirmClose : function(panel) {
5985 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
5986 SE.composeLayout.closeCompose(panel.id);
5994 * forces close of a compose screen
5996 forceCloseCompose : function(id) {
5997 SE.composeLayout.closeCompose(id);
5999 // handle flow back to originating view
6000 if(composePackage) {
6001 // check if it's a module we need to return to
6002 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6003 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6004 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6005 window.location = url;
6012 * closes the editor that just sent email
6013 * @param string id ID of composeLayout tab
6015 closeCompose : function(id) {
6016 // destroy tinyMCE instance
6017 var idx = id.substr(13, id.length);
6018 var instanceId = "htmleditor" + idx;
6019 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6021 // nullify DOM and namespace values.
6023 SE.composeLayout[idx] = null;
6024 SE.tinyInstances[instanceId] = null;
6025 var tabsArray = SE.innerLayout.get("tabs");
6026 for (i = 0 ; i < tabsArray.length ; i++) {
6027 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6028 tabsArray[i].close();
6032 //SE.innerLayout.getTab(idx).close();
6036 * Enable the quick search for the compose relate field or search tab
6038 enableQuickSearchRelate: function(idx,overides){
6040 if(typeof overides != 'undefined')
6042 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6043 var newModule = document.getElementById(newModuleID).value;
6044 var formName = overides['formName'];
6045 var fieldName = overides['fieldName'];
6046 var fieldId = overides['fieldId'];
6047 var fullName = formName + "_" + fieldName;
6048 var postBlurFunction = null;
6052 var newModule = document.getElementById('data_parent_type'+idx).value;
6053 var formName = 'emailCompose'+idx;
6054 var fieldName = 'data_parent_name'+idx;
6055 var fieldId = 'data_parent_id'+idx;
6056 var fullName = formName + "_" + fieldName;
6057 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6060 if(typeof sqs_objects == 'undefined')
6061 window['sqs_objects'] = new Array;
6063 window['sqs_objects'][fullName] = {
6066 modules:[newModule],
6068 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6069 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6070 post_onblur_function: postBlurFunction,
6071 order:"name","limit":"30","no_match_text":"No Match"};
6074 if(typeof QSProcessedFieldsArray != 'undefined')
6075 QSProcessedFieldsArray[fullName] = false;
6076 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6077 QSFieldsArray[fullName].destroy();
6078 delete QSFieldsArray[fullName];
6080 if (Dom.get(fullName + "_results")) {
6081 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6087 qsAddAddress : function(o) {
6088 if (o.name != "" && o.email1 != "")
6090 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6091 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6095 * Returns a new instance ID, 0-index
6097 getNewInstanceId : function() {
6098 this.currentInstanceId = this.currentInstanceId + 1;
6099 return this.currentInstanceId;
6103 * 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.
6105 loadAttachments : function(result) {
6106 var idx = SE.composeLayout.currentInstanceId;
6108 if(typeof(result) == 'object') {
6109 //jchi #20680. Clean the former template attachments;
6110 var basket = document.getElementById('addedTemplateAttachments' + idx);
6111 if(basket.innerHTML != ''){
6112 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6114 basket.innerHTML = '';
6119 if(typeof result[i] == 'object') {
6120 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6121 var bean = result[i];
6122 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6123 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6130 * fills drop-down values for email templates and signatures
6132 setComposeOptions : function(idx) {
6133 // send from accounts
6134 var addressFrom = document.getElementById('addressFrom' + idx);
6136 if (addressFrom.options.length <= 0) {
6137 SE.util.emptySelectOptions(addressFrom);
6138 var fromAccountOpts = SE.composeLayout.fromAccounts;
6139 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6140 var key = fromAccountOpts[id].value;
6141 var display = fromAccountOpts[id].text;
6142 var is_default = false;
6143 if(key == SUGAR.default_inbound_accnt_id)
6145 var opt = new Option(display, key);
6146 addressFrom.options.add(opt);
6147 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6152 var et = document.getElementById('email_template' + idx);
6153 SE.util.emptySelectOptions(et);
6155 for(var key in this.emailTemplates) { // iterate through assoc array
6156 var display = this.emailTemplates[key];
6157 var opt = new Option(display, key);
6158 et.options.add(opt);
6162 var sigs = document.getElementById('signatures' + idx);
6163 SE.util.emptySelectOptions(sigs);
6165 for(var key in this.signatures) { // iterate through assoc array
6166 var display = this.signatures[key];
6167 var opt = new Option(display, key);
6169 if(key == SE.userPrefs.signatures.signature_default) {
6170 opt.selected = true;
6173 sigs.options.add(opt);
6176 // html/plain email?
6177 var htmlEmail = document.getElementById('setEditor' + idx);
6178 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6179 htmlEmail.checked = true;
6181 htmlEmail.checked = false;
6184 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6188 * After compose screen is rendered, async call to get email body from Sugar
6190 replyForwardEmailStage2 : function() {
6191 SE.util.clearHiddenFieldValues('emailUIForm');
6192 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6194 var ieId = SE.composeLayout.replyForwardObj.ieId;
6195 var uid = SE.composeLayout.replyForwardObj.uid;
6196 var mbox = SE.composeLayout.replyForwardObj.mbox;
6197 var type = SE.composeLayout.replyForwardObj.type;
6198 var idx = SE.composeLayout.currentInstanceId;
6200 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6202 document.getElementById('emailSubject' + idx).value = type;
6203 document.getElementById('emailUIAction').value = 'composeEmail';
6204 document.getElementById('composeType').value = type;
6205 document.getElementById('ieId').value = ieId;
6206 document.getElementById('uid').value = uid;
6207 document.getElementById('mbox').value = mbox;
6208 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6209 var formObject = document.getElementById('emailUIForm');
6210 YAHOO.util.Connect.setForm(formObject);
6212 var sendType = type;
6213 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6217 * Show the hidden cc or bcc fields
6219 showHiddenAddress: function(addrType,idx){
6221 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6222 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6223 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6224 this[addrType+'Hidden'+idx] = false;
6226 //After bcc or cc is added, move options below last addr field
6227 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6229 //If both cc and bcc hidden, remove the empty row containing text.
6230 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6231 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6232 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6234 SE.composeLayout.resizeEditor(idx);
6237 * Hide the cc and bcc fields if they were shown.
6239 hideHiddenAddresses: function(idx){
6241 var addrTypes = ['cc','bcc'];
6242 for(var i = 0;i<addrTypes.length;i++)
6244 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6245 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6246 this[addrTypes[i] + 'Hidden'+idx] = true
6249 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6250 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6251 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6255 //// END SE.composeLayout
6256 ///////////////////////////////////////////////////////////////////////////////
6257 ///////////////////////////////////////////////////////////////////////////////
6261 * Cleans serialized UID lists of duplicates
6265 cleanUids : function(str) {
6266 var seen = new Object();
6268 var arr = new String(str).split(",");
6270 for(var i=0; i<arr.length; i++) {
6275 clean += (clean != "") ? "," : "";
6277 seen[arr[i]] = true;
6284 * Clears hidden field values
6285 * @param string id ID of form element to clear
6287 clearHiddenFieldValues : function(id) {
6288 var form = document.getElementById(id);
6290 for(i=0; i<form.elements.length; i++) {
6291 if(form.elements[i].type == 'hidden') {
6292 var e = form.elements[i];
6293 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6301 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6303 emptySelectOptions : function(el) {
6305 for(i=el.childNodes.length - 1; i >= 0; i--) {
6306 if(el.childNodes[i]) {
6307 el.removeChild(el.childNodes[i]);
6314 * Returns the MBOX path in the manner php_imap expects:
6315 * ie: INBOX.DEBUG.test
6316 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6318 generateMboxPath : function(str) {
6319 var ex = str.split("::");
6321 /* we have a serialized MBOX path */
6325 for(var i=0; i<ex.length; i++) {
6326 if(ex[i] == 'INBOX') {
6338 /* we have a Sugar folder GUID - do nothing */
6346 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6347 * @param HTMLElement el
6348 * @return string GUID of found element or empty on failure
6350 getGuidFromElement : function(el) {
6356 for(var i=0; i<iterations; i++) {
6358 if(el.id.match(SE.reGUID)) {
6370 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6373 getPanelId : function() {
6374 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6378 * wrapper to handle weirdness with IE
6379 * @param string instanceId
6380 * @return tinyMCE Controller object
6382 getTiny : function(instanceId) {
6383 if(instanceId == '') {
6387 var t = tinyMCE.getInstanceById(instanceId);
6391 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6397 * Simple check for MSIE browser
6401 var nav = new String(navigator.appVersion);
6402 if(nav.match(/MSIE/)) {
6409 * Recursively removes an element from the DOM
6410 * @param HTMLElement
6412 removeElementRecursive : function(el) {
6413 this.emptySelectOptions(el);
6420 sleep : function(secs) {
6421 setTimeout("void(0);", secs);
6425 * Converts a <select> element to an Ext.form.combobox
6427 convertSelect : function(select) {
6428 alert('in convertSelect');
6429 if (typeof(select) == "string") {
6430 select = document.getElementById(select);
6434 findChildNode : function (parent, property, value) {
6435 for (i in parent.children) {
6436 var child = parent.children[i];
6437 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6439 var searchChild = SE.util.findChildNode(child, property, value);
6446 cascadeNodes : function (parent, fn, scope, args) {
6447 for (i in parent.children) {
6448 var child = parent.children[i];
6449 var s = scope ? scope : child;
6450 var a = args ? args : child;
6452 SE.util.cascadeNodes(child, fn, scope, args);
6459 ///////////////////////////////////////////////////////////////////////////////
6462 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6464 /*********************************************************************************
6465 * SugarCRM is a customer relationship management program developed by
6466 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6468 * This program is free software; you can redistribute it and/or modify it under
6469 * the terms of the GNU Affero General Public License version 3 as published by the
6470 * Free Software Foundation with the addition of the following permission added
6471 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6472 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6473 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6475 * This program is distributed in the hope that it will be useful, but WITHOUT
6476 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6477 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6480 * You should have received a copy of the GNU Affero General Public License along with
6481 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6482 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6485 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6486 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6488 * The interactive user interfaces in modified source and object code versions
6489 * of this program must display Appropriate Legal Notices, as required under
6490 * Section 5 of the GNU Affero General Public License version 3.
6492 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6493 * these Appropriate Legal Notices must retain the display of the "Powered by
6494 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6495 * technical reasons, the Appropriate Legal Notices must display the words
6496 * "Powered by SugarCRM".
6497 ********************************************************************************/
6500 if (typeof console == "undefined")
6501 console = { log: function(o) {alert(o)} };
6505 currentRequestObject : null,
6506 //timeout : 30000, // 30 second timeout default
6507 timeout : 9999999999, // 30 second timeout default
6509 trail : new Array(),
6513 _reset : function() {
6514 this.timeout = 30000;
6515 this.forceAbort = false;
6518 folderRenameCleanup : function() {
6519 SUGAR.email2.folders.setSugarFolders();
6522 fullSyncCleanup : function(o) {
6523 this.folders.checkMailCleanup(o);
6524 SUGAR.email2.settings.settingsDialog.hide();
6529 composeCache : function(o) {
6530 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6531 // get email templates and user signatures
6532 var ret = JSON.parse(o.responseText);
6534 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6535 SUGAR.email2.composeLayout.signatures = ret.signatures;
6536 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6538 SUGAR.email2.composeLayout.setComposeOptions(idx);
6540 //Set the error array so we can notify the user when they try to hit send if any errors
6541 //are present. We will also notify them now (after hitting compose button).
6542 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6545 //if error element is returning an array, then check the length to make sure we have error messages
6546 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6547 //add error messages for display
6548 for(i in ret.errorArray)
6549 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6550 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6551 //if error element is returning an object, and the object value is not empty or null, then display error message
6552 for(i in ret.errorArray)
6553 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6556 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6558 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6560 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6566 handleDeleteSignature : function(o) {
6568 var ret = JSON.parse(o.responseText);
6569 SUGAR.email2.composeLayout.signatures = ret.signatures;
6570 var field = document.getElementById('signature_id');
6571 SUGAR.email2.util.emptySelectOptions(field);
6573 for(var i in ret.signatures) { // iterate through assoc array
6574 var opt = new Option(ret.signatures[i], i);
6575 field.options.add(opt);
6577 setSigEditButtonVisibility();
6582 handleDeleteReturn : function(o) {
6583 // force refresh ListView
6585 if(document.getElementById('focusEmailMbox')) {
6586 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6589 // need to display success message before calling next async call?
6590 document.getElementById(this.target).innerHTML = o.responseText;
6595 handleFailure : function(o) {
6597 overlay('Exception occurred...', o.statusText, 'alert');
6600 handleReplyForward : function(o) {
6601 var a = JSON.parse(o.responseText);
6603 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6605 document.getElementById('email_id' + idx).value = a.uid;
6606 document.getElementById('emailSubject' + idx).value = a.name;
6607 document.getElementById('addressTO' + idx).value = a.from;
6608 document.getElementById('uid' + idx).value = a.uid;
6610 document.getElementById('addressCC' + idx).value = a.cc;
6611 SE.composeLayout.showHiddenAddress('cc', idx);
6615 document.getElementById('type' + idx).value = a.type;
6618 // apply attachment values
6619 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6621 setTimeout("callbackReplyForward.finish(globalA);", 500);
6624 handleReplyForwardForDraft : function(o) {
6625 var a = JSON.parse(o.responseText);
6627 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6629 document.getElementById('email_id' + idx).value = a.uid;
6630 document.getElementById('emailSubject' + idx).value = a.name;
6631 document.getElementById('addressTO' + idx).value = a.to;
6634 document.getElementById('addressCC' + idx).value = a.cc;
6635 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6639 document.getElementById('addressBCC' + idx).value = a.bcc;
6640 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6645 document.getElementById('type' + idx).value = a.type;
6649 // apply attachment values
6650 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6652 setTimeout("callbackReplyForward.finish(globalA);", 500);
6657 handleSuccess : function(o) {
6658 document.getElementById(this.target).innerHTML = o.responseText;
6664 ieDeleteSuccess : function(o) {
6667 var ret = JSON.parse(o.responseText);
6669 SUGAR.email2.accounts.refreshInboundAccountTable();
6670 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6671 SUGAR.email2.accounts.rebuildFolderList();
6677 ieSaveSuccess : function(o) {
6678 document.getElementById('saveButton').disabled = false;
6679 var a = JSON.parse(o.responseText);
6682 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6683 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6685 resp = JSON.parse(o.responseText);
6686 SUGAR.email2.accounts.refreshInboundAccountTable();
6687 SUGAR.email2.accounts.refreshOuboundAccountTable();
6688 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6689 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6693 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6700 loadAttachments : function(o) {
6701 var result = JSON.parse(o.responseText);
6703 SUGAR.email2.composeLayout.loadAttachments(result);
6708 loadSignature : function(o) {
6709 var ret = JSON.parse(o.responseText);
6710 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6711 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6715 * Follow up to mark email read|unread|flagged
6717 markEmailCleanup : function(o) {
6718 var ret = JSON.parse(o.responseText);
6719 if (!ret['status']) {
6721 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6723 SUGAR.email2.contextMenus.markEmailCleanup();
6729 rebuildShowFolders : function(o) {
6730 var t = JSON.parse(o.responseText);
6731 var show = document.getElementById('ieAccountListShow');
6733 SUGAR.email2.util.emptySelectOptions(show);
6735 for(i=0; i<t.length; i++) { // iterate through assoc array
6736 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6737 opt.selected = t[i].selected;
6738 show.options.add(opt);
6741 SUGAR.email2.accounts.renderTree();
6745 saveListViewSortOrderPart2 : function() {
6746 // create the JSON string the func expects
6747 focusFolderPath = '[ "Home", "' + ieName + '"';
6749 var f = new String(focusFolder);
6750 var fEx = f.split('.');
6752 for(i=0; i<fEx.length; i++) {
6753 focusFolderPath += ', "' + fEx[i] +'"'
6756 focusFolderPath += ']';
6758 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6759 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6765 sendEmailCleanUp : function(o) {
6767 var ret = JSON.parse(o.responseText);
6769 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6770 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6771 } else if (o.responseText) {
6772 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6775 if (typeof(SE.grid) != 'undefined')
6776 SE.listView.refreshGrid();
6777 //Disabled while address book is disabled
6779 //If this call back was initiated by quick compose from a Detail View page, refresh the
6780 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6781 //close the shortcut bar menu
6782 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6783 if(action_sugar_grp1 == 'DetailView') {
6784 showSubPanel('history',null,true);
6785 } else if(action_sugar_grp1 == 'quickcreate') {
6786 closeEmailOverlay();
6792 ieSendSuccess : function(o) {
6794 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6799 settingsFolderRefresh : function(o) {
6800 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6801 var ret = JSON.parse(o.responseText);
6802 var user = document.getElementById('userFolders');
6804 SUGAR.email2.util.emptySelectOptions(user);
6806 for(i=0; i<ret.userFolders.length; i++) {
6807 var display = ret.userFolders[i].name;
6808 var value = ret.userFolders[i].id;
6809 var selected = (ret.userFolders[i].selected != "") ? true : false;
6810 var opt = new Option(display, value, selected);
6811 opt.selected = selected;
6812 user.options.add(opt);
6818 startRequest : function(callback, args, forceAbort) {
6819 if(this.currentRequestObject != null) {
6820 if(this.forceAbort == true) {
6821 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6824 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6828 requestInProgress : function() {
6829 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6834 updateFolderSubscriptions : function() {
6835 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6836 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6842 updateFrameFolder : function() {
6843 SUGAR.email2.folders.checkEmailAccounts();
6848 updateUserPrefs : function(o) {
6849 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6850 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6855 uploadAttachmentSuccessful : function(o) {
6857 document.getElementById('email_attachment').value = '';
6859 var ret = JSON.parse(o.responseText);
6860 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6861 var overall = document.getElementById('addedFiles' + idx);
6862 var index = overall.childNodes.length;
6864 "<div id='email_attachment_bucket" + idx + index + "'>" +
6866 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6867 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6868 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6870 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6871 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6873 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6875 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6878 overall.innerHTML += out;
6879 if(SUGAR.email2.util.isIe()) {
6880 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6884 SUGAR.email2.addFileDialog.hide();
6885 // focus attachments
6886 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6891 ///////////////////////////////////////////////////////////////////////////
6892 //// PER MODULE CALLBACK OBJECTS
6893 AjaxObject.accounts = {
6894 saveOutboundCleanup : function(o) {
6895 SUGAR.email2.accounts.refreshOuboundAccountTable();
6896 SUGAR.email2.accounts.outboundDialog.hide();
6897 var id = o.responseText;
6898 SUGAR.email2.accounts.newAddedOutboundId = id;
6900 saveDefaultOutboundCleanup: function(o){
6903 callbackEditOutbound : {
6904 success : function(o)
6906 var ret = JSON.parse(o.responseText);
6908 SUGAR.email2.accounts.showAddSmtp();
6911 document.getElementById("mail_id").value = ret.id;
6912 document.getElementById("type").value = ret.type;
6913 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6914 document.getElementById("mail_name").value = ret.name;
6915 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6916 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6917 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6918 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6919 document.getElementById("mail_smtppass").value = ret.mail_smtppass;
6920 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6921 SUGAR.email2.accounts.smtp_authenticate_field_display();
6922 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6924 if(ret.type == 'system-override') {
6925 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6926 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6929 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6930 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6935 failure : AjaxObject.handleFailure,
6936 timeout : AjaxObject.timeout,
6939 callbackDeleteOutbound : {
6940 success : function(o) {
6941 var ret = JSON.parse(o.responseText);
6944 if(confirm(ret.error_message))
6946 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6947 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6955 SUGAR.email2.accounts.refreshOuboundAccountTable();
6959 failure : AjaxObject.handleFailure,
6960 timeout : AjaxObject.timeout,
6964 callbackCheckMailProgress : {
6965 success : function(o) {
6966 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6967 SUGAR.email2.accounts.totalMsgCount = -1;
6970 //Check for server timeout / errors
6971 var ret = JSON.parse(o.responseText);
6974 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6976 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6977 SUGAR.email2.accounts.totalMsgCount = -1;
6978 //SUGAR.email2.folders.rebuildFolders();
6982 var currIeId = ret['ieid'];
6985 var serverCount = ret.count;
6987 if (ret['status'] == 'done') {
6988 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
6989 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
6993 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
6994 //Go to next account
6995 currIeId = SUGAR.email2.accounts.ieIds[i+1];
6997 SUGAR.email2.accounts.totalMsgCount = -1;
7002 else if (ret.mbox && ret.totalcount && ret.count) {
7003 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7004 if (ret.count >= ret.totalcount) {
7007 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7008 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7011 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7012 SUGAR.email2.accounts.totalMsgCount = -1;
7017 SUGAR.email2.accounts.totalMsgCount = -1;
7019 SUGAR.email2.folders.rebuildFolders();
7020 SE.listView.refreshGrid();
7021 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7022 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7023 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7024 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7026 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7027 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7028 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7029 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7030 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7033 failure : AjaxObject.handleFailure,
7034 timeout : AjaxObject.timeout,
7039 ///////////////////////////////////////////////////////////////////////////////
7041 AjaxObject.composeLayout = {
7043 * Populates the record id
7045 saveDraftCleanup : function(o) {
7047 var ret = JSON.parse(o.responseText);
7049 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7050 else if (o.responseText)
7051 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7055 AjaxObject.composeLayout.callback = {
7057 success : AjaxObject.composeLayout.saveDraftCleanup,
7058 failure : AjaxObject.handleFailure,
7059 timeout : AjaxObject.timeout,
7064 AjaxObject.detailView = {
7066 * Pops-up a printable view of an email
7068 displayPrintable : function(o) {
7069 var ret = JSON.parse(o.responseText);
7070 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7071 // 2 below must be in global context
7073 meta['panelId'] = SUGAR.email2.util.getPanelId();
7074 email = ret.meta.email;
7075 if (typeof(email.cc) == 'undefined') {
7079 var out = displayTemplate.exec({
7080 'app_strings' : app_strings,
7084 'email' : meta.email
7087 // open popup window
7088 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7089 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7091 popup.document.write(out);
7092 popup.document.close();
7096 * Takes formatted response and creates a modal pop-over containing a title and content
7098 displayView : function(o) {
7099 var SED = SUGAR.email2.detailView;
7100 var ret = JSON.parse(o.responseText);
7102 if(!SED.viewDialog) {
7103 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7107 constraintoviewport: true,
7110 SED.viewDialog.renderEvent.subscribe(function() {
7111 var content = this.body.firstChild;
7112 var viewH = YAHOO.util.Dom.getViewportHeight();
7114 this.body.style.overflow = "auto";
7115 this.body.style.width = "800px";
7116 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7120 SED.viewDialog.setHeader(ret.title);
7121 SED.viewDialog.setBody(ret.html);
7122 SED.viewDialog.render();
7123 SED.viewDialog.show();
7127 * Generates a modal popup to populate with the contents of bean's full EditView
7129 showQuickCreateForm : function(o) {
7130 var SED = SUGAR.email2.detailView;
7131 var ret = JSON.parse(o.responseText);
7133 if(!SED.quickCreateDialog) {
7134 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7138 constraintoviewport: true,
7142 SED.quickCreateDialog.renderEvent.subscribe(function() {
7143 var viewH = YAHOO.util.Dom.getViewportHeight();
7145 for (var i in this.body.childNodes) {
7146 if (this.body.childNodes[i].clientHeight) {
7147 contH += this.body.childNodes[i].clientHeight;
7148 } else if (this.body.childNodes[i].offsetHeight) {
7149 contH += this.body.childNodes[i].offsetHeight;
7152 this.body.style.width = "800px";
7153 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7154 this.body.style.overflow = "auto";
7155 }, SED.quickCreateDialog);
7157 SED.quickCreateDialog.hideEvent.subscribe(function(){
7158 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7159 /*for(var qsField in qsFields){
7160 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7161 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7164 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7167 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7169 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7170 SED.quickCreateDialog.render();
7171 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7173 SED.quickCreateDialog.ieId = ret.ieId;
7174 SED.quickCreateDialog.uid = ret.uid;
7175 SED.quickCreateDialog.mbox = ret.mbox;
7176 SED.quickCreateDialog.qcmodule = ret.module;
7178 SED.quickCreateDialog.show();
7180 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7182 editForm.module.value = 'Emails';
7183 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7184 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7185 var instId = ret.module + count;
7186 SED.quickCreateEmailsToAdd = ret.emailAddress;
7187 SED.quickCreateEmailCallback = function(instId, tableId) {
7188 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7189 if (typeof(eaw) == "undefined")
7190 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7191 + instId + "','" + tableId + "');", 100);
7192 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7194 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7195 + instId + "','" + tableId + "');", 100);
7199 saveQuickCreateForm : function(o) {
7201 SUGAR.email2.detailView.quickCreateDialog.hide();
7202 validate['EditView'] = [ ];
7205 saveQuickCreateFormAndReply : function(o) {
7207 var ret = JSON.parse(o.responseText);
7208 SUGAR.email2.detailView.quickCreateDialog.hide();
7209 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7210 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7212 var emailID = ret.id;
7213 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7215 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7217 //Cean the validate cache to prevent errors on the next call
7218 validate['EditView'] = [ ];
7221 saveQuickCreateFormAndAddToAddressBook : function(o) {
7223 SUGAR.email2.detailView.quickCreateDialog.hide();
7224 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7225 validate['EditView'] = [ ];
7228 handleAssignmentDialogAssignAction : function() {
7231 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7233 var dist = 'direct';
7237 var found_teams = false;
7238 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7239 if(!found_teams && assign_user_id == '' )
7241 alert(warning_message);
7245 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7247 for(i=0; i<emailUids.length; i++) {
7249 uids += app_strings.LBL_EMAIL_DELIMITER;
7251 uids += emailUids[i];
7254 var row = SUGAR.email2.grid.getSelectedRows()[0];
7255 var data = SUGAR.email2.grid.getRecord(row).getData();
7256 var ieid = data.ieId;
7257 var mbox = data.mbox;
7258 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7259 SUGAR.email2.contextMenus.assignToDialogue.hide();
7260 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7264 handleAssignmentDialogDeleteAction : function() {
7265 // TO pass list of UIDS/emailIds
7266 var uids = SUGAR.email2.listView.getUidsFromSelection();
7267 var row = SUGAR.email2.grid.getSelections()[0];
7268 var ieid = row.data.ieId;
7269 var mbox = row.data.mbox;
7270 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7271 SUGAR.email2.contextMenus.assignmentDialog.hide();
7272 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7278 showEmailDetailView : function(o) {
7280 var SED = SUGAR.email2.detailView;
7281 var ret = JSON.parse(o.responseText);
7283 if(!SED.quickCreateDialog) {
7284 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7288 constraintoviewport: true,
7290 autofillheight: "body",
7293 SED.quickCreateDialog.renderEvent.subscribe(function() {
7294 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7296 for (var i in this.body.childNodes) {
7297 if (this.body.childNodes[i].offsetHeight)
7298 contH += this.body.childNodes[i].offsetHeight;
7300 this.body.style.overflow = "auto";
7301 this.body.style.width = "800px";
7302 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7304 }, SED.quickCreateDialog);
7306 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7307 SED.quickCreateDialog.setBody(ret.html);
7308 SED.quickCreateDialog.render();
7309 SUGAR.util.evalScript(ret.html);
7310 SED.quickCreateDialog.show();
7313 showAssignmentDialogWithData : function(o) {
7314 var SEC = SUGAR.email2.contextMenus;
7316 var ret = JSON.parse(o.responseText);
7317 if (!SEC.assignmentDialog) {
7318 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7321 constraintoviewport: true,
7324 SEC.assignmentDialog.setBody("");
7325 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7326 SEC.assignmentDialog.renderEvent.subscribe(function() {
7327 var iev = YAHOO.util.Dom.get("Distribute");
7329 this.body.style.width = "700px";
7331 }, SEC.assignmentDialog);
7332 SEC.assignmentDialog.render();
7334 SEC.assignmentDialog.setBody(ret);
7335 SEC.assignmentDialog.render();
7337 SEC.assignmentDialog.show();
7338 SUGAR.util.evalScript(ret);
7341 showImportForm : function(o) {
7342 var SED = SUGAR.email2.detailView;
7343 var ret = JSON.parse(o.responseText);
7345 document.getElementById('quickCreateContent').innerHTML = "";
7351 if(!SED.importDialog) {
7352 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7356 constraintoviewport: true,
7358 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7359 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7363 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7364 SED.importDialog.setBody("");
7365 SED.importDialog.hideEvent.subscribe(function(){
7366 for(var i in QSFieldsArray) {
7367 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7368 QSFieldsArray[i].destroy();
7369 delete QSFieldsArray[i];
7371 if (QSProcessedFieldsArray[i]) {
7372 QSProcessedFieldsArray[i] = false;
7376 SED.importDialog.renderEvent.subscribe(function() {
7377 var iev = YAHOO.util.Dom.get("ImportEditView");
7379 //this.body.style.height = (iev.clientHeight + 10) + "px";
7380 this.body.style.width = "600px";
7382 }, SED.importDialog);
7383 SED.importDialog.render();
7385 SED.importDialog.setBody(ret.html);
7386 SED.importDialog.ret = ret;
7387 SUGAR.util.evalScript(ret.html);
7388 SED.importDialog.render();
7390 SED.importDialog.show();
7391 SED.importDialog.focusFirstButton();
7393 getImportAction : function(ret) {
7394 if (!check_form('ImportEditView')) return false;
7395 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7396 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7400 var editView = document.getElementById('ImportEditView');
7401 if (editView.assigned_user_id != null) {
7402 get = get + "&user_id=" + editView.assigned_user_id.value
7403 //var user_id = editView.assigned_user_id.value;
7405 var parent_id = editView.parent_id.value;
7406 var parent_type = editView.parent_type.value;
7407 var row = SUGAR.email2.grid.getSelectedRows()[0];
7408 row = SUGAR.email2.grid.getRecord(row);
7409 var data = row.getData();
7410 var ieId = data.ieId;
7411 var mbox = data.mbox;
7412 var serverDelete = editView.serverDelete.checked;
7413 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7415 for(i=0; i<emailUids.length; i++) {
7417 uids += app_strings.LBL_EMAIL_DELIMITER;
7419 uids += emailUids[i];
7422 var action = 'importEmail&uid=';
7424 action = 'moveEmails';
7425 action = action + '&sourceFolder=' + ret['srcFolder'];
7426 action = action + '&sourceIeId=' + ret['srcIeId'];
7427 action = action + '&destinationFolder=' + ret['dstFolder'];
7428 action = action + '&destinationIeId=' + ret['dstIeId'];
7429 action = action + '&emailUids=';
7431 if (action.search(/importEmail/) != -1) {
7432 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7434 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7437 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7438 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7439 SUGAR.email2.detailView.importDialog.hide();
7440 document.getElementById('importDialogContent').innerHTML = "";
7443 showRelateForm : function(o) {
7444 var SED = SUGAR.email2.detailView;
7445 var ret = JSON.parse(o.responseText);
7446 document.getElementById('quickCreateContent').innerHTML = "";
7451 dialog_loaded = true;
7453 if(!SED.relateDialog) {
7454 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7459 constraintoviewport: true,
7461 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7462 if (!check_form('RelateEditView')) return false;
7464 var editView = document.getElementById('RelateEditView');
7465 var parent_id = editView.parent_id.value;
7466 var parent_type = editView.parent_type.value;
7467 var row = SUGAR.email2.grid.getSelectedRows()[0];
7468 row = SUGAR.email2.grid.getRecord(row);
7469 var ieId = row.getData().ieId;
7470 var mbox = row.getData().mbox;
7471 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7473 for(i=0; i<emailUids.length; i++) {
7475 uids += app_strings.LBL_EMAIL_DELIMITER;
7477 uids += emailUids[i];
7479 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7480 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7481 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7482 SED.relateDialog.hide();
7483 document.getElementById('relateDialogContent').innerHTML = "";
7488 SED.relateDialog.hideEvent.subscribe(function(){
7489 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7490 QSFieldsArray['ImportEditView_parent_name'].destroy();
7491 delete QSFieldsArray['ImportEditView_parent_name'];
7493 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7494 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7498 SED.relateDialog.renderEvent.subscribe(function() {
7499 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7501 for (var i in this.body.childNodes) {
7502 if (this.body.childNodes[i].clientHeight)
7503 contH += this.body.childNodes[i].clientHeight;
7505 }, SED.relateDialog);
7506 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7509 SED.relateDialog.setBody(ret.html);
7510 SED.relateDialog.render();
7511 SUGAR.util.evalScript(ret.html);
7512 SED.relateDialog.show();
7516 * DetailView callbacks
7518 AjaxObject.detailView.callback = {
7520 success : function(o) {
7522 var ret = JSON.parse(o.responseText);
7523 SUGAR.email2.detailView.consumeMetaDetail(ret);
7525 argument: [targetDiv],
7526 failure : AjaxObject.handleFailure,
7531 success : function(o) {
7533 var ret = JSON.parse(o.responseText);
7534 SUGAR.email2.detailView.consumeMetaPreview(ret);
7536 failure : AjaxObject.handleFailure,
7541 success : AjaxObject.detailView.displayPrintable,
7542 failure : AjaxObject.handleFailure,
7543 timeout : AjaxObject.timeout,
7547 success : AjaxObject.detailView.displayView,
7548 failure : AjaxObject.handleFailure,
7549 timeout : AjaxObject.timeout,
7558 AjaxObject.folders = {
7560 * check-mail post actions
7562 checkMailCleanup : function(o) {
7564 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7566 // refresh focus ListView
7567 SE.listView.refreshGrid();
7568 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7573 rebuildFolders : function(o) {
7576 var data = JSON.parse(o.responseText);
7578 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7579 SUGAR.email2.folders.setSugarFolders();
7582 AjaxObject.folders.callback = {
7584 success : AjaxObject.folders.checkMailCleanup,
7585 failure : AjaxObject.handleFailure,
7586 timeout : 600000, // 5 mins
7591 AjaxObject.rules = {
7592 loadRulesForSettings : function(o) {
7593 document.getElementById("rulesListCell").innerHTML = o.responseText;
7594 // assume we have the class we need
7595 SUGAR.routing.getStrings();
7596 SUGAR.routing.getDependentDropdowns();
7599 //// END PER MODULE CALLBACK OBJECTS
7600 ///////////////////////////////////////////////////////////////////////////
7604 success : AjaxObject.handleSuccess,
7605 failure : AjaxObject.handleFailure,
7606 timeout : AjaxObject.timeout,
7609 var callbackAccount = {
7610 success : AjaxObject.ieSaveSuccess,
7611 failure : AjaxObject.handleFailure,
7612 timeout : AjaxObject.timeout,
7615 var callbackAccountDelete = {
7616 success : AjaxObject.ieDeleteSuccess,
7617 failure : AjaxObject.handleFailure,
7618 timeout : AjaxObject.timeout,
7621 var callbackOutboundTest = {
7622 success : AjaxObject.ieSendSuccess,
7623 failure : AjaxObject.handleFailure,
7624 timeout : AjaxObject.timeout,
7630 var callbackTeamInfoForSettings = {
7631 success : function (o) {
7632 var data = JSON.parse(o.responseText);
7633 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7635 failure : AjaxObject.handleFailure,
7636 timeout : AjaxObject.timeout,
7641 var callbackStatusForImport = {
7642 success : function (o) {
7644 if (o.responseText != "") {
7645 var statusString = "";
7646 var data = JSON.parse(o.responseText);
7647 for(i=0; i<data.length; i++) {
7648 statusString = statusString + data[i] + '<br/>';
7650 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7652 SE.listView.refreshGrid();
7655 failure : AjaxObject.handleFailure,
7656 timeout : AjaxObject.timeout,
7660 var callbackComposeCache = {
7661 success : AjaxObject.composeCache,
7662 failure : AjaxObject.handleFailure,
7663 timeout : AjaxObject.timeout,
7666 var callbackDelete = {
7667 success : AjaxObject.handleDeleteReturn,
7668 failure : AjaxObject.handleFailure,
7669 timeout : AjaxObject.timeout,
7672 var callbackEmailDetailMultiple = {
7673 success : function(o) {
7675 var retMulti = JSON.parse(o.responseText);
7676 var ret = new Object();
7678 for(var i=0; i<retMulti.length; i++) {
7681 SUGAR.email2._setDetailCache(ret);
7682 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7685 failure : AjaxObject.handleFailure,
7689 var callbackListViewSortOrderChange = {
7690 success : AjaxObject.saveListViewSortOrderPart2,
7691 failure : AjaxObject.handleFailure,
7692 timeout : AjaxObject.timeout,
7694 argument : [ieId, ieName, focusFolder]
7696 var callbackEmptyTrash = {
7697 success : function(o) {
7699 AjaxObject.folderRenameCleanup;
7701 failure : AjaxObject.handleFailure,
7702 timeout : AjaxObject.timeout,
7705 var callbackClearCacheFiles = {
7706 success : function(o) {
7709 failure : AjaxObject.handleFailure,
7710 timeout : AjaxObject.timeout,
7713 var callbackFolderRename = {
7714 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7715 failure : AjaxObject.handleFailure,
7716 timeout : AjaxObject.timeout,
7719 var callbackFolderDelete = {
7720 success : function(o) {
7721 var ret = JSON.parse(o.responseText);
7723 if (ret.folder_id) {
7724 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7726 SUGAR.email2.tree.removeNode(node, true);
7727 } else if (ret.ieId && ret.mbox) {
7728 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7730 SUGAR.email2.tree.removeNode(node, true);
7733 //SUGAR.email2.folders.loadSettingFolder();
7736 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7739 failure : AjaxObject.handleFailure,
7740 timeout : AjaxObject.timeout,
7743 var callbackFolderSave = {
7744 success : function(o) {
7745 var ret = JSON.parse(o.responseText);
7747 switch(ret.action) {
7748 case 'newFolderSave':
7749 SUGAR.email2.folders.rebuildFolders();
7753 failure : AjaxObject.handleFailure,
7754 timeout : AjaxObject.timeout,
7757 var callbackFolderSubscriptions = {
7758 success : AjaxObject.updateFolderSubscriptions,
7759 failure : AjaxObject.handleFailure,
7760 timeout : AjaxObject.timeout,
7763 var callbackFolderUpdate = {
7764 success : AjaxObject.updateFrameFolder,
7765 failure : AjaxObject.handleFailure,
7766 timeout : AjaxObject.timeout,
7769 var callbackFolders = {
7770 success : AjaxObject.folders.rebuildFolders,
7771 //success : void(true),
7772 failure : AjaxObject.handleFailure,
7773 timeout : AjaxObject.timeout,
7776 var callbackFullSync = {
7777 success : AjaxObject.fullSyncCleanup,
7778 failure : AjaxObject.handleFailure,
7779 timeout : 9999999999999,
7782 var callbackGeneric = {
7783 success : function() {
7786 failure : AjaxObject.handleFailure,
7787 timeout : AjaxObject.timeout,
7790 var callbackIeAccountRetrieve = {
7791 success : function(o) {
7792 // return JSON encoding
7794 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7795 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7797 failure : AjaxObject.handleFailure,
7798 timeout : AjaxObject.timeout,
7801 var callbackImportOneEmail = {
7802 success : AjaxObject.detailView.showImportForm,
7803 failure : AjaxObject.handleFailure,
7804 timeout : AjaxObject.timeout,
7807 var callbackRelateEmail = {
7808 success : AjaxObject.detailView.showRelateForm,
7809 failure : AjaxObject.handleFailure,
7810 timeout : AjaxObject.timeout,
7813 var callbackEmailDetailView = {
7814 success : AjaxObject.detailView.showEmailDetailView,
7815 failure : AjaxObject.handleFailure,
7816 timeout : AjaxObject.timeout,
7819 var callbackAssignmentDialog = {
7820 success : AjaxObject.detailView.showAssignmentDialogWithData,
7821 failure : AjaxObject.handleFailure,
7822 timeout : AjaxObject.timeout,
7825 var callbackAssignmentAction = {
7826 success : function(o) {
7827 SE.listView.refreshGrid();
7829 if(o.responseText != '') {
7830 overlay('Assignment action result', o.responseText, 'alert');
7833 failure : AjaxObject.handleFailure,
7834 timeout : AjaxObject.timeout,
7837 var callbackMoveEmails = {
7838 success : function(o) {
7839 SE.listView.refreshGrid();
7841 if(o.responseText != '') {
7842 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7845 failure : AjaxObject.handleFailure,
7846 timeout : AjaxObject.timeout,
7849 var callbackLoadAttachments = {
7850 success : AjaxObject.loadAttachments,
7851 failure : AjaxObject.handleFailure,
7852 timeout : AjaxObject.timeout,
7855 var callbackLoadRules = {
7856 success : AjaxObject.rules.loadRulesForSettings,
7857 failure : AjaxObject.handleFailure,
7858 timeout : AjaxObject.timeout,
7861 var callbackLoadSignature = {
7862 success : AjaxObject.loadSignature,
7863 failure : AjaxObject.handleFailure,
7864 timeout : AjaxObject.timeout,
7867 var callbackDeleteSignature = {
7868 success : AjaxObject.handleDeleteSignature,
7869 failure : AjaxObject.handleFailure,
7870 timeout : AjaxObject.timeout,
7873 /*var callbackMoveEmails = {
7874 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7875 failure : AjaxObject.handleFailure,
7876 timeout : AjaxObject.timeout,
7879 var callbackOutboundSave = {
7880 success : AjaxObject.accounts.saveOutboundCleanup,
7881 failure : AjaxObject.handleFailure,
7882 timeout : AjaxObject.timeout,
7885 var callbackDefaultOutboundSave = {
7886 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7887 failure : AjaxObject.handleFailure,
7888 timeout : AjaxObject.timeout,
7891 var callbackQuickCreate = {
7892 success : AjaxObject.detailView.showQuickCreateForm,
7893 failure : AjaxObject.handleFailure,
7894 timeout : AjaxObject.timeout,
7897 var callbackQuickCreateSave = {
7898 success : AjaxObject.detailView.saveQuickCreateForm,
7899 failure : AjaxObject.handleFailure,
7900 timeout : AjaxObject.timeout,
7903 var callbackQuickCreateSaveAndAddToAddressBook = {
7904 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7905 failure : AjaxObject.handleFailure,
7906 timeout : AjaxObject.timeout,
7909 var callbackQuickCreateSaveAndReply = {
7910 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7911 failure : AjaxObject.handleFailure,
7912 timeout : AjaxObject.timeout,
7915 var callbackQuickCreateSaveAndReplyCase = {
7916 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7917 failure : AjaxObject.handleFailure,
7918 timeout : AjaxObject.timeout,
7921 var callbackRebuildShowAccountList = {
7922 success : AjaxObject.rebuildShowFolders,
7923 failure : AjaxObject.handleFailure,
7924 timeout : AjaxObject.timeout,
7928 var callbackRefreshSugarFolders = {
7929 success : function(o) {
7930 var t = JSON.parse(o.responseText);
7931 SUGAR.email2.folders.setSugarFoldersEnd(t);
7933 failure : AjaxObject.handleFailure,
7934 timeout : AjaxObject.timeout,
7937 var callbackReplyForward = {
7938 success : AjaxObject.handleReplyForward,
7939 finish : function(a, retryCount) {
7940 if (typeof(retryCount) == 'undefined') {
7945 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7946 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7948 var html = t.getContent();
7950 if (a.type != 'draft') {
7951 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7952 html += " <div><hr></div>" + a.description;
7954 html = " <div><hr></div>" + a.description + html;
7957 html = a.description;
7960 t.setContent(html);//
7963 if (retryCount < 5) {
7964 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7968 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7969 if (tabArray != null && tabArray.length > 0) {
7970 for (i = 0 ; i < tabArray.length ; i++) {
7971 var tabObject = tabArray[i];
7972 if (tabObject.get("id") == ("composeTab" + idx)) {
7973 var tabLabel = a.name;
7974 if (tabLabel != null && tabLabel.length > 25) {
7975 tabLabel = tabLabel.substring(0, 25) + "...";
7977 tabObject.get("labelEl").firstChild.data = tabLabel;
7983 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
7984 if (a.parent_name != null && a.parent_name != "") {
7985 document.getElementById('data_parent_name' + idx).value = a.parent_name;
7987 if (a.parent_type != null && a.parent_type != "") {
7988 document.getElementById('data_parent_type' + idx).value = a.parent_type;
7990 if (a.parent_id != null && a.parent_id != "") {
7991 document.getElementById('data_parent_id' + idx).value = a.parent_id;
7993 if (a.fromAccounts.status) {
7994 var addressFrom = document.getElementById('addressFrom' + idx);
7995 SUGAR.email2.util.emptySelectOptions(addressFrom);
7996 var fromAccountOpts = a.fromAccounts.data;
7997 for(i=0; i<fromAccountOpts.length; i++) {
7998 var key = fromAccountOpts[i].value;
7999 var display = fromAccountOpts[i].text;
8000 var opt = new Option(display, key);
8001 if (fromAccountOpts[i].selected) {
8002 opt.selected = true;
8004 addressFrom.options.add(opt);
8010 failure : AjaxObject.handleFailure,
8011 timeout : AjaxObject.timeout,
8013 argument : [sendType]
8015 var callbackSendEmail = {
8016 success : AjaxObject.sendEmailCleanUp,
8017 failure : AjaxObject.handleFailure,
8018 timeout : AjaxObject.timeout,
8021 var callbackSettings = {
8022 success : AjaxObject.updateUserPrefs,
8023 failure : AjaxObject.handleFailure,
8024 timeout : AjaxObject.timeout,
8027 var callbackSettingsFolderRefresh = {
8028 success : AjaxObject.settingsFolderRefresh,
8029 failure : AjaxObject.handleFailure,
8030 timeout : AjaxObject.timeout,
8033 var callbackLoadSettingFolder = {
8034 success : function(o) {
8035 AjaxObject.settingsFolderRefresh(o);
8036 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8038 failure : AjaxObject.handleFailure,
8039 timeout : AjaxObject.timeout,
8043 var callbackUploadAttachment = {
8044 success : AjaxObject.uploadAttachmentSuccessful,
8045 upload : AjaxObject.uploadAttachmentSuccessful,
8046 failure : AjaxObject.handleFailure,
8047 timeout : AjaxObject.timeout,
8050 var callbackUserPrefs = {
8051 success : function(o) {
8052 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8054 failure : AjaxObject.handleFailure,
8055 timeout : AjaxObject.timeout,
8059 var callbackContextmenus = {
8061 success : AjaxObject.markEmailCleanup,
8062 failure : AjaxObject.handleFailure,
8063 timeout : AjaxObject.timeout,
8068 var callbackCheckEmail2 = {
8069 success : function(o) {
8070 var ret = JSON.parse(o.responseText);
8071 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8075 failure : AjaxObject.handleFailure,
8076 timeout : AjaxObject.timeout,
8078 }// End of File modules/Emails/javascript/ajax.js
8080 /*********************************************************************************
8081 * SugarCRM is a customer relationship management program developed by
8082 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8084 * This program is free software; you can redistribute it and/or modify it under
8085 * the terms of the GNU Affero General Public License version 3 as published by the
8086 * Free Software Foundation with the addition of the following permission added
8087 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8088 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8089 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8091 * This program is distributed in the hope that it will be useful, but WITHOUT
8092 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8093 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8096 * You should have received a copy of the GNU Affero General Public License along with
8097 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8098 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8101 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8102 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8104 * The interactive user interfaces in modified source and object code versions
8105 * of this program must display Appropriate Legal Notices, as required under
8106 * Section 5 of the GNU Affero General Public License version 3.
8108 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8109 * these Appropriate Legal Notices must retain the display of the "Powered by
8110 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8111 * technical reasons, the Appropriate Legal Notices must display the words
8112 * "Powered by SugarCRM".
8113 ********************************************************************************/
8115 function gridInit() {
8116 if(SUGAR.email2.grid) {
8117 SUGAR.email2.grid.destroy();
8123 var Ck = YAHOO.util.Cookie;
8124 var widths = [ 10, 10, 150, 250, 175, 125 ];
8126 if (Ck.get("EmailGridWidths")) {
8127 for (var i=0; i < widths.length; i++) {
8128 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8131 for (var i=0; i < widths.length; i++) {
8132 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8136 // changes "F" to an icon
8137 function flaggedIcon(cell, record, column, value) {
8139 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8142 // changes "A" to replied icon
8143 function repliedIcon(cell, record, column, value) {
8145 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8148 function attachIcon(cell, record, column, value) {
8150 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8157 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8162 formatter: attachIcon,
8166 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8171 formatter: flaggedIcon,
8175 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8180 formatter: repliedIcon,
8184 label: app_strings.LBL_EMAIL_FROM,
8191 label: app_strings.LBL_EMAIL_SUBJECT,
8198 label: mod_strings.LBL_LIST_DATE,
8205 label: app_strings.LBL_EMAIL_TO,
8241 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8242 responseType: YAHOO.util.DataSource.TYPE_JSON,
8244 resultsList: 'Email',
8245 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8246 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8252 action : "EmailUIAjax",
8253 emailUIAction : "getMessageList",
8256 forceRefresh : "false"
8258 if(lazyLoadFolder != null) {
8259 params['mbox'] = lazyLoadFolder.folder;
8260 params['ieId'] = lazyLoadFolder.ieId;
8261 //Check if the folder is a Sugar Folder
8262 var test = new String(lazyLoadFolder.folder);
8263 if(test.match(/SUGAR\./)) {
8264 params['emailUIAction'] = 'getMessageListSugarFolders';
8265 params['mbox'] = test.substr(6);
8268 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8271 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8272 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8274 paginator: new YAHOO.widget.Paginator({
8275 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8276 containers : ["dt-pag-nav"],
8277 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8278 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8279 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8280 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8281 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8283 initialRequest:SUGAR.util.paramsToUrl(params),
8290 //Override Paging request construction
8291 grid.set("generateRequest", function(oState, oSelf) {
8292 oState = oState || {pagination:null, sortedBy:null};
8293 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8294 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8295 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8296 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8297 // Build the request
8299 SUGAR.util.paramsToUrl(oSelf.params) +
8302 "&start=" + startIndex +
8303 ((results !== null) ? "&limit=" + results : "");
8308 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8309 oPayload = oPayload || { };
8311 oPayload.totalRecords = oResponse.meta.total;
8312 oPayload.unreadRecords = oResponse.meta.unread;
8314 var tabObject = SE.innerLayout.get("tabs")[0];
8316 if (this.params.mbox != null) {
8317 mboxTitle = this.params.mbox;
8319 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8320 tabObject.get("labelEl").firstChild.data = tabtext;
8323 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8325 node.data.unseen = oResponse.meta.unread;
8326 SE.accounts.renderTree();
8332 var resize = grid.resizeGrid = function () {
8333 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8334 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8336 grid.convertDDRows = function() {
8337 var rowEl = this.getFirstTrEl();
8338 while (rowEl != null) {
8339 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8340 rowEl = this.getNextTrEl(rowEl);
8345 grid.on("columnResizeEvent", function(o) {
8346 //Find the index of the column
8347 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8348 for (var i=0; i < colSet.length; i++) {
8349 if (o.column == colSet[i]) {
8350 //Store it in the cookie
8351 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8354 //this.resizeGrid();
8357 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8358 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8359 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8361 SUGAR.email2.listViewLayout.on("render", resize);
8364 //Setup the default load parameters
8365 SUGAR.email2.grid.params = params;
8367 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8368 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8369 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8376 function initRowDD() {
8377 var sg = SUGAR.email2.grid,
8378 Dom = YAHOO.util.Dom;
8379 sg.DDRow = function(oDataTable, oRecord, elTr) {
8380 if(oDataTable && oRecord && elTr) {
8381 this.ddtable = oDataTable;
8382 this.table = oDataTable.getTableEl();
8385 this.newIndex = null;
8387 this.initFrame(); // Needed for DDProxy
8388 this.invalidHandleTypes = {};
8392 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8393 _resizeProxy: function() {
8394 this.constructor.superclass._resizeProxy.apply(this, arguments);
8395 var dragEl = this.getDragEl(),
8397 var xy = Dom.getXY(el);
8399 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8400 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8401 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8402 Dom.setStyle(dragEl, 'display', "");
8405 startDrag: function(x, y) {
8406 //Check if we should be dragging a set of rows rather than just the one.
8407 var selectedRows = this.ddtable.getSelectedRows();
8408 var iSelected = false;
8409 for (var i in selectedRows) {
8410 if (this.rowEl.id == selectedRows[i]) {
8417 for (var i in selectedRows) {
8418 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8421 this.rows = [this.row];
8422 this.ddtable.unselectAllRows();
8423 this.ddtable.selectRow(this.row);
8426 //Initialize the dragable proxy
8427 var dragEl = this.getDragEl();
8428 var clickEl = this.getEl();
8429 Dom.setStyle(clickEl, "opacity", "0.25");
8430 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8431 Dom.addClass(dragEl, "yui-dt-liner");
8432 Dom.setStyle(dragEl, "opacity", "0.5");
8433 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8434 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8435 Dom.setStyle(dragEl, "border", "2px solid gray");
8438 clickValidator: function(e) {
8439 if (this.row.getData()[0] == " ")
8441 var target = YAHOO.util.Event.getTarget(e);
8442 return ( this.isValidHandleChild(target) &&
8443 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8446 * This funciton checks that the target of the drag is a table row in this
8447 * DDGroup and simply moves the sourceEL to that location as a preview.
8449 onDragOver: function(ev, id) {
8450 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8451 if (node && node != this.targetNode) {
8452 this.targetNode = node;
8453 SUGAR.email2.folders.unhighliteAll();
8458 onDragOut: function(e, id) {
8459 if (this.targetNode) {
8460 SUGAR.email2.folders.unhighliteAll();
8461 this.targetNode = false;
8464 endDrag: function() {
8465 Dom.setStyle(this.getEl(), "opacity", "");
8466 Dom.setStyle(this.getDragEl(), "display", "none");
8467 if (this.targetNode) {
8468 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8470 SUGAR.email2.folders.unhighliteAll();
8476 function AddressSearchGridInit() {
8477 function moduleIcon(elCell, oRecord, oColumn, oData) {
8478 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8480 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8481 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8483 var checkHeader = '<input type="checkbox" ';
8484 if (SUGAR.email2.util.isIe()) {
8485 checkHeader += 'style="top:-5px" ';
8487 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8492 formatter: selectionCheckBox,
8496 label: mod_strings.LBL_LIST_TYPE,
8498 formatter: moduleIcon,
8502 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8508 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8514 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8515 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8517 resultsList: 'Person',
8518 fields: ['name', 'email', 'bean_id', 'bean_module'],
8519 metaFields: {total: 'TotalCount'}
8521 //enable sorting on the server accross all data
8524 dataModel.params = {
8527 action : "EmailUIAjax",
8528 emailUIAction:"getAddressSearchResults"
8530 var rb = document.getElementById('hasRelatedBean').checked;
8532 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8533 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8534 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8535 dataModel.params['related_bean_id'] = relatedBeanId;
8536 dataModel.params['related_bean_type'] = relatedBeanType;
8537 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8539 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8541 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8542 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8544 paginator: new YAHOO.widget.Paginator({
8546 containers : ["dt-pag-nav-addressbook"],
8547 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8548 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8549 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8550 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8551 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8553 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8557 //Override Paging request construction
8558 grid.set("generateRequest", function(oState, oSelf) {
8559 oState = oState || {pagination:null, sortedBy:null};
8560 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8561 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8562 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8563 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8564 // Build the request
8566 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8567 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8568 ((results !== null) ? "&limit=" + results : "");
8572 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8573 oPayload = oPayload || { };
8574 oPayload.totalRecords = oResponse.meta.total;
8578 grid.clickToggleSelect= function(args) {
8579 var isIE = (args.event.target == null);
8580 var targetElement = isIE ? args.event.srcElement : args.event.target;
8581 if(targetElement.type == null || targetElement.type != 'checkbox') {
8582 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8586 grid.reSelectRowsOnRender = function (){
8587 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8588 for (var i = 0; i < rows.length; i++)
8590 var emailAddress = rows[i].getData("email");
8591 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8594 rows[i].setData("selected", true);
8595 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8599 rows[i].setData("selected", false);
8600 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8604 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8605 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8606 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8607 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8610 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8611 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8613 grid.toggleSelectCheckbox = function(id,checked){
8614 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8615 row.setData("checked",checked);
8617 grid.toggleSelect = function(id, checked) {
8618 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8619 checked = row.getData("selected");
8622 SUGAR.email2.addressBook.grid.selectRow(row);
8623 SE.addressBook.insertContactRowToResultTable(id,null)
8626 SUGAR.email2.addressBook.grid.unselectRow(row);
8627 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8629 row.setData("selected", !checked);
8632 grid.toggleSelectAll = function(checked) {
8633 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8634 for (var i = 0; i < rows.length; i++) {
8635 if (typeof(rows[i]) != "undefined")
8636 rows[i].setData("checked", checked);
8638 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8639 for (var i = 0; i < checkBoxes.length; i++) {
8640 checkBoxes[i].checked = checked;
8644 //Initialize the grid result table.
8645 AddressSearchResultsGridInit();
8651 * Initalize the results table for the address book selection.
8654 function AddressSearchResultsGridInit()
8657 /* Full name sort funciton to compare by last name if available */
8658 var fullNameSort = function(a, b, desc) {
8659 // Deal with empty values
8660 if(!YAHOO.lang.isValue(a))
8661 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8662 else if(!YAHOO.lang.isValue(b))
8665 var aNames = a.getData("name").split(' ');
8666 var bNames = b.getData("name").split(' ');
8668 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8669 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8671 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8675 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8676 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8677 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8679 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})},
8680 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8682 var myDataSource = new YAHOO.util.DataSource([]);
8683 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8684 myDataSource.responseSchema = {
8685 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8688 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8689 width: "350px",height: "250px", MSG_EMPTY: " "});
8691 var highlightEditableCell = function(oArgs) {
8692 var elCell = oArgs.target;
8693 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8694 this.highlightCell(elCell);
8698 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8699 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8700 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8701 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8702 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8704 //Setup the context menus
8705 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8706 var task = p_aArgs[1];
8709 var elRow = this.contextEventTarget;
8710 elRow = p_myDataTable.getTrEl(elRow);
8717 var oRecord = p_myDataTable.getRecord(elRow);
8718 p_myDataTable.deleteRow(elRow);
8719 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8724 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8725 {trigger:gridResults.getTbodyEl()});
8726 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8727 contextMenu.render("addrSearchResultGrid");
8728 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8730 // End of File modules/Emails/javascript/grid.js
8732 /*********************************************************************************
8733 * SugarCRM is a customer relationship management program developed by
8734 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8736 * This program is free software; you can redistribute it and/or modify it under
8737 * the terms of the GNU Affero General Public License version 3 as published by the
8738 * Free Software Foundation with the addition of the following permission added
8739 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8740 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8741 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8743 * This program is distributed in the hope that it will be useful, but WITHOUT
8744 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8745 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8748 * You should have received a copy of the GNU Affero General Public License along with
8749 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8750 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8753 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8754 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8756 * The interactive user interfaces in modified source and object code versions
8757 * of this program must display Appropriate Legal Notices, as required under
8758 * Section 5 of the GNU Affero General Public License version 3.
8760 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8761 * these Appropriate Legal Notices must retain the display of the "Powered by
8762 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8763 * technical reasons, the Appropriate Legal Notices must display the words
8764 * "Powered by SugarCRM".
8765 ********************************************************************************/
8770 function complexLayoutInit() {
8771 var se = SUGAR.email2;
8772 var Dom = YAHOO.util.Dom;
8774 getInnerLayout : function(rows) {
8775 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8776 parent: se.complexLayout,
8782 scroll:false, // grid should autoScroll itself
8784 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8792 body: "<div id='listBottom' />"
8800 body: "<div id='listRight' />",
8801 titlebar: false //,header: "right"
8804 se.complexLayout.on("render", function(){
8805 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8806 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8807 SUGAR.email2.listViewLayout.set("height", height);
8808 SUGAR.email2.listViewLayout.render();
8810 se.listViewLayout.render();
8812 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8813 var rp = se.listViewLayout.resizePreview = function() {
8814 var pre = Dom.get("displayEmailFramePreview");
8816 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8817 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8820 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8821 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8822 se.e2Layout.setPreviewPanel(rows);
8823 se.previewLayout = se.listViewLayout;
8824 return se.listViewLayout;
8827 getInnerLayout2Rows : function() {
8828 return this.getInnerLayout(true);
8830 getInnerLayout2Columns : function() {
8831 return this.getInnerLayout(false);
8835 // initialize state manager, we will use cookies
8836 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8837 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8838 se.complexLayout = new YAHOO.widget.Layout("container", {
8841 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8842 width: Dom.getViewportWidth() - 40,
8846 body: "<div id='emailtabs'></div>"
8851 body: "<div id='lefttabs'></div>",
8861 header: Dom.get('footerLinks').innerHTML,
8868 se.complexLayout.render();
8869 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8870 tp.addTab(new YAHOO.widget.Tab({
8873 content : "<div id='listViewDiv'/>",
8877 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8878 tp.appendTo(centerEl);
8880 tp.get("element").style.borderRight = "1px solid #666"
8882 var listV = this.getInnerLayout2Rows();
8883 listV.set("height", tp.get("element").clientHeight - 25);
8886 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8887 var folderTab = new YAHOO.widget.Tab({
8888 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8890 content : "<div id='emailtree'/>",
8894 folderTab.on("activeChange", function(o){
8896 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8899 se.leftTabs.addTab(folderTab);
8901 var tabContent = SUGAR.util.getAndRemove("searchTab");
8902 var searchTab = new YAHOO.widget.Tab({
8903 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8905 content : tabContent.innerHTML,
8908 searchTab.on("activeChange", function(o){
8911 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8912 //Setup the calendars if needed
8913 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_from", singleClick : true, step : 1, weekNumbers:false});
8914 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_to", singleClick : true, step : 1, weekNumbers:false});
8916 //Initalize sqs object for assigned user name
8917 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
8919 //Attach event handler for when the relate module option is selected for the correct sqs object
8920 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8921 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8922 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
8923 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8925 //If enter key is pressed, perform search
8926 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8927 for(var i=0; i < addKeyPressFields.length;i++)
8929 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8930 if (e.keyCode == 13) {
8931 YAHOO.util.Event.stopEvent(e);
8932 SUGAR.email2.search.searchAdvanced();
8936 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
8938 //Clear parent values if selecting another parent type.
8939 YAHOO.util.Event.addListener('data_parent_type_search','change',
8941 document.getElementById('data_parent_id_search').value ='';
8942 document.getElementById('data_parent_name_search').value ='';
8947 se.leftTabs.addTab(searchTab);
8949 var resizeTabBody = function() {
8950 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8951 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8954 se.complexLayout.on("render", resizeTabBody);
8955 se.leftTabs.on("activeTabChange", resizeTabBody);
8956 //hack to allow left pane scroll bar to fully show
8957 var lefttabsDiv = document.getElementById('lefttabs');
8958 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8959 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8960 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8963 initSQSObject: function(formName,fieldName)
8965 var fullFieldName = formName + '_' + fieldName; //SQS Convention
8966 var resultName = fullFieldName + '_' + 'results';
8968 if (QSFieldsArray[fullFieldName] != null)
8970 QSFieldsArray[fullFieldName].destroy();
8971 delete QSFieldsArray[fullFieldName];
8973 if (QSProcessedFieldsArray[fullFieldName])
8974 QSProcessedFieldsArray[fullFieldName] = false;
8976 if( Dom.get(resultName) )
8978 var obj = document.getElementById(resultName);
8979 obj.parentNode.removeChild(obj);
8982 setPreviewPanel: function(rows) {
8984 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
8985 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
8986 Dom.get("listRight").innerHTML = "";
8987 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
8989 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
8990 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
8991 Dom.get("listBottom").innerHTML = "";
8992 Dom.get("listRight").innerHTML = "<div id='_blank' />";
8999 var myBufferedListenerObject = new Object();
9000 myBufferedListenerObject.refit = function() {
9001 if(SUGAR.email2.grid) {
9002 SUGAR.email2.grid.autoSize();
9005 // End of File modules/Emails/javascript/complexLayout.js
9007 /*********************************************************************************
9008 * SugarCRM is a customer relationship management program developed by
9009 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9011 * This program is free software; you can redistribute it and/or modify it under
9012 * the terms of the GNU Affero General Public License version 3 as published by the
9013 * Free Software Foundation with the addition of the following permission added
9014 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9015 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9016 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9018 * This program is distributed in the hope that it will be useful, but WITHOUT
9019 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9020 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9023 * You should have received a copy of the GNU Affero General Public License along with
9024 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9025 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9028 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9029 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9031 * The interactive user interfaces in modified source and object code versions
9032 * of this program must display Appropriate Legal Notices, as required under
9033 * Section 5 of the GNU Affero General Public License version 3.
9035 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9036 * these Appropriate Legal Notices must retain the display of the "Powered by
9037 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9038 * technical reasons, the Appropriate Legal Notices must display the words
9039 * "Powered by SugarCRM".
9040 ********************************************************************************/
9043 /******************************************************************************
9044 * Initialize Email 2.0 Application
9047 //Override Sugar Languge so quick creates work properly
9050 function email2init() {
9053 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9054 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9055 if (!SUGAR.util.isTouchScreen()) {
9057 convert_urls : false,
9058 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9059 width: tinyConfig.width,
9060 theme: tinyConfig.theme,
9061 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9062 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9063 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9064 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9065 plugins : tinyConfig.plugins,
9066 elements : tinyConfig.elements,
9067 language : tinyConfig.language,
9068 extended_valid_elements : tinyConfig.extended_valid_elements,
9069 mode: tinyConfig.mode,
9070 strict_loading_mode : true,
9071 force_br_newlines : true,
9072 forced_root_block : ''
9075 //alert('loadedTiny');
9077 // initialze message overlay
9078 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9088 if (SUGAR.themes.tempHideLeftCol)
9089 SUGAR.themes.tempHideLeftCol();
9091 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9092 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9094 // set defaults for YAHOO.util.DragDropManager
9095 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9097 SUGAR.email2.nextYear = new Date();
9098 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9101 // initialize and display UI framework (complexLayout.js)
9102 complexLayoutInit();
9104 // initialize and display grid (grid.js)
9107 // initialize treeview for folders
9109 SUGAR.email2.folders.rebuildFolders(true);
9112 //Setup the Message Box overlay
9113 /*Ext.MessageBox.maxWidth = 350;
9114 Ext.MessageBox.minProgressWidth = 350;
9116 ///////////////////////////////////////////////////////////////////////////
9119 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9121 var SEC = SUGAR.email2.contextMenus;
9124 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9125 trigger: SUGAR.email2.grid.get("element"),
9128 emailMenu.subscribe("beforeShow", function() {
9129 var oTarget = this.contextEventTarget;
9130 if (typeof(oTarget) == "undefined")
9132 var grid = SUGAR.email2.grid;
9133 var selectedRows = grid.getSelectedRows();
9134 var multipleSelected = (selectedRows.length > 1) ? true: false;
9135 if (!multipleSelected)
9137 grid.unselectAllRows();
9138 grid.selectRow(oTarget);
9139 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9141 else if(multipleSelected)
9143 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9147 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9148 //us to access individual elements easier by name rather than by index
9149 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
9150 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9151 emailMenu.addItems([
9153 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9154 id: 'showDetailView',
9155 onclick: { fn: SEC.showDetailView }
9158 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9159 onclick: { fn: SEC.openMultiple }
9162 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9163 onclick: { fn: SEC.archiveToSugar }
9166 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9168 onclick: { fn: SEC.replyForwardEmailContext }
9171 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9173 onclick: { fn: SEC.replyForwardEmailContext }
9176 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9178 onclick: { fn: SEC.replyForwardEmailContext }
9181 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9183 onclick: { fn: SEC.markDeleted }
9186 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9188 onclick: { fn: SEC.viewPrintable }
9192 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9194 id: "markEmailMenu",
9197 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9198 onclick: { fn: SEC.markUnread }
9201 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9202 onclick: { fn: SEC.markRead }
9205 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9206 onclick: { fn: SEC.markFlagged }
9209 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9210 onclick: { fn: SEC.markUnflagged }
9216 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9218 onclick: { fn: SEC.assignEmailsTo }
9221 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9223 onclick: { fn: SEC.relateTo }
9226 SEC.emailListContextMenu.render();
9228 //Handle the Tree folder menu trigger ourselves
9229 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9233 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9237 SEC.frameFoldersContextMenu.addItems([
9238 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9239 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9240 onclick: { fn: function() {
9241 var node = SUGAR.email2.clickedFolderNode;
9242 if (node.data.ieId) {
9243 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9246 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9247 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9248 onclick: { fn: function() {
9249 var node = SUGAR.email2.clickedFolderNode;
9250 if (node.data.ieId) {
9251 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9255 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9256 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9257 onclick: { fn: SUGAR.email2.folders.folderAdd }
9260 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9261 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9262 onclick: { fn: SUGAR.email2.folders.folderDelete }
9265 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9266 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9267 onclick: { fn: SUGAR.email2.folders.folderRename }
9270 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9271 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9272 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9275 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9276 onclick: { fn: function() {
9277 var node = SUGAR.email2.clickedFolderNode;
9278 if (node.data.ieId) {
9279 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9283 SEC.frameFoldersContextMenu.render();
9285 SEC.initContactsMenu = function() {
9287 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9288 trigger: "contacts",
9291 SEC.contactsContextMenu.addItems([
9293 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9294 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9297 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9298 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9301 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9302 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9303 if (oTarget && !grid.isSelected(oTarget)) {
9304 grid.unselectAllRows();
9305 grid.selectRow(oTarget);
9308 SEC.contactsContextMenu.render();
9312 // set auto-check timer
9313 SUGAR.email2.folders.startCheckTimer();
9314 // check if we're coming from an email-link click
9315 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9317 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9319 //Init fix for YUI 2.7.0 datatable sort.
9320 SUGAR.email2.addressBook.initFixForDatatableSort();
9323 function createTreePanel(treeData, params) {
9324 var tree = new YAHOO.widget.TreeView(params.id);
9325 var root = tree.getRoot();
9327 //if (treeData.nodes && treeData[0].id == "Home")
9328 // treeData = treeData[0];
9330 addChildNodes(root, treeData);
9335 function addChildNodes(parentNode, parentData) {
9336 var Ck = YAHOO.util.Cookie;
9337 var nextyear = SUGAR.email2.nextYear;
9338 var nodes = parentData.nodes || parentData.children;
9340 if (typeof(nodes[i]) == 'object') {
9341 if (nodes[i].data) {
9342 nodes[i].data.href = '#';
9343 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9344 node.action = nodes[i].data.action;
9346 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9347 addChildNodes(parentNode, nodes[i]);
9350 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9351 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9353 nodes[i].className = nodes[i].cls;
9355 nodes[i].href = "#";
9356 if (nodes[i].text) nodes[i].label = nodes[i].text;
9357 //Override YUI child node creation
9358 if (nodes[i].children) {
9359 nodes[i].nodes = nodes[i].children;
9360 nodes[i].children = [ ];
9362 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9365 if (typeof(nodes[i].nodes) == 'object') {
9366 addChildNodes(node, nodes[i]);
9373 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9375 function email2treeinit(tree, treedata, treediv, params) {
9376 //ensure the tree data is not corrupt
9380 if (SUGAR.email2.tree) {
9381 SUGAR.email2.tree.destroy();
9382 SUGAR.email2.tree = null;
9385 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9389 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9390 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9391 tree.subscribe("expandComplete", function(node){
9392 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9393 for (var i in node.children) {
9394 SE.accounts.setupDDTarget(node.children[i]);
9397 tree.setCollapseAnim("TVSlideOut");
9398 tree.setExpandAnim("TVSlideIn");
9399 var root = tree.root;
9400 while (root.hasChildren()) {
9401 var node = root.children[0];
9403 tree.removeNode(root.children[0], false);
9405 addChildNodes(root, treedata);
9407 SUGAR.email2.accounts.renderTree();
9410 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9411 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9415 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9416 startDrag: function(x, y) {
9417 var Dom = YAHOO.util.Dom;
9418 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9421 var dragEl = this.getDragEl();
9422 var clickEl = this.getEl();
9423 Dom.setStyle(clickEl, "color", "#AAA");
9424 Dom.setStyle(clickEl, "opacity", "0.25");
9425 dragEl.innerHTML = clickEl.innerHTML;
9427 Dom.addClass(dragEl, "ygtvcell");
9428 Dom.addClass(dragEl, "ygtvcontent");
9429 Dom.addClass(dragEl, "folderDragProxy");
9430 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9431 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9432 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9433 Dom.setStyle(dragEl, "opacity", "0.5");
9434 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9437 onDragOver: function(ev, id) {
9438 var Dom = YAHOO.util.Dom;
9439 if (id != this.dragId)
9441 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9442 if(node.data.cls != "sugarFolder") {
9443 SUGAR.email2.folders.unhighliteAll();
9447 this.targetNode = node;
9448 SUGAR.email2.folders.unhighliteAll();
9453 onDragOut: function(e, id) {
9454 if (this.targetNode) {
9455 SUGAR.email2.folders.unhighliteAll();
9456 this.targetNode = false;
9457 this.dragId = false;
9461 endDrag: function() {
9462 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9463 if (this.targetNode) {
9464 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9467 });// End of File modules/Emails/javascript/init.js
9469 /*********************************************************************************
9470 * SugarCRM is a customer relationship management program developed by
9471 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9473 * This program is free software; you can redistribute it and/or modify it under
9474 * the terms of the GNU Affero General Public License version 3 as published by the
9475 * Free Software Foundation with the addition of the following permission added
9476 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9477 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9478 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9480 * This program is distributed in the hope that it will be useful, but WITHOUT
9481 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9482 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9485 * You should have received a copy of the GNU Affero General Public License along with
9486 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9487 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9490 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9491 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9493 * The interactive user interfaces in modified source and object code versions
9494 * of this program must display Appropriate Legal Notices, as required under
9495 * Section 5 of the GNU Affero General Public License version 3.
9497 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9498 * these Appropriate Legal Notices must retain the display of the "Powered by
9499 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9500 * technical reasons, the Appropriate Legal Notices must display the words
9501 * "Powered by SugarCRM".
9502 ********************************************************************************/
9504 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9505 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9506 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9507 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9508 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9509 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9510 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9511 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9512 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9513 ' <input type="hidden" id="composeType" name="composeType">' +
9514 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9515 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9516 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9517 ' <input type="hidden" id="sendTo" name="sendTo">' +
9518 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9519 ' <input type="hidden" id="sendCc" name="sendCc">' +
9520 ' <input type="hidden" id="setEditor" name="setEditor">' +
9521 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9522 ' <input type="hidden" id="parent_id" name="parent_id">' +
9523 ' <input type="hidden" id="parent_type" name="parent_type">' +
9524 ' <input type="hidden" id="attachments" name="attachments">' +
9525 ' <input type="hidden" id="documents" name="documents">' +
9526 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9527 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9528 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9529 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9531 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9532 ' <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>' +
9533 ' <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>' +
9534 ' <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>' +
9535 ' <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>' +
9536 '</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>' +
9537 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9538 '<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>' +
9539 ' </td></tr></tbody></table></th>' +
9543 ' <div style="margin:5px;">' +
9544 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9546 ' <td class="emailUILabel" NOWRAP >' +
9547 ' {app_strings.LBL_EMAIL_FROM}:' +
9549 ' <td class="emailUIField" NOWRAP>' +
9551 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9556 ' <td class="emailUILabel" NOWRAP>' +
9557 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9558 ' {app_strings.LBL_EMAIL_TO}:' +
9561 ' <td class="emailUIField" NOWRAP>' +
9562 ' <div class="ac_autocomplete">' +
9563 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9564 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9565 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9569 ' <tr id="add_addr_options_tr{idx}">' +
9570 ' <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>'+
9572 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9573 ' <td class="emailUILabel" NOWRAP>' +
9574 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9575 ' {app_strings.LBL_EMAIL_CC}:' +
9578 ' <td class="emailUIField" NOWRAP>' +
9579 ' <div class="ac_autocomplete">' +
9580 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9581 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9582 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9586 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9587 ' <td class="emailUILabel" NOWRAP>' +
9588 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9589 ' {app_strings.LBL_EMAIL_BCC}:' +
9592 ' <td class="emailUIField" NOWRAP>' +
9593 ' <div class="ac_autocomplete">' +
9594 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9595 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9596 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9601 ' <td class="emailUILabel" NOWRAP width="1%">' +
9602 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9604 ' <td class="emailUIField" NOWRAP width="99%">' +
9605 ' <div class="ac_autocomplete">' +
9606 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9615 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9616 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9617 ' <div style="padding:5px;">' +
9618 ' <table cellpadding="2" cellspacing="0" border="0">' +
9621 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9628 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9629 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9641 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9648 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9649 ' <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>' +
9661 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9668 ' <div id="addedTemplateAttachments{idx}"></div>' +
9675 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9676 ' <div style="padding:5px;">' +
9677 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9678 ' <table border="0" width="100%">' +
9680 ' <td NOWRAP style="padding:2px;">' +
9681 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9685 ' <td NOWRAP style="padding:2px;">' +
9686 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9691 ' <table border="0" width="100%">' +
9693 ' <td NOWRAP style="padding:2px;">' +
9694 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9698 ' <td NOWRAP style="padding:2px;">' +
9699 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9703 ' <table border="0" width="100%">' +
9705 ' <td NOWRAP style="padding:2px;">' +
9706 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9707 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9715 // End of File modules/Emails/javascript/composeEmailTemplate.js
9717 /*********************************************************************************
9718 * SugarCRM is a customer relationship management program developed by
9719 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9721 * This program is free software; you can redistribute it and/or modify it under
9722 * the terms of the GNU Affero General Public License version 3 as published by the
9723 * Free Software Foundation with the addition of the following permission added
9724 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9725 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9726 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9728 * This program is distributed in the hope that it will be useful, but WITHOUT
9729 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9730 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9733 * You should have received a copy of the GNU Affero General Public License along with
9734 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9735 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9738 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9739 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9741 * The interactive user interfaces in modified source and object code versions
9742 * of this program must display Appropriate Legal Notices, as required under
9743 * Section 5 of the GNU Affero General Public License version 3.
9745 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9746 * these Appropriate Legal Notices must retain the display of the "Powered by
9747 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9748 * technical reasons, the Appropriate Legal Notices must display the words
9749 * "Powered by SugarCRM".
9750 ********************************************************************************/
9752 SUGAR.email2.templates['displayOneEmail'] =
9753 '<div class="emailDetailTable" style="height:100%">' +
9754 '<div id="viewMenuDiv{idx}"></div>' +
9755 '<div width="100%" class="displayEmailValue">' +
9756 ' <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>' +
9757 ' <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>' +
9758 ' <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>' +
9759 ' <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>' +
9760 ' <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>' +
9761 ' <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>' +
9762 ' <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>' +
9763 ' <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>' +
9764 ' <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>' +
9766 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9768 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9769 ' {app_strings.LBL_EMAIL_FROM}:' +
9771 ' <td width="99%" class="displayEmailValue">' +
9772 ' {email.from_addr}' +
9776 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9777 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9779 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9780 ' <b>{email.name}</b>' +
9784 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9785 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9787 ' <td class="displayEmailValue">' +
9788 ' {email.date_start} {email.time_start}' +
9792 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9793 ' {app_strings.LBL_EMAIL_TO}:' +
9795 ' <td class="displayEmailValue">' +
9796 ' {email.toaddrs}' +
9799 ' <tr>{meta.cc}</tr>' +
9800 ' <tr>{email.attachments}</tr>' +
9802 ' <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>' +
9803 //' {email.description}' +
9805 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9807 /*********************************************************************************
9808 * SugarCRM is a customer relationship management program developed by
9809 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9811 * This program is free software; you can redistribute it and/or modify it under
9812 * the terms of the GNU Affero General Public License version 3 as published by the
9813 * Free Software Foundation with the addition of the following permission added
9814 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9815 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9816 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9818 * This program is distributed in the hope that it will be useful, but WITHOUT
9819 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9820 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9823 * You should have received a copy of the GNU Affero General Public License along with
9824 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9825 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9828 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9829 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9831 * The interactive user interfaces in modified source and object code versions
9832 * of this program must display Appropriate Legal Notices, as required under
9833 * Section 5 of the GNU Affero General Public License version 3.
9835 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9836 * these Appropriate Legal Notices must retain the display of the "Powered by
9837 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9838 * technical reasons, the Appropriate Legal Notices must display the words
9839 * "Powered by SugarCRM".
9840 ********************************************************************************/
9842 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9843 '<body onload="javascript:window.print();">' +
9847 ' font-family: helvetica, impact, sans-serif;' +
9848 ' font-size : 12pt;' +
9855 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9858 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9860 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9861 ' {app_strings.LBL_EMAIL_FROM}:' +
9863 ' <td width="99%" class="displayEmailValue">' +
9864 ' {email.from_name} <{email.from_addr}>' +
9868 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9869 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9871 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9872 ' <b>{email.name}</b>' +
9876 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9877 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9879 ' <td class="displayEmailValue">' +
9880 ' {email.date_start} {email.time_start}' +
9884 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9885 ' {app_strings.LBL_EMAIL_TO}:' +
9887 ' <td class="displayEmailValue">' +
9888 ' {email.toaddrs}' +
9892 ' {email.attachments}' +
9898 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9900 ' <td style="border-top: 1px solid #333;">' +
9901 ' <div style="padding:5px;">' +
9902 '{email.description}' +
9912 // End of File modules/Emails/javascript/viewPrintable.js
9914 /*********************************************************************************
9915 * SugarCRM is a customer relationship management program developed by
9916 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9918 * This program is free software; you can redistribute it and/or modify it under
9919 * the terms of the GNU Affero General Public License version 3 as published by the
9920 * Free Software Foundation with the addition of the following permission added
9921 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9922 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9923 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9925 * This program is distributed in the hope that it will be useful, but WITHOUT
9926 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9927 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9930 * You should have received a copy of the GNU Affero General Public License along with
9931 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9932 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9935 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9936 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9938 * The interactive user interfaces in modified source and object code versions
9939 * of this program must display Appropriate Legal Notices, as required under
9940 * Section 5 of the GNU Affero General Public License version 3.
9942 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9943 * these Appropriate Legal Notices must retain the display of the "Powered by
9944 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9945 * technical reasons, the Appropriate Legal Notices must display the words
9946 * "Powered by SugarCRM".
9947 ********************************************************************************/
9948 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9949 var Dom=YAHOO.util.Dom;var qsFields=Dom.getElementsByClassName('sqsEnabled');for(qsField in qsFields){if(typeof qsFields[qsField]=='function'||typeof qsFields[qsField].id=='undefined'){continue;}
9950 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');}
9951 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;}}
9952 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9953 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9954 if(!document.forms[qs_obj.form].elements[qsFields[qsField].id].readOnly&&qs_obj['disable']!=true){combo_id=qs_obj.form+'_'+qsFields[qsField].id;if(Dom.get(combo_id+"_results")){loaded=true}
9955 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,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){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)){document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value=data[i];}}}},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="";}}
9956 this.oldValue="";}});if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9957 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];}}}
9958 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]];}
9959 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
9960 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9961 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js