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,ie_id)
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]
367 +'&personal='+isPersonal;var SI=SUGAR.inboundEmail;if(!SI.testDlg){SI.testDlg=new YAHOO.widget.SimpleDialog("testSettingsDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.testDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);if(this.evalJS)
368 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
369 this.body.style.width=w}}
370 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
371 title=SUGAR.language.get('InboundEmail','LBL_TEST_SETTINGS');SI.testDlg.setHeader(title);SI.testDlg.setBody(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.testDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.testDlg._updateContent,failure:SI.testDlg.hide,scope:SI.testDlg});SI.testDlg.show();}
372 function isDataValid(formName,validateMonitoredFolder){var formObject=document.getElementById(formName);var errors=new Array();var out=new String();if(trim(formObject.server_url.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_SERVER'));}
373 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
374 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
375 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
376 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
377 if(errors.length>0){out=SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_DESC');for(i=0;i<errors.length;i++){if(out!=""){out+="\n";}
379 alert(out);return false;}else{return true;}}
380 function getFoldersListForInboundAccount(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,searchFieldValue,formName){if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';URL='index.php?'
381 +'module='+module_name
384 +'&target='+pageTarget
385 +'&target1='+pageTarget
386 +'&server_url='+mail_server
387 +'&email_user='+words[0]
388 +'&protocol='+protocol
390 +'&email_password='+words[1]
391 +'&mailbox='+words[2]
393 +'&personal='+isPersonal
394 +'&searchField='+searchFieldValue;var SI=SUGAR.inboundEmail;if(!SI.listDlg){SI.listDlg=new YAHOO.widget.SimpleDialog("selectFoldersDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.listDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
395 this.body.style.width=w}}
396 SI.listDlg.setHeader(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.listDlg.setBody('');SI.listDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.listDlg._updateContent,failure:SI.listDlg.hide,scope:SI.listDlg});SI.listDlg.show();}
397 function setPortDefault(){var prot=document.getElementById('protocol');var ssl=document.getElementById('ssl');var port=document.getElementById('port');var stdPorts=new Array("110","143","993","995");var stdBool=new Boolean(false);if(port.value==''){stdBool.value=true;}else{for(i=0;i<stdPorts.length;i++){if(stdPorts[i]==port.value){stdBool.value=true;}}}
398 if(stdBool.value==true){if(prot.value=='imap'&&ssl.checked==false){port.value="143";}else if(prot.value=='imap'&&ssl.checked==true){port.value='993';}else if(prot.value=='pop3'&&ssl.checked==false){port.value='110';}else if(prot.value=='pop3'&&ssl.checked==true){port.value='995';}}}
399 function toggle_monitored_folder(field){var field1=document.getElementById('protocol');var mailbox=document.getElementById('mailbox');var label_inbox=document.getElementById('label_inbox');var subscribeFolderButton=document.getElementById('subscribeFolderButton');var trashFolderRow=document.getElementById('trashFolderRow');var trashFolderRow1=document.getElementById('trashFolderRow1');var sentFolderRow=document.getElementById('sentFolderRow');if(field1.value=='imap'){mailbox.disabled=false;try{mailbox.style.display='';trashFolderRow.style.display='';sentFolderRow.style.display='';trashFolderRow1.style.display='';subscribeFolderButton.style.display='';}catch(e){};label_inbox.style.display='';}
400 else{mailbox.value="INBOX";mailbox.disabled=false;try{mailbox.style.display="none";trashFolderRow.style.display="none";sentFolderRow.style.display="none";trashFolderRow1.style.display="none";subscribeFolderButton.style.display="none";}catch(e){};label_inbox.style.display="none";}}// End of File modules/InboundEmail/InboundEmail.js
402 /*********************************************************************************
403 * SugarCRM 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();
813 SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
817 * Set all fields on the outbound edit form to either enabled/disabled
818 * except for the username/password.
821 toggleOutboundAccountDisabledFields: function(disable)
823 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
824 for(var i=0;i<fields.length;i++)
826 document.getElementById(fields[i]).disabled = disable;
829 Dom.addClass("mail_smtpssl_row", "yui-hidden");
831 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
835 * Refresh the inbound accounts table.
837 refreshInboundAccountTable : function()
839 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
841 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
842 scope: this.inboundAccountsSettingsTable }
846 * Refresh the outbound accounts table.
848 refreshOuboundAccountTable : function()
850 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
852 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
853 scope: this.outboundAccountsSettingsTable }
857 * Displays a modal diaglogue to add a SMTP server
859 showAddSmtp : function() {
860 // lazy load dialogue
861 if(!this.outboundDialog) {
862 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
866 constraintoviewport: true,
870 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
871 this.outboundDialog.hideEvent.subscribe(function(){
872 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
873 var out = Dom.get("outbound_email");
874 if (out && out.value == "SYSTEM_ADD")
876 out.value = out.options[0].value;
878 //Check if we should display username/password for system account.
879 SE.accounts.checkOutBoundSelection();
883 Dom.removeClass("outboundDialog", "yui-hidden");
887 var form = document.getElementById('outboundEmailForm');
888 for(i=0; i<form.elements.length; i++) {
889 if(form.elements[i].name == 'mail_smtpport') {
890 form.elements[i].value = 25;
891 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
892 form.elements[i].value = '';
893 } else if(form.elements[i].type == 'checkbox') {
894 form.elements[i].checked = false;
897 //Render the SMTP buttons
898 if ( !SUGAR.smtpButtonGroup ) {
899 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
900 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
902 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
903 document.getElementById('smtp_settings').style.display = '';
904 form.mail_smtptype.value = e.newValue.get('value');
906 YAHOO.widget.Button.addHiddenFieldsToForm(form);
908 //Hide Username/Password
909 SUGAR.email2.accounts.smtp_authenticate_field_display();
910 //Unset readonly fields
911 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
912 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
913 this.outboundDialog.render();
914 this.outboundDialog.show();
918 * Accounts' Advanced Settings view toggle
920 toggleAdv : function() {
921 var adv = document.getElementById("ie_adv");
922 if(adv.style.display == 'none') {
923 adv.style.display = "";
925 adv.style.display = 'none';
929 smtp_authenticate_field_display : function() {
930 var smtpauth_req = document.getElementById("mail_smtpauth_req");
931 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
932 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
936 * Changes the display used in the outbound email SMTP dialog to match the
938 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
940 document.getElementById("smtpButtonGroupTD").style.display = '';
941 document.getElementById("chooseEmailProviderTD").style.display = '';
942 document.getElementById("mailsettings1").style.display = '';
943 document.getElementById("mailsettings2").style.display = '';
944 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
945 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
946 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
947 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
951 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
952 document.getElementById("mail_smtpport").value = '465';
953 document.getElementById("mail_smtpauth_req").checked = true;
954 var ssl = document.getElementById("mail_smtpssl");
955 for(var j=0;j<ssl.options.length;j++) {
956 if(ssl.options[j].text == 'SSL') {
957 ssl.options[j].selected = true;
961 document.getElementById("mailsettings1").style.display = 'none';
962 document.getElementById("mailsettings2").style.display = 'none';
963 document.getElementById("mail_smtppass_label").innerHTML =
964 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
965 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
968 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
969 document.getElementById("mail_smtpport").value = '587';
970 document.getElementById("mail_smtpauth_req").checked = true;
971 var ssl = document.getElementById("mail_smtpssl");
972 for(var j=0;j<ssl.options.length;j++) {
973 if(ssl.options[j].text == 'TLS') {
974 ssl.options[j].selected = true;
978 document.getElementById("mailsettings1").style.display = 'none';
979 document.getElementById("mailsettings2").style.display = 'none';
980 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
981 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
984 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
985 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
986 document.getElementById("mail_smtpserver").value = '';
988 document.getElementById("mail_smtpport").value = '25';
989 document.getElementById("mail_smtpauth_req").checked = true;
990 document.getElementById("mailsettings1").style.display = '';
991 document.getElementById("mailsettings2").style.display = '';
992 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
993 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
994 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
995 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
998 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1000 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1001 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1002 document.getElementById("mailsettings2").style.display = 'none';
1005 SUGAR.email2.accounts.smtp_authenticate_field_display();
1009 * Fill the gmail default values for inbound accounts.
1011 fillInboundGmailDefaults: function () {
1013 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1014 document.forms['ieAccount'].elements['ssl'].checked = true;
1015 document.forms['ieAccount'].elements['protocol'].value = "imap";
1016 SUGAR.email2.accounts.setPortDefault();
1017 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1020 * Sets Port field to selected protocol and SSL settings defaults
1022 setPortDefault : function() {
1023 var prot = document.getElementById('protocol');
1024 var ssl = document.getElementById('ssl');
1025 var port = document.getElementById('port');
1026 var stdPorts= new Array("110", "143", "993", "995");
1027 var stdBool = new Boolean(false);
1028 var mailboxdiv = document.getElementById("mailboxdiv");
1029 var trashFolderdiv = document.getElementById("trashFolderdiv");
1030 var sentFolderdiv = document.getElementById("sentFolderdiv");
1031 var monitoredFolder = document.getElementById("subscribeFolderButton");
1032 if(port.value == '') {
1033 stdBool.value = true;
1035 for(i=0; i<stdPorts.length; i++) {
1036 if(stdPorts[i] == port.value) {
1037 stdBool.value = true;
1042 if(stdBool.value == true) {
1043 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1045 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1047 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1049 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1054 if (prot.value == 'imap') {
1055 mailboxdiv.style.display = "";
1056 trashFolderdiv.style.display = "";
1057 sentFolderdiv.style.display = "";
1058 monitoredFolder.style.display = "";
1059 if (document.getElementById('mailbox').value == "") {
1060 document.getElementById('mailbox').value = "INBOX";
1063 mailboxdiv.style.display = "none";
1064 trashFolderdiv.style.display = "none";
1065 sentFolderdiv.style.display = "none";
1066 monitoredFolder.style.display = "none";
1067 document.getElementById('mailbox').value = "";
1072 * Draws/removes red boxes around required fields.
1074 ieAccountError : function(style) {
1075 document.getElementById('server_url').className = style;
1076 document.getElementById('email_user').className = style;
1077 document.getElementById('email_password').className = style;
1078 document.getElementById('protocol').className = style;
1079 document.getElementById('port').className = style;
1082 checkOutBoundSelection: function() {
1083 var select = Dom.get('outbound_email');
1084 if (!select || select.selectedIndex == -1) { return; }
1086 var v = select.options[select.selectedIndex].value;
1090 select.options[select.selectedIndex].selected = false;
1091 v = select.options[0].value;
1093 else if (v == 'SYSTEM_ADD')
1094 SUGAR.email2.accounts.showAddSmtp();
1096 var foundError = false;
1097 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1098 for(i in errorAccounts)
1107 //Should username/password fields for outbound account.
1109 this.toggleInboundOutboundFields(true);
1111 this.toggleInboundOutboundFields(false);
1116 toggleInboundOutboundFields : function (display)
1120 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1121 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1125 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1126 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1130 * rebuilds the select options for mailer options
1132 rebuildMailerOptions : function() {
1133 var select = document.forms['ieAccount'].elements['outbound_email'];
1134 SE.util.emptySelectOptions(select);
1136 //Get the available sugar mailers
1137 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1139 for(i=0;i<a_outbound.length;i++)
1141 var t_record = a_outbound[i];
1142 var key = t_record.getData('id');
1143 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1145 var opt = new Option(display, key);
1146 select.options.add(opt);
1147 if (key == SE.accounts.newAddedOutboundId) {
1148 select.options.selectedIndex = i;
1152 select.options.add(new Option('',''));
1153 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1154 //Hide/Show username password fields if necessary.
1155 SE.accounts.checkOutBoundSelection();
1158 * Empties all the fields in the accounts edit view
1160 clearInboundAccountEditScreen:function() {
1162 document.getElementById('ie_id').value = '';
1163 document.getElementById('ie_name').value = '';
1164 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1165 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1166 document.getElementById('reply_to_addr').value = '';
1167 document.getElementById('server_url').value = '';
1168 document.getElementById('email_user').value = '';
1169 document.getElementById('email_password').value = '';
1170 document.getElementById('port').value = '';
1171 document.getElementById('inbound_mail_smtpuser').value = '';
1172 document.getElementById('inbound_mail_smtppass').value = '';
1173 document.ieAccount.protocol.options[0].selected = true;
1175 document.getElementById('ssl').checked = false;
1176 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1180 * Populates an account's fields in Settings->Accounts
1182 fillIeAccount:function(jsonstr) {
1183 var o = JSON.parse(jsonstr);
1185 document.getElementById('ie_id').value = o.id;
1186 document.getElementById('ie_name').value = o.name;
1187 if (o.stored_options != null) {
1188 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1189 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1190 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1191 if (o.stored_options.trashFolder != null) {
1192 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1194 if (o.stored_options.sentFolder != null) {
1195 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1198 document.getElementById('server_url').value = o.server_url;
1199 document.getElementById('email_user').value = o.email_user;
1200 document.getElementById('port').value = o.port;
1201 document.getElementById('group_id').value = o.group_id;
1202 document.getElementById('mailbox').value = o.mailbox;
1208 if(typeof(o.service[2]) != 'undefined') {
1209 document.getElementById('ssl').checked = true;
1213 if(document.getElementById('protocol').value != o.protocol) {
1214 var prot = document.getElementById('protocol');
1215 for(i=0; i<prot.options.length; i++) {
1216 if(prot.options[i].value == o.service[3]) {
1217 prot.options[i].selected = true;
1218 this.setPortDefault();
1222 // handle SMTP selection
1223 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1224 var opts = document.getElementById('outbound_email').options;
1225 for(i=0; i<opts.length; i++) {
1226 if(opts[i].value == o.stored_options.outbound_email) {
1227 opts[i].selected = true;
1233 deleteIeAccount : function(IeAccountID,IeGroupID) {
1234 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1236 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1238 AjaxObject.target = 'frameFlex';
1239 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1240 SUGAR.email2.accounts.refreshInboundAccountTable();
1244 // Null check for Outbound Settings.
1245 checkOutboundSettings: function() {
1246 var errorMessage = '';
1247 var isError = false;
1248 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1249 var mailName = document.getElementById('mail_name').value;
1250 var smtpServer = document.getElementById('mail_smtpserver').value;
1251 var smtpPort = document.getElementById('mail_smtpport').value;
1253 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1254 if(trim(mailName) == '') {
1256 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1258 if(trim(smtpServer) == '') {
1260 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1262 if(trim(smtpPort) == '') {
1264 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1266 if(mailsmtpauthreq.checked) {
1267 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1269 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1274 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1281 testOutboundSettings: function() {
1282 var errorMessage = '';
1283 var isError = false;
1284 var fromAddress = document.getElementById("outboundtest_from_address").value;
1285 if (trim(fromAddress) == "") {
1286 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1287 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1291 else if (!isValidEmail(fromAddress)) {
1292 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1293 overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1297 //Hide the dialogue and show an in progress indicator.
1298 SE.accounts.testOutboundDialog.hide();
1299 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1301 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1302 //nothing is sent in the request.
1303 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1304 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1306 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1307 if(outboundType == 'system-override')
1308 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1310 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1311 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1315 testOutboundSettingsDialog: function() {
1316 //Ensure that all settings are correct before proceeding to send test email.
1317 if(!SE.accounts.checkOutboundSettings())
1320 // lazy load dialogue
1321 if(!SE.accounts.testOutboundDialog) {
1322 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1326 constraintoviewport: true,
1330 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1331 Dom.removeClass("testOutboundDialog", "yui-hidden");
1333 SE.accounts.testOutboundDialog.render();
1334 SE.accounts.testOutboundDialog.show();
1338 * Saves Outbound email settings
1340 saveOutboundSettings : function() {
1341 if(SE.accounts.checkOutboundSettings()) {
1342 //Enable the form fields for the post.
1343 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1344 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1345 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1351 saveIeAccount : function() {
1353 //Before saving check if there are any error messages associated with the outbound account.
1354 var outboundID = document.getElementById('outbound_email').value;
1356 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1357 'validateSMTPCreds':true}) )
1359 document.getElementById('saveButton').disabled = true;
1361 overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1363 var formObject = document.getElementById('ieAccount');
1364 YAHOO.util.Connect.setForm(formObject);
1366 AjaxObject._reset();
1367 AjaxObject.target = 'frameFlex';
1368 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1372 testSettings : function() {
1373 form = document.getElementById('ieAccount');
1375 if(SE.accounts.checkIeCreds()) {
1376 ie_test_open_popup_with_submit("InboundEmail", "Popup", "Popup", 400, 300, trim(form.server_url.value), form.protocol.value, trim(form.port.value), trim(form.email_user.value), Rot13.write(form.email_password.value), trim(form.mailbox.value), form.ssl.checked, true, "ieAccount", form.ie_id.value);
1380 getFoldersListForInboundAccountForEmail2 : function() {
1381 form = document.getElementById('ieAccount');
1382 if(SE.accounts.checkIeCreds()) {
1383 var mailBoxValue = form.mailbox.value;
1384 if (form.searchField.value.length > 0) {
1387 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 );
1392 checkIeCreds : function(validateRules) {
1393 if(typeof(validateRules) == 'undefined')
1396 var errors = new Array();
1397 var out = new String();
1399 var ie_name = Dom.get('ie_name').value;
1400 var fromAddress = Dom.get('ie_from_addr').value;
1401 var server_url = Dom.get('server_url').value;
1402 var email_user = Dom.get('email_user').value;
1403 var email_password = Dom.get('email_password').value;
1404 var protocol = Dom.get('protocol').value;
1405 var port = Dom.get('port').value;
1406 var oe = Dom.get('outbound_email');
1407 var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1409 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1410 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1412 //If the username and password were provided then ignore the error messge
1414 var outboundCredentialsFound = false;
1416 if(outboundUserName != "" && outboundPass != "")
1417 outboundCredentialsFound = true;
1419 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1421 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1422 && validateSMTPCreds)
1424 if(trim(outboundUserName) == "") {
1425 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1427 if(trim(outboundPass) == "") {
1428 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1432 if(trim(ie_name) == "") {
1433 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1436 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1438 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1439 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1444 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1445 || trim(oe_value) == "SYSTEM_ADD") ) {
1446 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1448 if(trim(server_url) == "") {
1449 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1451 if(trim(email_user) == "") {
1452 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1454 if(protocol == "") {
1455 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1457 if (protocol == 'imap') {
1458 var mailbox = document.getElementById('mailbox').value;
1459 if (trim(mailbox) == "") {
1460 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1462 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1463 var trashFolder = document.getElementById('trashFolder').value;
1464 if (trim(trashFolder) == "") {
1465 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1470 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1473 if(errors.length > 0) {
1474 out = app_strings.LBL_EMAIL_ERROR_DESC;
1475 for(i=0; i<errors.length; i++) {
1490 getIeAccount : function(ieId) {
1494 overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1495 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1497 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1501 * Iterates through TreeView nodes to apply styles dependent nature of node
1503 renderTree:function() {
1504 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1508 //Sets the style for any nodes that need it.
1509 setNodeStyle : function(node) {
1510 if (!node.data.origText) {
1511 node.data.origText = node.data.text;
1514 if (typeof(node.data.unseen) != 'undefined') {
1515 if (node.data.unseen > 0) {
1516 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1519 node.setUpLabel(node.data.origText);
1522 node.setUpLabel('<span>' + node.data.origText + '</span>');
1524 SE.accounts.setupDDTarget(node);
1527 setupDDTarget : function(node) {
1528 if (node.ddTarget) {
1529 node.ddTarget.removeFromGroup();
1530 delete node.ddTarget;
1532 var id = node.getElId();
1533 var num = id.substring(4);
1534 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1535 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1536 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1538 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1540 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1541 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1546 * Async call to rebuild the folder list. After a folder delete or account delete
1548 rebuildFolderList : function() {
1549 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1550 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1554 * Returns the number of remote accounts the user has active.
1556 getAccountCount : function() {
1559 for(i=0; i<tree._nodes.length; i++) {
1560 var node = tree._nodes[i];
1562 if(typeof(node) != 'undefined' && node.data.ieId) {
1570 ///////////////////////////////////////////////////////////////////////////////
1575 ///////////////////////////////////////////////////////////////////////////////
1576 //// CONTEXT MENU CALLS
1579 assignToDialogue : null,
1581 * Archives from context menu
1583 * @param string ieId
1584 * @param string folder
1586 _archiveToSugar : function(uids, ieId, folder) {
1589 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1590 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1593 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1597 * Archives from context menu
1599 archiveToSugar : function(menuItem) {
1600 SE.contextMenus.emailListContextMenu.hide();
1602 var rows = SE.grid.getSelectedRows();
1604 /* iterate through available rows JIC a row is deleted - use first available */
1605 for(var i=0; i<rows.length; i++) {
1606 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1608 var data = SE.grid.getRecord(rows[0]).getData();
1609 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1613 * Popup the printable version and start system's print function.
1615 viewPrintable : function(menuItem) {
1616 var rows = SE.grid.getSelectedRows();
1617 var data = SE.grid.getRecord(rows[0]).getData();
1618 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1622 * Marks email flagged on mail server
1624 markRead : function(type, contextMenuId) {
1625 SE.contextMenus.markEmail('read');
1629 * Assign this emails to people based on assignment rules
1631 assignEmailsTo : function(type, contextMenuId) {
1632 if(!SE.contextMenus.assignToDialogue)
1634 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1638 constraintoviewport: true,
1642 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1646 Dom.removeClass("assignToDiv", "yui-hidden");
1647 SE.contextMenus.assignToDialogue.render();
1648 SE.contextMenus.assignToDialogue.show();
1652 * Marks email flagged on mail server
1654 markFlagged : function(contextMenuId) {
1655 SE.contextMenus.markEmail('flagged');
1659 * Marks email unflagged on mail server
1661 markUnflagged : function(contextMenuId) {
1662 SE.contextMenus.markEmail('unflagged');
1666 * Marks email unread on mail server
1668 markUnread : function() {
1669 SE.contextMenus.markEmail('unread');
1673 * Deletes an email from context menu
1675 markDeleted : function() {
1676 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1677 document.getElementById('_blank').innerHTML = "";
1678 SE.contextMenus.markEmail('deleted');
1683 * generic call API to apply a flag to emails on the server and on sugar
1684 * @param string type "read" | "unread" | "flagged" | "deleted"
1686 markEmail : function(type) {
1687 SE.contextMenus.emailListContextMenu.hide();
1689 //var dm = SE.grid.getStore();
1690 //var uids = SE.grid.getSelectedRowIds();
1691 //var indexes = SE.grid.getSelectedRowIndexes();
1692 var rows = SE.grid.getSelectedRows();
1693 if (rows.length == 0)
1694 rows = [SE.contextMenus.currentRow];
1697 for(var i=0; i<rows.length; i++) {
1698 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1701 ser = YAHOO.lang.JSON.stringify(ser);
1703 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1704 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1710 if(type == 'read' || type == 'deleted') {
1712 for(var j=0; j<rows.length; j++) {
1713 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1715 SE.grid.getRecord(rows[j]).setData("seen", "1");
1718 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1720 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1721 var unseenCount = node.data.unseen;
1722 if (isNaN(unseenCount)) {
1725 var finalCount = parseInt(unseenCount) - count;
1726 node.data.unseen = finalCount;
1728 SE.accounts.renderTree();
1730 } else if(type == 'unread') {
1732 for(var j=0; j<rows.length; j++) {
1733 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1738 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1739 var unseenCount = node.data.unseen;
1740 if (isNaN(unseenCount)) {
1743 var finalCount = parseInt(unseenCount) + count;
1744 node.data.unseen = finalCount;
1745 SE.accounts.renderTree();
1748 if (type == 'unread') {
1749 for(var i=0; i<rows.length; i++) {
1750 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1754 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1755 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1759 * refreshes the ListView to show changes to cache
1761 markEmailCleanup : function() {
1762 SE.accounts.renderTree();
1764 SE.listView.refreshGrid();
1767 showAssignmentDialog : function() {
1768 if (SE.contextMenus.assignmentDialog == null) {
1769 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1771 SE.contextMenus.assignmentDialog.show();
1776 * shows the import dialog with only relate visible.
1778 relateTo : function() {
1779 SE.contextMenus.emailListContextMenu.hide();
1781 var rows = SE.grid.getSelectedRows();
1782 var data = SE.grid.getRecord(rows[0]).getData();
1783 var ieId = data.ieId;
1784 var folder = data.mbox;
1786 /* iterate through available rows JIC a row is deleted - use first available */
1787 for(var i=0; i<rows.length; i++) {
1788 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1790 var ser = JSON.stringifyNoSecurity(uids);
1792 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1796 * shows the import dialog with only relate visible.
1798 showDetailView : function() {
1799 SE.contextMenus.emailListContextMenu.hide();
1800 var rows = SE.grid.getSelectedRows();
1801 if (rows.length > 1) {
1802 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1805 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1806 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1807 /* iterate through available rows JIC a row is deleted - use first available */
1808 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1809 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1815 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1816 overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1817 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1821 * Opens multiple messages from ListView context click
1823 openMultiple : function() {
1824 SE.contextMenus.emailListContextMenu.hide();
1826 var rows = SE.grid.getSelectedRows();
1827 var uids = SE.listView.getUidsFromSelection();
1829 if(uids.length > 0) {
1830 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1831 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1832 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1837 * Replies/forwards email
1839 replyForwardEmailContext : function() {
1840 SE.contextMenus.emailListContextMenu.hide();
1842 var indexes = SE.grid.getSelectedRows();
1843 //var dm = SE.grid.getDataModel();
1846 for(var i=0; i<indexes.length; i++) {
1847 var row = SE.grid.getRecord(indexes[i]).getData();
1848 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1852 //show menu functions
1853 showEmailsListMenu : function(grid, row) {
1855 var data = row.getData();
1856 var draft = (data.type == "draft");
1857 var menu = SE.contextMenus.emailListContextMenu;
1862 if (data.mbox == 'sugar::Emails')
1863 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1865 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1867 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1868 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1869 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1870 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1872 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1875 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1877 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1878 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1879 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1880 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1881 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1884 if (data.mbox == "sugar::Emails")
1886 //Allow users to reassign imported emails
1887 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1888 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1889 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1890 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1894 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1895 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1899 showFolderMenu : function(grid, rowIndex, event) {
1901 var coords = event.getXY();
1902 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1906 SE.contextMenus.dv = {
1907 archiveToSugar : function(contextMenuId) {
1909 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1912 replyForwardEmailContext : function(all) {
1913 SE.contextMenus.detailViewContextMenu.hide();
1922 //// END SE.contextMenus
1923 ///////////////////////////////////////////////////////////////////////////////
1927 ///////////////////////////////////////////////////////////////////////////////
1930 consumeMetaDetail : function(ret) {
1931 // handling if the Email drafts
1932 if(ret.type == 'draft') {
1933 SE.composeLayout.c0_composeDraft();
1938 // cache contents browser-side
1939 SE._setDetailCache(ret);
1941 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1942 // 2 below must be in global context
1944 meta['panelId'] = SE.util.getPanelId();
1946 email = ret.meta.email;
1947 var out = displayTemplate.exec({
1948 'app_strings' : app_strings,
1950 'idx' : targetDiv.id,
1952 'email' : meta.email,
1953 'linkBeans' : linkBeans
1955 var tabLabel = meta.email.name;
1956 if (tabLabel != null && tabLabel.length > 25) {
1957 tabLabel = tabLabel.substring(0, 25) + "...";
1959 targetDiv.set("label", tabLabel);
1960 targetDiv.set("content", out);
1962 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1963 if (SUGAR.email2.util.isIe()) {
1964 displayEmailFrameDiv.style.height = "390px";
1966 displayEmailFrameDiv.style.height = "410px";
1969 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1970 displayFrame.contentWindow.document.write(email.description);
1971 displayFrame.contentWindow.document.close();
1973 // hide archive links
1974 if(ret.meta.is_sugarEmail) {
1975 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1976 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1978 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1979 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1984 consumeMetaPreview : function(ret) {
1985 // cache contents browser-side
1986 SE._setDetailCache(ret);
1990 var currrow = SE.grid.getLastSelectedRecord();
1991 currrow = SE.grid.getRecord(currrow);
1993 document.getElementById('_blank').innerHTML = '';
1996 // handling if the Email drafts
1997 if(ret.type == 'draft'){
1998 if (currrow.getData().uid == ret.uid) {
1999 SE.composeLayout.c0_composeDraft();
2004 if (currrow.getData().uid != ret.meta.uid) {
2008 // remove loading sprite
2009 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2010 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2012 meta['panelId'] = SE.util.getPanelId();
2013 email = ret.meta.email;
2015 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2016 'app_strings' : app_strings,
2020 'email' :meta.email,
2021 'linkBeans' : linkBeans
2023 // document.getElementById('_blank').innerHTML = meta.email;
2024 /* displayTemplate.append('_blank', {
2025 'app_strings' : app_strings,
2029 'email' :meta.email,
2030 'linkBeans' : linkBeans
2033 var displayFrame = document.getElementById('displayEmailFramePreview');
2034 displayFrame.contentWindow.document.write(email.description);
2035 displayFrame.contentWindow.document.close();
2037 SE.listViewLayout.resizePreview();
2039 // hide archive links
2040 if(ret.meta.is_sugarEmail) {
2041 document.getElementById("archiveEmailPreview").innerHTML = " ";
2042 document.getElementById("btnEmailViewPreview").style.display = "none";
2043 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2045 //hide view relationship link
2046 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2051 * wraps emailDelete() for single messages, comes from preview or tab
2053 emailDeleteSingle : function(ieId, uid, mbox) {
2054 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2055 // find active panel and close if the user double clicked the email to view.
2056 var activeTabId = SE.util.getPanelId();
2057 if(activeTabId != 'Preview')
2058 SE.innerLayout.get("activeTab").close();
2060 document.getElementById('_blank').innerHTML = "";
2063 uid = JSON.stringifyNoSecurity(ser);
2064 this.emailDelete(ieId, uid, mbox);
2069 * Sends async call to delete a given message
2072 emailDelete : function(ieId, uid, mbox) {
2073 overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2074 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2075 uid + "&ieId=" + ieId + "&folder=" + mbox);
2079 * retrieves one email to display in the preview pane.
2081 getEmailPreview : function() {
2082 var row = SUGAR.email2.listView.currentRow;
2083 var data = row.getData();
2084 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2085 var setRead = (data['seen'] == 0) ? true : false;
2086 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2087 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2092 * Imports one email into Sugar
2094 importEmail : function(ieId, uid, mbox) {
2095 SE.util.clearHiddenFieldValues('emailUIForm');
2097 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2099 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2100 AjaxObject.target = '';
2101 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2105 * Populates the frameFlex div with the contents of an email
2107 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2108 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2110 var mboxStr = new String(mbox);
2111 var compKey = mbox + uid;
2113 if(setRead == true) {
2114 SE.listView.boldUnreadRows()
2115 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2118 if(destination == SE.innerLayout) {
2120 * loading email into a tab, peer with ListView
2121 * targetDiv must remain in the global namespace as it is used by AjaxObject
2123 //Check if we already have a tab of the email open
2124 var tabs = SE.innerLayout.get("tabs");
2125 for (var t in tabs) {
2126 if (tabs[t].id && tabs[t].id == uid) {
2127 SE.innerLayout.set("activeTab", tabs[t]);
2132 targetDiv = new YAHOO.SUGAR.ClosableTab({
2133 label: loadingSprite,
2139 SE.innerLayout.addTab(targetDiv);
2141 // use cache if available
2142 if(SE.cache[compKey]) {
2143 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2145 // open email as peer-tab to listView
2146 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2147 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2150 // loading email into preview pane
2151 document.getElementById('_blank').innerHTML = loadingSprite;
2153 // use cache if available
2154 if(SE.cache[compKey]) {
2155 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2157 AjaxObject.forceAbort = true;
2158 // open in preview window
2159 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2160 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2165 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2167 if(mboxStr.substring(0,7) == 'sugar::') {
2168 // display an email from Sugar
2169 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2171 // display an email from an email server
2172 document.getElementById('emailUIAction').value = 'getSingleMessage';
2174 document.getElementById('mbox').value = mbox;
2175 document.getElementById('ieId').value = ieId;
2176 document.getElementById('uid').value = uid;
2178 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2180 AjaxObject.forceAbort = true;
2181 AjaxObject.target = '_blank';
2182 AjaxObject.startRequest(callback, null);
2186 * Retrieves multiple emails for DetailView
2188 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2189 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2190 SE.util.clearHiddenFieldValues('emailUIForm');
2192 var mboxStr = new String(mbox);
2194 uids = SE.util.cleanUids(uids);
2196 if(mboxStr.substring(0,7) == 'sugar::') {
2197 // display an email from Sugar
2198 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2199 document.getElementById('uid').value = uids;
2201 // display an email from an email server
2202 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2203 document.getElementById('mbox').value = mbox;
2204 document.getElementById('ieId').value = ieId;
2205 document.getElementById('uid').value = uids;
2208 var formObject = document.getElementById('emailUIForm');
2209 YAHOO.util.Connect.setForm(formObject);
2211 AjaxObject.target = 'frameFlex';
2212 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2214 if(setRead == true) {
2215 var c = uids.split(",");
2216 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2221 * Makes async call to get QuickCreate form
2222 * Renders a modal edit view for a given module
2224 quickCreate : function(module, ieId, uid, mailbox) {
2225 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2227 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2228 get += "&sugarEmail=true";
2231 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2235 * Makes async call to save a quick create
2238 saveQuickCreate : function(action) {
2239 var qcd = SE.detailView.quickCreateDialog;
2240 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2241 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2242 var theCallback = callbackQuickCreateSave;
2243 var accountType = '&sugarEmail=true';
2244 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2245 accountType = '&ieId=' + qcd.ieId;
2248 if (action == 'reply') {
2249 theCallback = callbackQuickCreateSaveAndReply;
2250 } else if (action == true) {
2251 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2253 formObject.action.value = 'EmailUIAjax';
2254 YAHOO.util.Connect.setForm(formObject);
2255 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2256 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2257 accountType + '&mbox=' + qcd.mbox);
2262 * Code to show/hide long list of email address in DetailView
2264 showCroppedEmailList : function(el) {
2265 el.style.display = 'none';
2266 el.previousSibling.style.display = 'inline'
2268 showFullEmailList : function(el) {
2269 el.style.display = 'none';
2270 el.nextSibling.style.display = 'inline';
2274 * Shows the QuickCreate overlay
2275 * @param string ieId
2277 * @param string mailbox
2279 showQuickCreate : function(ieId, uid, mailbox) {
2280 var panelId = SE.util.getPanelId();
2281 var context = document.getElementById("quickCreateSpan" + panelId);
2283 if (!SE.detailView.cqMenus)
2284 SE.detailView.cqMenus = {};
2286 if (SE.detailView.cqMenus[context])
2287 SE.detailView.cqMenus[context].destroy();
2289 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2291 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2294 for (var i=0; i < this.qcmodules.length; i++) {
2295 var module = this.qcmodules[i];
2297 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2300 onclick: { fn: function() {
2301 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2307 menu.render(document.body);
2312 * Displays the "View" submenu in the detailView
2313 * @param string ieId
2315 * @param string mailbox
2317 showViewMenu : function(ieId, uid, mailbox) {
2318 var panelId = SE.util.getPanelId();
2319 var context = "btnEmailView" + panelId;
2320 if (!SE.detailView.viewMenus)
2321 SE.detailView.viewMenus = {};
2323 if (SE.detailView.viewMenus[context])
2324 SE.detailView.viewMenus[context].destroy();
2326 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2328 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2332 (ieId == 'null' || ieId == null) ?
2333 //No ieId - Sugar Email
2335 text: app_strings.LBL_EMAIL_VIEW_RAW,
2336 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2339 //IeID exists, on a remote server
2341 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2342 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2344 text: app_strings.LBL_EMAIL_VIEW_RAW,
2345 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2348 menu.render(document.body);
2353 //#23108 jchi@07/17/2008
2354 menu.render('quickCreateSpan'+ panelId);*/
2355 //this.viewMenu = menu;
2356 //this.viewMenu.show(context);
2359 * Makes async call to get an email's headers
2361 viewHeaders : function(ieId, uid, mailbox) {
2362 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2363 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2367 * Makes async call to get a printable version
2369 viewPrintable : function(ieId, uid, mailbox) {
2370 if(mailbox == 'sugar::Emails') {
2371 // display an email from Sugar
2372 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2374 // display an email from an email server
2375 var emailUIAction = '&emailUIAction=getSingleMessage';
2378 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2379 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2383 * Makes async call to get an email's raw source
2385 viewRaw : function(ieId, uid, mailbox) {
2386 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2387 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2391 * Display all email addresses in detailview.
2393 displayAllAddrs : function(el) {
2394 el.style.display = 'none';
2395 Dom.getNextSibling(el).style.display = 'inline';
2398 //// END SE.detailView
2399 ///////////////////////////////////////////////////////////////////////////////
2403 ///////////////////////////////////////////////////////////////////////////////
2406 contextMenuFocus : new Object(),
2409 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2410 * SugarFolder ID - folder strings
2412 _createFolderId : function(node) {
2418 if(node.data.ieId) {
2419 /* we have a local Sugar folder */
2420 if(node.data.ieId == 'folder') {
2421 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2422 } else if(node.data.ieId.match(SE.reGUID)) {
2423 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2432 addChildNode : function(parentNode, childNode) {
2433 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2434 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2435 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2437 if(childNode.nodes) {
2438 if(childNode.nodes.length > 0) {
2439 for(j=0; j<childNode.nodes.length; j++) {
2440 var newChildNode = childNode.nodes[j];
2441 this.addChildNode(node, newChildNode);
2448 * Builds and returns a new TreeView Node
2449 * @param string name
2451 * @param int is_group
2454 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2455 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2457 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2458 node.expanded = expanded;
2459 node.data = new Object;
2460 node.data['id'] = id;
2461 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2462 node.data['label'] = name;
2463 node.data['ieId'] = 'folder';
2464 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2465 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2466 node.data['unseen'] = unseen;
2471 * ensures that a new folder has a valid name
2473 checkFolderName : function(name) {
2477 this.folderAdd(name);
2481 * Pings email servers for new email - forces refresh of folder pane
2483 checkEmailAccounts : function() {
2484 this.checkEmailAccountsSilent(true);
2487 checkEmailAccountsSilent : function(showOverlay) {
2488 if(typeof(SE.folders.checkingMail)) {
2489 clearTimeout(SE.folders.checkingMail);
2492 // don't stomp an on-going request
2493 if(AjaxObject.currentRequestObject.conn == null) {
2495 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2496 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2498 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2500 // wait 5 secs before trying again.
2501 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2506 * Starts check of all email Accounts using a loading bar for large POP accounts
2508 startEmailAccountCheck : function() {
2509 // don't do two checks at the same time
2510 if(!AjaxObject.requestInProgress()) {
2511 overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2512 SE.accounts.ieIds = SE.folders.getIeIds();
2513 if (SE.accounts.ieIds.length > 0) {
2514 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2515 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2520 // wait 5 secs before trying again.
2521 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2526 * Checks a single Account check based on passed ieId
2528 startEmailCheckOneAccount : function(ieId, synch) {
2535 var node = SE.clickedFolderNode;
2536 if (node && !synch) {
2537 mbox = node.data.mbox;
2539 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2540 SE.accounts.ieIds = [ieId];
2541 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2542 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2547 * Empties trash for subscribed accounts
2549 emptyTrash : function() {
2550 SE.contextMenus.frameFoldersContextMenu.hide();
2551 overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2552 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2556 * Clears Cache files of the inboundemail account
2558 clearCacheFiles : function(ieId) {
2559 SE.contextMenus.frameFoldersContextMenu.hide();
2560 overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2561 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2566 * Returns an array of all the active accounts in the folder view
2568 getIeIds : function() {
2570 var root = SE.tree.getRoot();
2571 for(i=0; i < root.children.length; i++) {
2572 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2573 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2574 ieIds.push(root.children[i].children[0].data.ieId);
2581 * loads folder lists in Settings->Folders
2583 lazyLoadSettings : function() {
2584 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2585 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2589 * After the add new folder is done via folders tab on seetings, this function should get called
2590 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2592 loadSettingFolder : function() {
2593 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2594 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2598 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2600 removeSugarFolders : function() {
2602 var root = tree.getRoot();
2603 var folder = SE.util.findChildNode(root, "ieId", "folder");
2605 tree.removeNode(folder);
2606 folder = SE.util.findChildNode(root, "ieId", "folder");
2608 if (!root.childrenRendered) {
2609 root.childrenRendered = true;
2613 rebuildFolders : function(silent) {
2614 if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2615 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2621 * Updates TreeView with Sugar Folders
2623 setSugarFolders : function(delay) {
2624 this.removeSugarFolders();
2625 //AjaxObject.forceAbort = true;
2626 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2630 * Takes async data object and creates the sugar folders in TreeView
2632 setSugarFoldersEnd : function(o) {
2633 var root = SE.tree.getRoot();
2634 addChildNodes(root, {nodes: o});
2635 SE.accounts.renderTree();
2636 //If nothing is loaded in the grid, load "My Inbox"
2637 if (SE.grid.params.ieId == "undefined") {
2638 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2642 startCheckTimer : function() {
2643 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2644 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2646 if(typeof(SE.folders.checkTimer) != 'undefined') {
2647 clearTimeout(SE.folders.checkTimer);
2650 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2651 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2653 SE.userPrefs.emailSettings.firstAutoCheck = true;
2654 SE.folders.checkEmailAccountsSilent(false);
2660 * makes an async call to save user preference and refresh folder view
2661 * @param object SELECT list object
2663 setFolderSelection : function() {
2664 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2666 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2667 var a_active_accnts = "";
2668 for(i=0;i<a_rs.length;i++)
2670 var t_record = a_rs[i];
2671 var is_active = t_record.getData('is_active');
2673 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2676 if(a_active_accnts == "")
2677 a_active_accnts = "&ieIdShow[]=";
2679 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2681 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2685 * makes async call to save user preference for a given node's open state
2686 * @param object node YUI TextNode object
2688 setOpenState : function(node) {
2689 SE.util.clearHiddenFieldValues('emailUIForm');
2690 var nodePath = node.data.id;
2691 var nodeParent = node.parent;
2693 while(nodeParent != null) {
2694 // root node has no ID param
2695 if(nodeParent.data != null) {
2696 nodePath = nodeParent.data.id + "::" + nodePath;
2699 var nodeParent = nodeParent.parent;
2702 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2703 document.getElementById('focusFolder').value = nodePath;
2705 if(node.expanded == true) {
2706 document.getElementById('focusFolderOpen').value = 'open';
2708 document.getElementById('focusFolderOpen').value = 'closed';
2711 var formObject = document.getElementById('emailUIForm');
2712 YAHOO.util.Connect.setForm(formObject);
2714 AjaxObject.startRequest(null, null);
2717 getNodeFromMboxPath : function(path) {
2718 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2719 var a = JSON.parse(path);
2721 var node = tree.getRoot();
2724 while(i < a.length) {
2725 node = this.getChildNodeFromLabel(node, a[i]);
2732 getChildNodeFromLabel : function(node, nodeLabel) {
2733 for(i=0; i<node.children.length; i++) {
2734 if(node.children[i].data.id == nodeLabel) {
2735 return node.children[i];
2741 * returns the node that presumably under the user's right-click
2743 getNodeFromContextMenuFocus : function() {
2744 //// get the target(parent) node
2745 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2747 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2749 // filter local folders
2750 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2751 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2752 if(target.id == '') {
2753 target = target.parentNode;
2760 var targetNode = document.getElementById(target.id);
2761 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2764 var matches = re.exec(targetNode.id);
2766 return document.getElementById(ygtvlabelel1);
2772 // usually parent node
2773 matches = re.exec(targetNode.parentNode.id);
2780 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2781 parentNode.expand();
2787 * Decrements the Unread Email count in folder text
2788 * @param string ieId ID to look for
2789 * @param string mailbox name
2790 * @param count how many to decrement
2792 decrementUnreadCount : function(ieId, mbox, count) {
2797 if(mbox.indexOf("sugar::") === 0) {
2798 var node = this.getNodeFromId(ieId);
2800 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2803 var unseen = node.data.unseen;
2805 var check = unseen - count;
2806 var finalCount = (check >= 0) ? check : 0;
2807 node.data.unseen = finalCount;
2809 SE.accounts.renderTree();
2814 * gets the TreeView node with a given ID/ieId
2815 * @param string id ID to look for
2816 * @return object Node
2818 getNodeFromId : function(id) {
2819 SE.folders.focusNode = null;
2820 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2821 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2822 SE.folders.focusNode = this;
2826 return SE.folders.focusNode;
2830 * Uses ieId and mailbox to try to find a node in the tree
2832 getNodeFromIeIdAndMailbox : function(id, mbox) {
2833 SE.folders.focusNode = null;
2834 if (mbox == "sugar::Emails") {
2838 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2839 if (varsarray instanceof Array) {
2840 if (this.data.ieId && this.data.ieId == varsarray[0]
2841 && this.data.mbox == varsarray[1]) {
2842 SE.folders.focusNode = this;
2846 if (this.data.ieId && this.data.ieId == varsarray) {
2847 SE.folders.focusNode = this;
2851 }, null, [id, mbox]);
2852 return SE.folders.focusNode;
2855 unhighliteAll : function() {
2856 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2860 * Displays a short form
2862 folderAdd : function() {
2863 SE.contextMenus.frameFoldersContextMenu.hide();
2865 var node = SE.clickedFolderNode;
2867 if(node != null && node.data) {
2868 overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2869 app_strings.LBL_EMAIL_SETTINGS_NAME,
2870 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2872 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2876 folderAddRegisterEnter : function() {
2877 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2878 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2879 this.buttons[1].handler);
2881 this.enterKeyListener.enable();
2884 folderRemoveRegisterEnter : function() {
2885 this.enterKeyListener.disable();
2888 folderAddXmlCall : function(name) {
2889 if (trim(name) == "") {
2890 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2893 name = escape(name);
2897 var parentNode = SE.clickedFolderNode;
2899 this.contextMenuFocus = parentNode;
2901 if(parentNode.data.ieId) {
2902 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2906 if(type == 'imap') {
2907 // make an IMAP folder
2908 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2909 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2910 } else if(type == 'sugar') {
2911 // make a Sugar folder
2912 if(SE.folders.isUniqueFolderName(name)) {
2913 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2914 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2916 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2917 SE.folders.folderAdd();
2921 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2924 // hide add-folder diaglogue
2925 SE.e2overlay.hide();
2929 * Removes either an IMAP folder or a Sugar Folder
2931 folderDelete : function() {
2932 SE.contextMenus.frameFoldersContextMenu.hide();
2934 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2936 var parentNode = SE.clickedFolderNode;
2938 if(parentNode != null && parentNode.data) {
2939 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2940 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2944 AjaxObject.target = 'frameFlex';
2946 if(parentNode.data.ieId != 'folder') {
2947 // delete an IMAP folder
2948 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2950 // delete a sugar folder
2951 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2953 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2954 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2956 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2962 * Rename folder form
2965 folderRename : function() {
2966 SE.contextMenus.frameFoldersContextMenu.hide();
2967 var node = SE.clickedFolderNode;
2970 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2971 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2975 overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2976 app_strings.LBL_EMAIL_SETTINGS_NAME,
2978 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2980 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2985 * fills an Object with key-value pairs of available folders
2987 getAvailableFoldersObject : function() {
2988 var ret = new Object();
2989 var tree = SE.tree.root;
2992 for(var i=0; i<tree.children.length; i++) {
2993 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
2996 ret['none'] = app_strings.LBL_NONE;
3003 * Fills in key-value pairs for dependent dropdowns
3004 * @param object ret Associative array
3005 * @param object node TreeView node in focus
3006 * @param string currentPath Built up path thus far
3007 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3009 getFolderFromChild : function(ret, node, currentPath, spacer) {
3010 if(node.data != null && node.depth > 0) {
3011 /* handle visual separtors differentiating b/t mailserver and local */
3012 if(node.data.ieId && node.data.ieId == 'folder') {
3013 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3017 ret['spacer0'] = spacer;
3018 } else if(ret.spacer0 != spacer) {
3019 ret['spacer1'] = spacer
3022 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3023 var depthMarker = currentPath;
3024 var retIndex = SE.folders._createFolderId(node);
3025 ret[retIndex] = depthMarker + theLabel;
3028 if(node.children != null) {
3030 currentPath += theLabel + "/";
3033 for(var i=0; i<node.children.length; i++) {
3034 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3042 * Wrapper to refresh folders tree
3044 getFolders : function() {
3045 SE.accounts.rebuildFolderList();
3049 * handles events around folder-rename input field changes
3050 * @param object YUI event object
3052 handleEnter : function(e) {
3053 switch(e.browserEvent.type) {
3055 e.preventDefault(); // click in text field
3059 SE.folders.submitFolderRename(e);
3063 var kc = e.browserEvent.keyCode;
3067 SE.folders.submitFolderRename(e);
3071 e.preventDefault(e);
3072 SE.folders.cancelFolderRename(e);
3079 * Called when a node is clicked on in the folder tree
3080 * @param node, The node clicked on
3081 * @param e, The click event
3083 handleClick : function(o) {
3085 //If the click was on a sugar folder
3086 if (node.data.ieId == "folder") {
3087 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3090 SE.listView.populateListFrame(node, node.data.ieId, false);
3092 //eval(node.data.click);
3097 * Called when a node is right-clicked on in the folder tree
3099 handleRightClick : function(e) {
3100 YAHOO.util.Event.preventDefault(e);
3102 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3103 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3105 //If the click was on a sugar folder
3106 SE.clickedFolderNode = node;
3107 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3108 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3109 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3110 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3111 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3112 menu.getItem(3).cfg.setProperty("disabled", false);
3113 menu.getItem(4).cfg.setProperty("disabled", false);
3114 menu.getItem(5).cfg.setProperty("disabled", false);
3115 menu.getItem(6).cfg.setProperty("disabled", true);
3117 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3118 menu.getItem(0).cfg.setProperty("disabled", true);
3119 menu.getItem(1).cfg.setProperty("disabled", true);
3120 menu.getItem(2).cfg.setProperty("disabled", true);
3121 menu.getItem(3).cfg.setProperty("disabled", true);
3122 menu.getItem(4).cfg.setProperty("disabled", true);
3124 if (node.data.protocol != null) {
3125 menu.getItem(6).cfg.setProperty("disabled", false);
3127 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3128 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3129 //Sent or Draft folders
3130 menu.getItem(3).cfg.setProperty("disabled", true);
3131 menu.getItem(4).cfg.setProperty("disabled", true);
3132 menu.getItem(5).cfg.setProperty("disabled", true);
3135 //For group with auto inbound, disable everything.
3136 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3138 menu.getItem(0).cfg.setProperty("disabled", true);
3139 menu.getItem(1).cfg.setProperty("disabled", true);
3140 menu.getItem(2).cfg.setProperty("disabled", true);
3141 menu.getItem(3).cfg.setProperty("disabled", true);
3142 menu.getItem(4).cfg.setProperty("disabled", true);
3143 menu.getItem(5).cfg.setProperty("disabled", true);
3144 menu.getItem(6).cfg.setProperty("disabled", true);
3147 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3152 * Called when a row is dropped on a node
3154 handleDrop : function(rows, targetFolder) {
3155 var rowData = rows[0].getData();
3156 if (rowData.mbox != targetFolder.data.mbox) {
3157 var srcIeId = rowData.ieId;
3158 var srcFolder = rowData.mbox;
3159 var destIeId = targetFolder.data.ieId;
3160 var destFolder = targetFolder.data.mbox;
3162 for(var i=0; i<rows.length; i++) {
3163 uids[i] = rows[i].getData().uid;
3165 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3170 * Called when something is dragged over a Folder Node
3172 dragOver : function(dragObject) {
3177 * Determines if a folder name is unique to the folder tree
3178 * @param string name
3180 isUniqueFolderName : function(name) {
3181 uniqueFolder = true;
3182 var root = SE.tree.getRoot();
3183 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3184 if (this.attributes && this.attributes.ieId == "folder") {
3185 if (this.attributes.text == name) {
3186 uniqueFolder = false;
3191 return uniqueFolder;
3195 * Makes async call to rename folder in focus
3196 * @param object e Event Object
3198 submitFolderRename : function(newName) {
3199 if (trim(newName) == "") {
3200 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3203 newName = escape(newName);
3204 var node = SE.clickedFolderNode;
3205 var origName = node.data.text
3207 if (newName == origName) {
3210 if(SE.folders.isUniqueFolderName(newName)) {
3211 overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3212 if (node.data.ieId == "folder") {
3214 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3217 //IMAP folder or POP mailbox
3218 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3219 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3220 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3224 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3229 moveFolder : function(folderId, parentFolderId) {
3230 if (folderId != parentFolderId)
3232 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3233 + folderId + "&newParentId=" + parentFolderId);
3238 * makes async call to do a full synchronization of all accounts
3240 synchronizeAccounts : function() {
3241 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3242 overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3243 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3248 * Updates user's folder subscriptsion (Sugar only)
3249 * @param object SELECT DOM object in focus
3250 * @param string type of Folder selection
3252 updateSubscriptions : function() {
3253 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3257 select = document.getElementById('userFolders');
3259 for(i=0; i<select.options.length; i++) {
3260 var opt = select.options[i];
3261 if(opt.selected && opt.value != "") {
3265 active += opt.value;
3269 //Add the group folder ids.
3270 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3271 for(i=0; i<group_folders.length; i++)
3273 active += ("::" + group_folders[i]);
3276 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3279 * Updates user's group folder subscriptsion (Sugar only)
3280 * @param ieID The group folder to add to the tree view
3282 retrieveGroupFolderSubscriptions : function() {
3284 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3285 var activeGroupFolders = "";
3286 var activeGroupIds = [];
3287 for(i=0;i<a_rs.length;i++)
3289 var t_record = a_rs[i];
3290 var is_active = t_record.getData('is_active');
3291 var isGroupFolder = t_record.getData('has_groupfolder');
3292 var ieID = t_record.getData('id');
3296 activeGroupIds.push(ieID);
3300 return activeGroupIds;
3305 SE.folders.checkEmail2 = function() {
3306 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3308 //// END FOLDERS OBJECT
3309 ///////////////////////////////////////////////////////////////////////////////
3312 ///////////////////////////////////////////////////////////////////////////////
3315 * Keypress Event capture and processing
3318 overall : function(e) {
3319 switch(e.charCode) {
3321 if(e.ctrlKey || e.altKey) {
3322 var focusRegion = SE.innerLayout.regions.center;
3323 if(focusRegion.activePanel.closable == true) {
3324 focusRegion.remove(focusRegion.activePanel);
3332 ///////////////////////////////////////////////////////////////////////////////
3335 ///////////////////////////////////////////////////////////////////////////////
3338 * ListView object methods and attributes
3344 * Fills the ListView pane with detected messages.
3346 populateListFrame : function(node, ieId, forceRefresh) {
3347 SE.innerLayout.selectTab(0);
3348 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3350 Dom.get('_blank').innerHTML = "";
3351 SE.grid.params['emailUIAction'] = 'getMessageList';
3352 SE.grid.params['mbox'] = node.data.mbox;
3353 SE.grid.params['ieId'] = ieId;
3354 forcePreview = true; // loads the preview pane with first item in grid
3355 SE.listView.refreshGrid();
3359 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3361 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3362 SE.innerLayout.selectTab(0);
3363 Dom.get('_blank').innerHTML = "";
3364 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3365 SE.grid.params['ieId'] = node.data.id;
3366 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3367 SE.listView.refreshGrid();
3371 * Sets sort order as user preference
3374 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3376 ieName = ieNamePassed;
3377 focusFolder = focusFolderPassed;
3379 SE.util.clearHiddenFieldValues('emailUIForm');
3380 var previousSort = document.getElementById('sortBy').value;
3382 document.getElementById('sortBy').value = sortBy;
3383 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3384 document.getElementById('focusFolder').value = focusFolder;
3385 document.getElementById('ieId').value = ieId;
3387 if(sortBy == previousSort) {
3388 document.getElementById('reverse').value = '1';
3391 var formObject = document.getElementById('emailUIForm');
3392 YAHOO.util.Connect.setForm(formObject);
3394 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3399 * Enables click/arrow select of grid items which then populate the preview pane.
3401 selectFirstRow : function() {
3402 SE.grid.selModel.selectFirstRow();
3405 selectLastRow : function() {
3406 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3409 setEmailListStyles : function() {
3410 SE.listView.boldUnreadRows();
3412 var ds = SE.grid.getStore();
3413 if (SE.grid.getSelections().length == 0) {
3414 document.getElementById('_blank').innerHTML = '';
3418 if(typeof(ds.baseParams.mbox) != 'undefined') {
3419 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3420 var cm = SE.grid.getColumnModel();
3421 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3422 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3424 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3425 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3429 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3430 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3433 // 4/20/2007 added to hide overlay after search
3435 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3436 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3437 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3438 if (node) node.data.unseen = unread;
3440 SE.accounts.renderTree();
3443 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3444 if(forcePreview && ds.totalCount > 0) {
3445 SE.detailView.getEmailPreview();
3446 forcePreview = false;
3451 * Removes a row if found via its UID
3453 removeRowByUid : function(uid) {
3454 uid = new String(uid);
3455 uids = uid.split(',');
3456 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3458 for(j=0; j<uids.length; j++) {
3459 var theUid = uids[j];
3460 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3461 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3462 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3468 displaySelectedEmails : function(rows) {
3469 var dm = SE.grid.getDataModel();
3472 for(i=0; i<rows.length; i++) {
3473 var rowIndex = rows[i].rowIndex;
3474 var metadata = dm.data[rowIndex];
3479 uids += metadata[5];
3481 // unbold unseen email
3482 this.unboldRow(rowIndex);
3485 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3489 * exception handler for data load failures
3491 loadException : function(dataModel, ex, response) {
3496 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3497 * @param string sourceIeId Email's source I-E id
3498 * @param string sourceFolder Email's current folder
3499 * @param destinationIeId Destination I-E id
3500 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3502 * @param array emailUids Array of email's UIDs
3504 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3505 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3506 overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3508 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3509 // remove rows from visibility
3510 for(row in selectedRows) {
3511 //SE.grid.getStore().remove(row);
3514 var baseUrl = '&sourceIeId=' + sourceIeId +
3515 '&sourceFolder=' + sourceFolder +
3516 '&destinationIeId=' + destinationIeId +
3517 '&destinationFolder=' + destinationFolder;
3520 for(i=0; i<emailUids.length; i++) {
3522 uids += app_strings.LBL_EMAIL_DELIMITER;
3524 uids += emailUids[i];
3526 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3527 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3529 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3535 * Unbolds text in the grid view to denote read status
3537 markRead : function(index, record) {
3538 // unbold unseen email
3539 var row = SE.grid.getRecord(record);
3540 row.getData().seen = 1;
3541 SE.grid.getTrEl(record).style.fontWeight = "normal";
3545 * grid row output, bolding unread emails
3547 boldUnreadRows : function() {
3548 // bold unread emails
3549 var trEl = SE.grid.getFirstTrEl();
3550 while(trEl != null) {
3551 if(SE.grid.getRecord(trEl).getData().seen == "0")
3552 trEl.style.fontWeight = "bold";
3554 trEl.style.fontWeight = "";
3555 trEl = SE.grid.getNextTrEl(trEl);
3560 * Show preview for an email if 1 and only 1 is selected
3561 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3563 handleRowSelect : function(e) {
3564 if(e.selectedRows.length == 1) {
3565 SE.detailView.getEmailPreview();
3569 handleDrop : function(e, dd, targetId, e2) {
3571 case 'htmleditordiv':
3572 var rows = SE.grid.getSelectedRows();
3573 if(rows.length > 0) {
3574 SE.listView.displaySelectedEmails(rows);
3579 var targetElId = new String(targetId);
3580 var targetIndex = targetElId.replace('ygtvlabelel',"");
3581 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3582 var dm = SE.grid.getDataModel();
3583 var emailUids = new Array();
3584 var destinationIeId = targetNode.data.ieId;
3585 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3588 var rows = SE.grid.getSelectedRows();
3589 // iterate through dragged rows
3590 for(i=0; i<rows.length; i++) {
3591 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3592 var rowIndex = rows[i].rowIndex;
3593 var dataModelRow = dm.data[rowIndex];
3594 var sourceIeId = dataModelRow[7];
3595 var sourceFolder = dataModelRow[6];
3596 emailUids[i] = dataModelRow[5];
3599 // event wrapped call - need FQ
3600 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3601 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3607 * Hack-around to get double-click and single clicks to work on the grid
3608 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3610 handleClick : function(o) {
3611 SUGAR.email2.grid.clearTextSelection();
3613 var el = SUGAR.email2.grid.getSelectedRows();
3615 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3616 if ( el.length == 1)
3619 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3620 SUGAR.email2.listView.currentRowIndex = rowId;
3621 clearTimeout(SUGAR.email2.detailView.previewTimer);
3622 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3627 * Custom handler for double-click/enter
3628 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3630 getEmail : function(e) {
3631 var rows = SE.grid.getSelectedRows();
3632 var row = SE.grid.getRecord(rows[0]).getData();
3634 clearTimeout(SE.detailView.previewTimer);
3635 document.getElementById("_blank").innerHTML = "";
3637 if(row.type != "draft") {
3638 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3640 // circumventing yui-ext tab generation, let callback handler build new view
3641 SE.util.clearHiddenFieldValues('emailUIForm');
3642 //function(uid, mbox, ieId, setRead, destination) {
3643 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3644 document.getElementById('uid').value = row.uid; // uid;
3645 document.getElementById('mbox').value = row.mbox; // mbox;
3646 document.getElementById('ieId').value = row.ieId; // ieId;
3648 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3649 AjaxObject.target = '_blank';
3650 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3655 * Retrieves a row if found via its UID
3659 getRowIndexByUid : function(uid) {
3660 uid = new String(uid);
3661 uids = uid.split(',');
3663 for(j=0; j<uids.length; j++) {
3664 var theUid = uids[j];
3666 for(i=0; i<SE.grid.getStore().data.length; i++) {
3667 if(SE.grid.getStore().data[i].id == theUid) {
3675 * Returns the UID's of the seleted rows
3678 getUidsFromSelection : function() {
3679 var rows = SE.grid.getSelectedRows();
3681 /* iterate through available rows JIC a row is deleted - use first available */
3682 for(var i=0; i<rows.length; i++) {
3683 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3688 refreshGrid : function() {
3689 SE.grid.getDataSource().sendRequest(
3690 SUGAR.util.paramsToUrl(SE.grid.params),
3691 SE.grid.onDataReturnInitializeTable,
3697 //// END SE.listView
3698 ///////////////////////////////////////////////////////////////////////////////
3700 ///////////////////////////////////////////////////////////////////////////////
3704 * sends search criteria
3705 * @param reference element search field
3707 search : function(el) {
3708 var searchCriteria = new String(el.value);
3710 if(searchCriteria == '') {
3711 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3715 var safeCriteria = escape(searchCriteria);
3717 var accountListSearch = document.getElementById('accountListSearch');
3718 //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3720 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3721 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3722 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3723 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3724 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3729 * sends advanced search criteria
3731 searchAdvanced : function() {
3732 var formObject = document.getElementById('advancedSearchForm');
3735 //Set assigned user id to blank if name is not present.
3736 if (formObject.elements['assigned_user_name'].value == "")
3737 formObject.elements['assigned_user_id'].value = "";
3739 for(i=0; i<formObject.elements.length; i++) {
3740 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3743 if(formObject.elements[i].type == 'text') {
3744 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3746 if(formObject.elements[i].type == 'hidden') {
3747 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3749 if(formObject.elements[i].type == 'select-one') {
3750 var el = formObject.elements[i];
3751 var v = el.options[el.selectedIndex].value;
3754 SE.grid.params[el.name] = v;
3757 //Clear previous search results if necessary
3758 if(typeof( SE.grid.params[el.name]) != 'undefined')
3759 delete SE.grid.params[el.name]
3766 if(! this.validateSearchFormInput() )
3769 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3770 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3771 var accountListSearch = document.getElementById('accountListSearch');
3772 SE.listView.refreshGrid();
3774 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3779 * Validates the search form inputs to ensure all parameters are valid
3782 validateSearchFormInput: function()
3784 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3785 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3786 var dateCheck = check_form('advancedSearchForm');
3788 //If the parent type is selected ensure the user selected a parent_id.
3789 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3795 * Toggles the advanced options, either hidding or showing the selection.
3797 toggleAdvancedOptions: function()
3799 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3801 for(var i=0;i<el.length;i++)
3803 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3804 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3806 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3810 * clears adv search form fields
3812 searchClearAdvanced : function() {
3813 var form = document.getElementById('advancedSearchForm');
3815 for(i=0; i<form.elements.length; i++) {
3816 if(form.elements[i].type != 'button') {
3817 form.elements[i].value = '';
3823 //////////////////////////////////////////////////////////////////////////////
3826 //////////////////////////////////////////////////////////////////////////////
3829 /******************************************************************************
3830 * USER SIGNATURES calls stolen from Users module
3831 *****************************************************************************/
3832 createSignature : function(record, the_user_id) {
3833 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3835 URL += "&record="+record;
3837 if(the_user_id != "") {
3838 URL += "&the_user_id="+the_user_id;
3840 var windowName = 'email_signature';
3841 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3843 var win = window.open(URL, windowName, windowFeatures);
3844 if(win && win.focus) {
3845 // put the focus on the popup if the browser supports the focus() method
3850 deleteSignature : function() {
3851 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3852 overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3853 var singature_id = document.getElementById('signature_id').value;
3854 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3858 saveOptionsGeneral : function(displayMessage) {
3859 var formObject = document.getElementById('formEmailSettingsGeneral');
3860 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3861 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3864 YAHOO.util.Connect.setForm(formObject);
3865 SE.composeLayout.emailTemplates = null;
3867 AjaxObject.target = 'frameFlex';
3868 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3871 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3873 SE.settings.settingsDialog.hide();
3877 * Shows settings container screen
3879 showSettings : function() {
3880 if(!SE.settings.settingsDialog) {
3881 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3887 constraintoviewport: true
3889 dlg.showEvent.subscribe( function (){
3890 var el = this.element;
3891 var viewH = YAHOO.util.Dom.getViewportHeight();
3892 if (this.header && el && viewH - 50 < el.clientHeight) {
3893 var body = this.header.nextElementSibling;
3894 body.style.overflow = "auto";
3895 body.style.height = (viewH - 50) + "px";
3898 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3899 dlg.setBody('<div id="settingsTabDiv"/>');
3900 dlg.beforeRenderEvent.subscribe(function() {
3901 var dd = new YAHOO.util.DDProxy(dlg.element);
3902 dd.setHandleElId(dlg.header);
3903 dd.on('endDragEvent', function() {
3909 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3910 var tabContent = Dom.get("tab_general");
3911 tp.addTab(new YAHOO.widget.Tab({
3912 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3914 content : tabContent.innerHTML,
3915 id : "generalSettings",
3918 tabContent.parentNode.removeChild(tabContent);
3919 tabContent = Dom.get("tab_accounts");
3920 var accountTab = new YAHOO.widget.Tab({
3921 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3923 content : tabContent.innerHTML,
3924 id : "accountSettings"
3926 tp.addTab(accountTab);
3927 tabContent.parentNode.removeChild(tabContent);
3929 tp.appendTo(dlg.body);
3932 SE.settings.settingsDialog.show();
3933 SE.folders.lazyLoadSettings();
3934 SE.accounts.lazyLoad();
3938 lazyLoadRules : function() {
3939 if(false/*!SE.settings.rules*/) {
3940 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3945 //// END SE.settings
3946 ///////////////////////////////////////////////////////////////////////////////
3949 /******************************************************************************
3951 *****************************************************************************/
3952 function removeHiddenNodes(nodes, grid) {
3954 for(var i = nodes.length - 1; i > -1; i--) {
3955 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3956 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3962 function strpad(val) {
3963 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3966 function refreshTodos() {
3967 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3968 AjaxObject.target = 'todo';
3969 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3972 /******************************************************************************
3973 * MUST STAY IN GLOBAL NAMESPACE
3974 *****************************************************************************/
3975 function refresh_signature_list(signature_id, signature_name) {
3976 var field=document.getElementById('signature_id');
3978 for (var i=0; i < field.options.length; i++) {
3979 if (field.options[i].value == signature_id) {
3980 if (field.options[i].selected==false) {
3981 field.options[i].selected=true;
3986 //add item to selection list.
3988 var newElement=document.createElement('option');
3989 newElement.text=signature_name;
3990 newElement.value=signature_id;
3991 field.options.add(newElement);
3992 newElement.selected=true;
3995 //enable the edit button.
3996 var field1=document.getElementById('edit_sig');
3997 field1.style.visibility="inherit";
3998 var deleteButt = document.getElementById('delete_sig');
3999 deleteButt.style.visibility="inherit";
4002 function setDefaultSigId(id) {
4003 var checkbox = document.getElementById("signature_default");
4004 var default_sig = document.getElementById("signatureDefault");
4006 if(checkbox.checked) {
4007 default_sig.value = id;
4009 default_sig.value = "";
4013 function setSigEditButtonVisibility() {
4014 var field = document.getElementById('signature_id');
4015 var editButt = document.getElementById('edit_sig');
4016 var deleteButt = document.getElementById('delete_sig');
4017 if(field.value != '') {
4018 editButt.style.visibility = "inherit";
4019 deleteButt.style.visibility = "inherit";
4021 editButt.style.visibility = "hidden";
4022 deleteButt.style.visibility = "hidden";
4024 }// End of File modules/Emails/javascript/EmailUI.js
4026 /*********************************************************************************
4027 * SugarCRM is a customer relationship management program developed by
4028 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4030 * This program is free software; you can redistribute it and/or modify it under
4031 * the terms of the GNU Affero General Public License version 3 as published by the
4032 * Free Software Foundation with the addition of the following permission added
4033 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4034 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4035 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4037 * This program is distributed in the hope that it will be useful, but WITHOUT
4038 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4039 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4042 * You should have received a copy of the GNU Affero General Public License along with
4043 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4044 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4047 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4048 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4050 * The interactive user interfaces in modified source and object code versions
4051 * of this program must display Appropriate Legal Notices, as required under
4052 * Section 5 of the GNU Affero General Public License version 3.
4054 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4055 * these Appropriate Legal Notices must retain the display of the "Powered by
4056 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4057 * technical reasons, the Appropriate Legal Notices must display the words
4058 * "Powered by SugarCRM".
4059 ********************************************************************************/
4062 var sw = YAHOO.SUGAR,
4063 Event = YAHOO.util.Event,
4064 Connect = YAHOO.util.Connect,
4065 Dom = YAHOO.util.Dom
4068 ///////////////////////////////////////////////////////////////////////////////
4071 _contactCache : new Array(), // cache of contacts
4072 _dd : new Array(), // filtered list, same format as _contactCache
4073 _ddLists : new Array(), // list of Lists
4074 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4075 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4076 clickBubble : true, // hack to get around onclick event bubbling
4078 relatedBeanType : '',
4081 itemSpacing : 'white-space:nowrap; padding:2px;',
4087 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4089 initFixForDatatableSort: function () {
4090 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4091 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4092 var oColumn = this._oColumnSet.getColumn(column);
4095 // Validate TD element
4096 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4098 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4100 // Validate TH element
4102 elCell = this.getThEl(column);
4105 var allColumns = this._oColumnSet.flat;
4106 for(var i=0, len=allColumns.length; i<len; i++) {
4107 if(allColumns[i].getThEl().id === elCell.id) {
4108 oColumn = allColumns[i];
4119 cancelEdit : function() {
4120 if(this.editContactDialog)
4121 this.editContactDialog.hide();
4122 if(this.editMailingListDialog)
4123 this.editMailingListDialog.hide();
4127 * Clears filter form
4129 clear : function() {
4130 var t = document.getElementById('contactsFilter');
4136 * handle context-menu Compose-to call
4137 * @param string type 'contacts' or 'lists'
4139 composeTo : function(type, waited) {
4140 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4141 if (activePanel.substring(0, 10) != "composeTab") {
4142 SE.composeLayout.c0_composeNewEmail();
4143 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4144 SE.contextMenus.contactsContextMenu.hide();
4147 var idx = activePanel.substring(10);
4150 // determine if we have a selection to work with
4151 if(type == 'contacts') {
4152 var ids = SE.contactView.getSelectedRows();
4153 for (var i in ids) {
4154 rows[i] = SE.contactView.getRecord(ids[i]);
4156 removeHiddenNodes(rows, SE.contactView);
4160 if(rows.length > 0) {
4161 SE.composeLayout.handleDrop(
4162 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4163 null, rows, 'addressTO' + idx );
4165 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4169 editContact : function() {
4170 SE.contextMenus.contactsContextMenu.hide();
4171 var element = SE.contactView.getSelectedNodes()[0];
4173 if (element.className.indexOf('address-contact') > -1) {
4174 elementId = element.id;
4175 } else if (element.className.indexOf('address-exp-contact') > -1) {
4176 elementId = element.id.substring(2);
4182 * Filters contact entries based on user input
4184 filter : function(inputEl) {
4185 var ret = new Object();
4186 var re = new RegExp(inputEl.value, "gi");
4188 for(var i in this._contactCache) {
4189 if(this._contactCache[i].name.match(re)) {
4190 ret[i] = this._contactCache[i];
4194 this.buildContactList(ret);
4197 fullForm : function(id, module) {
4198 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4202 * returns a formatted email address from the addressBook cache
4204 getFormattedAddress : function(id) {
4205 var o = this._contactCache[id];
4206 var primaryEmail = '';
4208 for(var i=0; i<o.email.length; i++) {
4209 var currentEmail = o.email[i].email_address;
4211 if(o.email[i].primary_address == 1) {
4212 primaryEmail = o.email[i].email_address;
4216 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4217 var name = new String(o.name);
4218 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4219 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4225 * Sets up async call to query for matching contacts, users, etc.
4227 searchContacts : function() {
4228 var fn = document.getElementById('input_searchField').value;
4229 var pe = document.getElementById('input_searchPerson').value;
4231 var rb = document.getElementById('hasRelatedBean').checked;
4234 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4235 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4236 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4237 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4239 this.addressBookDataModel.params['related_bean_id'] = '';
4242 this.addressBookDataModel.params['search_field'] = fn;
4243 this.addressBookDataModel.params['person'] = pe;
4244 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4245 this.grid._oDataSource = this.addressBookDataModel;
4246 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4250 * Clear Search Crieteria For Addressbook
4252 clearAddressBookSearch : function() {
4253 document.getElementById('input_searchField').value = "";
4254 document.getElementById('input_searchPerson').selectedIndex = 0;
4258 * Opens modal select window to add contacts to addressbook
4260 selectContactsDialogue : function(destId) {
4261 if(!this.contactsDialogue) {
4262 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4266 constraintoviewport: true,
4268 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4269 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4271 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4273 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4274 dlg.setBody(body.innerHTML);
4275 dlg.renderEvent.subscribe(function() {
4276 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4277 if (iev && !SUGAR.isIE) {
4278 this.body.style.width = "950px";
4283 dlg.beforeRenderEvent.subscribe(function() {
4284 var dd = new YAHOO.util.DDProxy(dlg.element);
4285 dd.setHandleElId(dlg.header);
4286 dd.on('endDragEvent', function() {
4292 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4294 var tabContent = SUGAR.util.getAndRemove("searchForm");
4295 tp.addTab(new YAHOO.widget.Tab({
4296 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4298 content : tabContent.innerHTML,
4299 id : "addressSearchTab",
4303 var addListenerFields = ['input_searchPerson','input_searchField' ]
4304 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4305 if (e.keyCode == 13) {
4306 YAHOO.util.Event.stopEvent(e);
4307 SUGAR.email2.addressBook.searchContacts();
4311 this.contactsDialogue.render();
4314 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4315 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4319 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4320 var idx = activePanel.substring(10);
4322 SE.addressBook.idx = idx;
4325 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4326 document.getElementById('relatedBeanColumn').style.display = '';
4327 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4328 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4329 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4330 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4331 SE.addressBook.relatedBeanType = relatedBeanType;
4333 document.getElementById('relatedBeanColumn').style.display = 'none';
4334 document.getElementById('hasRelatedBean').checked = false;
4337 if (!SE.addressBook.grid)
4339 if (hasRelatedBeanId) {
4340 document.getElementById('hasRelatedBean').checked = true;
4342 AddressSearchGridInit();
4343 SE.addressBook.relatedBeanId = relatedBeanId;
4347 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4349 SE.addressBook.relatedBeanId = relatedBeanId;
4350 document.getElementById('hasRelatedBean').checked = true;
4352 if (document.getElementById('hasRelatedBean').checked == true)
4354 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4355 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4357 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4358 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4360 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4361 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4362 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4365 //Remove any lingering rows in the result set table if the module was closed.
4366 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4368 SE.addressBook.populateResulstTableEmailAddresses();
4370 this.contactsDialogue.show();
4373 * Clear all email addresses from result table.
4376 clearAllEmailAddressFieldsFromResultTable: function () {
4377 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4378 //Unhighlight any rows currently selected if the emails were cleared.
4379 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4380 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4383 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4384 * results table. This function is called when the address book is displayed.
4386 populateResulstTableEmailAddresses: function () {
4388 var idx = SE.addressBook.idx;
4389 var emailFields = ['to','cc','bcc'];
4391 for(var k=0;k<emailFields.length;k++)
4393 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4394 var allEmails = document.getElementById(elKey).value;
4398 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4400 for (var i=0; i<formatedEmails.length; i++)
4402 var t_name = formatedEmails[i].name;
4403 var t_emailAddr = formatedEmails[i].email_address;
4404 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4406 t_name = displayEmail = t_emailAddr;
4408 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4409 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4410 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4416 * Checks all entries in the result table against a particular email address, returning true
4417 * if the email address is found, false otherwise.
4419 doesEmailAdddressExistInResultTable: function(emailAddress)
4421 if(trim(emailAddress) == '')
4424 var emailAddressFound = false;
4425 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4426 for (var i=0; i < contacts.length; i++)
4428 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4429 //If we are adding to cc or bcc fields, make them visible.
4430 if(data.email_address == emailAddress)
4432 emailAddressFound = true;
4437 return emailAddressFound;
4440 * Takes all email addresses that the users wishes to add from the address book and populates the To
4441 * fields on the compose tab.
4443 populateEmailAddressFieldsFromResultTable: function()
4445 //Clear the fields first, all email addresses are stored in the address book
4446 var idx = SE.addressBook.idx;
4447 var emailFields = ['to','cc','bcc'];
4448 for(var k=0;k<emailFields.length;k++)
4450 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4451 document.getElementById(elKey).value = "";
4454 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4455 for (var i=0; i < contacts.length; i++)
4457 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4459 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4460 //If we are adding to cc or bcc fields, make them visible.
4461 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4462 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4463 //Construct the target id
4464 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4466 var target = document.getElementById(target_id);
4467 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4470 //Delete all rows from the result set table
4471 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4474 SE.addressBook.contactsDialogue.hide()
4477 * Insert contacts into the result table.
4479 insertContactToResultTable : function(event,address_type) {
4481 var contactsDialogue = SE.addressBook.contactsDialogue;
4482 var contacts = SE.addressBook.grid.getSelectedRows();
4484 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4485 for (var i = 0; i < rows.length; i++)
4487 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4489 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4490 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4491 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4492 rows[i].setData("selected",true);
4495 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4496 for (var i = 0; i < checkBoxes.length; i++) {
4497 checkBoxes[i].checked = false;
4503 insertContactRowToResultTable : function(rowId, addressType) {
4504 var data = SE.addressBook.grid.getRecord(rowId).getData();
4505 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4507 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4508 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4509 if(addressType == null)
4510 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4511 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});
4514 * Remove a row from the gridsResult table.
4516 removeRowFromGridResults : function(rowId,emailAddress)
4518 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4519 for (var i=0; i < contacts.length; i++)
4521 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4522 var data = rec.getData();
4523 if(data.email_address == emailAddress)
4525 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4530 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4533 * Translates between the addressType To|Cc|Bcc labels/keys.
4535 translateAddresType: function(addressType,fromKey)
4537 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4538 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4539 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4540 var mappingObject = {};
4543 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4546 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4547 mappingObject[displayCc] = 'cc';
4548 mappingObject[displayBcc] = 'bcc';
4551 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4557 toggleSearchRowIcon : function(rowId,show)
4561 var idToShow = rowId + '_add_img';
4562 var idToHide = rowId + '_rm_img';
4566 var idToShow = rowId + '_rm_img';
4567 var idToHide = rowId + '_add_img';
4571 Dom.addClass(idToHide, "yui-hidden");
4572 Dom.removeClass(idToShow, "yui-hidden");
4575 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4577 doesGridResultsEntryExist: function(emailAddrs)
4580 var contactExists = false;
4581 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4582 for (var i=0; i < contacts.length; i++)
4584 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4585 if(data.email_address == emailAddrs)
4587 contactExists = true;
4591 return contactExists;
4595 * adds an email address to a string, but first checks if it exists
4596 * @param string concat The string we are appending email addresses to
4597 * @param string addr Email address to add
4600 smartAddEmailAddressToComposeField : function(concat, addr) {
4601 var re = new RegExp(addr);
4603 if(!concat.match(re)) {
4605 concat += "; " + addr;
4614 //// END ADDRESS BOOK
4615 ///////////////////////////////////////////////////////////////////////////////
4619 ///////////////////////////////////////////////////////////////////////////////
4622 * Auto-complete object
4626 delimChar : [";", ","],
4630 prehighlightClassName : "yui-ac-prehighlight",
4633 instances : new Array(),
4636 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4637 * @param object Contact from AddressBook
4640 getPrimaryAddress : function(contact) {
4641 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4643 for(var eIndex in contact.email) {
4644 address = contact.email[eIndex].email_address;
4645 if(contact.email[eIndex].primary_address == 1) {
4646 return contact.email[eIndex].email_address;
4654 * initializes autocomplete widgets for a given compose view
4657 init : function(idx) {
4658 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4659 "queryMatchContains" : false,
4660 "queryMatchSubset" : true
4663 this.instances[idx] = {
4670 // instantiate the autoComplete widgets
4671 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4672 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4673 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4675 // enable hiding of interfering textareas
4676 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4677 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4678 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4680 // enable reshowing of hidden textareas
4681 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4682 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4683 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4685 // enable refreshes of contact lists
4686 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4687 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4688 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4691 refreshDataSource : function(sType, aArgs) {
4692 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4694 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4696 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4697 idx = textBoxId.substr(9);
4699 idx = textBoxId.substr(10);
4702 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4703 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4704 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4708 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4710 returnDataSource : function(contacts) {
4711 var ret = new Array();
4712 for(var id in contacts) {
4713 if (contacts[id].name) {
4714 var primary = this.getPrimaryAddress(contacts[id]);
4716 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4717 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4719 for(var emailIndex in contacts[id].email) {
4720 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4729 * Hides address textareas to prevent autocomplete dropdown from being obscured
4731 toggleTextareaHide : function(sType, aArgs) {
4732 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4736 if(textBoxId.indexOf("addressTO") > -1) {
4738 } else if(textBoxId.indexOf("addressCC") > -1) {
4741 idx = textBoxId.substr(9);
4743 // follow through if not BCC
4745 var cc = document.getElementById("addressCC" + idx);
4746 var bcc = document.getElementById("addressBCC" + idx);
4750 cc.style.visibility = 'hidden';
4752 bcc.style.visibility = 'hidden';
4759 * Redisplays the textareas after an address is commited
4761 toggleTextareaShow : function(sType, aArgs) {
4762 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4766 if(textBoxId.indexOf("addressTO") > -1) {
4768 } else if(textBoxId.indexOf("addressCC") > -1) {
4771 idx = textBoxId.substr(9);
4773 // follow through if not BCC
4775 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4776 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4781 //// END AUTOCOMPLETE
4782 ///////////////////////////////////////////////////////////////////////////////
4784 ///////////////////////////////////////////////////////////////////////////////
4787 * expands the options sidebar
4789 SE.composeLayout = {
4790 currentInstanceId : 0,
4793 outboundAccountErrors : null,
4794 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4796 showAddressDetails : function(e) {
4797 var linkElement = document.getElementById("More"+e.id);
4798 var spanElement = document.getElementById("Detail"+e.id);
4799 var emailAddressList = e.value;
4800 if(e.value.length > 96)
4802 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4803 var displayArray = [];
4804 for (var i=0; i<resultArray.length; i++)
4806 var t_name = resultArray[i].name;
4807 var t_emailAddr = resultArray[i].email_address;
4809 displayArray.push('<br/><' + t_emailAddr + '>');
4811 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4814 var result = displayArray.join('<br/>');
4816 linkElement.style.display = "inline";
4817 linkElement.style.height="10px";
4818 linkElement.style.overflow="visible";
4819 spanElement.innerHTML = result;
4822 linkElement.style.display = "none";
4827 * Given a string of email address, return an array containing the name portion (if available)
4828 * and email portion.
4830 _getEmailArrayFromString : function (emailAddressList){
4833 while ((results = reg.exec(emailAddressList)) != null)
4835 orignial = results[0];
4836 parsedResult = results[0].replace(';', ':::::');
4837 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4841 while ((results = reg.exec(emailAddressList)) != null)
4843 orignial = results[0];
4844 parsedResult = results[0].replace(',', ':::::');
4845 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4847 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4848 var emailArr = emailAddressList.split(":::::");
4849 var resultsArray = [];
4851 for (var i=0; i<emailArr.length; i++)
4853 var rposition = emailArr[i].indexOf('<');
4854 var lposition = emailArr[i].indexOf('>');
4856 if(trim(emailArr[i]) != '')
4858 if(rposition != -1 && lposition != -1)
4860 var t_name = emailArr[i].substr(0, rposition-1);
4861 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4862 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4866 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4870 return resultsArray;
4872 ///////////////////////////////////////////////////////////////////////////
4875 * Prepare bucket DIV and yui-ext tab panels
4877 _0_yui : function() {
4878 var idx = this.currentInstanceId;
4880 var composeTab = new YAHOO.SUGAR.ClosableTab({
4881 label: mod_strings.LNK_NEW_SEND_EMAIL,
4883 content : "<div id='htmleditordiv" + idx + "'/>",
4884 id : "composeTab" + idx,
4885 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4888 SE.innerLayout.addTab(composeTab);
4890 // get template engine with template
4891 if (!SE.composeLayout.composeTemplate) {
4892 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4895 // create Tab inner layout
4896 var composePanel = this.getComposeLayout();
4897 composePanel.getUnitByPosition("right").collapse();
4898 composePanel.autoSize();
4902 * Generate the quick compose layout
4903 * @method getQuickComposeLayout
4904 * @param {Pannel} parentPanel Parent pannel
4905 * @param {Object} o Options
4908 getQuickComposeLayout : function (parentPanel,o) {
4909 var idx = SE.composeLayout.currentInstanceId;
4911 //Before rendering the parent pannel we need to initalize the grid layout
4912 parentPanel.beforeRenderEvent.subscribe(function() {
4914 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4915 SE.composeLayout._createComposeLayout(idx);
4916 SE.composeLayout[idx].set('height', 350);
4917 SE.composeLayout[idx].render();
4921 //Wait until the Compose Layout has rendered, then add the
4922 //options tab and perform the tiny initialization.
4923 parentPanel.renderEvent.subscribe(function() {
4925 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4926 SE.composeLayout._initComposeOptionTabs(idx);
4927 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4928 //Initialize tinyMCE
4929 if (!SUGAR.util.isTouchScreen())
4930 SE.composeLayout._1_tiny();
4931 //Init templates and address book
4932 SE.composeLayout._2_final();
4934 SE.composeLayout.quickCreateComposePackage(o);
4939 //Check if we have the div override for the shortcut bar
4940 if(typeof o.menu_id != 'undefined') {
4941 parentPanel.render(o.menu_id);
4943 parentPanel.render(document.body);
4946 return SE.composeLayout[idx];
4949 * Fill in all fields into the quick compose layout.
4950 * @method quickCreateComposePackage
4951 * @param {Object} o Options
4954 quickCreateComposePackage: function(o)
4956 //If we have a compose package fill in defaults.
4957 if (typeof(o.composePackage) != 'undefined')
4959 composePackage = o.composePackage; //Set the compose data object
4960 //Hijack this method called by composePackage as it's not need for quick creates.
4961 SE.composeLayout.c0_composeNewEmail = function(){};
4962 SE.composeLayout.composePackage(); //Fill in defaults.
4965 getComposeLayout : function() {
4966 var idx = SE.composeLayout.currentInstanceId;
4968 this._createComposeLayout(idx);
4969 SE.composeLayout[idx].render();
4970 this._initComposeOptionTabs(idx);
4972 return SE.composeLayout[idx];
4976 * Create the layout manager for the compose window.
4978 _createComposeLayout : function(idx)
4980 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
4981 parent: SE.complexLayout,
4991 SE.composeLayout.composeTemplate.exec({
4992 'app_strings':app_strings,
4993 'mod_strings':mod_strings,
4995 'linkbeans_options' : linkBeans,
4996 'idx' : SE.composeLayout.currentInstanceId
5007 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5010 header: app_strings.LBL_EMAIL_OPTIONS
5016 * Create compose tab which will populate the 'right' container in the compose window.
5018 _initComposeOptionTabs : function(idx)
5020 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5021 var tab = new YAHOO.widget.Tab({
5022 label: app_strings.LBL_EMAIL_ATTACHMENT,
5024 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5025 id : "divAttachments" + idx,
5029 tab.layout = SE.composeLayout[idx];
5031 tab.on("activeChange", function(o){
5033 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5039 tab = new YAHOO.widget.Tab({
5040 label: app_strings.LBL_EMAIL_OPTIONS,
5042 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5043 id : "divOptions" + idx,
5047 tab.layout = SE.composeLayout[idx];
5048 tab.on("activeChange", function(o){
5050 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5055 SE.composeLayout[idx].autoSize = function() {
5056 var pEl = this.get("element").parentNode.parentNode.parentNode;
5057 this.set("height", pEl.clientHeight-30);
5061 SE.composeLayout[idx].rightTabs = cTabs;
5063 isParentTypeValid : function(idx) {
5064 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5065 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5066 if (trim(parentTypeValue) == ""){
5067 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5073 isParentTypeAndNameValid : function(idx) {
5074 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5075 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5076 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5077 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5078 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5079 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5085 callopenpopupForEmail2 : function(idx,options) {
5087 var formName = 'emailCompose' + idx;
5089 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5090 formName = options.form_name;
5092 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5093 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5094 if (!SE.composeLayout.isParentTypeValid(idx)) {
5097 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5099 call_back_function:"SE.composeLayout.popupAddEmail",
5101 field_to_name_array:{
5102 id:'data_parent_id' + idx,
5103 name:'data_parent_name' + idx,
5108 popupAddEmail : function(o)
5110 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5111 var data = o.name_to_value_array;
5112 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5113 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5115 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5116 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5123 _1_tiny : function() {
5124 var idx = SE.composeLayout.currentInstanceId;
5125 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5126 SE.tinyInstances[elId] = { };
5127 SE.tinyInstances[elId].ready = false;
5128 var t = tinyMCE.getInstanceById(elId);
5130 if(typeof(t) == 'undefined') {
5131 tinyMCE.execCommand('mceAddControl', false, elId);
5132 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5133 SE.composeLayout.resizeEditor(idx);
5134 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
5139 resizeEditor : function(idx)
5141 var cof = Dom.get('composeOverFrame' + idx);
5142 var head = Dom.get('composeHeaderTable' + idx);
5143 var targetHeight = cof.clientHeight - head.clientHeight;
5144 var instance = tinyMCE.get(SE.tinyInstances.currentHtmleditor);
5146 var parentEl = Dom.get(instance.editorId + '_parent');
5147 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5148 var contentEl = instance.contentAreaContainer;
5149 var iFrame = contentEl.firstChild;
5150 var tinMceToolbarOffset = 18;
5151 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5155 * Initializes d&d, auto-complete, email templates
5157 _2_final : function() {
5158 var idx = SE.composeLayout.currentInstanceId;
5160 if(this.emailTemplates) {
5161 this.setComposeOptions(idx);
5163 //populate email template cache
5164 AjaxObject.target = '';
5165 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5168 // handle drop targets for addressBook
5169 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5170 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5171 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5172 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5174 // auto-complete setup
5175 SE.autoComplete.init(idx);
5178 document.getElementById("addressTO" + idx).focus();
5182 * hide tinyMCE tool bar if send email as plaintext is checked
5184 renderTinyMCEToolBar : function (idx, hide) {
5186 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5188 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5192 c1_composeEmail : function(isReplyForward, retry) {
5196 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5197 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5202 if(isReplyForward) {
5203 this.replyForwardEmailStage2();
5209 * takes draft info and prepopulates
5211 c0_composeDraft : function() {
5212 this.getNewInstanceId();
5214 document.getElementById('_blank').innerHTML = '';
5215 var idx = SE.composeLayout.currentInstanceId;
5216 SE.composeLayout.draftObject = new Object();
5217 SE.composeLayout.draftObject.id = idx;
5218 SE.composeLayout.draftObject.isDraft = true;
5219 SE.composeLayout.currentInstanceId = idx;
5220 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5221 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5222 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5224 SE.composeLayout._0_yui();
5225 SE.composeLayout._1_tiny();
5228 SE.composeLayout._2_final();
5230 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5231 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5235 * Strip & Prep editor hidden fields
5237 c0_composeNewEmail : function() {
5238 this.getNewInstanceId();
5239 this.c1_composeEmail(false);
5243 * Sends async request to get the compose view.
5244 * Requests come from "reply" or "forwards"
5246 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5247 SE.composeLayout.replyForwardObj = new Object();
5248 SE.composeLayout.replyForwardObj.ieId = ieId;
5249 SE.composeLayout.replyForwardObj.uid = uid;
5250 SE.composeLayout.replyForwardObj.mbox = mbox;
5251 SE.composeLayout.replyForwardObj.type = type;
5253 if(mbox == 'sugar::Emails') {
5254 SE.composeLayout.replyForwardObj.sugarEmail = true;
5257 SE.composeLayout.getNewInstanceId();
5258 SE.composeLayout.c1_composeEmail(true);
5260 //// END COMPOSE FLOW
5261 ///////////////////////////////////////////////////////////////////////////
5264 * Called when a contact, email, or mailinglist is dropped
5265 * into one of the compose fields.
5267 handleDrop : function (source, event, data, target) {
5270 target = event.getTarget();
5272 data.nodes = [data.nodes];
5276 target = document.getElementById(target);
5280 if (target.id.indexOf('address') > -1) {
5281 // dropped onto email to/cc/bcc field
5282 for(var i in nodes) {
5283 var node = nodes[i].getData();
5285 if (node[1].indexOf('contact') > -1) {
5286 email = SE.addressBook.getFormattedAddress(node[0]);
5287 } else if (node[1].indexOf('address-email') > -1){
5288 email = node[3].replace(/ /gi, '');
5289 email = email.replace('<', '<').replace('>', '>');
5290 var tr = source.getTrEl(nodes[i]);
5291 while (tr && !Dom.hasClass(tr, "address-contact")) {
5292 tr = source.getPreviousTrEl(tr);
5294 var CID = source.getRecord(tr).getData()[0];
5295 var o = SE.addressBook._contactCache[CID];
5296 var name = new String(o.name);
5297 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5298 email = finalName + email;
5300 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5306 /*/////////////////////////////////////////////////////////////////////////////
5307 /// EMAIL TEMPLATE CODE
5309 applyEmailTemplate : function (idx, id) {
5312 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5313 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5314 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5316 // id is selected index of email template drop-down
5317 if(id == '' || id == "0") {
5318 YAHOO.SUGAR.MessageBox.show({
5323 if(btn=='no'){return;};
5324 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5331 YAHOO.SUGAR.MessageBox.show({
5336 if(btn=='no'){return;};
5337 SUGAR.email2.composeLayout.processResult(idx, id);},
5343 processNoneResult : function(idx, id) {
5344 var tiny = SE.util.getTiny('htmleditor' + idx);
5345 var tinyHTML = tiny.getContent();
5346 var openTag = '<div><span><span>';
5347 var htmllow = tinyHTML.toLowerCase();
5348 var start = htmllow.indexOf(openTag);
5350 tinyHTML = tinyHTML.substr(start);
5351 tiny.setContent(tinyHTML);
5353 tiny.setContent('');
5357 processResult : function(idx , id){
5358 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5360 // get attachments if any
5361 AjaxObject.target = '';
5362 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5365 appendEmailTemplateJSON : function() {
5366 var idx = SE.composeLayout.currentInstanceId; // post increment
5368 // query based on template, contact_id0,related_to
5369 //jchi 09/10/2008 refix #7743
5370 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5371 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5374 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,'"');
5376 // cn: bug 14361 - text-only templates don't fill compose screen
5378 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/>");
5381 var tiny = SE.util.getTiny('htmleditor' + idx);
5382 var tinyHTML = tiny.getContent();
5383 var openTag = '<div><span><span>';
5384 var closeTag = '</span></span></div>';
5385 var htmllow = tinyHTML.toLowerCase();
5386 var start = htmllow.indexOf(openTag);
5388 var htmlPart2 = tinyHTML.substr(start);
5389 tinyHTML = text + htmlPart2;
5390 tiny.setContent(tinyHTML);
5392 tiny.setContent(text);
5397 * Writes out the signature in the email editor
5399 setSignature : function(idx) {
5402 var hide = document.getElementById('setEditor' + idx).checked;
5403 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5404 //wait for signatures to load before trying to set them
5405 if (!SE.composeLayout.signatures) {
5406 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5411 var sel = document.getElementById('signatures' + idx);
5413 var sel = document.getElementById('signature_id');
5414 idx = SE.tinyInstances.currentHtmleditor;
5417 //Ensure that the tinyMCE html has been rendered.
5418 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5419 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5426 signature = sel.options[sel.selectedIndex].value;
5431 var openTag = '<div><span><span>';
5432 var closeTag = '</span></span></div>';
5433 var t = SE.util.getTiny('htmleditor' + idx);
5435 if(typeof(t) != 'undefined')
5437 t.contentDocument = t.contentWindow.document;
5438 var html = t.getContent();
5443 var htmllow = html.toLowerCase();
5444 var start = htmllow.indexOf(openTag);
5445 var end = htmllow.indexOf(closeTag) + closeTag.length;
5447 // selected "none" - remove signature from email
5448 if(signature == '') {
5450 var htmlPart1 = html.substr(0, start);
5451 var htmlPart2 = html.substr(end, html.length);
5453 html = htmlPart1 + htmlPart2;
5456 SE.signatures.lastAttemptedLoad = '';
5460 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5461 SE.signatures.lastAttemptedLoad = '';
5463 SE.signatures.lastAttemptedLoad = signature;
5465 if(typeof(SE.signatures[signature]) == 'undefined') {
5467 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5468 SE.signatures.targetInstance = (idx) ? idx : "";
5469 AjaxObject.target = '';
5470 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5472 var newSignature = this.prepareSignature(SE.signatures[signature]);
5474 // clear out old signature
5475 if(SE.signatures.lastAttemptedLoad && start > -1) {
5476 var htmlPart1 = html.substr(0, start);
5477 var htmlPart2 = html.substr(end, html.length);
5479 html = htmlPart1 + htmlPart2;
5483 start = html.indexOf('<div><hr></div>');
5484 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5485 var htmlPart1 = html.substr(0, start);
5486 var htmlPart2 = html.substr(start, html.length);
5487 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5488 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5489 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5491 var newHtml = html + openTag + newSignature + closeTag;
5493 //tinyMCE.setContent(newHtml);
5494 t.setContent(newHtml);
5498 prepareSignature : function(str) {
5499 var signature = new String(str);
5501 signature = signature.replace(/</gi, '<');
5502 signature = signature.replace(/>/gi, '>');
5508 showAttachmentPanel : function(idx) {
5509 var east = SE.composeLayout[idx].getUnitByPosition("right");
5510 var tabs = SE.composeLayout[idx].rightTabs;
5512 tabs.set("activeTab", tabs.getTab(0));
5516 * expands sidebar and displays options panel
5518 showOptionsPanel : function(idx) {
5519 var east = SE.composeLayout[idx].getUnitByPosition("right");
5520 var tabs = SE.composeLayout[idx].rightTabs;
5522 tabs.set("activeTab", tabs.getTab(1));
5526 * Selects the Contacts tab
5528 showContactsPanel : function() {
5529 SE.complexLayout.regions.west.showPanel("contactsTab");
5533 * Generates fields for Select Document
5535 addDocumentField : function(idx) {
5536 var basket = document.getElementById('addedDocuments' + idx);
5538 var index = (basket.childNodes.length / 7) - 1;
5545 var test = document.getElementById('documentId' + idx + index);
5547 while(test != null) {
5549 test = document.getElementById('documentId' + idx + index);
5552 var documentCup = document.createElement("div");
5553 documentCup.id = 'documentCup' + idx + index;
5554 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5555 // document id field
5556 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5557 // document name field
5558 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5560 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5561 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5562 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5564 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5565 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5566 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5569 basket.appendChild(documentCup);
5570 //basket.innerHTML += out;
5575 * Makes async call to save a draft of the email
5576 * @param int Instance index
5578 saveDraft : function(tinyInstance) {
5579 this.sendEmail(tinyInstance, true);
5582 selectDocument : function(target) {
5583 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5584 windowName = 'selectDocument';
5585 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5587 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5589 // put the focus on the popup if the browser supports the focus() method
5595 * Modal popup for file attachment dialogue
5597 addFileField : function() {
5598 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5599 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5603 constraintoviewport: true,
5605 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5606 fn:function(){SE.addFileDialog.hide();}
5609 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5610 SE.addFileDialog.render();
5611 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5613 Dom.removeClass("addFileDialog", "yui-hidden");
5615 SE.addFileDialog.show();
5619 * Async upload of file to temp dir
5621 uploadAttachment : function() {
5622 if(document.getElementById('email_attachment').value != "") {
5623 var formObject = document.getElementById('uploadAttachment');
5624 YAHOO.util.Connect.setForm(formObject, true, true);
5625 AjaxObject.target = '';
5626 AjaxObject.startRequest(callbackUploadAttachment, null);
5628 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5633 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5634 * @param string target in focus compose layout
5636 setDocument : function(idx, target, documentId, documentName, docRevId) {
5637 // fields are named/id'd [fieldName][instanceId][index]
5638 var addedDocs = document.getElementById("addedDocuments" + idx);
5639 var docId = document.getElementById('documentId' + idx + target);
5640 var docName = document.getElementById('documentName' + idx + target);
5641 var docRevisionId = document.getElementById('document' + idx + target);
5642 docId.value = documentId;
5643 docName.value = documentName;
5644 docRevisionId.value = docRevId;
5648 * Removes the bucket div containing the document input fields
5650 deleteDocumentField : function(documentCup) {
5651 var f0 = document.getElementById(documentCup);
5652 f0.parentNode.removeChild(f0);
5656 * Removes a Template Attachment field
5660 deleteTemplateAttachmentField : function(idx, index) {
5661 // create not-in-array values for removal filtering
5662 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5668 r += document.getElementById('templateAttachmentId' + idx + index).value;
5669 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5671 var target = 'templateAttachmentCup' + idx + index;
5672 d = document.getElementById(target);
5673 d.parentNode.removeChild(d);
5677 * Async removal of uploaded temp file
5678 * @param string index Should be a concatenation of idx and index
5681 deleteUploadAttachment : function(index, file) {
5682 var d = document.getElementById('email_attachment_bucket' + index);
5683 d.parentNode.removeChild(d);
5685 // make async call to delete cached file
5686 AjaxObject.target = '';
5687 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5691 * Attaches files coming from Email Templates
5693 addTemplateAttachmentField : function(idx) {
5695 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5697 var basket = document.getElementById('addedTemplateAttachments' + idx);
5700 var index = basket.childNodes.length;
5707 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5709 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5710 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5711 idx + "\",\"" + index + "\");'/>" +
5713 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5714 // templateAttachment field
5715 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5717 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5719 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5720 "<br id='br" + index + "></br>" +
5721 "<br id='brdoc" + index + "></br>" +
5723 basket.innerHTML = basket.innerHTML + out;
5729 * Sends one email via async call
5730 * @param int idx Editor instance ID
5731 * @param bool isDraft
5733 sendEmail : function(idx, isDraft) {
5735 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5736 var obAccountID = document.getElementById('addressFrom' + idx).value;
5738 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5740 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5745 var form = document.getElementById('emailCompose' + idx);
5746 var composeOptionsFormName = "composeOptionsForm" + idx;
5747 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5748 var html = t.getContent();
5749 var subj = document.getElementById('emailSubject' + idx).value;
5750 var to = trim(document.getElementById('addressTO' + idx).value);
5751 var cc = trim(document.getElementById('addressCC' + idx).value);
5752 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5753 var email_id = document.getElementById('email_id' + idx).value;
5754 var composeType = document.getElementById('composeType').value;
5755 var parent_type = document.getElementById("parent_type").value;
5756 var parent_id = document.getElementById("parent_id").value;
5758 var el_uid = document.getElementById("uid");
5759 var uid = (el_uid == null) ? '' : el_uid.value;
5761 var el_ieId = document.getElementById("ieId");
5762 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5764 var el_mbox = document.getElementById("mbox");
5765 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5767 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5768 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5772 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5775 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5776 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5777 parent_id = parentIdValue;
5778 parent_type = parentTypeValue;
5780 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5781 // baseline viability check
5783 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5784 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5786 } else if(subj == '' && !isDraft) {
5787 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5790 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5792 } else if(html == '' && !isDraft) {
5793 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5798 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5799 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5800 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5801 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5802 html = html.replace(/</ig, "sugarLessThan");
5803 html = html.replace(/>/ig, "sugarGreaterThan");
5805 form.sendDescription.value = html;
5806 form.sendSubject.value = subj;
5807 form.sendTo.value = to;
5808 form.sendCc.value = cc;
5809 form.sendBcc.value = bcc;
5810 form.email_id.value = email_id;
5811 form.composeType.value = composeType;
5812 form.composeLayoutId.value = 'composeLayout' + idx;
5813 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5814 form.saveToSugar.value = 1;
5815 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5816 form.parent_type.value = parent_type;
5817 form.parent_id.value = parent_id;
5818 form.uid.value = uid;
5819 form.ieId.value = ieId;
5820 form.mbox.value = mbox;
5822 // email attachments
5823 var addedFiles = document.getElementById('addedFiles' + idx);
5825 for(i=0; i<addedFiles.childNodes.length; i++) {
5826 var bucket = addedFiles.childNodes[i];
5828 for(j=0; j<bucket.childNodes.length; j++) {
5829 var node = bucket.childNodes[j];
5830 var nName = new String(node.name);
5832 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5833 if(form.attachments.value != '') {
5834 form.attachments.value += "::";
5836 form.attachments.value += node.value;
5843 var addedDocs = document.getElementById('addedDocuments' + idx);
5845 for(i=0; i<addedDocs.childNodes.length; i++) {
5846 var cNode = addedDocs.childNodes[i];
5847 for(j=0; j<cNode.childNodes.length; j++) {
5848 var node = cNode.childNodes[j];
5849 var nName = new String(node.name);
5850 if(node.type == 'hidden' && nName.match(/documentId/)) {
5851 if(form.documents.value != '') {
5852 form.documents.value += "::";
5854 form.documents.value += node.value;
5860 // template attachments
5861 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5862 if(addedTemplateAttachments) {
5863 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5864 var cNode = addedTemplateAttachments.childNodes[i];
5865 for(j=0; j<cNode.childNodes.length; j++) {
5866 var node = cNode.childNodes[j];
5867 var nName = new String(node.name);
5868 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5869 if(form.templateAttachments.value != "") {
5870 form.templateAttachments.value += "::";
5872 form.templateAttachments.value += node.value;
5878 // remove attachments
5879 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5881 YAHOO.util.Connect.setForm(form);
5883 AjaxObject.target = 'frameFlex';
5885 // sending a draft email
5886 if(!isDraft && in_draft) {
5888 SE.listView.removeRowByUid(email_id);
5891 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5892 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5894 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5898 * Handles clicking the email address link from a given view
5900 composePackage : function() {
5901 if(composePackage != null) {
5902 SE.composeLayout.c0_composeNewEmail();
5905 if(composePackage.to_email_addrs) {
5906 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5908 if (composePackage.subject != null && composePackage.subject.length > 0) {
5909 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5912 //If no parent fields are set in the composePackage, ensure they are cleared.
5913 var parentFields = ['parent_type','parent_name','parent_id'];
5914 for(var i=0;i<parentFields.length;i++)
5916 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5917 composePackage[parentFields[i]] = "";
5920 document.getElementById("parent_type").value = composePackage.parent_type;
5921 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5922 document.getElementById("parent_id").value = composePackage.parent_id;
5923 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5924 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5926 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5927 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5929 if (composePackage.body != null && composePackage.body.length > 0) {
5930 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5931 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5932 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5934 if (composePackage.attachments != null) {
5935 SE.composeLayout.loadAttachments(composePackage.attachments);
5938 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5939 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5940 SE.util.emptySelectOptions(addressFrom);
5941 var fromAccountOpts = composePackage.fromAccounts.data;
5942 for(i=0; i<fromAccountOpts.length; i++) {
5943 var key = fromAccountOpts[i].value;
5944 var display = fromAccountOpts[i].text;
5945 var opt = new Option(display, key);
5946 if (fromAccountOpts[i].selected) {
5947 opt.selected = true;
5949 addressFrom.options.add(opt);
5956 setContentOnThisTiny : function() {
5957 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5958 var tinyHTML = tiny.getContent();
5959 composePackage.body = decodeURI(encodeURI(composePackage.body));
5960 // cn: bug 14361 - text-only templates don't fill compose screen
5961 if(composePackage.body == '') {
5962 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
5964 //Flag determines if we should clear the tiny contents or just append
5965 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5966 SE.composeLayout.tinyHTML = '';
5968 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
5970 tiny.setContent(SE.composeLayout.tinyHTML);
5971 //Indicate that the contents has been loaded successfully.
5972 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5975 * Confirms closure of a compose screen if "x" is clicked
5977 confirmClose : function(panel) {
5978 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
5979 SE.composeLayout.closeCompose(panel.id);
5987 * forces close of a compose screen
5989 forceCloseCompose : function(id) {
5990 SE.composeLayout.closeCompose(id);
5992 // handle flow back to originating view
5993 if(composePackage) {
5994 // check if it's a module we need to return to
5995 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
5996 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
5997 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
5998 window.location = url;
6005 * closes the editor that just sent email
6006 * @param string id ID of composeLayout tab
6008 closeCompose : function(id) {
6009 // destroy tinyMCE instance
6010 var idx = id.substr(13, id.length);
6011 var instanceId = "htmleditor" + idx;
6012 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6014 // nullify DOM and namespace values.
6016 SE.composeLayout[idx] = null;
6017 SE.tinyInstances[instanceId] = null;
6018 var tabsArray = SE.innerLayout.get("tabs");
6019 for (i = 0 ; i < tabsArray.length ; i++) {
6020 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6021 tabsArray[i].close();
6025 //SE.innerLayout.getTab(idx).close();
6029 * Enable the quick search for the compose relate field or search tab
6031 enableQuickSearchRelate: function(idx,overides){
6033 if(typeof overides != 'undefined')
6035 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6036 var newModule = document.getElementById(newModuleID).value;
6037 var formName = overides['formName'];
6038 var fieldName = overides['fieldName'];
6039 var fieldId = overides['fieldId'];
6040 var fullName = formName + "_" + fieldName;
6041 var postBlurFunction = null;
6045 var newModule = document.getElementById('data_parent_type'+idx).value;
6046 var formName = 'emailCompose'+idx;
6047 var fieldName = 'data_parent_name'+idx;
6048 var fieldId = 'data_parent_id'+idx;
6049 var fullName = formName + "_" + fieldName;
6050 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6053 if(typeof sqs_objects == 'undefined')
6054 window['sqs_objects'] = new Array;
6056 window['sqs_objects'][fullName] = {
6059 modules:[newModule],
6061 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6062 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6063 post_onblur_function: postBlurFunction,
6064 order:"name","limit":"30","no_match_text":"No Match"};
6067 if(typeof QSProcessedFieldsArray != 'undefined')
6068 QSProcessedFieldsArray[fullName] = false;
6069 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6070 QSFieldsArray[fullName].destroy();
6071 delete QSFieldsArray[fullName];
6073 if (Dom.get(fullName + "_results")) {
6074 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6080 qsAddAddress : function(o) {
6081 if (o.name != "" && o.email1 != "")
6083 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6084 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6088 * Returns a new instance ID, 0-index
6090 getNewInstanceId : function() {
6091 this.currentInstanceId = this.currentInstanceId + 1;
6092 return this.currentInstanceId;
6096 * 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.
6098 loadAttachments : function(result) {
6099 var idx = SE.composeLayout.currentInstanceId;
6101 if(typeof(result) == 'object') {
6102 //jchi #20680. Clean the former template attachments;
6103 var basket = document.getElementById('addedTemplateAttachments' + idx);
6104 if(basket.innerHTML != ''){
6105 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6107 basket.innerHTML = '';
6112 if(typeof result[i] == 'object') {
6113 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6114 var bean = result[i];
6115 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6116 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6123 * fills drop-down values for email templates and signatures
6125 setComposeOptions : function(idx) {
6126 // send from accounts
6127 var addressFrom = document.getElementById('addressFrom' + idx);
6129 if (addressFrom.options.length <= 0) {
6130 SE.util.emptySelectOptions(addressFrom);
6131 var fromAccountOpts = SE.composeLayout.fromAccounts;
6132 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6133 var key = fromAccountOpts[id].value;
6134 var display = fromAccountOpts[id].text;
6135 var is_default = false;
6136 if(key == SUGAR.default_inbound_accnt_id)
6138 var opt = new Option(display, key);
6139 addressFrom.options.add(opt);
6140 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6145 var et = document.getElementById('email_template' + idx);
6146 SE.util.emptySelectOptions(et);
6148 for(var key in this.emailTemplates) { // iterate through assoc array
6149 var display = this.emailTemplates[key];
6150 var opt = new Option(display, key);
6151 et.options.add(opt);
6155 var sigs = document.getElementById('signatures' + idx);
6156 SE.util.emptySelectOptions(sigs);
6158 for(var key in this.signatures) { // iterate through assoc array
6159 var display = this.signatures[key];
6160 var opt = new Option(display, key);
6162 if(key == SE.userPrefs.signatures.signature_default) {
6163 opt.selected = true;
6166 sigs.options.add(opt);
6169 // html/plain email?
6170 var htmlEmail = document.getElementById('setEditor' + idx);
6171 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6172 htmlEmail.checked = true;
6174 htmlEmail.checked = false;
6177 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6181 * After compose screen is rendered, async call to get email body from Sugar
6183 replyForwardEmailStage2 : function() {
6184 SE.util.clearHiddenFieldValues('emailUIForm');
6185 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6187 var ieId = SE.composeLayout.replyForwardObj.ieId;
6188 var uid = SE.composeLayout.replyForwardObj.uid;
6189 var mbox = SE.composeLayout.replyForwardObj.mbox;
6190 var type = SE.composeLayout.replyForwardObj.type;
6191 var idx = SE.composeLayout.currentInstanceId;
6193 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6195 document.getElementById('emailSubject' + idx).value = type;
6196 document.getElementById('emailUIAction').value = 'composeEmail';
6197 document.getElementById('composeType').value = type;
6198 document.getElementById('ieId').value = ieId;
6199 document.getElementById('uid').value = uid;
6200 document.getElementById('mbox').value = mbox;
6201 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6202 var formObject = document.getElementById('emailUIForm');
6203 YAHOO.util.Connect.setForm(formObject);
6205 var sendType = type;
6206 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6210 * Show the hidden cc or bcc fields
6212 showHiddenAddress: function(addrType,idx){
6214 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6215 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6216 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6217 this[addrType+'Hidden'+idx] = false;
6219 //After bcc or cc is added, move options below last addr field
6220 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6222 //If both cc and bcc hidden, remove the empty row containing text.
6223 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6224 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6225 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6227 SE.composeLayout.resizeEditor(idx);
6230 * Hide the cc and bcc fields if they were shown.
6232 hideHiddenAddresses: function(idx){
6234 var addrTypes = ['cc','bcc'];
6235 for(var i = 0;i<addrTypes.length;i++)
6237 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6238 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6239 this[addrTypes[i] + 'Hidden'+idx] = true
6242 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6243 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6244 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6248 //// END SE.composeLayout
6249 ///////////////////////////////////////////////////////////////////////////////
6250 ///////////////////////////////////////////////////////////////////////////////
6254 * Cleans serialized UID lists of duplicates
6258 cleanUids : function(str) {
6259 var seen = new Object();
6261 var arr = new String(str).split(",");
6263 for(var i=0; i<arr.length; i++) {
6268 clean += (clean != "") ? "," : "";
6270 seen[arr[i]] = true;
6277 * Clears hidden field values
6278 * @param string id ID of form element to clear
6280 clearHiddenFieldValues : function(id) {
6281 var form = document.getElementById(id);
6283 for(i=0; i<form.elements.length; i++) {
6284 if(form.elements[i].type == 'hidden') {
6285 var e = form.elements[i];
6286 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6294 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6296 emptySelectOptions : function(el) {
6298 for(i=el.childNodes.length - 1; i >= 0; i--) {
6299 if(el.childNodes[i]) {
6300 el.removeChild(el.childNodes[i]);
6307 * Returns the MBOX path in the manner php_imap expects:
6308 * ie: INBOX.DEBUG.test
6309 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6311 generateMboxPath : function(str) {
6312 var ex = str.split("::");
6314 /* we have a serialized MBOX path */
6318 for(var i=0; i<ex.length; i++) {
6319 if(ex[i] == 'INBOX') {
6331 /* we have a Sugar folder GUID - do nothing */
6339 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6340 * @param HTMLElement el
6341 * @return string GUID of found element or empty on failure
6343 getGuidFromElement : function(el) {
6349 for(var i=0; i<iterations; i++) {
6351 if(el.id.match(SE.reGUID)) {
6363 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6366 getPanelId : function() {
6367 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6371 * wrapper to handle weirdness with IE
6372 * @param string instanceId
6373 * @return tinyMCE Controller object
6375 getTiny : function(instanceId) {
6376 if(instanceId == '') {
6380 var t = tinyMCE.getInstanceById(instanceId);
6384 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6390 * Simple check for MSIE browser
6394 var nav = new String(navigator.appVersion);
6395 if(nav.match(/MSIE/)) {
6402 * Recursively removes an element from the DOM
6403 * @param HTMLElement
6405 removeElementRecursive : function(el) {
6406 this.emptySelectOptions(el);
6413 sleep : function(secs) {
6414 setTimeout("void(0);", secs);
6418 * Converts a <select> element to an Ext.form.combobox
6420 convertSelect : function(select) {
6421 alert('in convertSelect');
6422 if (typeof(select) == "string") {
6423 select = document.getElementById(select);
6427 findChildNode : function (parent, property, value) {
6428 for (i in parent.children) {
6429 var child = parent.children[i];
6430 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6432 var searchChild = SE.util.findChildNode(child, property, value);
6439 cascadeNodes : function (parent, fn, scope, args) {
6440 for (i in parent.children) {
6441 var child = parent.children[i];
6442 var s = scope ? scope : child;
6443 var a = args ? args : child;
6445 SE.util.cascadeNodes(child, fn, scope, args);
6452 ///////////////////////////////////////////////////////////////////////////////
6455 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6457 /*********************************************************************************
6458 * SugarCRM is a customer relationship management program developed by
6459 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6461 * This program is free software; you can redistribute it and/or modify it under
6462 * the terms of the GNU Affero General Public License version 3 as published by the
6463 * Free Software Foundation with the addition of the following permission added
6464 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6465 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6466 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6468 * This program is distributed in the hope that it will be useful, but WITHOUT
6469 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6470 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6473 * You should have received a copy of the GNU Affero General Public License along with
6474 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6475 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6478 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6479 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6481 * The interactive user interfaces in modified source and object code versions
6482 * of this program must display Appropriate Legal Notices, as required under
6483 * Section 5 of the GNU Affero General Public License version 3.
6485 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6486 * these Appropriate Legal Notices must retain the display of the "Powered by
6487 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6488 * technical reasons, the Appropriate Legal Notices must display the words
6489 * "Powered by SugarCRM".
6490 ********************************************************************************/
6493 if (typeof console == "undefined")
6494 console = { log: function(o) {alert(o)} };
6498 currentRequestObject : null,
6499 //timeout : 30000, // 30 second timeout default
6500 timeout : 9999999999, // 30 second timeout default
6502 trail : new Array(),
6506 _reset : function() {
6507 this.timeout = 30000;
6508 this.forceAbort = false;
6511 folderRenameCleanup : function() {
6512 SUGAR.email2.folders.setSugarFolders();
6515 fullSyncCleanup : function(o) {
6516 this.folders.checkMailCleanup(o);
6517 SUGAR.email2.settings.settingsDialog.hide();
6522 composeCache : function(o) {
6523 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6524 // get email templates and user signatures
6525 var ret = JSON.parse(o.responseText);
6527 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6528 SUGAR.email2.composeLayout.signatures = ret.signatures;
6529 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6531 SUGAR.email2.composeLayout.setComposeOptions(idx);
6533 //Set the error array so we can notify the user when they try to hit send if any errors
6534 //are present. We will also notify them now (after hitting compose button).
6535 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6538 //if error element is returning an array, then check the length to make sure we have error messages
6539 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6540 //add error messages for display
6541 for(i in ret.errorArray)
6542 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6543 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6544 //if error element is returning an object, and the object value is not empty or null, then display error message
6545 for(i in ret.errorArray)
6546 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6549 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6551 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6553 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6559 handleDeleteSignature : function(o) {
6561 var ret = JSON.parse(o.responseText);
6562 SUGAR.email2.composeLayout.signatures = ret.signatures;
6563 var field = document.getElementById('signature_id');
6564 SUGAR.email2.util.emptySelectOptions(field);
6566 for(var i in ret.signatures) { // iterate through assoc array
6567 var opt = new Option(ret.signatures[i], i);
6568 field.options.add(opt);
6570 setSigEditButtonVisibility();
6575 handleDeleteReturn : function(o) {
6576 // force refresh ListView
6578 if(document.getElementById('focusEmailMbox')) {
6579 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6582 // need to display success message before calling next async call?
6583 document.getElementById(this.target).innerHTML = o.responseText;
6588 handleFailure : function(o) {
6590 overlay('Exception occurred...', o.statusText, 'alert');
6593 handleReplyForward : function(o) {
6594 var a = JSON.parse(o.responseText);
6596 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6598 document.getElementById('email_id' + idx).value = a.uid;
6599 document.getElementById('emailSubject' + idx).value = a.name;
6600 document.getElementById('addressTO' + idx).value = a.from;
6601 document.getElementById('uid' + idx).value = a.uid;
6603 document.getElementById('addressCC' + idx).value = a.cc;
6604 SE.composeLayout.showHiddenAddress('cc', idx);
6608 document.getElementById('type' + idx).value = a.type;
6611 // apply attachment values
6612 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6614 setTimeout("callbackReplyForward.finish(globalA);", 500);
6617 handleReplyForwardForDraft : function(o) {
6618 var a = JSON.parse(o.responseText);
6620 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6622 document.getElementById('email_id' + idx).value = a.uid;
6623 document.getElementById('emailSubject' + idx).value = a.name;
6624 document.getElementById('addressTO' + idx).value = a.to;
6627 document.getElementById('addressCC' + idx).value = a.cc;
6628 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6632 document.getElementById('addressBCC' + idx).value = a.bcc;
6633 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6638 document.getElementById('type' + idx).value = a.type;
6642 // apply attachment values
6643 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6645 setTimeout("callbackReplyForward.finish(globalA);", 500);
6650 handleSuccess : function(o) {
6651 document.getElementById(this.target).innerHTML = o.responseText;
6657 ieDeleteSuccess : function(o) {
6660 var ret = JSON.parse(o.responseText);
6662 SUGAR.email2.accounts.refreshInboundAccountTable();
6663 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6664 SUGAR.email2.accounts.rebuildFolderList();
6670 ieSaveSuccess : function(o) {
6671 document.getElementById('saveButton').disabled = false;
6672 var a = JSON.parse(o.responseText);
6675 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6676 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6678 resp = JSON.parse(o.responseText);
6679 SUGAR.email2.accounts.refreshInboundAccountTable();
6680 SUGAR.email2.accounts.refreshOuboundAccountTable();
6681 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6682 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6686 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6693 loadAttachments : function(o) {
6694 var result = JSON.parse(o.responseText);
6696 SUGAR.email2.composeLayout.loadAttachments(result);
6701 loadSignature : function(o) {
6702 var ret = JSON.parse(o.responseText);
6703 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6704 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6708 * Follow up to mark email read|unread|flagged
6710 markEmailCleanup : function(o) {
6711 var ret = JSON.parse(o.responseText);
6712 if (!ret['status']) {
6714 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6716 SUGAR.email2.contextMenus.markEmailCleanup();
6722 rebuildShowFolders : function(o) {
6723 var t = JSON.parse(o.responseText);
6724 var show = document.getElementById('ieAccountListShow');
6726 SUGAR.email2.util.emptySelectOptions(show);
6728 for(i=0; i<t.length; i++) { // iterate through assoc array
6729 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6730 opt.selected = t[i].selected;
6731 show.options.add(opt);
6734 SUGAR.email2.accounts.renderTree();
6738 saveListViewSortOrderPart2 : function() {
6739 // create the JSON string the func expects
6740 focusFolderPath = '[ "Home", "' + ieName + '"';
6742 var f = new String(focusFolder);
6743 var fEx = f.split('.');
6745 for(i=0; i<fEx.length; i++) {
6746 focusFolderPath += ', "' + fEx[i] +'"'
6749 focusFolderPath += ']';
6751 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6752 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6758 sendEmailCleanUp : function(o) {
6760 var ret = JSON.parse(o.responseText);
6762 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6763 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6764 } else if (o.responseText) {
6765 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6768 if (typeof(SE.grid) != 'undefined')
6769 SE.listView.refreshGrid();
6770 //Disabled while address book is disabled
6772 //If this call back was initiated by quick compose from a Detail View page, refresh the
6773 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6774 //close the shortcut bar menu
6775 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6776 if(action_sugar_grp1 == 'DetailView') {
6777 showSubPanel('history',null,true);
6778 } else if(action_sugar_grp1 == 'quickcreate') {
6779 closeEmailOverlay();
6785 ieSendSuccess : function(o) {
6787 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6792 settingsFolderRefresh : function(o) {
6793 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6794 var ret = JSON.parse(o.responseText);
6795 var user = document.getElementById('userFolders');
6797 SUGAR.email2.util.emptySelectOptions(user);
6799 for(i=0; i<ret.userFolders.length; i++) {
6800 var display = ret.userFolders[i].name;
6801 var value = ret.userFolders[i].id;
6802 var selected = (ret.userFolders[i].selected != "") ? true : false;
6803 var opt = new Option(display, value, selected);
6804 opt.selected = selected;
6805 user.options.add(opt);
6811 startRequest : function(callback, args, forceAbort) {
6812 if(this.currentRequestObject != null) {
6813 if(this.forceAbort == true) {
6814 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6817 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6821 requestInProgress : function() {
6822 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6827 updateFolderSubscriptions : function() {
6828 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6829 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6835 updateFrameFolder : function() {
6836 SUGAR.email2.folders.checkEmailAccounts();
6841 updateUserPrefs : function(o) {
6842 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6843 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6848 uploadAttachmentSuccessful : function(o) {
6850 document.getElementById('email_attachment').value = '';
6852 var ret = JSON.parse(o.responseText);
6853 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6854 var overall = document.getElementById('addedFiles' + idx);
6855 var index = overall.childNodes.length;
6857 "<div id='email_attachment_bucket" + idx + index + "'>" +
6859 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6860 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6861 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6863 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6864 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6866 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6868 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6871 overall.innerHTML += out;
6872 if(SUGAR.email2.util.isIe()) {
6873 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6877 SUGAR.email2.addFileDialog.hide();
6878 // focus attachments
6879 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6884 ///////////////////////////////////////////////////////////////////////////
6885 //// PER MODULE CALLBACK OBJECTS
6886 AjaxObject.accounts = {
6887 saveOutboundCleanup : function(o) {
6888 SUGAR.email2.accounts.refreshOuboundAccountTable();
6889 SUGAR.email2.accounts.outboundDialog.hide();
6890 var id = o.responseText;
6891 SUGAR.email2.accounts.newAddedOutboundId = id;
6893 saveDefaultOutboundCleanup: function(o){
6896 callbackEditOutbound : {
6897 success : function(o)
6899 var ret = JSON.parse(o.responseText);
6901 SUGAR.email2.accounts.showAddSmtp();
6904 document.getElementById("mail_id").value = ret.id;
6905 document.getElementById("type").value = ret.type;
6906 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6907 document.getElementById("mail_name").value = ret.name;
6908 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6909 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6910 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6911 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6912 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6913 SUGAR.email2.accounts.smtp_authenticate_field_display();
6914 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6916 if(ret.type == 'system-override') {
6917 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6918 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6921 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6922 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6924 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6927 failure : AjaxObject.handleFailure,
6928 timeout : AjaxObject.timeout,
6931 callbackDeleteOutbound : {
6932 success : function(o) {
6933 var ret = JSON.parse(o.responseText);
6936 if(confirm(ret.error_message))
6938 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6939 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6947 SUGAR.email2.accounts.refreshOuboundAccountTable();
6951 failure : AjaxObject.handleFailure,
6952 timeout : AjaxObject.timeout,
6956 callbackCheckMailProgress : {
6957 success : function(o) {
6958 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6959 SUGAR.email2.accounts.totalMsgCount = -1;
6962 //Check for server timeout / errors
6963 var ret = JSON.parse(o.responseText);
6966 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6968 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6969 SUGAR.email2.accounts.totalMsgCount = -1;
6970 //SUGAR.email2.folders.rebuildFolders();
6974 var currIeId = ret['ieid'];
6977 var serverCount = ret.count;
6979 if (ret['status'] == 'done') {
6980 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
6981 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
6985 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
6986 //Go to next account
6987 currIeId = SUGAR.email2.accounts.ieIds[i+1];
6989 SUGAR.email2.accounts.totalMsgCount = -1;
6994 else if (ret.mbox && ret.totalcount && ret.count) {
6995 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
6996 if (ret.count >= ret.totalcount) {
6999 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7000 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7003 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7004 SUGAR.email2.accounts.totalMsgCount = -1;
7009 SUGAR.email2.accounts.totalMsgCount = -1;
7011 SUGAR.email2.folders.rebuildFolders();
7012 SE.listView.refreshGrid();
7013 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7014 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7015 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7016 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7018 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7019 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7020 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7021 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7022 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7025 failure : AjaxObject.handleFailure,
7026 timeout : AjaxObject.timeout,
7031 ///////////////////////////////////////////////////////////////////////////////
7033 AjaxObject.composeLayout = {
7035 * Populates the record id
7037 saveDraftCleanup : function(o) {
7039 var ret = JSON.parse(o.responseText);
7041 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7042 else if (o.responseText)
7043 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7047 AjaxObject.composeLayout.callback = {
7049 success : AjaxObject.composeLayout.saveDraftCleanup,
7050 failure : AjaxObject.handleFailure,
7051 timeout : AjaxObject.timeout,
7056 AjaxObject.detailView = {
7058 * Pops-up a printable view of an email
7060 displayPrintable : function(o) {
7061 var ret = JSON.parse(o.responseText);
7062 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7063 // 2 below must be in global context
7065 meta['panelId'] = SUGAR.email2.util.getPanelId();
7066 email = ret.meta.email;
7067 if (typeof(email.cc) == 'undefined') {
7071 var out = displayTemplate.exec({
7072 'app_strings' : app_strings,
7076 'email' : meta.email
7079 // open popup window
7080 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7081 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7083 popup.document.write(out);
7084 popup.document.close();
7088 * Takes formatted response and creates a modal pop-over containing a title and content
7090 displayView : function(o) {
7091 var SED = SUGAR.email2.detailView;
7092 var ret = JSON.parse(o.responseText);
7094 if(!SED.viewDialog) {
7095 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7099 constraintoviewport: true,
7102 SED.viewDialog.renderEvent.subscribe(function() {
7103 var content = this.body.firstChild;
7104 var viewH = YAHOO.util.Dom.getViewportHeight();
7106 this.body.style.overflow = "auto";
7107 this.body.style.width = "800px";
7108 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7112 SED.viewDialog.setHeader(ret.title);
7113 SED.viewDialog.setBody(ret.html);
7114 SED.viewDialog.render();
7115 SED.viewDialog.show();
7119 * Generates a modal popup to populate with the contents of bean's full EditView
7121 showQuickCreateForm : function(o) {
7122 var SED = SUGAR.email2.detailView;
7123 var ret = JSON.parse(o.responseText);
7125 if(!SED.quickCreateDialog) {
7126 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7130 constraintoviewport: true,
7134 SED.quickCreateDialog.renderEvent.subscribe(function() {
7135 var viewH = YAHOO.util.Dom.getViewportHeight();
7137 for (var i in this.body.childNodes) {
7138 if (this.body.childNodes[i].clientHeight) {
7139 contH += this.body.childNodes[i].clientHeight;
7140 } else if (this.body.childNodes[i].offsetHeight) {
7141 contH += this.body.childNodes[i].offsetHeight;
7144 this.body.style.width = "800px";
7145 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7146 this.body.style.overflow = "auto";
7147 }, SED.quickCreateDialog);
7149 SED.quickCreateDialog.hideEvent.subscribe(function(){
7150 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7151 /*for(var qsField in qsFields){
7152 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7153 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7156 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7159 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7161 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7162 SED.quickCreateDialog.render();
7163 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7165 SED.quickCreateDialog.ieId = ret.ieId;
7166 SED.quickCreateDialog.uid = ret.uid;
7167 SED.quickCreateDialog.mbox = ret.mbox;
7168 SED.quickCreateDialog.qcmodule = ret.module;
7170 SED.quickCreateDialog.show();
7172 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7174 editForm.module.value = 'Emails';
7175 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7176 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7177 var instId = ret.module + count;
7178 SED.quickCreateEmailsToAdd = ret.emailAddress;
7179 SED.quickCreateEmailCallback = function(instId, tableId) {
7180 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7181 if (typeof(eaw) == "undefined")
7182 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7183 + instId + "','" + tableId + "');", 100);
7184 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7186 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7187 + instId + "','" + tableId + "');", 100);
7191 saveQuickCreateForm : function(o) {
7193 SUGAR.email2.detailView.quickCreateDialog.hide();
7194 validate['EditView'] = [ ];
7197 saveQuickCreateFormAndReply : function(o) {
7199 var ret = JSON.parse(o.responseText);
7200 SUGAR.email2.detailView.quickCreateDialog.hide();
7201 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7202 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7204 var emailID = ret.id;
7205 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7207 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7209 //Cean the validate cache to prevent errors on the next call
7210 validate['EditView'] = [ ];
7213 saveQuickCreateFormAndAddToAddressBook : function(o) {
7215 SUGAR.email2.detailView.quickCreateDialog.hide();
7216 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7217 validate['EditView'] = [ ];
7220 handleAssignmentDialogAssignAction : function() {
7223 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7225 var dist = 'direct';
7229 var found_teams = false;
7230 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7231 if(!found_teams && assign_user_id == '' )
7233 alert(warning_message);
7237 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7239 for(i=0; i<emailUids.length; i++) {
7241 uids += app_strings.LBL_EMAIL_DELIMITER;
7243 uids += emailUids[i];
7246 var row = SUGAR.email2.grid.getSelectedRows()[0];
7247 var data = SUGAR.email2.grid.getRecord(row).getData();
7248 var ieid = data.ieId;
7249 var mbox = data.mbox;
7250 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7251 SUGAR.email2.contextMenus.assignToDialogue.hide();
7252 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7256 handleAssignmentDialogDeleteAction : function() {
7257 // TO pass list of UIDS/emailIds
7258 var uids = SUGAR.email2.listView.getUidsFromSelection();
7259 var row = SUGAR.email2.grid.getSelections()[0];
7260 var ieid = row.data.ieId;
7261 var mbox = row.data.mbox;
7262 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7263 SUGAR.email2.contextMenus.assignmentDialog.hide();
7264 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7270 showEmailDetailView : function(o) {
7272 var SED = SUGAR.email2.detailView;
7273 var ret = JSON.parse(o.responseText);
7275 if(!SED.quickCreateDialog) {
7276 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7280 constraintoviewport: true,
7282 autofillheight: "body",
7285 SED.quickCreateDialog.renderEvent.subscribe(function() {
7286 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7288 for (var i in this.body.childNodes) {
7289 if (this.body.childNodes[i].offsetHeight)
7290 contH += this.body.childNodes[i].offsetHeight;
7292 this.body.style.overflow = "auto";
7293 this.body.style.width = "800px";
7294 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7296 }, SED.quickCreateDialog);
7298 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7299 SED.quickCreateDialog.setBody(ret.html);
7300 SED.quickCreateDialog.render();
7301 SUGAR.util.evalScript(ret.html);
7302 SED.quickCreateDialog.show();
7305 showAssignmentDialogWithData : function(o) {
7306 var SEC = SUGAR.email2.contextMenus;
7308 var ret = JSON.parse(o.responseText);
7309 if (!SEC.assignmentDialog) {
7310 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7313 constraintoviewport: true,
7316 SEC.assignmentDialog.setBody("");
7317 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7318 SEC.assignmentDialog.renderEvent.subscribe(function() {
7319 var iev = YAHOO.util.Dom.get("Distribute");
7321 this.body.style.width = "700px";
7323 }, SEC.assignmentDialog);
7324 SEC.assignmentDialog.render();
7326 SEC.assignmentDialog.setBody(ret);
7327 SEC.assignmentDialog.render();
7329 SEC.assignmentDialog.show();
7330 SUGAR.util.evalScript(ret);
7333 showImportForm : function(o) {
7334 var SED = SUGAR.email2.detailView;
7335 var ret = JSON.parse(o.responseText);
7337 document.getElementById('quickCreateContent').innerHTML = "";
7343 if(!SED.importDialog) {
7344 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7348 constraintoviewport: true,
7350 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7351 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7355 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7356 SED.importDialog.setBody("");
7357 SED.importDialog.hideEvent.subscribe(function(){
7358 for(var i in QSFieldsArray) {
7359 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7360 QSFieldsArray[i].destroy();
7361 delete QSFieldsArray[i];
7363 if (QSProcessedFieldsArray[i]) {
7364 QSProcessedFieldsArray[i] = false;
7368 SED.importDialog.renderEvent.subscribe(function() {
7369 var iev = YAHOO.util.Dom.get("ImportEditView");
7371 //this.body.style.height = (iev.clientHeight + 10) + "px";
7372 this.body.style.width = "600px";
7374 }, SED.importDialog);
7375 SED.importDialog.render();
7377 SED.importDialog.setBody(ret.html);
7378 SED.importDialog.ret = ret;
7379 SUGAR.util.evalScript(ret.html);
7380 SED.importDialog.render();
7382 SED.importDialog.show();
7383 SED.importDialog.focusFirstButton();
7385 getImportAction : function(ret) {
7386 if (!check_form('ImportEditView')) return false;
7387 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7388 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7392 var editView = document.getElementById('ImportEditView');
7393 if (editView.assigned_user_id != null) {
7394 get = get + "&user_id=" + editView.assigned_user_id.value
7395 //var user_id = editView.assigned_user_id.value;
7397 var parent_id = editView.parent_id.value;
7398 var parent_type = editView.parent_type.value;
7399 var row = SUGAR.email2.grid.getSelectedRows()[0];
7400 row = SUGAR.email2.grid.getRecord(row);
7401 var data = row.getData();
7402 var ieId = data.ieId;
7403 var mbox = data.mbox;
7404 var serverDelete = editView.serverDelete.checked;
7405 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7407 for(i=0; i<emailUids.length; i++) {
7409 uids += app_strings.LBL_EMAIL_DELIMITER;
7411 uids += emailUids[i];
7414 var action = 'importEmail&uid=';
7416 action = 'moveEmails';
7417 action = action + '&sourceFolder=' + ret['srcFolder'];
7418 action = action + '&sourceIeId=' + ret['srcIeId'];
7419 action = action + '&destinationFolder=' + ret['dstFolder'];
7420 action = action + '&destinationIeId=' + ret['dstIeId'];
7421 action = action + '&emailUids=';
7423 if (action.search(/importEmail/) != -1) {
7424 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7426 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7429 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7430 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7431 SUGAR.email2.detailView.importDialog.hide();
7432 document.getElementById('importDialogContent').innerHTML = "";
7435 showRelateForm : function(o) {
7436 var SED = SUGAR.email2.detailView;
7437 var ret = JSON.parse(o.responseText);
7438 document.getElementById('quickCreateContent').innerHTML = "";
7443 dialog_loaded = true;
7445 if(!SED.relateDialog) {
7446 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7451 constraintoviewport: true,
7453 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7454 if (!check_form('RelateEditView')) return false;
7456 var editView = document.getElementById('RelateEditView');
7457 var parent_id = editView.parent_id.value;
7458 var parent_type = editView.parent_type.value;
7459 var row = SUGAR.email2.grid.getSelectedRows()[0];
7460 row = SUGAR.email2.grid.getRecord(row);
7461 var ieId = row.getData().ieId;
7462 var mbox = row.getData().mbox;
7463 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7465 for(i=0; i<emailUids.length; i++) {
7467 uids += app_strings.LBL_EMAIL_DELIMITER;
7469 uids += emailUids[i];
7471 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7472 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7473 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7474 SED.relateDialog.hide();
7475 document.getElementById('relateDialogContent').innerHTML = "";
7480 SED.relateDialog.hideEvent.subscribe(function(){
7481 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7482 QSFieldsArray['ImportEditView_parent_name'].destroy();
7483 delete QSFieldsArray['ImportEditView_parent_name'];
7485 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7486 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7490 SED.relateDialog.renderEvent.subscribe(function() {
7491 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7493 for (var i in this.body.childNodes) {
7494 if (this.body.childNodes[i].clientHeight)
7495 contH += this.body.childNodes[i].clientHeight;
7497 }, SED.relateDialog);
7498 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7501 SED.relateDialog.setBody(ret.html);
7502 SED.relateDialog.render();
7503 SUGAR.util.evalScript(ret.html);
7504 SED.relateDialog.show();
7508 * DetailView callbacks
7510 AjaxObject.detailView.callback = {
7512 success : function(o) {
7514 var ret = JSON.parse(o.responseText);
7515 SUGAR.email2.detailView.consumeMetaDetail(ret);
7517 argument: [targetDiv],
7518 failure : AjaxObject.handleFailure,
7523 success : function(o) {
7525 var ret = JSON.parse(o.responseText);
7526 SUGAR.email2.detailView.consumeMetaPreview(ret);
7528 failure : AjaxObject.handleFailure,
7533 success : AjaxObject.detailView.displayPrintable,
7534 failure : AjaxObject.handleFailure,
7535 timeout : AjaxObject.timeout,
7539 success : AjaxObject.detailView.displayView,
7540 failure : AjaxObject.handleFailure,
7541 timeout : AjaxObject.timeout,
7550 AjaxObject.folders = {
7552 * check-mail post actions
7554 checkMailCleanup : function(o) {
7556 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7558 // refresh focus ListView
7559 SE.listView.refreshGrid();
7560 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7565 rebuildFolders : function(o) {
7568 var data = JSON.parse(o.responseText);
7570 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7571 SUGAR.email2.folders.setSugarFolders();
7574 AjaxObject.folders.callback = {
7576 success : AjaxObject.folders.checkMailCleanup,
7577 failure : AjaxObject.handleFailure,
7578 timeout : 600000, // 5 mins
7583 AjaxObject.rules = {
7584 loadRulesForSettings : function(o) {
7585 document.getElementById("rulesListCell").innerHTML = o.responseText;
7586 // assume we have the class we need
7587 SUGAR.routing.getStrings();
7588 SUGAR.routing.getDependentDropdowns();
7591 //// END PER MODULE CALLBACK OBJECTS
7592 ///////////////////////////////////////////////////////////////////////////
7596 success : AjaxObject.handleSuccess,
7597 failure : AjaxObject.handleFailure,
7598 timeout : AjaxObject.timeout,
7601 var callbackAccount = {
7602 success : AjaxObject.ieSaveSuccess,
7603 failure : AjaxObject.handleFailure,
7604 timeout : AjaxObject.timeout,
7607 var callbackAccountDelete = {
7608 success : AjaxObject.ieDeleteSuccess,
7609 failure : AjaxObject.handleFailure,
7610 timeout : AjaxObject.timeout,
7613 var callbackOutboundTest = {
7614 success : AjaxObject.ieSendSuccess,
7615 failure : AjaxObject.handleFailure,
7616 timeout : AjaxObject.timeout,
7622 var callbackTeamInfoForSettings = {
7623 success : function (o) {
7624 var data = JSON.parse(o.responseText);
7625 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7627 failure : AjaxObject.handleFailure,
7628 timeout : AjaxObject.timeout,
7633 var callbackStatusForImport = {
7634 success : function (o) {
7636 if (o.responseText != "") {
7637 var statusString = "";
7638 var data = JSON.parse(o.responseText);
7639 for(i=0; i<data.length; i++) {
7640 statusString = statusString + data[i] + '<br/>';
7642 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7644 SE.listView.refreshGrid();
7647 failure : AjaxObject.handleFailure,
7648 timeout : AjaxObject.timeout,
7652 var callbackComposeCache = {
7653 success : AjaxObject.composeCache,
7654 failure : AjaxObject.handleFailure,
7655 timeout : AjaxObject.timeout,
7658 var callbackDelete = {
7659 success : AjaxObject.handleDeleteReturn,
7660 failure : AjaxObject.handleFailure,
7661 timeout : AjaxObject.timeout,
7664 var callbackEmailDetailMultiple = {
7665 success : function(o) {
7667 var retMulti = JSON.parse(o.responseText);
7668 var ret = new Object();
7670 for(var i=0; i<retMulti.length; i++) {
7673 SUGAR.email2._setDetailCache(ret);
7674 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7677 failure : AjaxObject.handleFailure,
7681 var callbackListViewSortOrderChange = {
7682 success : AjaxObject.saveListViewSortOrderPart2,
7683 failure : AjaxObject.handleFailure,
7684 timeout : AjaxObject.timeout,
7686 argument : [ieId, ieName, focusFolder]
7688 var callbackEmptyTrash = {
7689 success : function(o) {
7691 AjaxObject.folderRenameCleanup;
7693 failure : AjaxObject.handleFailure,
7694 timeout : AjaxObject.timeout,
7697 var callbackClearCacheFiles = {
7698 success : function(o) {
7701 failure : AjaxObject.handleFailure,
7702 timeout : AjaxObject.timeout,
7705 var callbackFolderRename = {
7706 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7707 failure : AjaxObject.handleFailure,
7708 timeout : AjaxObject.timeout,
7711 var callbackFolderDelete = {
7712 success : function(o) {
7713 var ret = JSON.parse(o.responseText);
7715 if (ret.folder_id) {
7716 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7718 SUGAR.email2.tree.removeNode(node, true);
7719 } else if (ret.ieId && ret.mbox) {
7720 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7722 SUGAR.email2.tree.removeNode(node, true);
7725 //SUGAR.email2.folders.loadSettingFolder();
7728 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7731 failure : AjaxObject.handleFailure,
7732 timeout : AjaxObject.timeout,
7735 var callbackFolderSave = {
7736 success : function(o) {
7737 var ret = JSON.parse(o.responseText);
7739 switch(ret.action) {
7740 case 'newFolderSave':
7741 SUGAR.email2.folders.rebuildFolders();
7745 failure : AjaxObject.handleFailure,
7746 timeout : AjaxObject.timeout,
7749 var callbackFolderSubscriptions = {
7750 success : AjaxObject.updateFolderSubscriptions,
7751 failure : AjaxObject.handleFailure,
7752 timeout : AjaxObject.timeout,
7755 var callbackFolderUpdate = {
7756 success : AjaxObject.updateFrameFolder,
7757 failure : AjaxObject.handleFailure,
7758 timeout : AjaxObject.timeout,
7761 var callbackFolders = {
7762 success : AjaxObject.folders.rebuildFolders,
7763 //success : void(true),
7764 failure : AjaxObject.handleFailure,
7765 timeout : AjaxObject.timeout,
7768 var callbackFullSync = {
7769 success : AjaxObject.fullSyncCleanup,
7770 failure : AjaxObject.handleFailure,
7771 timeout : 9999999999999,
7774 var callbackGeneric = {
7775 success : function() {
7778 failure : AjaxObject.handleFailure,
7779 timeout : AjaxObject.timeout,
7782 var callbackIeAccountRetrieve = {
7783 success : function(o) {
7784 // return JSON encoding
7786 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7787 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7789 failure : AjaxObject.handleFailure,
7790 timeout : AjaxObject.timeout,
7793 var callbackImportOneEmail = {
7794 success : AjaxObject.detailView.showImportForm,
7795 failure : AjaxObject.handleFailure,
7796 timeout : AjaxObject.timeout,
7799 var callbackRelateEmail = {
7800 success : AjaxObject.detailView.showRelateForm,
7801 failure : AjaxObject.handleFailure,
7802 timeout : AjaxObject.timeout,
7805 var callbackEmailDetailView = {
7806 success : AjaxObject.detailView.showEmailDetailView,
7807 failure : AjaxObject.handleFailure,
7808 timeout : AjaxObject.timeout,
7811 var callbackAssignmentDialog = {
7812 success : AjaxObject.detailView.showAssignmentDialogWithData,
7813 failure : AjaxObject.handleFailure,
7814 timeout : AjaxObject.timeout,
7817 var callbackAssignmentAction = {
7818 success : function(o) {
7819 SE.listView.refreshGrid();
7821 if(o.responseText != '') {
7822 overlay('Assignment action result', o.responseText, 'alert');
7825 failure : AjaxObject.handleFailure,
7826 timeout : AjaxObject.timeout,
7829 var callbackMoveEmails = {
7830 success : function(o) {
7831 SE.listView.refreshGrid();
7833 if(o.responseText != '') {
7834 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7837 failure : AjaxObject.handleFailure,
7838 timeout : AjaxObject.timeout,
7841 var callbackLoadAttachments = {
7842 success : AjaxObject.loadAttachments,
7843 failure : AjaxObject.handleFailure,
7844 timeout : AjaxObject.timeout,
7847 var callbackLoadRules = {
7848 success : AjaxObject.rules.loadRulesForSettings,
7849 failure : AjaxObject.handleFailure,
7850 timeout : AjaxObject.timeout,
7853 var callbackLoadSignature = {
7854 success : AjaxObject.loadSignature,
7855 failure : AjaxObject.handleFailure,
7856 timeout : AjaxObject.timeout,
7859 var callbackDeleteSignature = {
7860 success : AjaxObject.handleDeleteSignature,
7861 failure : AjaxObject.handleFailure,
7862 timeout : AjaxObject.timeout,
7865 /*var callbackMoveEmails = {
7866 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7867 failure : AjaxObject.handleFailure,
7868 timeout : AjaxObject.timeout,
7871 var callbackOutboundSave = {
7872 success : AjaxObject.accounts.saveOutboundCleanup,
7873 failure : AjaxObject.handleFailure,
7874 timeout : AjaxObject.timeout,
7877 var callbackDefaultOutboundSave = {
7878 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7879 failure : AjaxObject.handleFailure,
7880 timeout : AjaxObject.timeout,
7883 var callbackQuickCreate = {
7884 success : AjaxObject.detailView.showQuickCreateForm,
7885 failure : AjaxObject.handleFailure,
7886 timeout : AjaxObject.timeout,
7889 var callbackQuickCreateSave = {
7890 success : AjaxObject.detailView.saveQuickCreateForm,
7891 failure : AjaxObject.handleFailure,
7892 timeout : AjaxObject.timeout,
7895 var callbackQuickCreateSaveAndAddToAddressBook = {
7896 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7897 failure : AjaxObject.handleFailure,
7898 timeout : AjaxObject.timeout,
7901 var callbackQuickCreateSaveAndReply = {
7902 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7903 failure : AjaxObject.handleFailure,
7904 timeout : AjaxObject.timeout,
7907 var callbackQuickCreateSaveAndReplyCase = {
7908 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7909 failure : AjaxObject.handleFailure,
7910 timeout : AjaxObject.timeout,
7913 var callbackRebuildShowAccountList = {
7914 success : AjaxObject.rebuildShowFolders,
7915 failure : AjaxObject.handleFailure,
7916 timeout : AjaxObject.timeout,
7920 var callbackRefreshSugarFolders = {
7921 success : function(o) {
7922 var t = JSON.parse(o.responseText);
7923 SUGAR.email2.folders.setSugarFoldersEnd(t);
7925 failure : AjaxObject.handleFailure,
7926 timeout : AjaxObject.timeout,
7929 var callbackReplyForward = {
7930 success : AjaxObject.handleReplyForward,
7931 finish : function(a, retryCount) {
7932 if (typeof(retryCount) == 'undefined') {
7937 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7938 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7940 var html = t.getContent();
7942 if (a.type != 'draft') {
7943 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7944 html += " <div><hr></div>" + a.description;
7946 html = " <div><hr></div>" + a.description + html;
7949 html = a.description;
7952 t.setContent(html);//
7955 if (retryCount < 5) {
7956 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7960 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7961 if (tabArray != null && tabArray.length > 0) {
7962 for (i = 0 ; i < tabArray.length ; i++) {
7963 var tabObject = tabArray[i];
7964 if (tabObject.get("id") == ("composeTab" + idx)) {
7965 var tabLabel = a.name;
7966 if (tabLabel != null && tabLabel.length > 25) {
7967 tabLabel = tabLabel.substring(0, 25) + "...";
7969 tabObject.get("labelEl").firstChild.data = tabLabel;
7975 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
7976 if (a.parent_name != null && a.parent_name != "") {
7977 document.getElementById('data_parent_name' + idx).value = a.parent_name;
7979 if (a.parent_type != null && a.parent_type != "") {
7980 document.getElementById('data_parent_type' + idx).value = a.parent_type;
7982 if (a.parent_id != null && a.parent_id != "") {
7983 document.getElementById('data_parent_id' + idx).value = a.parent_id;
7985 if (a.fromAccounts.status) {
7986 var addressFrom = document.getElementById('addressFrom' + idx);
7987 SUGAR.email2.util.emptySelectOptions(addressFrom);
7988 var fromAccountOpts = a.fromAccounts.data;
7989 for(i=0; i<fromAccountOpts.length; i++) {
7990 var key = fromAccountOpts[i].value;
7991 var display = fromAccountOpts[i].text;
7992 var opt = new Option(display, key);
7993 if (fromAccountOpts[i].selected) {
7994 opt.selected = true;
7996 addressFrom.options.add(opt);
8002 failure : AjaxObject.handleFailure,
8003 timeout : AjaxObject.timeout,
8005 argument : [sendType]
8007 var callbackSendEmail = {
8008 success : AjaxObject.sendEmailCleanUp,
8009 failure : AjaxObject.handleFailure,
8010 timeout : AjaxObject.timeout,
8013 var callbackSettings = {
8014 success : AjaxObject.updateUserPrefs,
8015 failure : AjaxObject.handleFailure,
8016 timeout : AjaxObject.timeout,
8019 var callbackSettingsFolderRefresh = {
8020 success : AjaxObject.settingsFolderRefresh,
8021 failure : AjaxObject.handleFailure,
8022 timeout : AjaxObject.timeout,
8025 var callbackLoadSettingFolder = {
8026 success : function(o) {
8027 AjaxObject.settingsFolderRefresh(o);
8028 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8030 failure : AjaxObject.handleFailure,
8031 timeout : AjaxObject.timeout,
8035 var callbackUploadAttachment = {
8036 success : AjaxObject.uploadAttachmentSuccessful,
8037 upload : AjaxObject.uploadAttachmentSuccessful,
8038 failure : AjaxObject.handleFailure,
8039 timeout : AjaxObject.timeout,
8042 var callbackUserPrefs = {
8043 success : function(o) {
8044 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8046 failure : AjaxObject.handleFailure,
8047 timeout : AjaxObject.timeout,
8051 var callbackContextmenus = {
8053 success : AjaxObject.markEmailCleanup,
8054 failure : AjaxObject.handleFailure,
8055 timeout : AjaxObject.timeout,
8060 var callbackCheckEmail2 = {
8061 success : function(o) {
8062 var ret = JSON.parse(o.responseText);
8063 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8067 failure : AjaxObject.handleFailure,
8068 timeout : AjaxObject.timeout,
8070 }// End of File modules/Emails/javascript/ajax.js
8072 /*********************************************************************************
8073 * SugarCRM is a customer relationship management program developed by
8074 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8076 * This program is free software; you can redistribute it and/or modify it under
8077 * the terms of the GNU Affero General Public License version 3 as published by the
8078 * Free Software Foundation with the addition of the following permission added
8079 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8080 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8081 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8083 * This program is distributed in the hope that it will be useful, but WITHOUT
8084 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8085 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8088 * You should have received a copy of the GNU Affero General Public License along with
8089 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8090 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8093 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8094 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8096 * The interactive user interfaces in modified source and object code versions
8097 * of this program must display Appropriate Legal Notices, as required under
8098 * Section 5 of the GNU Affero General Public License version 3.
8100 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8101 * these Appropriate Legal Notices must retain the display of the "Powered by
8102 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8103 * technical reasons, the Appropriate Legal Notices must display the words
8104 * "Powered by SugarCRM".
8105 ********************************************************************************/
8107 function gridInit() {
8108 if(SUGAR.email2.grid) {
8109 SUGAR.email2.grid.destroy();
8115 var Ck = YAHOO.util.Cookie;
8116 var widths = [ 10, 10, 150, 250, 175, 125 ];
8118 if (Ck.get("EmailGridWidths")) {
8119 for (var i=0; i < widths.length; i++) {
8120 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8123 for (var i=0; i < widths.length; i++) {
8124 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8128 // changes "F" to an icon
8129 function flaggedIcon(cell, record, column, value) {
8131 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8134 // changes "A" to replied icon
8135 function repliedIcon(cell, record, column, value) {
8137 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8140 function attachIcon(cell, record, column, value) {
8142 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8149 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8154 formatter: attachIcon,
8158 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8163 formatter: flaggedIcon,
8167 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8172 formatter: repliedIcon,
8176 label: app_strings.LBL_EMAIL_FROM,
8183 label: app_strings.LBL_EMAIL_SUBJECT,
8190 label: mod_strings.LBL_LIST_DATE,
8197 label: app_strings.LBL_EMAIL_TO,
8233 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8234 responseType: YAHOO.util.DataSource.TYPE_JSON,
8236 resultsList: 'Email',
8237 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8238 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8244 action : "EmailUIAjax",
8245 emailUIAction : "getMessageList",
8248 forceRefresh : "false"
8250 if(lazyLoadFolder != null) {
8251 params['mbox'] = lazyLoadFolder.folder;
8252 params['ieId'] = lazyLoadFolder.ieId;
8253 //Check if the folder is a Sugar Folder
8254 var test = new String(lazyLoadFolder.folder);
8255 if(test.match(/SUGAR\./)) {
8256 params['emailUIAction'] = 'getMessageListSugarFolders';
8257 params['mbox'] = test.substr(6);
8260 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8263 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8264 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8266 paginator: new YAHOO.widget.Paginator({
8267 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8268 containers : ["dt-pag-nav"],
8269 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8270 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8271 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8272 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8273 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8275 initialRequest:SUGAR.util.paramsToUrl(params),
8282 //Override Paging request construction
8283 grid.set("generateRequest", function(oState, oSelf) {
8284 oState = oState || {pagination:null, sortedBy:null};
8285 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8286 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8287 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8288 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8289 // Build the request
8291 SUGAR.util.paramsToUrl(oSelf.params) +
8294 "&start=" + startIndex +
8295 ((results !== null) ? "&limit=" + results : "");
8300 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8301 oPayload = oPayload || { };
8303 oPayload.totalRecords = oResponse.meta.total;
8304 oPayload.unreadRecords = oResponse.meta.unread;
8306 var tabObject = SE.innerLayout.get("tabs")[0];
8308 if (this.params.mbox != null) {
8309 mboxTitle = this.params.mbox;
8311 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8312 tabObject.get("labelEl").firstChild.data = tabtext;
8315 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8317 node.data.unseen = oResponse.meta.unread;
8318 SE.accounts.renderTree();
8324 var resize = grid.resizeGrid = function () {
8325 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8326 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8328 grid.convertDDRows = function() {
8329 var rowEl = this.getFirstTrEl();
8330 while (rowEl != null) {
8331 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8332 rowEl = this.getNextTrEl(rowEl);
8337 grid.on("columnResizeEvent", function(o) {
8338 //Find the index of the column
8339 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8340 for (var i=0; i < colSet.length; i++) {
8341 if (o.column == colSet[i]) {
8342 //Store it in the cookie
8343 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8346 //this.resizeGrid();
8349 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8350 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8351 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8353 SUGAR.email2.listViewLayout.on("render", resize);
8356 //Setup the default load parameters
8357 SUGAR.email2.grid.params = params;
8359 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8360 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8361 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8368 function initRowDD() {
8369 var sg = SUGAR.email2.grid,
8370 Dom = YAHOO.util.Dom;
8371 sg.DDRow = function(oDataTable, oRecord, elTr) {
8372 if(oDataTable && oRecord && elTr) {
8373 this.ddtable = oDataTable;
8374 this.table = oDataTable.getTableEl();
8377 this.newIndex = null;
8379 this.initFrame(); // Needed for DDProxy
8380 this.invalidHandleTypes = {};
8384 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8385 _resizeProxy: function() {
8386 this.constructor.superclass._resizeProxy.apply(this, arguments);
8387 var dragEl = this.getDragEl(),
8389 var xy = Dom.getXY(el);
8391 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8392 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8393 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8394 Dom.setStyle(dragEl, 'display', "");
8397 startDrag: function(x, y) {
8398 //Check if we should be dragging a set of rows rather than just the one.
8399 var selectedRows = this.ddtable.getSelectedRows();
8400 var iSelected = false;
8401 for (var i in selectedRows) {
8402 if (this.rowEl.id == selectedRows[i]) {
8409 for (var i in selectedRows) {
8410 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8413 this.rows = [this.row];
8414 this.ddtable.unselectAllRows();
8415 this.ddtable.selectRow(this.row);
8418 //Initialize the dragable proxy
8419 var dragEl = this.getDragEl();
8420 var clickEl = this.getEl();
8421 Dom.setStyle(clickEl, "opacity", "0.25");
8422 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8423 Dom.addClass(dragEl, "yui-dt-liner");
8424 Dom.setStyle(dragEl, "opacity", "0.5");
8425 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8426 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8427 Dom.setStyle(dragEl, "border", "2px solid gray");
8430 clickValidator: function(e) {
8431 if (this.row.getData()[0] == " ")
8433 var target = YAHOO.util.Event.getTarget(e);
8434 return ( this.isValidHandleChild(target) &&
8435 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8438 * This funciton checks that the target of the drag is a table row in this
8439 * DDGroup and simply moves the sourceEL to that location as a preview.
8441 onDragOver: function(ev, id) {
8442 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8443 if (node && node != this.targetNode) {
8444 this.targetNode = node;
8445 SUGAR.email2.folders.unhighliteAll();
8450 onDragOut: function(e, id) {
8451 if (this.targetNode) {
8452 SUGAR.email2.folders.unhighliteAll();
8453 this.targetNode = false;
8456 endDrag: function() {
8457 Dom.setStyle(this.getEl(), "opacity", "");
8458 Dom.setStyle(this.getDragEl(), "display", "none");
8459 if (this.targetNode) {
8460 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8462 SUGAR.email2.folders.unhighliteAll();
8468 function AddressSearchGridInit() {
8469 function moduleIcon(elCell, oRecord, oColumn, oData) {
8470 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8472 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8473 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8475 var checkHeader = '<input type="checkbox" ';
8476 if (SUGAR.email2.util.isIe()) {
8477 checkHeader += 'style="top:-5px" ';
8479 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8484 formatter: selectionCheckBox,
8488 label: mod_strings.LBL_LIST_TYPE,
8490 formatter: moduleIcon,
8494 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8500 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8506 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8507 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8509 resultsList: 'Person',
8510 fields: ['name', 'email', 'bean_id', 'bean_module'],
8511 metaFields: {total: 'TotalCount'}
8513 //enable sorting on the server accross all data
8516 dataModel.params = {
8519 action : "EmailUIAjax",
8520 emailUIAction:"getAddressSearchResults"
8522 var rb = document.getElementById('hasRelatedBean').checked;
8524 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8525 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8526 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8527 dataModel.params['related_bean_id'] = relatedBeanId;
8528 dataModel.params['related_bean_type'] = relatedBeanType;
8529 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8531 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8533 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8534 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8536 paginator: new YAHOO.widget.Paginator({
8538 containers : ["dt-pag-nav-addressbook"],
8539 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8540 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8541 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8542 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8543 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8545 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8549 //Override Paging request construction
8550 grid.set("generateRequest", function(oState, oSelf) {
8551 oState = oState || {pagination:null, sortedBy:null};
8552 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8553 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8554 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8555 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8556 // Build the request
8558 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8559 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8560 ((results !== null) ? "&limit=" + results : "");
8564 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8565 oPayload = oPayload || { };
8566 oPayload.totalRecords = oResponse.meta.total;
8570 grid.clickToggleSelect= function(args) {
8571 var isIE = (args.event.target == null);
8572 var targetElement = isIE ? args.event.srcElement : args.event.target;
8573 if(targetElement.type == null || targetElement.type != 'checkbox') {
8574 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8578 grid.reSelectRowsOnRender = function (){
8579 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8580 for (var i = 0; i < rows.length; i++)
8582 var emailAddress = rows[i].getData("email");
8583 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8586 rows[i].setData("selected", true);
8587 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8591 rows[i].setData("selected", false);
8592 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8596 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8597 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8598 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8599 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8602 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8603 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8605 grid.toggleSelectCheckbox = function(id,checked){
8606 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8607 row.setData("checked",checked);
8609 grid.toggleSelect = function(id, checked) {
8610 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8611 checked = row.getData("selected");
8614 SUGAR.email2.addressBook.grid.selectRow(row);
8615 SE.addressBook.insertContactRowToResultTable(id,null)
8618 SUGAR.email2.addressBook.grid.unselectRow(row);
8619 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8621 row.setData("selected", !checked);
8624 grid.toggleSelectAll = function(checked) {
8625 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8626 for (var i = 0; i < rows.length; i++) {
8627 if (typeof(rows[i]) != "undefined")
8628 rows[i].setData("checked", checked);
8630 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8631 for (var i = 0; i < checkBoxes.length; i++) {
8632 checkBoxes[i].checked = checked;
8636 //Initialize the grid result table.
8637 AddressSearchResultsGridInit();
8643 * Initalize the results table for the address book selection.
8646 function AddressSearchResultsGridInit()
8649 /* Full name sort funciton to compare by last name if available */
8650 var fullNameSort = function(a, b, desc) {
8651 // Deal with empty values
8652 if(!YAHOO.lang.isValue(a))
8653 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8654 else if(!YAHOO.lang.isValue(b))
8657 var aNames = a.getData("name").split(' ');
8658 var bNames = b.getData("name").split(' ');
8660 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8661 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8663 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8667 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8668 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8669 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8671 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})},
8672 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8674 var myDataSource = new YAHOO.util.DataSource([]);
8675 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8676 myDataSource.responseSchema = {
8677 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8680 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8681 width: "350px",height: "250px", MSG_EMPTY: " "});
8683 var highlightEditableCell = function(oArgs) {
8684 var elCell = oArgs.target;
8685 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8686 this.highlightCell(elCell);
8690 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8691 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8692 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8693 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8694 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8696 //Setup the context menus
8697 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8698 var task = p_aArgs[1];
8701 var elRow = this.contextEventTarget;
8702 elRow = p_myDataTable.getTrEl(elRow);
8709 var oRecord = p_myDataTable.getRecord(elRow);
8710 p_myDataTable.deleteRow(elRow);
8711 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8716 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8717 {trigger:gridResults.getTbodyEl()});
8718 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8719 contextMenu.render("addrSearchResultGrid");
8720 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8722 // End of File modules/Emails/javascript/grid.js
8724 /*********************************************************************************
8725 * SugarCRM is a customer relationship management program developed by
8726 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8728 * This program is free software; you can redistribute it and/or modify it under
8729 * the terms of the GNU Affero General Public License version 3 as published by the
8730 * Free Software Foundation with the addition of the following permission added
8731 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8732 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8733 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8735 * This program is distributed in the hope that it will be useful, but WITHOUT
8736 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8737 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8740 * You should have received a copy of the GNU Affero General Public License along with
8741 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8742 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8745 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8746 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8748 * The interactive user interfaces in modified source and object code versions
8749 * of this program must display Appropriate Legal Notices, as required under
8750 * Section 5 of the GNU Affero General Public License version 3.
8752 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8753 * these Appropriate Legal Notices must retain the display of the "Powered by
8754 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8755 * technical reasons, the Appropriate Legal Notices must display the words
8756 * "Powered by SugarCRM".
8757 ********************************************************************************/
8762 function complexLayoutInit() {
8763 var se = SUGAR.email2;
8764 var Dom = YAHOO.util.Dom;
8766 getInnerLayout : function(rows) {
8767 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8768 parent: se.complexLayout,
8774 scroll:false, // grid should autoScroll itself
8776 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8784 body: "<div id='listBottom' />"
8792 body: "<div id='listRight' />",
8793 titlebar: false //,header: "right"
8796 se.complexLayout.on("render", function(){
8797 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8798 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8799 SUGAR.email2.listViewLayout.set("height", height);
8800 SUGAR.email2.listViewLayout.render();
8802 se.listViewLayout.render();
8804 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8805 var rp = se.listViewLayout.resizePreview = function() {
8806 var pre = Dom.get("displayEmailFramePreview");
8808 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8809 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8812 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8813 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8814 se.e2Layout.setPreviewPanel(rows);
8815 se.previewLayout = se.listViewLayout;
8816 return se.listViewLayout;
8819 getInnerLayout2Rows : function() {
8820 return this.getInnerLayout(true);
8822 getInnerLayout2Columns : function() {
8823 return this.getInnerLayout(false);
8827 // initialize state manager, we will use cookies
8828 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8829 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8830 se.complexLayout = new YAHOO.widget.Layout("container", {
8833 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8834 width: Dom.getViewportWidth() - 40,
8838 body: "<div id='emailtabs'></div>"
8843 body: "<div id='lefttabs'></div>",
8853 header: Dom.get('footerLinks').innerHTML,
8860 se.complexLayout.render();
8861 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8862 tp.addTab(new YAHOO.widget.Tab({
8865 content : "<div id='listViewDiv'/>",
8869 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8870 tp.appendTo(centerEl);
8872 tp.get("element").style.borderRight = "1px solid #666"
8874 var listV = this.getInnerLayout2Rows();
8875 listV.set("height", tp.get("element").clientHeight - 25);
8878 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8879 var folderTab = new YAHOO.widget.Tab({
8880 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8882 content : "<div id='emailtree'/>",
8886 folderTab.on("activeChange", function(o){
8888 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8891 se.leftTabs.addTab(folderTab);
8893 var tabContent = SUGAR.util.getAndRemove("searchTab");
8894 var searchTab = new YAHOO.widget.Tab({
8895 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8897 content : tabContent.innerHTML,
8900 searchTab.on("activeChange", function(o){
8903 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8904 //Setup the calendars if needed
8905 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_from", singleClick : true, step : 1, weekNumbers:false});
8906 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_to", singleClick : true, step : 1, weekNumbers:false});
8908 //Initalize sqs object for assigned user name
8909 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
8911 //Attach event handler for when the relate module option is selected for the correct sqs object
8912 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8913 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8914 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
8915 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8917 //If enter key is pressed, perform search
8918 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8919 for(var i=0; i < addKeyPressFields.length;i++)
8921 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8922 if (e.keyCode == 13) {
8923 YAHOO.util.Event.stopEvent(e);
8924 SUGAR.email2.search.searchAdvanced();
8928 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
8930 //Clear parent values if selecting another parent type.
8931 YAHOO.util.Event.addListener('data_parent_type_search','change',
8933 document.getElementById('data_parent_id_search').value ='';
8934 document.getElementById('data_parent_name_search').value ='';
8939 se.leftTabs.addTab(searchTab);
8941 var resizeTabBody = function() {
8942 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8943 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8946 se.complexLayout.on("render", resizeTabBody);
8947 se.leftTabs.on("activeTabChange", resizeTabBody);
8948 //hack to allow left pane scroll bar to fully show
8949 var lefttabsDiv = document.getElementById('lefttabs');
8950 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8951 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8952 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8955 initSQSObject: function(formName,fieldName)
8957 var fullFieldName = formName + '_' + fieldName; //SQS Convention
8958 var resultName = fullFieldName + '_' + 'results';
8960 if (QSFieldsArray[fullFieldName] != null)
8962 QSFieldsArray[fullFieldName].destroy();
8963 delete QSFieldsArray[fullFieldName];
8965 if (QSProcessedFieldsArray[fullFieldName])
8966 QSProcessedFieldsArray[fullFieldName] = false;
8968 if( Dom.get(resultName) )
8970 var obj = document.getElementById(resultName);
8971 obj.parentNode.removeChild(obj);
8974 setPreviewPanel: function(rows) {
8976 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
8977 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
8978 Dom.get("listRight").innerHTML = "";
8979 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
8981 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
8982 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
8983 Dom.get("listBottom").innerHTML = "";
8984 Dom.get("listRight").innerHTML = "<div id='_blank' />";
8991 var myBufferedListenerObject = new Object();
8992 myBufferedListenerObject.refit = function() {
8993 if(SUGAR.email2.grid) {
8994 SUGAR.email2.grid.autoSize();
8997 // End of File modules/Emails/javascript/complexLayout.js
8999 /*********************************************************************************
9000 * SugarCRM is a customer relationship management program developed by
9001 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9003 * This program is free software; you can redistribute it and/or modify it under
9004 * the terms of the GNU Affero General Public License version 3 as published by the
9005 * Free Software Foundation with the addition of the following permission added
9006 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9007 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9008 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9010 * This program is distributed in the hope that it will be useful, but WITHOUT
9011 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9012 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9015 * You should have received a copy of the GNU Affero General Public License along with
9016 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9017 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9020 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9021 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9023 * The interactive user interfaces in modified source and object code versions
9024 * of this program must display Appropriate Legal Notices, as required under
9025 * Section 5 of the GNU Affero General Public License version 3.
9027 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9028 * these Appropriate Legal Notices must retain the display of the "Powered by
9029 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9030 * technical reasons, the Appropriate Legal Notices must display the words
9031 * "Powered by SugarCRM".
9032 ********************************************************************************/
9035 /******************************************************************************
9036 * Initialize Email 2.0 Application
9039 //Override Sugar Languge so quick creates work properly
9042 function email2init() {
9045 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9046 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9047 if (!SUGAR.util.isTouchScreen()) {
9049 convert_urls : false,
9050 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9051 width: tinyConfig.width,
9052 theme: tinyConfig.theme,
9053 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9054 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9055 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9056 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9057 plugins : tinyConfig.plugins,
9058 elements : tinyConfig.elements,
9059 language : tinyConfig.language,
9060 extended_valid_elements : tinyConfig.extended_valid_elements,
9061 mode: tinyConfig.mode,
9062 strict_loading_mode : true,
9063 force_br_newlines : true,
9064 forced_root_block : ''
9067 //alert('loadedTiny');
9069 // initialze message overlay
9070 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9080 if (SUGAR.themes.tempHideLeftCol)
9081 SUGAR.themes.tempHideLeftCol();
9083 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9084 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9086 // set defaults for YAHOO.util.DragDropManager
9087 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9089 SUGAR.email2.nextYear = new Date();
9090 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9093 // initialize and display UI framework (complexLayout.js)
9094 complexLayoutInit();
9096 // initialize and display grid (grid.js)
9099 // initialize treeview for folders
9101 SUGAR.email2.folders.rebuildFolders(true);
9104 //Setup the Message Box overlay
9105 /*Ext.MessageBox.maxWidth = 350;
9106 Ext.MessageBox.minProgressWidth = 350;
9108 ///////////////////////////////////////////////////////////////////////////
9111 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9113 var SEC = SUGAR.email2.contextMenus;
9116 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9117 trigger: SUGAR.email2.grid.get("element"),
9120 emailMenu.subscribe("beforeShow", function() {
9121 var oTarget = this.contextEventTarget;
9122 if (typeof(oTarget) == "undefined")
9124 var grid = SUGAR.email2.grid;
9125 var selectedRows = grid.getSelectedRows();
9126 var multipleSelected = (selectedRows.length > 1) ? true: false;
9127 if (!multipleSelected)
9129 grid.unselectAllRows();
9130 grid.selectRow(oTarget);
9131 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9133 else if(multipleSelected)
9135 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9139 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9140 //us to access individual elements easier by name rather than by index
9141 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
9142 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9143 emailMenu.addItems([
9145 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9146 id: 'showDetailView',
9147 onclick: { fn: SEC.showDetailView }
9150 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9151 onclick: { fn: SEC.openMultiple }
9154 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9155 onclick: { fn: SEC.archiveToSugar }
9158 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9160 onclick: { fn: SEC.replyForwardEmailContext }
9163 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9165 onclick: { fn: SEC.replyForwardEmailContext }
9168 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9170 onclick: { fn: SEC.replyForwardEmailContext }
9173 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9175 onclick: { fn: SEC.markDeleted }
9178 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9180 onclick: { fn: SEC.viewPrintable }
9184 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9186 id: "markEmailMenu",
9189 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9190 onclick: { fn: SEC.markUnread }
9193 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9194 onclick: { fn: SEC.markRead }
9197 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9198 onclick: { fn: SEC.markFlagged }
9201 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9202 onclick: { fn: SEC.markUnflagged }
9208 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9210 onclick: { fn: SEC.assignEmailsTo }
9213 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9215 onclick: { fn: SEC.relateTo }
9218 SEC.emailListContextMenu.render();
9220 //Handle the Tree folder menu trigger ourselves
9221 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9225 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9229 SEC.frameFoldersContextMenu.addItems([
9230 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9231 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9232 onclick: { fn: function() {
9233 var node = SUGAR.email2.clickedFolderNode;
9234 if (node.data.ieId) {
9235 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9238 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
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, true)};
9247 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9248 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9249 onclick: { fn: SUGAR.email2.folders.folderAdd }
9252 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9253 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9254 onclick: { fn: SUGAR.email2.folders.folderDelete }
9257 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9258 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9259 onclick: { fn: SUGAR.email2.folders.folderRename }
9262 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9263 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9264 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9267 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9268 onclick: { fn: function() {
9269 var node = SUGAR.email2.clickedFolderNode;
9270 if (node.data.ieId) {
9271 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9275 SEC.frameFoldersContextMenu.render();
9277 SEC.initContactsMenu = function() {
9279 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9280 trigger: "contacts",
9283 SEC.contactsContextMenu.addItems([
9285 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9286 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9289 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9290 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9293 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9294 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9295 if (oTarget && !grid.isSelected(oTarget)) {
9296 grid.unselectAllRows();
9297 grid.selectRow(oTarget);
9300 SEC.contactsContextMenu.render();
9304 // set auto-check timer
9305 SUGAR.email2.folders.startCheckTimer();
9306 // check if we're coming from an email-link click
9307 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9309 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9311 //Init fix for YUI 2.7.0 datatable sort.
9312 SUGAR.email2.addressBook.initFixForDatatableSort();
9315 function createTreePanel(treeData, params) {
9316 var tree = new YAHOO.widget.TreeView(params.id);
9317 var root = tree.getRoot();
9319 //if (treeData.nodes && treeData[0].id == "Home")
9320 // treeData = treeData[0];
9322 addChildNodes(root, treeData);
9327 function addChildNodes(parentNode, parentData) {
9328 var Ck = YAHOO.util.Cookie;
9329 var nextyear = SUGAR.email2.nextYear;
9330 var nodes = parentData.nodes || parentData.children;
9332 if (typeof(nodes[i]) == 'object') {
9333 if (nodes[i].data) {
9334 nodes[i].data.href = '#';
9335 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9336 node.action = nodes[i].data.action;
9338 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9339 addChildNodes(parentNode, nodes[i]);
9342 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9343 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9345 nodes[i].className = nodes[i].cls;
9347 nodes[i].href = "#";
9348 if (nodes[i].text) nodes[i].label = nodes[i].text;
9349 //Override YUI child node creation
9350 if (nodes[i].children) {
9351 nodes[i].nodes = nodes[i].children;
9352 nodes[i].children = [ ];
9354 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9357 if (typeof(nodes[i].nodes) == 'object') {
9358 addChildNodes(node, nodes[i]);
9365 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9367 function email2treeinit(tree, treedata, treediv, params) {
9368 //ensure the tree data is not corrupt
9372 if (SUGAR.email2.tree) {
9373 SUGAR.email2.tree.destroy();
9374 SUGAR.email2.tree = null;
9377 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9381 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9382 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9383 tree.subscribe("expandComplete", function(node){
9384 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9385 for (var i in node.children) {
9386 SE.accounts.setupDDTarget(node.children[i]);
9389 tree.setCollapseAnim("TVSlideOut");
9390 tree.setExpandAnim("TVSlideIn");
9391 var root = tree.root;
9392 while (root.hasChildren()) {
9393 var node = root.children[0];
9395 tree.removeNode(root.children[0], false);
9397 addChildNodes(root, treedata);
9399 SUGAR.email2.accounts.renderTree();
9402 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9403 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9407 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9408 startDrag: function(x, y) {
9409 var Dom = YAHOO.util.Dom;
9410 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9413 var dragEl = this.getDragEl();
9414 var clickEl = this.getEl();
9415 Dom.setStyle(clickEl, "color", "#AAA");
9416 Dom.setStyle(clickEl, "opacity", "0.25");
9417 dragEl.innerHTML = clickEl.innerHTML;
9419 Dom.addClass(dragEl, "ygtvcell");
9420 Dom.addClass(dragEl, "ygtvcontent");
9421 Dom.addClass(dragEl, "folderDragProxy");
9422 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9423 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9424 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9425 Dom.setStyle(dragEl, "opacity", "0.5");
9426 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9429 onDragOver: function(ev, id) {
9430 var Dom = YAHOO.util.Dom;
9431 if (id != this.dragId)
9433 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9434 if(node.data.cls != "sugarFolder") {
9435 SUGAR.email2.folders.unhighliteAll();
9439 this.targetNode = node;
9440 SUGAR.email2.folders.unhighliteAll();
9445 onDragOut: function(e, id) {
9446 if (this.targetNode) {
9447 SUGAR.email2.folders.unhighliteAll();
9448 this.targetNode = false;
9449 this.dragId = false;
9453 endDrag: function() {
9454 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9455 if (this.targetNode) {
9456 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9459 });// End of File modules/Emails/javascript/init.js
9461 /*********************************************************************************
9462 * SugarCRM is a customer relationship management program developed by
9463 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9465 * This program is free software; you can redistribute it and/or modify it under
9466 * the terms of the GNU Affero General Public License version 3 as published by the
9467 * Free Software Foundation with the addition of the following permission added
9468 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9469 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9470 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9472 * This program is distributed in the hope that it will be useful, but WITHOUT
9473 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9474 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9477 * You should have received a copy of the GNU Affero General Public License along with
9478 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9479 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9482 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9483 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9485 * The interactive user interfaces in modified source and object code versions
9486 * of this program must display Appropriate Legal Notices, as required under
9487 * Section 5 of the GNU Affero General Public License version 3.
9489 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9490 * these Appropriate Legal Notices must retain the display of the "Powered by
9491 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9492 * technical reasons, the Appropriate Legal Notices must display the words
9493 * "Powered by SugarCRM".
9494 ********************************************************************************/
9496 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9497 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9498 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9499 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9500 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9501 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9502 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9503 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9504 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9505 ' <input type="hidden" id="composeType" name="composeType">' +
9506 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9507 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9508 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9509 ' <input type="hidden" id="sendTo" name="sendTo">' +
9510 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9511 ' <input type="hidden" id="sendCc" name="sendCc">' +
9512 ' <input type="hidden" id="setEditor" name="setEditor">' +
9513 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9514 ' <input type="hidden" id="parent_id" name="parent_id">' +
9515 ' <input type="hidden" id="parent_type" name="parent_type">' +
9516 ' <input type="hidden" id="attachments" name="attachments">' +
9517 ' <input type="hidden" id="documents" name="documents">' +
9518 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9519 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9520 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9521 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9523 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9524 ' <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>' +
9525 ' <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>' +
9526 ' <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>' +
9527 ' <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>' +
9528 '</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>' +
9529 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9530 '<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>' +
9531 ' </td></tr></tbody></table></th>' +
9535 ' <div style="margin:5px;">' +
9536 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9538 ' <td class="emailUILabel" NOWRAP >' +
9539 ' {app_strings.LBL_EMAIL_FROM}:' +
9541 ' <td class="emailUIField" NOWRAP>' +
9543 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9548 ' <td class="emailUILabel" NOWRAP>' +
9549 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9550 ' {app_strings.LBL_EMAIL_TO}:' +
9553 ' <td class="emailUIField" NOWRAP>' +
9554 ' <div class="ac_autocomplete">' +
9555 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9556 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9557 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9561 ' <tr id="add_addr_options_tr{idx}">' +
9562 ' <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>'+
9564 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9565 ' <td class="emailUILabel" NOWRAP>' +
9566 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9567 ' {app_strings.LBL_EMAIL_CC}:' +
9570 ' <td class="emailUIField" NOWRAP>' +
9571 ' <div class="ac_autocomplete">' +
9572 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9573 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9574 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9578 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9579 ' <td class="emailUILabel" NOWRAP>' +
9580 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9581 ' {app_strings.LBL_EMAIL_BCC}:' +
9584 ' <td class="emailUIField" NOWRAP>' +
9585 ' <div class="ac_autocomplete">' +
9586 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9587 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9588 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9593 ' <td class="emailUILabel" NOWRAP width="1%">' +
9594 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9596 ' <td class="emailUIField" NOWRAP width="99%">' +
9597 ' <div class="ac_autocomplete">' +
9598 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9607 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9608 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9609 ' <div style="padding:5px;">' +
9610 ' <table cellpadding="2" cellspacing="0" border="0">' +
9613 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9620 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9621 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9633 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9640 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9641 ' <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>' +
9653 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9660 ' <div id="addedTemplateAttachments{idx}"></div>' +
9667 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9668 ' <div style="padding:5px;">' +
9669 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9670 ' <table border="0" width="100%">' +
9672 ' <td NOWRAP style="padding:2px;">' +
9673 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9677 ' <td NOWRAP style="padding:2px;">' +
9678 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9683 ' <table border="0" width="100%">' +
9685 ' <td NOWRAP style="padding:2px;">' +
9686 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9690 ' <td NOWRAP style="padding:2px;">' +
9691 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9695 ' <table border="0" width="100%">' +
9697 ' <td NOWRAP style="padding:2px;">' +
9698 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9699 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9707 // End of File modules/Emails/javascript/composeEmailTemplate.js
9709 /*********************************************************************************
9710 * SugarCRM is a customer relationship management program developed by
9711 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9713 * This program is free software; you can redistribute it and/or modify it under
9714 * the terms of the GNU Affero General Public License version 3 as published by the
9715 * Free Software Foundation with the addition of the following permission added
9716 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9717 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9718 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9720 * This program is distributed in the hope that it will be useful, but WITHOUT
9721 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9722 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9725 * You should have received a copy of the GNU Affero General Public License along with
9726 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9727 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9730 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9731 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9733 * The interactive user interfaces in modified source and object code versions
9734 * of this program must display Appropriate Legal Notices, as required under
9735 * Section 5 of the GNU Affero General Public License version 3.
9737 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9738 * these Appropriate Legal Notices must retain the display of the "Powered by
9739 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9740 * technical reasons, the Appropriate Legal Notices must display the words
9741 * "Powered by SugarCRM".
9742 ********************************************************************************/
9744 SUGAR.email2.templates['displayOneEmail'] =
9745 '<div class="emailDetailTable" style="height:100%">' +
9746 '<div id="viewMenuDiv{idx}"></div>' +
9747 '<div width="100%" class="displayEmailValue">' +
9748 ' <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>' +
9749 ' <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>' +
9750 ' <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>' +
9751 ' <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>' +
9752 ' <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>' +
9753 ' <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>' +
9754 ' <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>' +
9755 ' <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>' +
9756 ' <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>' +
9758 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9760 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9761 ' {app_strings.LBL_EMAIL_FROM}:' +
9763 ' <td width="99%" class="displayEmailValue">' +
9764 ' {email.from_addr}' +
9768 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9769 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9771 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9772 ' <b>{email.name}</b>' +
9776 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9777 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9779 ' <td class="displayEmailValue">' +
9780 ' {email.date_start} {email.time_start}' +
9784 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9785 ' {app_strings.LBL_EMAIL_TO}:' +
9787 ' <td class="displayEmailValue">' +
9788 ' {email.toaddrs}' +
9791 ' <tr>{meta.cc}</tr>' +
9792 ' <tr>{email.attachments}</tr>' +
9794 ' <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>' +
9795 //' {email.description}' +
9797 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9799 /*********************************************************************************
9800 * SugarCRM is a customer relationship management program developed by
9801 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9803 * This program is free software; you can redistribute it and/or modify it under
9804 * the terms of the GNU Affero General Public License version 3 as published by the
9805 * Free Software Foundation with the addition of the following permission added
9806 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9807 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9808 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9810 * This program is distributed in the hope that it will be useful, but WITHOUT
9811 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9812 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9815 * You should have received a copy of the GNU Affero General Public License along with
9816 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9817 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9820 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9821 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9823 * The interactive user interfaces in modified source and object code versions
9824 * of this program must display Appropriate Legal Notices, as required under
9825 * Section 5 of the GNU Affero General Public License version 3.
9827 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9828 * these Appropriate Legal Notices must retain the display of the "Powered by
9829 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9830 * technical reasons, the Appropriate Legal Notices must display the words
9831 * "Powered by SugarCRM".
9832 ********************************************************************************/
9834 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9835 '<body onload="javascript:window.print();">' +
9839 ' font-family: helvetica, impact, sans-serif;' +
9840 ' font-size : 12pt;' +
9847 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9850 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9852 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9853 ' {app_strings.LBL_EMAIL_FROM}:' +
9855 ' <td width="99%" class="displayEmailValue">' +
9856 ' {email.from_name} <{email.from_addr}>' +
9860 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9861 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9863 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9864 ' <b>{email.name}</b>' +
9868 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9869 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9871 ' <td class="displayEmailValue">' +
9872 ' {email.date_start} {email.time_start}' +
9876 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9877 ' {app_strings.LBL_EMAIL_TO}:' +
9879 ' <td class="displayEmailValue">' +
9880 ' {email.toaddrs}' +
9884 ' {email.attachments}' +
9890 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9892 ' <td style="border-top: 1px solid #333;">' +
9893 ' <div style="padding:5px;">' +
9894 '{email.description}' +
9904 // End of File modules/Emails/javascript/viewPrintable.js
9906 /*********************************************************************************
9907 * SugarCRM is a customer relationship management program developed by
9908 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9910 * This program is free software; you can redistribute it and/or modify it under
9911 * the terms of the GNU Affero General Public License version 3 as published by the
9912 * Free Software Foundation with the addition of the following permission added
9913 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9914 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9915 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9917 * This program is distributed in the hope that it will be useful, but WITHOUT
9918 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9919 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9922 * You should have received a copy of the GNU Affero General Public License along with
9923 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9924 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9927 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9928 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9930 * The interactive user interfaces in modified source and object code versions
9931 * of this program must display Appropriate Legal Notices, as required under
9932 * Section 5 of the GNU Affero General Public License version 3.
9934 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9935 * these Appropriate Legal Notices must retain the display of the "Powered by
9936 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9937 * technical reasons, the Appropriate Legal Notices must display the words
9938 * "Powered by SugarCRM".
9939 ********************************************************************************/
9940 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9941 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;}
9942 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');}
9943 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;}}
9944 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9945 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9946 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}
9947 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="";}}
9948 this.oldValue="";}});if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9949 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];}}}
9950 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]];}
9951 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
9952 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9953 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js