2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
5 * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6 * dragged element is inserted before the dragged-over element.
8 * @extends YAHOO.util.DDProxy
10 * @param {String} id the id of the linked element
11 * @param {String} sGroup the group of related DragDrop objects
13 function ygDDList(id, sGroup) {
16 this.init(id, sGroup);
18 //this.logger = new ygLogger("ygDDList");
21 var s = this.getDragEl().style;
22 s.borderColor = "transparent";
23 s.backgroundColor = "#f6f5e5";
25 s.filter = "alpha(opacity=76)";
28 ygDDList.prototype = new YAHOO.util.DDProxy();
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
33 ygDDList.prototype.startDrag = function(x, y) {
34 //this.logger.debug(this.id + " startDrag");
36 var dragEl = this.getDragEl();
37 var clickEl = this.getEl();
39 dragEl.innerHTML = clickEl.innerHTML;
40 dragElObjects = dragEl.getElementsByTagName('object');
43 dragEl.className = clickEl.className;
44 dragEl.style.color = clickEl.style.color;
45 dragEl.style.border = "1px solid #aaa";
47 // save the style of the object
48 clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
50 this.borderDiv = document.createElement('div'); // create a div to display border
51 this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52 this.borderDiv.style.border = '2px dashed #cccccc';
54 for(i in clickEl.childNodes) { // hide contents of the target elements contents
55 if(typeof clickEl.childNodes[i].style != 'undefined') {
56 this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57 clickEl.childNodes[i].style.display = 'none';
61 clickEl.appendChild(this.borderDiv);
64 ygDDList.prototype.endDrag = function(e) {
65 // disable moving the linked element
66 var clickEl = this.getEl();
68 clickEl.removeChild(this.borderDiv); // remove border div
70 for(i in clickEl.childNodes) { // show target elements contents
71 if(typeof clickEl.childNodes[i].style != 'undefined') {
72 clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
77 clickEl.style.height = this.clickHeight;
79 clickEl.style.height = '';
82 clickEl.style.border = this.clickBorder;
84 clickEl.style.border = '';
86 dragEl = this.getDragEl();
87 dragEl.innerHTML = '';
92 ygDDList.prototype.afterEndDrag = function(e) {
96 ygDDList.prototype.onDrag = function(e, id) {
100 ygDDList.prototype.onDragOver = function(e, id) {
101 // this.logger.debug(this.id.toString() + " onDragOver " + id);
104 if ("string" == typeof id) {
105 el = YAHOO.util.DDM.getElement(id);
107 el = YAHOO.util.DDM.getBestMatch(id).getEl();
110 dragEl = this.getDragEl();
111 elRegion = YAHOO.util.Dom.getRegion(el);
113 // this.logger.debug('id: ' + el.id);
114 // this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 // this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116 var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 // this.logger.debug('mid: ' + mid);
119 // this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " < " + mid);
120 // this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
122 if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123 var el2 = this.getEl();
124 var p = el.parentNode;
125 p.insertBefore(el2, el);
127 if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128 var el2 = this.getEl();
129 var p = el.parentNode;
130 p.insertBefore(el2, el.nextSibling);
134 ygDDList.prototype.onDragEnter = function(e, id) {
135 // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136 // this.getDragEl().style.border = "1px solid #449629";
139 ygDDList.prototype.onDragOut = function(e, id) {
140 // I need to know when we are over nothing
141 // this.getDragEl().style.border = "1px solid #964428";
144 /////////////////////////////////////////////////////////////////////////////
146 function ygDDListBoundary(id, sGroup) {
148 this.init(id, sGroup);
149 //this.logger = new ygLogger("ygDDListBoundary");
150 this.isBoundary = true;
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
157 /*********************************************************************************
158 * SugarCRM is a customer relationship management program developed by
159 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
161 * This program is free software; you can redistribute it and/or modify it under
162 * the terms of the GNU Affero General Public License version 3 as published by the
163 * Free Software Foundation with the addition of the following permission added
164 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
168 * This program is distributed in the hope that it will be useful, but WITHOUT
169 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
173 * You should have received a copy of the GNU Affero General Public License along with
174 * this program; if not, see http://www.gnu.org/licenses or write to the Free
175 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
178 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
181 * The interactive user interfaces in modified source and object code versions
182 * of this program must display Appropriate Legal Notices, as required under
183 * Section 5 of the GNU Affero General Public License version 3.
185 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186 * these Appropriate Legal Notices must retain the display of the "Powered by
187 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188 * technical reasons, the Appropriate Legal Notices must display the words
189 * "Powered by SugarCRM".
190 ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span> </span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&themeName=Sugar&imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace(''',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML=' ';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};addToValidate(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,'email',this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
216 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
217 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
218 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
219 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
220 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
221 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
222 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
223 if(SUGAR.isIE){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
224 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
225 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();// End of File include/SugarEmailAddress/SugarEmailAddress.js
227 /*********************************************************************************
228 * SugarCRM is a customer relationship management program developed by
229 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
231 * This program is free software; you can redistribute it and/or modify it under
232 * the terms of the GNU Affero General Public License version 3 as published by the
233 * Free Software Foundation with the addition of the following permission added
234 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
235 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
236 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
238 * This program is distributed in the hope that it will be useful, but WITHOUT
239 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
240 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
243 * You should have received a copy of the GNU Affero General Public License along with
244 * this program; if not, see http://www.gnu.org/licenses or write to the Free
245 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
248 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
249 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
251 * The interactive user interfaces in modified source and object code versions
252 * of this program must display Appropriate Legal Notices, as required under
253 * Section 5 of the GNU Affero General Public License version 3.
255 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
256 * these Appropriate Legal Notices must retain the display of the "Powered by
257 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
258 * technical reasons, the Appropriate Legal Notices must display the words
259 * "Powered by SugarCRM".
260 ********************************************************************************/
261 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
262 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
263 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
264 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
265 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
266 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
267 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
268 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
269 this.js_more();this.js_more();}
270 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
271 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
272 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
273 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
274 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&¤tNode.tagName=='SPAN'){currentNode.id=/_input/.test(currentNode.id)?this.field_element_name+'_input_div_'+this.fields_count:this.field_element_name+'_radio_div_'+this.fields_count;if(/_input/.test(currentNode.id)){currentNode.name='teamset_div';}
275 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
276 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
277 currentNode.name=new_name;currentNode.id=new_name;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_name;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
278 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
279 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
281 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
283 if(!has_primary){return false;}
285 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
286 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
287 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
288 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
289 if(noAdd){enableQS(false);}
290 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_collection_"+i);var id_field=document.getElementById("id_"+this.field+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].id==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
292 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
293 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
295 SUGAR.collection.safe_clone=function(e,recursive)
296 {if(e.nodeName=="#text")
297 {return document.createTextNode(e.data);}
298 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];for(var i in properties)
299 {if(e[properties[i]])
300 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
301 newNode[properties[i]]=e[properties[i]];}}
303 {for(var i in e.childNodes)
304 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
305 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
306 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
308 /*********************************************************************************
309 * SugarCRM is a customer relationship management program developed by
310 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
312 * This program is free software; you can redistribute it and/or modify it under
313 * the terms of the GNU Affero General Public License version 3 as published by the
314 * Free Software Foundation with the addition of the following permission added
315 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
316 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
317 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
319 * This program is distributed in the hope that it will be useful, but WITHOUT
320 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
321 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
324 * You should have received a copy of the GNU Affero General Public License along with
325 * this program; if not, see http://www.gnu.org/licenses or write to the Free
326 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
329 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
330 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
332 * The interactive user interfaces in modified source and object code versions
333 * of this program must display Appropriate Legal Notices, as required under
334 * Section 5 of the GNU Affero General Public License version 3.
336 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
337 * these Appropriate Legal Notices must retain the display of the "Powered by
338 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
339 * technical reasons, the Appropriate Legal Notices must display the words
340 * "Powered by SugarCRM".
341 ********************************************************************************/
342 SUGAR.inboundEmail={};Rot13={map:null,convert:function(a){Rot13.init();var s="";for(i=0;i<a.length;i++){var b=a.charAt(i);s+=((b>='A'&&b<='Z')||(b>='a'&&b<='z')?Rot13.map[b]:b);}
343 return s;},init:function(){if(Rot13.map!=null)
344 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
345 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
346 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
347 function getEncryptedPassword(login,password,mailbox){var words=new Array(login,password,mailbox);for(i=0;i<3;i++){word=words[i];if(word.indexOf('&')>0){fragment1=word.substr(0,word.indexOf('&'));fragment2=word.substr(word.indexOf('&')+1,word.length);newWord=fragment1+'::amp::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
348 if(word.indexOf('+')>0){fragment1=word.substr(0,word.indexOf('+'));fragment2=word.substr(word.indexOf('+')+1,word.length);newWord=fragment1+'::plus::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
349 if(word.indexOf('%')>0){fragment1=word.substr(0,word.indexOf('%'));fragment2=word.substr(word.indexOf('%')+1,word.length);newWord=fragment1+'::percent::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}}
351 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName)
352 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
353 ie_id=document.getElementById(formName).ie_id.value;URL='index.php?'
354 +'module='+module_name
357 +'&target='+pageTarget
358 +'&target1='+pageTarget
359 +'&server_url='+mail_server
360 +'&email_user='+words[0]
361 +'&protocol='+protocol
363 +'&email_password='+words[1]
364 +'&mailbox='+words[2]
367 +'&personal='+isPersonal;var SI=SUGAR.inboundEmail;if(!SI.testDlg){SI.testDlg=new YAHOO.widget.SimpleDialog("testSettingsDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.testDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);if(this.evalJS)
368 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
369 this.body.style.width=w}}
370 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
371 title=SUGAR.language.get('InboundEmail','LBL_TEST_SETTINGS');SI.testDlg.setHeader(title);SI.testDlg.setBody(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.testDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.testDlg._updateContent,failure:SI.testDlg.hide,scope:SI.testDlg});SI.testDlg.show();}
372 function isDataValid(formName,validateMonitoredFolder){var formObject=document.getElementById(formName);var errors=new Array();var out=new String();if(trim(formObject.server_url.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_SERVER'));}
373 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
374 if(trim(formObject.email_password.value)==""&&trim(formObject.ie_id.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PASSWORD'));}
375 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
376 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
377 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
378 if(errors.length>0){out=SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_DESC');for(i=0;i<errors.length;i++){if(out!=""){out+="\n";}
380 alert(out);return false;}else{return true;}}
381 function getFoldersListForInboundAccount(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,searchFieldValue,formName){if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';URL='index.php?'
382 +'module='+module_name
385 +'&target='+pageTarget
386 +'&target1='+pageTarget
387 +'&server_url='+mail_server
388 +'&email_user='+words[0]
389 +'&protocol='+protocol
391 +'&email_password='+words[1]
392 +'&mailbox='+words[2]
394 +'&personal='+isPersonal
395 +'&searchField='+searchFieldValue;var SI=SUGAR.inboundEmail;if(!SI.listDlg){SI.listDlg=new YAHOO.widget.SimpleDialog("selectFoldersDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.listDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
396 this.body.style.width=w}}
397 SI.listDlg.setHeader(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.listDlg.setBody('');SI.listDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.listDlg._updateContent,failure:SI.listDlg.hide,scope:SI.listDlg});SI.listDlg.show();}
398 function setPortDefault(){var prot=document.getElementById('protocol');var ssl=document.getElementById('ssl');var port=document.getElementById('port');var stdPorts=new Array("110","143","993","995");var stdBool=new Boolean(false);if(port.value==''){stdBool.value=true;}else{for(i=0;i<stdPorts.length;i++){if(stdPorts[i]==port.value){stdBool.value=true;}}}
399 if(stdBool.value==true){if(prot.value=='imap'&&ssl.checked==false){port.value="143";}else if(prot.value=='imap'&&ssl.checked==true){port.value='993';}else if(prot.value=='pop3'&&ssl.checked==false){port.value='110';}else if(prot.value=='pop3'&&ssl.checked==true){port.value='995';}}}
400 function toggle_monitored_folder(field){var field1=document.getElementById('protocol');var mailbox=document.getElementById('mailbox');var label_inbox=document.getElementById('label_inbox');var subscribeFolderButton=document.getElementById('subscribeFolderButton');var trashFolderRow=document.getElementById('trashFolderRow');var trashFolderRow1=document.getElementById('trashFolderRow1');var sentFolderRow=document.getElementById('sentFolderRow');if(field1.value=='imap'){mailbox.disabled=false;try{mailbox.style.display='';trashFolderRow.style.display='';sentFolderRow.style.display='';trashFolderRow1.style.display='';subscribeFolderButton.style.display='';}catch(e){};label_inbox.style.display='';}
401 else{mailbox.value="INBOX";mailbox.disabled=false;try{mailbox.style.display="none";trashFolderRow.style.display="none";sentFolderRow.style.display="none";trashFolderRow1.style.display="none";subscribeFolderButton.style.display="none";}catch(e){};label_inbox.style.display="none";}}// End of File modules/InboundEmail/InboundEmail.js
403 /*********************************************************************************
404 * SugarCRM is a customer relationship management program developed by
405 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
407 * This program is free software; you can redistribute it and/or modify it under
408 * the terms of the GNU Affero General Public License version 3 as published by the
409 * Free Software Foundation with the addition of the following permission added
410 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
411 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
412 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
414 * This program is distributed in the hope that it will be useful, but WITHOUT
415 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
416 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
419 * You should have received a copy of the GNU Affero General Public License along with
420 * this program; if not, see http://www.gnu.org/licenses or write to the Free
421 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
424 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
425 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
427 * The interactive user interfaces in modified source and object code versions
428 * of this program must display Appropriate Legal Notices, as required under
429 * Section 5 of the GNU Affero General Public License version 3.
431 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
432 * these Appropriate Legal Notices must retain the display of the "Powered by
433 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
434 * technical reasons, the Appropriate Legal Notices must display the words
435 * "Powered by SugarCRM".
436 ********************************************************************************/
439 cache : new Object(),
440 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
441 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
444 currentHtmleditor : ''
448 * preserves hits from email server
450 _setDetailCache : function(ret) {
452 var compKey = ret.meta.mbox + ret.meta.uid;
454 if(!SUGAR.email2.cache[compKey]) {
455 SUGAR.email2.cache[compKey] = ret;
460 autoSetLayout : function() {
461 var c = document.getElementById('container');
462 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
463 //Ensure a minimum height.
464 tHeight = Math.max(tHeight, 550);
465 c.style.height = tHeight + "px";
466 SUGAR.email2.complexLayout.set('height', tHeight);
467 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
468 SUGAR.email2.complexLayout.render();
469 SUGAR.email2.listViewLayout.resizePreview();
474 * Shows overlay progress message
476 function overlayModal(title, body) {
477 overlay(title, body);
479 function overlay(reqtitle, body, type, additconfig) {
481 if (typeof(additconfig) == "object") {
482 var config = additconfig;
485 config.title = reqtitle;
487 YAHOO.SUGAR.MessageBox.show(config);
490 function hideOverlay() {
491 YAHOO.SUGAR.MessageBox.hide();
493 // End of File modules/Emails/javascript/EmailUIShared.js
495 /*********************************************************************************
496 * SugarCRM is a customer relationship management program developed by
497 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
499 * This program is free software; you can redistribute it and/or modify it under
500 * the terms of the GNU Affero General Public License version 3 as published by the
501 * Free Software Foundation with the addition of the following permission added
502 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
503 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
504 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
506 * This program is distributed in the hope that it will be useful, but WITHOUT
507 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
508 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
511 * You should have received a copy of the GNU Affero General Public License along with
512 * this program; if not, see http://www.gnu.org/licenses or write to the Free
513 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
516 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
517 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
519 * The interactive user interfaces in modified source and object code versions
520 * of this program must display Appropriate Legal Notices, as required under
521 * Section 5 of the GNU Affero General Public License version 3.
523 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
524 * these Appropriate Legal Notices must retain the display of the "Powered by
525 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
526 * technical reasons, the Appropriate Legal Notices must display the words
527 * "Powered by SugarCRM".
528 ********************************************************************************/
532 var sw = YAHOO.SUGAR,
533 Event = YAHOO.util.Event,
534 Connect = YAHOO.util.Connect,
538 ///////////////////////////////////////////////////////////////////////////////
541 outboundDialog : null,
542 inboundAccountEditDialog : null,
543 inboundAccountsSettingsTable : null,
544 outboundAccountsSettingsTable : null,
545 testOutboundDialog : null,
546 errorStyle : 'input-error',
548 newAddedOutboundId : '',
551 * makes async call to retrieve an outbound instance for editting
554 editOutbound : function(obi) {
556 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
559 deleteOutbound : function(obi) {
561 if(obi.match(/^(add|line|sendmail)+/)) {
562 alert('Invalid Operation');
564 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
565 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
569 getReplyAddress : function() {
572 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
573 var addy = SE.userPrefs.current_user.emailAddresses[i];
575 if(addy.primary_address == "1") {
576 primary = addy.email_address;
579 if(addy.reply_to == "1") {
580 return addy.email_address;
588 * Called on "Accounts" tab activation event
590 lazyLoad : function() {
592 this._setupInboundAccountTable();
593 this._setupOutboundAccountTable();
597 _setupInboundAccountTable: function()
599 //Setup the inbound mail settings
600 if(!this.inboundAccountsSettingsTable)
602 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
603 var clckEvent = oColumn.key;
605 var is_group = oRecord.getData("is_group");
608 if(oColumn.key == 'edit')
610 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
611 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
613 else if(oColumn.key == 'delete')
615 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
616 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
618 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
622 this.showBoolean = function(el, oRecord, oColumn, oData)
624 var is_group = oRecord.getData("is_group");
625 var bChecked = oData;
626 bChecked = (bChecked) ? " checked" : "";
629 el.innerHTML = "<input type=\"radio\"" + bChecked +
630 " name=\"col" + oColumn.getId() + "-radio\"" +
631 " class=\"yui-dt-radio\">";
636 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
637 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
639 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
640 '<img border="0" src="themes/default/images/helpInline.gif">' +
641 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
644 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
645 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
646 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
647 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
648 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
649 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
650 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
651 this.ieDataSource = new YAHOO.util.DataSource(query);
652 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
653 this.ieDataSource.responseSchema = {
654 resultsList: "account_list",
655 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
657 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
658 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
660 var elCheckbox = oArgs.target;
661 var oColumn = this.getColumn(elCheckbox);
662 if(oColumn.key == 'is_active')
664 var oRecord = this.getRecord(elCheckbox);
665 oRecord.setData("is_active",elCheckbox.checked);
666 var t_id = oRecord.getData('id');
667 var isGroupFolder = oRecord.getData('has_groupfolder');
670 SUGAR.email2.folders.updateSubscriptions();
672 SUGAR.email2.folders.setFolderSelection();
676 var lastDefaultSelectedId = "";
677 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
679 var elRadio = oArgs.target;
680 var oColumn = this.getColumn(elRadio);
681 if(oColumn.key == 'is_default')
683 var oRecord = this.getRecord(elRadio);
684 var t_id = oRecord.getData('id');
685 var t_isGroup = oRecord.getData('is_group');
686 if(t_id != lastDefaultSelectedId && !t_isGroup)
688 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
689 lastDefaultSelectedId = t_id;
690 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
693 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
698 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
699 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
702 _setupOutboundAccountTable: function()
704 if(!this.outboundAccountsSettingsTable)
706 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
707 var clckEvent = oColumn.key;
709 var isEditable = oRecord.getData("is_editable");
710 var type = oRecord.getData("type");
713 if(oColumn.key == 'edit')
715 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
716 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
718 else if(oColumn.key == 'delete' && type == 'user')
720 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
721 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
724 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
728 //Custom formatter to display any error messages.
729 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
731 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
732 SUGAR.email2.composeLayout.outboundAccountErrors = {};
734 var id = oRecord.getData('id');
735 var message = oRecord.getData("errors");
738 elLiner.innerHTML = '<span class="required">' + message + '</span>';
739 //Add the id and message for all outbound accounts.
740 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
744 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
745 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
748 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
749 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
751 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
752 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
753 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
754 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
756 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
757 this.obDataSource = new YAHOO.util.DataSource(query);
758 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
759 this.obDataSource.responseSchema = {
761 resultsList: "outbound_account_list",
762 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
765 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
768 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
769 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
770 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
774 * Displays a modal diaglogue to edit outbound account settings
776 showEditInboundAccountDialogue : function(clear) {
778 if(!this.inboundAccountEditDialog) {
779 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
783 constraintoviewport: true,
787 EAD.showEvent.subscribe(function() {
788 var el = this.element;
789 var viewH = YAHOO.util.Dom.getViewportHeight();
790 if (this.header && el && viewH - 50 < el.clientHeight) {
791 var body = this.header.nextElementSibling;
792 body.style.overflow = "auto";
793 body.style.height = (viewH - 50) + "px";
796 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
797 Dom.removeClass("editAccountDialogue", "yui-hidden");
801 if(clear == undefined || clear == true)
803 SE.accounts.clearInboundAccountEditScreen();
804 //Set default protocol to IMAP when creating new records
805 document.forms['ieAccount'].elements['protocol'].value = "imap";
806 SE.accounts.setPortDefault();
809 //Check if we should display username/password fields for outbound account if errors were detected.
810 this.checkOutBoundSelection();
812 this.inboundAccountEditDialog.render();
813 this.inboundAccountEditDialog.show();
814 SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
818 * Set all fields on the outbound edit form to either enabled/disabled
819 * except for the username/password.
822 toggleOutboundAccountDisabledFields: function(disable)
824 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
825 for(var i=0;i<fields.length;i++)
827 document.getElementById(fields[i]).disabled = disable;
830 Dom.addClass("mail_smtpssl_row", "yui-hidden");
832 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
836 * Refresh the inbound accounts table.
838 refreshInboundAccountTable : function()
840 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
842 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
843 scope: this.inboundAccountsSettingsTable }
847 * Refresh the outbound accounts table.
849 refreshOuboundAccountTable : function()
851 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
853 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
854 scope: this.outboundAccountsSettingsTable }
858 * Displays a modal diaglogue to add a SMTP server
860 showAddSmtp : function() {
861 // lazy load dialogue
862 if(!this.outboundDialog) {
863 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
867 constraintoviewport: true,
871 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
872 this.outboundDialog.hideEvent.subscribe(function(){
873 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
874 var out = Dom.get("outbound_email");
875 if (out && out.value == "SYSTEM_ADD")
877 out.value = out.options[0].value;
879 //Check if we should display username/password for system account.
880 SE.accounts.checkOutBoundSelection();
884 Dom.removeClass("outboundDialog", "yui-hidden");
888 var form = document.getElementById('outboundEmailForm');
889 for(i=0; i<form.elements.length; i++) {
890 if(form.elements[i].name == 'mail_smtpport') {
891 form.elements[i].value = 25;
892 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
893 form.elements[i].value = '';
894 } else if(form.elements[i].type == 'checkbox') {
895 form.elements[i].checked = false;
898 //Render the SMTP buttons
899 if ( !SUGAR.smtpButtonGroup ) {
900 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
901 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
903 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
904 document.getElementById('smtp_settings').style.display = '';
905 form.mail_smtptype.value = e.newValue.get('value');
907 YAHOO.widget.Button.addHiddenFieldsToForm(form);
909 //Hide Username/Password
910 SUGAR.email2.accounts.smtp_authenticate_field_display();
911 //Unset readonly fields
912 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
913 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
914 this.outboundDialog.render();
915 this.outboundDialog.show();
919 * Accounts' Advanced Settings view toggle
921 toggleAdv : function() {
922 var adv = document.getElementById("ie_adv");
923 if(adv.style.display == 'none') {
924 adv.style.display = "";
926 adv.style.display = 'none';
930 smtp_authenticate_field_display : function() {
931 var smtpauth_req = document.getElementById("mail_smtpauth_req");
932 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
933 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
937 * Changes the display used in the outbound email SMTP dialog to match the
939 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
941 document.getElementById("smtpButtonGroupTD").style.display = '';
942 document.getElementById("chooseEmailProviderTD").style.display = '';
943 document.getElementById("mailsettings1").style.display = '';
944 document.getElementById("mailsettings2").style.display = '';
945 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
946 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
947 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
948 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
952 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
953 document.getElementById("mail_smtpport").value = '465';
954 document.getElementById("mail_smtpauth_req").checked = true;
955 var ssl = document.getElementById("mail_smtpssl");
956 for(var j=0;j<ssl.options.length;j++) {
957 if(ssl.options[j].text == 'SSL') {
958 ssl.options[j].selected = true;
962 document.getElementById("mailsettings1").style.display = 'none';
963 document.getElementById("mailsettings2").style.display = 'none';
964 document.getElementById("mail_smtppass_label").innerHTML =
965 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
966 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
969 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
970 document.getElementById("mail_smtpport").value = '587';
971 document.getElementById("mail_smtpauth_req").checked = true;
972 var ssl = document.getElementById("mail_smtpssl");
973 for(var j=0;j<ssl.options.length;j++) {
974 if(ssl.options[j].text == 'TLS') {
975 ssl.options[j].selected = true;
979 document.getElementById("mailsettings1").style.display = 'none';
980 document.getElementById("mailsettings2").style.display = 'none';
981 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
982 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
985 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
986 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
987 document.getElementById("mail_smtpserver").value = '';
989 document.getElementById("mail_smtpport").value = '25';
990 document.getElementById("mail_smtpauth_req").checked = true;
991 document.getElementById("mailsettings1").style.display = '';
992 document.getElementById("mailsettings2").style.display = '';
993 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
994 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
995 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
996 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
999 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1001 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1002 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1003 document.getElementById("mailsettings2").style.display = 'none';
1006 SUGAR.email2.accounts.smtp_authenticate_field_display();
1010 * Fill the gmail default values for inbound accounts.
1012 fillInboundGmailDefaults: function () {
1014 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1015 document.forms['ieAccount'].elements['ssl'].checked = true;
1016 document.forms['ieAccount'].elements['protocol'].value = "imap";
1017 SUGAR.email2.accounts.setPortDefault();
1018 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1021 * Sets Port field to selected protocol and SSL settings defaults
1023 setPortDefault : function() {
1024 var prot = document.getElementById('protocol');
1025 var ssl = document.getElementById('ssl');
1026 var port = document.getElementById('port');
1027 var stdPorts= new Array("110", "143", "993", "995");
1028 var stdBool = new Boolean(false);
1029 var mailboxdiv = document.getElementById("mailboxdiv");
1030 var trashFolderdiv = document.getElementById("trashFolderdiv");
1031 var sentFolderdiv = document.getElementById("sentFolderdiv");
1032 var monitoredFolder = document.getElementById("subscribeFolderButton");
1033 if(port.value == '') {
1034 stdBool.value = true;
1036 for(i=0; i<stdPorts.length; i++) {
1037 if(stdPorts[i] == port.value) {
1038 stdBool.value = true;
1043 if(stdBool.value == true) {
1044 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1046 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1048 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1050 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1055 if (prot.value == 'imap') {
1056 mailboxdiv.style.display = "";
1057 trashFolderdiv.style.display = "";
1058 sentFolderdiv.style.display = "";
1059 monitoredFolder.style.display = "";
1060 if (document.getElementById('mailbox').value == "") {
1061 document.getElementById('mailbox').value = "INBOX";
1064 mailboxdiv.style.display = "none";
1065 trashFolderdiv.style.display = "none";
1066 sentFolderdiv.style.display = "none";
1067 monitoredFolder.style.display = "none";
1068 document.getElementById('mailbox').value = "";
1073 * Draws/removes red boxes around required fields.
1075 ieAccountError : function(style) {
1076 document.getElementById('server_url').className = style;
1077 document.getElementById('email_user').className = style;
1078 document.getElementById('email_password').className = style;
1079 document.getElementById('protocol').className = style;
1080 document.getElementById('port').className = style;
1083 checkOutBoundSelection: function() {
1084 var select = Dom.get('outbound_email');
1085 if (!select || select.selectedIndex == -1) { return; }
1087 var v = select.options[select.selectedIndex].value;
1091 select.options[select.selectedIndex].selected = false;
1092 v = select.options[0].value;
1094 else if (v == 'SYSTEM_ADD')
1095 SUGAR.email2.accounts.showAddSmtp();
1097 var foundError = false;
1098 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1099 for(i in errorAccounts)
1108 //Should username/password fields for outbound account.
1110 this.toggleInboundOutboundFields(true);
1112 this.toggleInboundOutboundFields(false);
1117 toggleInboundOutboundFields : function (display)
1121 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1122 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1126 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1127 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1131 * rebuilds the select options for mailer options
1133 rebuildMailerOptions : function() {
1134 var select = document.forms['ieAccount'].elements['outbound_email'];
1135 SE.util.emptySelectOptions(select);
1137 //Get the available sugar mailers
1138 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1140 for(i=0;i<a_outbound.length;i++)
1142 var t_record = a_outbound[i];
1143 var key = t_record.getData('id');
1144 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1146 var opt = new Option(display, key);
1147 select.options.add(opt);
1148 if (key == SE.accounts.newAddedOutboundId) {
1149 select.options.selectedIndex = i;
1153 select.options.add(new Option('',''));
1154 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1155 //Hide/Show username password fields if necessary.
1156 SE.accounts.checkOutBoundSelection();
1159 * Empties all the fields in the accounts edit view
1161 clearInboundAccountEditScreen:function() {
1163 document.getElementById('ie_id').value = '';
1164 document.getElementById('ie_name').value = '';
1165 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1166 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1167 document.getElementById('reply_to_addr').value = '';
1168 document.getElementById('server_url').value = '';
1169 document.getElementById('email_user').value = '';
1170 document.getElementById('email_password').value = '';
1171 document.getElementById('port').value = '';
1172 document.getElementById('inbound_mail_smtpuser').value = '';
1173 document.getElementById('inbound_mail_smtppass').value = '';
1174 document.ieAccount.protocol.options[0].selected = true;
1176 document.getElementById('ssl').checked = false;
1177 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1181 * Populates an account's fields in Settings->Accounts
1183 fillIeAccount:function(jsonstr) {
1184 var o = JSON.parse(jsonstr);
1186 document.getElementById('ie_id').value = o.id;
1187 document.getElementById('ie_name').value = o.name;
1188 if (o.stored_options != null) {
1189 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1190 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1191 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1192 if (o.stored_options.trashFolder != null) {
1193 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1195 if (o.stored_options.sentFolder != null) {
1196 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1199 document.getElementById('server_url').value = o.server_url;
1200 document.getElementById('email_user').value = o.email_user;
1201 document.getElementById('port').value = o.port;
1202 document.getElementById('group_id').value = o.group_id;
1203 document.getElementById('mailbox').value = o.mailbox;
1209 if(typeof(o.service[2]) != 'undefined') {
1210 document.getElementById('ssl').checked = true;
1214 if(document.getElementById('protocol').value != o.protocol) {
1215 var prot = document.getElementById('protocol');
1216 for(i=0; i<prot.options.length; i++) {
1217 if(prot.options[i].value == o.service[3]) {
1218 prot.options[i].selected = true;
1219 this.setPortDefault();
1223 // handle SMTP selection
1224 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1225 var opts = document.getElementById('outbound_email').options;
1226 for(i=0; i<opts.length; i++) {
1227 if(opts[i].value == o.stored_options.outbound_email) {
1228 opts[i].selected = true;
1234 deleteIeAccount : function(IeAccountID,IeGroupID) {
1235 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1237 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1239 AjaxObject.target = 'frameFlex';
1240 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1241 SUGAR.email2.accounts.refreshInboundAccountTable();
1245 // Null check for Outbound Settings.
1246 checkOutboundSettings: function() {
1247 var errorMessage = '';
1248 var isError = false;
1249 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1250 var mailName = document.getElementById('mail_name').value;
1251 var smtpServer = document.getElementById('mail_smtpserver').value;
1252 var smtpPort = document.getElementById('mail_smtpport').value;
1254 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1255 if(trim(mailName) == '') {
1257 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1259 if(trim(smtpServer) == '') {
1261 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1263 if(trim(smtpPort) == '') {
1265 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1267 if(mailsmtpauthreq.checked) {
1268 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1270 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1275 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1282 testOutboundSettings: function() {
1283 var errorMessage = '';
1284 var isError = false;
1285 var fromAddress = document.getElementById("outboundtest_from_address").value;
1286 if (trim(fromAddress) == "") {
1287 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1288 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1292 else if (!isValidEmail(fromAddress)) {
1293 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1294 overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1298 //Hide the dialogue and show an in progress indicator.
1299 SE.accounts.testOutboundDialog.hide();
1300 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1302 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1303 //nothing is sent in the request.
1304 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1305 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1307 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1308 if(outboundType == 'system-override')
1309 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1311 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1312 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1316 testOutboundSettingsDialog: function() {
1317 //Ensure that all settings are correct before proceeding to send test email.
1318 if(!SE.accounts.checkOutboundSettings())
1321 // lazy load dialogue
1322 if(!SE.accounts.testOutboundDialog) {
1323 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1327 constraintoviewport: true,
1331 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1332 Dom.removeClass("testOutboundDialog", "yui-hidden");
1334 SE.accounts.testOutboundDialog.render();
1335 SE.accounts.testOutboundDialog.show();
1339 * Saves Outbound email settings
1341 saveOutboundSettings : function() {
1342 if(SE.accounts.checkOutboundSettings()) {
1343 //Enable the form fields for the post.
1344 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1345 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1346 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1352 saveIeAccount : function() {
1354 //Before saving check if there are any error messages associated with the outbound account.
1355 var outboundID = document.getElementById('outbound_email').value;
1357 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1358 'validateSMTPCreds':true}) )
1360 document.getElementById('saveButton').disabled = true;
1362 overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1364 var formObject = document.getElementById('ieAccount');
1365 YAHOO.util.Connect.setForm(formObject);
1367 AjaxObject._reset();
1368 AjaxObject.target = 'frameFlex';
1369 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1373 testSettings : function() {
1374 form = document.getElementById('ieAccount');
1376 if(SE.accounts.checkIeCreds()) {
1377 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");
1381 getFoldersListForInboundAccountForEmail2 : function() {
1382 form = document.getElementById('ieAccount');
1383 if(SE.accounts.checkIeCreds()) {
1384 var mailBoxValue = form.mailbox.value;
1385 if (form.searchField.value.length > 0) {
1388 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 );
1393 checkIeCreds : function(validateRules) {
1394 if(typeof(validateRules) == 'undefined')
1397 var errors = new Array();
1398 var out = new String();
1400 var ie_name = Dom.get('ie_name').value;
1401 var fromAddress = Dom.get('ie_from_addr').value;
1402 var server_url = Dom.get('server_url').value;
1403 var email_user = Dom.get('email_user').value;
1404 var email_password = Dom.get('email_password').value;
1405 var protocol = Dom.get('protocol').value;
1406 var port = Dom.get('port').value;
1407 var oe = Dom.get('outbound_email');
1408 var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1410 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1411 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1413 //If the username and password were provided then ignore the error messge
1415 var outboundCredentialsFound = false;
1417 if(outboundUserName != "" && outboundPass != "")
1418 outboundCredentialsFound = true;
1420 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1422 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1423 && validateSMTPCreds)
1425 if(trim(outboundUserName) == "") {
1426 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1428 if(trim(outboundPass) == "") {
1429 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1433 if(trim(ie_name) == "") {
1434 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1437 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1439 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1440 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1445 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1446 || trim(oe_value) == "SYSTEM_ADD") ) {
1447 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1449 if(trim(server_url) == "") {
1450 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1452 if(trim(email_user) == "") {
1453 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1455 if(protocol == "") {
1456 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1458 if (protocol == 'imap') {
1459 var mailbox = document.getElementById('mailbox').value;
1460 if (trim(mailbox) == "") {
1461 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1463 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1464 var trashFolder = document.getElementById('trashFolder').value;
1465 if (trim(trashFolder) == "") {
1466 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1471 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1474 if(errors.length > 0) {
1475 out = app_strings.LBL_EMAIL_ERROR_DESC;
1476 for(i=0; i<errors.length; i++) {
1491 getIeAccount : function(ieId) {
1495 overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1496 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1498 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1502 * Iterates through TreeView nodes to apply styles dependent nature of node
1504 renderTree:function() {
1505 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1509 //Sets the style for any nodes that need it.
1510 setNodeStyle : function(node) {
1511 if (!node.data.origText) {
1512 node.data.origText = node.data.text;
1515 if (typeof(node.data.unseen) != 'undefined') {
1516 if (node.data.unseen > 0) {
1517 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1520 node.setUpLabel(node.data.origText);
1523 node.setUpLabel('<span>' + node.data.origText + '</span>');
1525 SE.accounts.setupDDTarget(node);
1528 setupDDTarget : function(node) {
1529 if (node.ddTarget) {
1530 node.ddTarget.removeFromGroup();
1531 delete node.ddTarget;
1533 var id = node.getElId();
1534 var num = id.substring(4);
1535 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1536 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1537 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1539 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1541 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1542 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1547 * Async call to rebuild the folder list. After a folder delete or account delete
1549 rebuildFolderList : function() {
1550 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1551 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1555 * Returns the number of remote accounts the user has active.
1557 getAccountCount : function() {
1560 for(i=0; i<tree._nodes.length; i++) {
1561 var node = tree._nodes[i];
1563 if(typeof(node) != 'undefined' && node.data.ieId) {
1571 ///////////////////////////////////////////////////////////////////////////////
1576 ///////////////////////////////////////////////////////////////////////////////
1577 //// CONTEXT MENU CALLS
1580 assignToDialogue : null,
1582 * Archives from context menu
1584 * @param string ieId
1585 * @param string folder
1587 _archiveToSugar : function(uids, ieId, folder) {
1590 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1591 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1594 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1598 * Archives from context menu
1600 archiveToSugar : function(menuItem) {
1601 SE.contextMenus.emailListContextMenu.hide();
1603 var rows = SE.grid.getSelectedRows();
1605 /* iterate through available rows JIC a row is deleted - use first available */
1606 for(var i=0; i<rows.length; i++) {
1607 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1609 var data = SE.grid.getRecord(rows[0]).getData();
1610 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1614 * Popup the printable version and start system's print function.
1616 viewPrintable : function(menuItem) {
1617 var rows = SE.grid.getSelectedRows();
1618 var data = SE.grid.getRecord(rows[0]).getData();
1619 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1623 * Marks email flagged on mail server
1625 markRead : function(type, contextMenuId) {
1626 SE.contextMenus.markEmail('read');
1630 * Assign this emails to people based on assignment rules
1632 assignEmailsTo : function(type, contextMenuId) {
1633 if(!SE.contextMenus.assignToDialogue)
1635 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1639 constraintoviewport: true,
1643 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1647 Dom.removeClass("assignToDiv", "yui-hidden");
1648 SE.contextMenus.assignToDialogue.render();
1649 SE.contextMenus.assignToDialogue.show();
1653 * Marks email flagged on mail server
1655 markFlagged : function(contextMenuId) {
1656 SE.contextMenus.markEmail('flagged');
1660 * Marks email unflagged on mail server
1662 markUnflagged : function(contextMenuId) {
1663 SE.contextMenus.markEmail('unflagged');
1667 * Marks email unread on mail server
1669 markUnread : function() {
1670 SE.contextMenus.markEmail('unread');
1674 * Deletes an email from context menu
1676 markDeleted : function() {
1677 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1678 document.getElementById('_blank').innerHTML = "";
1679 SE.contextMenus.markEmail('deleted');
1684 * generic call API to apply a flag to emails on the server and on sugar
1685 * @param string type "read" | "unread" | "flagged" | "deleted"
1687 markEmail : function(type) {
1688 SE.contextMenus.emailListContextMenu.hide();
1690 //var dm = SE.grid.getStore();
1691 //var uids = SE.grid.getSelectedRowIds();
1692 //var indexes = SE.grid.getSelectedRowIndexes();
1693 var rows = SE.grid.getSelectedRows();
1694 if (rows.length == 0)
1695 rows = [SE.contextMenus.currentRow];
1698 for(var i=0; i<rows.length; i++) {
1699 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1702 ser = YAHOO.lang.JSON.stringify(ser);
1704 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1705 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1711 if(type == 'read' || type == 'deleted') {
1713 for(var j=0; j<rows.length; j++) {
1714 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1716 SE.grid.getRecord(rows[j]).setData("seen", "1");
1719 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1721 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1722 var unseenCount = node.data.unseen;
1723 if (isNaN(unseenCount)) {
1726 var finalCount = parseInt(unseenCount) - count;
1727 node.data.unseen = finalCount;
1729 SE.accounts.renderTree();
1731 } else if(type == 'unread') {
1733 for(var j=0; j<rows.length; j++) {
1734 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1739 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1740 var unseenCount = node.data.unseen;
1741 if (isNaN(unseenCount)) {
1744 var finalCount = parseInt(unseenCount) + count;
1745 node.data.unseen = finalCount;
1746 SE.accounts.renderTree();
1749 if (type == 'unread') {
1750 for(var i=0; i<rows.length; i++) {
1751 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1755 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1756 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1760 * refreshes the ListView to show changes to cache
1762 markEmailCleanup : function() {
1763 SE.accounts.renderTree();
1765 SE.listView.refreshGrid();
1768 showAssignmentDialog : function() {
1769 if (SE.contextMenus.assignmentDialog == null) {
1770 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1772 SE.contextMenus.assignmentDialog.show();
1777 * shows the import dialog with only relate visible.
1779 relateTo : function() {
1780 SE.contextMenus.emailListContextMenu.hide();
1782 var rows = SE.grid.getSelectedRows();
1783 var data = SE.grid.getRecord(rows[0]).getData();
1784 var ieId = data.ieId;
1785 var folder = data.mbox;
1787 /* iterate through available rows JIC a row is deleted - use first available */
1788 for(var i=0; i<rows.length; i++) {
1789 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1791 var ser = JSON.stringifyNoSecurity(uids);
1793 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1797 * shows the import dialog with only relate visible.
1799 showDetailView : function() {
1800 SE.contextMenus.emailListContextMenu.hide();
1801 var rows = SE.grid.getSelectedRows();
1802 if (rows.length > 1) {
1803 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1806 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1807 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1808 /* iterate through available rows JIC a row is deleted - use first available */
1809 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1810 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1816 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1817 overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1818 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1822 * Opens multiple messages from ListView context click
1824 openMultiple : function() {
1825 SE.contextMenus.emailListContextMenu.hide();
1827 var rows = SE.grid.getSelectedRows();
1828 var uids = SE.listView.getUidsFromSelection();
1830 if(uids.length > 0) {
1831 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1832 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1833 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1838 * Replies/forwards email
1840 replyForwardEmailContext : function() {
1841 SE.contextMenus.emailListContextMenu.hide();
1843 var indexes = SE.grid.getSelectedRows();
1844 //var dm = SE.grid.getDataModel();
1847 for(var i=0; i<indexes.length; i++) {
1848 var row = SE.grid.getRecord(indexes[i]).getData();
1849 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1853 //show menu functions
1854 showEmailsListMenu : function(grid, row) {
1856 var data = row.getData();
1857 var draft = (data.type == "draft");
1858 var menu = SE.contextMenus.emailListContextMenu;
1863 if (data.mbox == 'sugar::Emails')
1864 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1866 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1868 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1869 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1870 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1871 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1873 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1876 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1878 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1879 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1880 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1881 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1882 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1885 if (data.mbox == "sugar::Emails")
1887 //Allow users to reassign imported emails
1888 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1889 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1890 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1891 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1895 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1896 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1900 showFolderMenu : function(grid, rowIndex, event) {
1902 var coords = event.getXY();
1903 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1907 SE.contextMenus.dv = {
1908 archiveToSugar : function(contextMenuId) {
1910 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1913 replyForwardEmailContext : function(all) {
1914 SE.contextMenus.detailViewContextMenu.hide();
1923 //// END SE.contextMenus
1924 ///////////////////////////////////////////////////////////////////////////////
1928 ///////////////////////////////////////////////////////////////////////////////
1931 consumeMetaDetail : function(ret) {
1932 // handling if the Email drafts
1933 if(ret.type == 'draft') {
1934 SE.composeLayout.c0_composeDraft();
1939 // cache contents browser-side
1940 SE._setDetailCache(ret);
1942 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1943 // 2 below must be in global context
1945 meta['panelId'] = SE.util.getPanelId();
1947 email = ret.meta.email;
1948 var out = displayTemplate.exec({
1949 'app_strings' : app_strings,
1951 'idx' : targetDiv.id,
1953 'email' : meta.email,
1954 'linkBeans' : linkBeans
1956 var tabLabel = meta.email.name;
1957 if (tabLabel != null && tabLabel.length > 25) {
1958 tabLabel = tabLabel.substring(0, 25) + "...";
1960 targetDiv.set("label", tabLabel);
1961 targetDiv.set("content", out);
1963 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1964 if (SUGAR.email2.util.isIe()) {
1965 displayEmailFrameDiv.style.height = "390px";
1967 displayEmailFrameDiv.style.height = "410px";
1970 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1971 displayFrame.contentWindow.document.write(email.description);
1972 displayFrame.contentWindow.document.close();
1974 // hide archive links
1975 if(ret.meta.is_sugarEmail) {
1976 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1977 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1979 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1980 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1985 consumeMetaPreview : function(ret) {
1986 // cache contents browser-side
1987 SE._setDetailCache(ret);
1991 var currrow = SE.grid.getLastSelectedRecord();
1992 currrow = SE.grid.getRecord(currrow);
1994 document.getElementById('_blank').innerHTML = '';
1997 // handling if the Email drafts
1998 if(ret.type == 'draft'){
1999 if (currrow.getData().uid == ret.uid) {
2000 SE.composeLayout.c0_composeDraft();
2005 if (currrow.getData().uid != ret.meta.uid) {
2009 // remove loading sprite
2010 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2011 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2013 meta['panelId'] = SE.util.getPanelId();
2014 email = ret.meta.email;
2016 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2017 'app_strings' : app_strings,
2021 'email' :meta.email,
2022 'linkBeans' : linkBeans
2024 // document.getElementById('_blank').innerHTML = meta.email;
2025 /* displayTemplate.append('_blank', {
2026 'app_strings' : app_strings,
2030 'email' :meta.email,
2031 'linkBeans' : linkBeans
2034 var displayFrame = document.getElementById('displayEmailFramePreview');
2035 displayFrame.contentWindow.document.write(email.description);
2036 displayFrame.contentWindow.document.close();
2038 SE.listViewLayout.resizePreview();
2040 // hide archive links
2041 if(ret.meta.is_sugarEmail) {
2042 document.getElementById("archiveEmailPreview").innerHTML = " ";
2043 document.getElementById("btnEmailViewPreview").style.display = "none";
2044 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2046 //hide view relationship link
2047 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2052 * wraps emailDelete() for single messages, comes from preview or tab
2054 emailDeleteSingle : function(ieId, uid, mbox) {
2055 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2056 // find active panel and close if the user double clicked the email to view.
2057 var activeTabId = SE.util.getPanelId();
2058 if(activeTabId != 'Preview')
2059 SE.innerLayout.get("activeTab").close();
2061 document.getElementById('_blank').innerHTML = "";
2064 uid = JSON.stringifyNoSecurity(ser);
2065 this.emailDelete(ieId, uid, mbox);
2070 * Sends async call to delete a given message
2073 emailDelete : function(ieId, uid, mbox) {
2074 overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2075 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2076 uid + "&ieId=" + ieId + "&folder=" + mbox);
2080 * retrieves one email to display in the preview pane.
2082 getEmailPreview : function() {
2083 var row = SUGAR.email2.listView.currentRow;
2084 var data = row.getData();
2085 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2086 var setRead = (data['seen'] == 0) ? true : false;
2087 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2088 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2093 * Imports one email into Sugar
2095 importEmail : function(ieId, uid, mbox) {
2096 SE.util.clearHiddenFieldValues('emailUIForm');
2098 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2100 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2101 AjaxObject.target = '';
2102 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2106 * Populates the frameFlex div with the contents of an email
2108 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2109 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2111 var mboxStr = new String(mbox);
2112 var compKey = mbox + uid;
2114 if(setRead == true) {
2115 SE.listView.boldUnreadRows()
2116 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2119 if(destination == SE.innerLayout) {
2121 * loading email into a tab, peer with ListView
2122 * targetDiv must remain in the global namespace as it is used by AjaxObject
2124 //Check if we already have a tab of the email open
2125 var tabs = SE.innerLayout.get("tabs");
2126 for (var t in tabs) {
2127 if (tabs[t].id && tabs[t].id == uid) {
2128 SE.innerLayout.set("activeTab", tabs[t]);
2133 targetDiv = new YAHOO.SUGAR.ClosableTab({
2134 label: loadingSprite,
2140 SE.innerLayout.addTab(targetDiv);
2142 // use cache if available
2143 if(SE.cache[compKey]) {
2144 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2146 // open email as peer-tab to listView
2147 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2148 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2151 // loading email into preview pane
2152 document.getElementById('_blank').innerHTML = loadingSprite;
2154 // use cache if available
2155 if(SE.cache[compKey]) {
2156 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2158 AjaxObject.forceAbort = true;
2159 // open in preview window
2160 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2161 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2166 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2168 if(mboxStr.substring(0,7) == 'sugar::') {
2169 // display an email from Sugar
2170 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2172 // display an email from an email server
2173 document.getElementById('emailUIAction').value = 'getSingleMessage';
2175 document.getElementById('mbox').value = mbox;
2176 document.getElementById('ieId').value = ieId;
2177 document.getElementById('uid').value = uid;
2179 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2181 AjaxObject.forceAbort = true;
2182 AjaxObject.target = '_blank';
2183 AjaxObject.startRequest(callback, null);
2187 * Retrieves multiple emails for DetailView
2189 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2190 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2191 SE.util.clearHiddenFieldValues('emailUIForm');
2193 var mboxStr = new String(mbox);
2195 uids = SE.util.cleanUids(uids);
2197 if(mboxStr.substring(0,7) == 'sugar::') {
2198 // display an email from Sugar
2199 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2200 document.getElementById('uid').value = uids;
2202 // display an email from an email server
2203 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2204 document.getElementById('mbox').value = mbox;
2205 document.getElementById('ieId').value = ieId;
2206 document.getElementById('uid').value = uids;
2209 var formObject = document.getElementById('emailUIForm');
2210 YAHOO.util.Connect.setForm(formObject);
2212 AjaxObject.target = 'frameFlex';
2213 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2215 if(setRead == true) {
2216 var c = uids.split(",");
2217 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2222 * Makes async call to get QuickCreate form
2223 * Renders a modal edit view for a given module
2225 quickCreate : function(module, ieId, uid, mailbox) {
2226 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2228 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2229 get += "&sugarEmail=true";
2232 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2236 * Makes async call to save a quick create
2239 saveQuickCreate : function(action) {
2240 var qcd = SE.detailView.quickCreateDialog;
2241 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2242 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2243 var theCallback = callbackQuickCreateSave;
2244 var accountType = '&sugarEmail=true';
2245 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2246 accountType = '&ieId=' + qcd.ieId;
2249 if (action == 'reply') {
2250 theCallback = callbackQuickCreateSaveAndReply;
2251 } else if (action == true) {
2252 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2254 formObject.action.value = 'EmailUIAjax';
2255 YAHOO.util.Connect.setForm(formObject);
2256 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2257 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2258 accountType + '&mbox=' + qcd.mbox);
2263 * Code to show/hide long list of email address in DetailView
2265 showCroppedEmailList : function(el) {
2266 el.style.display = 'none';
2267 el.previousSibling.style.display = 'inline'
2269 showFullEmailList : function(el) {
2270 el.style.display = 'none';
2271 el.nextSibling.style.display = 'inline';
2275 * Shows the QuickCreate overlay
2276 * @param string ieId
2278 * @param string mailbox
2280 showQuickCreate : function(ieId, uid, mailbox) {
2281 var panelId = SE.util.getPanelId();
2282 var context = document.getElementById("quickCreateSpan" + panelId);
2284 if (!SE.detailView.cqMenus)
2285 SE.detailView.cqMenus = {};
2287 if (SE.detailView.cqMenus[context])
2288 SE.detailView.cqMenus[context].destroy();
2290 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2292 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2295 for (var i=0; i < this.qcmodules.length; i++) {
2296 var module = this.qcmodules[i];
2298 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2301 onclick: { fn: function() {
2302 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2308 menu.render(document.body);
2313 * Displays the "View" submenu in the detailView
2314 * @param string ieId
2316 * @param string mailbox
2318 showViewMenu : function(ieId, uid, mailbox) {
2319 var panelId = SE.util.getPanelId();
2320 var context = "btnEmailView" + panelId;
2321 if (!SE.detailView.viewMenus)
2322 SE.detailView.viewMenus = {};
2324 if (SE.detailView.viewMenus[context])
2325 SE.detailView.viewMenus[context].destroy();
2327 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2329 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2333 (ieId == 'null' || ieId == null) ?
2334 //No ieId - Sugar Email
2336 text: app_strings.LBL_EMAIL_VIEW_RAW,
2337 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2340 //IeID exists, on a remote server
2342 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2343 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2345 text: app_strings.LBL_EMAIL_VIEW_RAW,
2346 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2349 menu.render(document.body);
2354 //#23108 jchi@07/17/2008
2355 menu.render('quickCreateSpan'+ panelId);*/
2356 //this.viewMenu = menu;
2357 //this.viewMenu.show(context);
2360 * Makes async call to get an email's headers
2362 viewHeaders : function(ieId, uid, mailbox) {
2363 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2364 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2368 * Makes async call to get a printable version
2370 viewPrintable : function(ieId, uid, mailbox) {
2371 if(mailbox == 'sugar::Emails') {
2372 // display an email from Sugar
2373 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2375 // display an email from an email server
2376 var emailUIAction = '&emailUIAction=getSingleMessage';
2379 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2380 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2384 * Makes async call to get an email's raw source
2386 viewRaw : function(ieId, uid, mailbox) {
2387 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2388 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2392 * Display all email addresses in detailview.
2394 displayAllAddrs : function(el) {
2395 el.style.display = 'none';
2396 Dom.getNextSibling(el).style.display = 'inline';
2399 //// END SE.detailView
2400 ///////////////////////////////////////////////////////////////////////////////
2404 ///////////////////////////////////////////////////////////////////////////////
2407 contextMenuFocus : new Object(),
2410 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2411 * SugarFolder ID - folder strings
2413 _createFolderId : function(node) {
2419 if(node.data.ieId) {
2420 /* we have a local Sugar folder */
2421 if(node.data.ieId == 'folder') {
2422 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2423 } else if(node.data.ieId.match(SE.reGUID)) {
2424 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2433 addChildNode : function(parentNode, childNode) {
2434 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2435 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2436 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2438 if(childNode.nodes) {
2439 if(childNode.nodes.length > 0) {
2440 for(j=0; j<childNode.nodes.length; j++) {
2441 var newChildNode = childNode.nodes[j];
2442 this.addChildNode(node, newChildNode);
2449 * Builds and returns a new TreeView Node
2450 * @param string name
2452 * @param int is_group
2455 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2456 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2458 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2459 node.expanded = expanded;
2460 node.data = new Object;
2461 node.data['id'] = id;
2462 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2463 node.data['label'] = name;
2464 node.data['ieId'] = 'folder';
2465 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2466 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2467 node.data['unseen'] = unseen;
2472 * ensures that a new folder has a valid name
2474 checkFolderName : function(name) {
2478 this.folderAdd(name);
2482 * Pings email servers for new email - forces refresh of folder pane
2484 checkEmailAccounts : function() {
2485 this.checkEmailAccountsSilent(true);
2488 checkEmailAccountsSilent : function(showOverlay) {
2489 if(typeof(SE.folders.checkingMail)) {
2490 clearTimeout(SE.folders.checkingMail);
2493 // don't stomp an on-going request
2494 if(AjaxObject.currentRequestObject.conn == null) {
2496 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2497 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2499 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2501 // wait 5 secs before trying again.
2502 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2507 * Starts check of all email Accounts using a loading bar for large POP accounts
2509 startEmailAccountCheck : function() {
2510 // don't do two checks at the same time
2511 if(!AjaxObject.requestInProgress()) {
2512 overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2513 SE.accounts.ieIds = SE.folders.getIeIds();
2514 if (SE.accounts.ieIds.length > 0) {
2515 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2516 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2521 // wait 5 secs before trying again.
2522 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2527 * Checks a single Account check based on passed ieId
2529 startEmailCheckOneAccount : function(ieId, synch) {
2536 var node = SE.clickedFolderNode;
2537 if (node && !synch) {
2538 mbox = node.data.mbox;
2540 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2541 SE.accounts.ieIds = [ieId];
2542 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2543 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2548 * Empties trash for subscribed accounts
2550 emptyTrash : function() {
2551 SE.contextMenus.frameFoldersContextMenu.hide();
2552 overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2553 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2557 * Clears Cache files of the inboundemail account
2559 clearCacheFiles : function(ieId) {
2560 SE.contextMenus.frameFoldersContextMenu.hide();
2561 overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2562 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2567 * Returns an array of all the active accounts in the folder view
2569 getIeIds : function() {
2571 var root = SE.tree.getRoot();
2572 for(i=0; i < root.children.length; i++) {
2573 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2574 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2575 ieIds.push(root.children[i].children[0].data.ieId);
2582 * loads folder lists in Settings->Folders
2584 lazyLoadSettings : function() {
2585 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2586 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2590 * After the add new folder is done via folders tab on seetings, this function should get called
2591 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2593 loadSettingFolder : function() {
2594 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2595 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2599 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2601 removeSugarFolders : function() {
2603 var root = tree.getRoot();
2604 var folder = SE.util.findChildNode(root, "ieId", "folder");
2606 tree.removeNode(folder);
2607 folder = SE.util.findChildNode(root, "ieId", "folder");
2609 if (!root.childrenRendered) {
2610 root.childrenRendered = true;
2614 rebuildFolders : function(silent) {
2615 if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2616 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2622 * Updates TreeView with Sugar Folders
2624 setSugarFolders : function(delay) {
2625 this.removeSugarFolders();
2626 //AjaxObject.forceAbort = true;
2627 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2631 * Takes async data object and creates the sugar folders in TreeView
2633 setSugarFoldersEnd : function(o) {
2634 var root = SE.tree.getRoot();
2635 addChildNodes(root, {nodes: o});
2636 SE.accounts.renderTree();
2637 //If nothing is loaded in the grid, load "My Inbox"
2638 if (SE.grid.params.ieId == "undefined") {
2639 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2643 startCheckTimer : function() {
2644 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2645 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2647 if(typeof(SE.folders.checkTimer) != 'undefined') {
2648 clearTimeout(SE.folders.checkTimer);
2651 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2652 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2654 SE.userPrefs.emailSettings.firstAutoCheck = true;
2655 SE.folders.checkEmailAccountsSilent(false);
2661 * makes an async call to save user preference and refresh folder view
2662 * @param object SELECT list object
2664 setFolderSelection : function() {
2665 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2667 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2668 var a_active_accnts = "";
2669 for(i=0;i<a_rs.length;i++)
2671 var t_record = a_rs[i];
2672 var is_active = t_record.getData('is_active');
2674 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2677 if(a_active_accnts == "")
2678 a_active_accnts = "&ieIdShow[]=";
2680 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2682 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2686 * makes async call to save user preference for a given node's open state
2687 * @param object node YUI TextNode object
2689 setOpenState : function(node) {
2690 SE.util.clearHiddenFieldValues('emailUIForm');
2691 var nodePath = node.data.id;
2692 var nodeParent = node.parent;
2694 while(nodeParent != null) {
2695 // root node has no ID param
2696 if(nodeParent.data != null) {
2697 nodePath = nodeParent.data.id + "::" + nodePath;
2700 var nodeParent = nodeParent.parent;
2703 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2704 document.getElementById('focusFolder').value = nodePath;
2706 if(node.expanded == true) {
2707 document.getElementById('focusFolderOpen').value = 'open';
2709 document.getElementById('focusFolderOpen').value = 'closed';
2712 var formObject = document.getElementById('emailUIForm');
2713 YAHOO.util.Connect.setForm(formObject);
2715 AjaxObject.startRequest(null, null);
2718 getNodeFromMboxPath : function(path) {
2719 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2720 var a = JSON.parse(path);
2722 var node = tree.getRoot();
2725 while(i < a.length) {
2726 node = this.getChildNodeFromLabel(node, a[i]);
2733 getChildNodeFromLabel : function(node, nodeLabel) {
2734 for(i=0; i<node.children.length; i++) {
2735 if(node.children[i].data.id == nodeLabel) {
2736 return node.children[i];
2742 * returns the node that presumably under the user's right-click
2744 getNodeFromContextMenuFocus : function() {
2745 //// get the target(parent) node
2746 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2748 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2750 // filter local folders
2751 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2752 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2753 if(target.id == '') {
2754 target = target.parentNode;
2761 var targetNode = document.getElementById(target.id);
2762 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2765 var matches = re.exec(targetNode.id);
2767 return document.getElementById(ygtvlabelel1);
2773 // usually parent node
2774 matches = re.exec(targetNode.parentNode.id);
2781 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2782 parentNode.expand();
2788 * Decrements the Unread Email count in folder text
2789 * @param string ieId ID to look for
2790 * @param string mailbox name
2791 * @param count how many to decrement
2793 decrementUnreadCount : function(ieId, mbox, count) {
2798 if(mbox.indexOf("sugar::") === 0) {
2799 var node = this.getNodeFromId(ieId);
2801 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2804 var unseen = node.data.unseen;
2806 var check = unseen - count;
2807 var finalCount = (check >= 0) ? check : 0;
2808 node.data.unseen = finalCount;
2810 SE.accounts.renderTree();
2815 * gets the TreeView node with a given ID/ieId
2816 * @param string id ID to look for
2817 * @return object Node
2819 getNodeFromId : function(id) {
2820 SE.folders.focusNode = null;
2821 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2822 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2823 SE.folders.focusNode = this;
2827 return SE.folders.focusNode;
2831 * Uses ieId and mailbox to try to find a node in the tree
2833 getNodeFromIeIdAndMailbox : function(id, mbox) {
2834 SE.folders.focusNode = null;
2835 if (mbox == "sugar::Emails") {
2839 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2840 if (varsarray instanceof Array) {
2841 if (this.data.ieId && this.data.ieId == varsarray[0]
2842 && this.data.mbox == varsarray[1]) {
2843 SE.folders.focusNode = this;
2847 if (this.data.ieId && this.data.ieId == varsarray) {
2848 SE.folders.focusNode = this;
2852 }, null, [id, mbox]);
2853 return SE.folders.focusNode;
2856 unhighliteAll : function() {
2857 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2861 * Displays a short form
2863 folderAdd : function() {
2864 SE.contextMenus.frameFoldersContextMenu.hide();
2866 var node = SE.clickedFolderNode;
2868 if(node != null && node.data) {
2869 overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2870 app_strings.LBL_EMAIL_SETTINGS_NAME,
2871 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2873 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2877 folderAddRegisterEnter : function() {
2878 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2879 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2880 this.buttons[1].handler);
2882 this.enterKeyListener.enable();
2885 folderRemoveRegisterEnter : function() {
2886 this.enterKeyListener.disable();
2889 folderAddXmlCall : function(name) {
2890 if (trim(name) == "") {
2891 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2894 name = escape(name);
2898 var parentNode = SE.clickedFolderNode;
2900 this.contextMenuFocus = parentNode;
2902 if(parentNode.data.ieId) {
2903 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2907 if(type == 'imap') {
2908 // make an IMAP folder
2909 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2910 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2911 } else if(type == 'sugar') {
2912 // make a Sugar folder
2913 if(SE.folders.isUniqueFolderName(name)) {
2914 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2915 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2917 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2918 SE.folders.folderAdd();
2922 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2925 // hide add-folder diaglogue
2926 SE.e2overlay.hide();
2930 * Removes either an IMAP folder or a Sugar Folder
2932 folderDelete : function() {
2933 SE.contextMenus.frameFoldersContextMenu.hide();
2935 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2937 var parentNode = SE.clickedFolderNode;
2939 if(parentNode != null && parentNode.data) {
2940 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2941 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2945 AjaxObject.target = 'frameFlex';
2947 if(parentNode.data.ieId != 'folder') {
2948 // delete an IMAP folder
2949 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2951 // delete a sugar folder
2952 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2954 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2955 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2957 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2963 * Rename folder form
2966 folderRename : function() {
2967 SE.contextMenus.frameFoldersContextMenu.hide();
2968 var node = SE.clickedFolderNode;
2971 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2972 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2976 overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2977 app_strings.LBL_EMAIL_SETTINGS_NAME,
2979 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2981 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2986 * fills an Object with key-value pairs of available folders
2988 getAvailableFoldersObject : function() {
2989 var ret = new Object();
2990 var tree = SE.tree.root;
2993 for(var i=0; i<tree.children.length; i++) {
2994 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
2997 ret['none'] = app_strings.LBL_NONE;
3004 * Fills in key-value pairs for dependent dropdowns
3005 * @param object ret Associative array
3006 * @param object node TreeView node in focus
3007 * @param string currentPath Built up path thus far
3008 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3010 getFolderFromChild : function(ret, node, currentPath, spacer) {
3011 if(node.data != null && node.depth > 0) {
3012 /* handle visual separtors differentiating b/t mailserver and local */
3013 if(node.data.ieId && node.data.ieId == 'folder') {
3014 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3018 ret['spacer0'] = spacer;
3019 } else if(ret.spacer0 != spacer) {
3020 ret['spacer1'] = spacer
3023 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3024 var depthMarker = currentPath;
3025 var retIndex = SE.folders._createFolderId(node);
3026 ret[retIndex] = depthMarker + theLabel;
3029 if(node.children != null) {
3031 currentPath += theLabel + "/";
3034 for(var i=0; i<node.children.length; i++) {
3035 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3043 * Wrapper to refresh folders tree
3045 getFolders : function() {
3046 SE.accounts.rebuildFolderList();
3050 * handles events around folder-rename input field changes
3051 * @param object YUI event object
3053 handleEnter : function(e) {
3054 switch(e.browserEvent.type) {
3056 e.preventDefault(); // click in text field
3060 SE.folders.submitFolderRename(e);
3064 var kc = e.browserEvent.keyCode;
3068 SE.folders.submitFolderRename(e);
3072 e.preventDefault(e);
3073 SE.folders.cancelFolderRename(e);
3080 * Called when a node is clicked on in the folder tree
3081 * @param node, The node clicked on
3082 * @param e, The click event
3084 handleClick : function(o) {
3086 //If the click was on a sugar folder
3087 if (node.data.ieId == "folder") {
3088 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3091 SE.listView.populateListFrame(node, node.data.ieId, false);
3093 //eval(node.data.click);
3098 * Called when a node is right-clicked on in the folder tree
3100 handleRightClick : function(e) {
3101 YAHOO.util.Event.preventDefault(e);
3103 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3104 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3106 //If the click was on a sugar folder
3107 SE.clickedFolderNode = node;
3108 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3109 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3110 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3111 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3112 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3113 menu.getItem(3).cfg.setProperty("disabled", false);
3114 menu.getItem(4).cfg.setProperty("disabled", false);
3115 menu.getItem(5).cfg.setProperty("disabled", false);
3116 menu.getItem(6).cfg.setProperty("disabled", true);
3118 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3119 menu.getItem(0).cfg.setProperty("disabled", true);
3120 menu.getItem(1).cfg.setProperty("disabled", true);
3121 menu.getItem(2).cfg.setProperty("disabled", true);
3122 menu.getItem(3).cfg.setProperty("disabled", true);
3123 menu.getItem(4).cfg.setProperty("disabled", true);
3125 if (node.data.protocol != null) {
3126 menu.getItem(6).cfg.setProperty("disabled", false);
3128 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3129 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3130 //Sent or Draft folders
3131 menu.getItem(3).cfg.setProperty("disabled", true);
3132 menu.getItem(4).cfg.setProperty("disabled", true);
3133 menu.getItem(5).cfg.setProperty("disabled", true);
3136 //For group with auto inbound, disable everything.
3137 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3139 menu.getItem(0).cfg.setProperty("disabled", true);
3140 menu.getItem(1).cfg.setProperty("disabled", true);
3141 menu.getItem(2).cfg.setProperty("disabled", true);
3142 menu.getItem(3).cfg.setProperty("disabled", true);
3143 menu.getItem(4).cfg.setProperty("disabled", true);
3144 menu.getItem(5).cfg.setProperty("disabled", true);
3145 menu.getItem(6).cfg.setProperty("disabled", true);
3148 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3153 * Called when a row is dropped on a node
3155 handleDrop : function(rows, targetFolder) {
3156 var rowData = rows[0].getData();
3157 if (rowData.mbox != targetFolder.data.mbox) {
3158 var srcIeId = rowData.ieId;
3159 var srcFolder = rowData.mbox;
3160 var destIeId = targetFolder.data.ieId;
3161 var destFolder = targetFolder.data.mbox;
3163 for(var i=0; i<rows.length; i++) {
3164 uids[i] = rows[i].getData().uid;
3166 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3171 * Called when something is dragged over a Folder Node
3173 dragOver : function(dragObject) {
3178 * Determines if a folder name is unique to the folder tree
3179 * @param string name
3181 isUniqueFolderName : function(name) {
3182 uniqueFolder = true;
3183 var root = SE.tree.getRoot();
3184 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3185 if (this.attributes && this.attributes.ieId == "folder") {
3186 if (this.attributes.text == name) {
3187 uniqueFolder = false;
3192 return uniqueFolder;
3196 * Makes async call to rename folder in focus
3197 * @param object e Event Object
3199 submitFolderRename : function(newName) {
3200 if (trim(newName) == "") {
3201 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3204 newName = escape(newName);
3205 var node = SE.clickedFolderNode;
3206 var origName = node.data.text
3208 if (newName == origName) {
3211 if(SE.folders.isUniqueFolderName(newName)) {
3212 overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3213 if (node.data.ieId == "folder") {
3215 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3218 //IMAP folder or POP mailbox
3219 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3220 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3221 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3225 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3230 moveFolder : function(folderId, parentFolderId) {
3231 if (folderId != parentFolderId)
3233 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3234 + folderId + "&newParentId=" + parentFolderId);
3239 * makes async call to do a full synchronization of all accounts
3241 synchronizeAccounts : function() {
3242 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3243 overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3244 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3249 * Updates user's folder subscriptsion (Sugar only)
3250 * @param object SELECT DOM object in focus
3251 * @param string type of Folder selection
3253 updateSubscriptions : function() {
3254 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3258 select = document.getElementById('userFolders');
3260 for(i=0; i<select.options.length; i++) {
3261 var opt = select.options[i];
3262 if(opt.selected && opt.value != "") {
3266 active += opt.value;
3270 //Add the group folder ids.
3271 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3272 for(i=0; i<group_folders.length; i++)
3274 active += ("::" + group_folders[i]);
3277 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3280 * Updates user's group folder subscriptsion (Sugar only)
3281 * @param ieID The group folder to add to the tree view
3283 retrieveGroupFolderSubscriptions : function() {
3285 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3286 var activeGroupFolders = "";
3287 var activeGroupIds = [];
3288 for(i=0;i<a_rs.length;i++)
3290 var t_record = a_rs[i];
3291 var is_active = t_record.getData('is_active');
3292 var isGroupFolder = t_record.getData('has_groupfolder');
3293 var ieID = t_record.getData('id');
3297 activeGroupIds.push(ieID);
3301 return activeGroupIds;
3306 SE.folders.checkEmail2 = function() {
3307 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3309 //// END FOLDERS OBJECT
3310 ///////////////////////////////////////////////////////////////////////////////
3313 ///////////////////////////////////////////////////////////////////////////////
3316 * Keypress Event capture and processing
3319 overall : function(e) {
3320 switch(e.charCode) {
3322 if(e.ctrlKey || e.altKey) {
3323 var focusRegion = SE.innerLayout.regions.center;
3324 if(focusRegion.activePanel.closable == true) {
3325 focusRegion.remove(focusRegion.activePanel);
3333 ///////////////////////////////////////////////////////////////////////////////
3336 ///////////////////////////////////////////////////////////////////////////////
3339 * ListView object methods and attributes
3345 * Fills the ListView pane with detected messages.
3347 populateListFrame : function(node, ieId, forceRefresh) {
3348 SE.innerLayout.selectTab(0);
3349 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3351 Dom.get('_blank').innerHTML = "";
3352 SE.grid.params['emailUIAction'] = 'getMessageList';
3353 SE.grid.params['mbox'] = node.data.mbox;
3354 SE.grid.params['ieId'] = ieId;
3355 forcePreview = true; // loads the preview pane with first item in grid
3356 SE.listView.refreshGrid();
3360 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3362 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3363 SE.innerLayout.selectTab(0);
3364 Dom.get('_blank').innerHTML = "";
3365 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3366 SE.grid.params['ieId'] = node.data.id;
3367 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3368 SE.listView.refreshGrid();
3372 * Sets sort order as user preference
3375 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3377 ieName = ieNamePassed;
3378 focusFolder = focusFolderPassed;
3380 SE.util.clearHiddenFieldValues('emailUIForm');
3381 var previousSort = document.getElementById('sortBy').value;
3383 document.getElementById('sortBy').value = sortBy;
3384 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3385 document.getElementById('focusFolder').value = focusFolder;
3386 document.getElementById('ieId').value = ieId;
3388 if(sortBy == previousSort) {
3389 document.getElementById('reverse').value = '1';
3392 var formObject = document.getElementById('emailUIForm');
3393 YAHOO.util.Connect.setForm(formObject);
3395 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3400 * Enables click/arrow select of grid items which then populate the preview pane.
3402 selectFirstRow : function() {
3403 SE.grid.selModel.selectFirstRow();
3406 selectLastRow : function() {
3407 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3410 setEmailListStyles : function() {
3411 SE.listView.boldUnreadRows();
3413 var ds = SE.grid.getStore();
3414 if (SE.grid.getSelections().length == 0) {
3415 document.getElementById('_blank').innerHTML = '';
3419 if(typeof(ds.baseParams.mbox) != 'undefined') {
3420 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3421 var cm = SE.grid.getColumnModel();
3422 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3423 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3425 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3426 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3430 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3431 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3434 // 4/20/2007 added to hide overlay after search
3436 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3437 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3438 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3439 if (node) node.data.unseen = unread;
3441 SE.accounts.renderTree();
3444 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3445 if(forcePreview && ds.totalCount > 0) {
3446 SE.detailView.getEmailPreview();
3447 forcePreview = false;
3452 * Removes a row if found via its UID
3454 removeRowByUid : function(uid) {
3455 uid = new String(uid);
3456 uids = uid.split(',');
3457 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3459 for(j=0; j<uids.length; j++) {
3460 var theUid = uids[j];
3461 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3462 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3463 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3469 displaySelectedEmails : function(rows) {
3470 var dm = SE.grid.getDataModel();
3473 for(i=0; i<rows.length; i++) {
3474 var rowIndex = rows[i].rowIndex;
3475 var metadata = dm.data[rowIndex];
3480 uids += metadata[5];
3482 // unbold unseen email
3483 this.unboldRow(rowIndex);
3486 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3490 * exception handler for data load failures
3492 loadException : function(dataModel, ex, response) {
3497 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3498 * @param string sourceIeId Email's source I-E id
3499 * @param string sourceFolder Email's current folder
3500 * @param destinationIeId Destination I-E id
3501 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3503 * @param array emailUids Array of email's UIDs
3505 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3506 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3507 overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3509 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3510 // remove rows from visibility
3511 for(row in selectedRows) {
3512 //SE.grid.getStore().remove(row);
3515 var baseUrl = '&sourceIeId=' + sourceIeId +
3516 '&sourceFolder=' + sourceFolder +
3517 '&destinationIeId=' + destinationIeId +
3518 '&destinationFolder=' + destinationFolder;
3521 for(i=0; i<emailUids.length; i++) {
3523 uids += app_strings.LBL_EMAIL_DELIMITER;
3525 uids += emailUids[i];
3527 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3528 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3530 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3536 * Unbolds text in the grid view to denote read status
3538 markRead : function(index, record) {
3539 // unbold unseen email
3540 var row = SE.grid.getRecord(record);
3541 row.getData().seen = 1;
3542 SE.grid.getTrEl(record).style.fontWeight = "normal";
3546 * grid row output, bolding unread emails
3548 boldUnreadRows : function() {
3549 // bold unread emails
3550 var trEl = SE.grid.getFirstTrEl();
3551 while(trEl != null) {
3552 if(SE.grid.getRecord(trEl).getData().seen == "0")
3553 trEl.style.fontWeight = "bold";
3555 trEl.style.fontWeight = "";
3556 trEl = SE.grid.getNextTrEl(trEl);
3561 * Show preview for an email if 1 and only 1 is selected
3562 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3564 handleRowSelect : function(e) {
3565 if(e.selectedRows.length == 1) {
3566 SE.detailView.getEmailPreview();
3570 handleDrop : function(e, dd, targetId, e2) {
3572 case 'htmleditordiv':
3573 var rows = SE.grid.getSelectedRows();
3574 if(rows.length > 0) {
3575 SE.listView.displaySelectedEmails(rows);
3580 var targetElId = new String(targetId);
3581 var targetIndex = targetElId.replace('ygtvlabelel',"");
3582 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3583 var dm = SE.grid.getDataModel();
3584 var emailUids = new Array();
3585 var destinationIeId = targetNode.data.ieId;
3586 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3589 var rows = SE.grid.getSelectedRows();
3590 // iterate through dragged rows
3591 for(i=0; i<rows.length; i++) {
3592 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3593 var rowIndex = rows[i].rowIndex;
3594 var dataModelRow = dm.data[rowIndex];
3595 var sourceIeId = dataModelRow[7];
3596 var sourceFolder = dataModelRow[6];
3597 emailUids[i] = dataModelRow[5];
3600 // event wrapped call - need FQ
3601 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3602 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3608 * Hack-around to get double-click and single clicks to work on the grid
3609 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3611 handleClick : function(o) {
3612 SUGAR.email2.grid.clearTextSelection();
3614 var el = SUGAR.email2.grid.getSelectedRows();
3616 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3617 if ( el.length == 1)
3620 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3621 SUGAR.email2.listView.currentRowIndex = rowId;
3622 clearTimeout(SUGAR.email2.detailView.previewTimer);
3623 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3628 * Custom handler for double-click/enter
3629 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3631 getEmail : function(e) {
3632 var rows = SE.grid.getSelectedRows();
3633 var row = SE.grid.getRecord(rows[0]).getData();
3635 clearTimeout(SE.detailView.previewTimer);
3636 document.getElementById("_blank").innerHTML = "";
3638 if(row.type != "draft") {
3639 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3641 // circumventing yui-ext tab generation, let callback handler build new view
3642 SE.util.clearHiddenFieldValues('emailUIForm');
3643 //function(uid, mbox, ieId, setRead, destination) {
3644 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3645 document.getElementById('uid').value = row.uid; // uid;
3646 document.getElementById('mbox').value = row.mbox; // mbox;
3647 document.getElementById('ieId').value = row.ieId; // ieId;
3649 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3650 AjaxObject.target = '_blank';
3651 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3656 * Retrieves a row if found via its UID
3660 getRowIndexByUid : function(uid) {
3661 uid = new String(uid);
3662 uids = uid.split(',');
3664 for(j=0; j<uids.length; j++) {
3665 var theUid = uids[j];
3667 for(i=0; i<SE.grid.getStore().data.length; i++) {
3668 if(SE.grid.getStore().data[i].id == theUid) {
3676 * Returns the UID's of the seleted rows
3679 getUidsFromSelection : function() {
3680 var rows = SE.grid.getSelectedRows();
3682 /* iterate through available rows JIC a row is deleted - use first available */
3683 for(var i=0; i<rows.length; i++) {
3684 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3689 refreshGrid : function() {
3690 SE.grid.getDataSource().sendRequest(
3691 SUGAR.util.paramsToUrl(SE.grid.params),
3692 SE.grid.onDataReturnInitializeTable,
3698 //// END SE.listView
3699 ///////////////////////////////////////////////////////////////////////////////
3701 ///////////////////////////////////////////////////////////////////////////////
3705 * sends search criteria
3706 * @param reference element search field
3708 search : function(el) {
3709 var searchCriteria = new String(el.value);
3711 if(searchCriteria == '') {
3712 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3716 var safeCriteria = escape(searchCriteria);
3718 var accountListSearch = document.getElementById('accountListSearch');
3719 //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3721 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3722 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3723 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3724 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3725 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3730 * sends advanced search criteria
3732 searchAdvanced : function() {
3733 var formObject = document.getElementById('advancedSearchForm');
3736 //Set assigned user id to blank if name is not present.
3737 if (formObject.elements['assigned_user_name'].value == "")
3738 formObject.elements['assigned_user_id'].value = "";
3740 for(i=0; i<formObject.elements.length; i++) {
3741 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3744 if(formObject.elements[i].type == 'text') {
3745 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3747 if(formObject.elements[i].type == 'hidden') {
3748 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3750 if(formObject.elements[i].type == 'select-one') {
3751 var el = formObject.elements[i];
3752 var v = el.options[el.selectedIndex].value;
3755 SE.grid.params[el.name] = v;
3758 //Clear previous search results if necessary
3759 if(typeof( SE.grid.params[el.name]) != 'undefined')
3760 delete SE.grid.params[el.name]
3767 if(! this.validateSearchFormInput() )
3770 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3771 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3772 var accountListSearch = document.getElementById('accountListSearch');
3773 SE.listView.refreshGrid();
3775 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3780 * Validates the search form inputs to ensure all parameters are valid
3783 validateSearchFormInput: function()
3785 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3786 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3787 var dateCheck = check_form('advancedSearchForm');
3789 //If the parent type is selected ensure the user selected a parent_id.
3790 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3796 * Toggles the advanced options, either hidding or showing the selection.
3798 toggleAdvancedOptions: function()
3800 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3802 for(var i=0;i<el.length;i++)
3804 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3805 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3807 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3811 * clears adv search form fields
3813 searchClearAdvanced : function() {
3814 var form = document.getElementById('advancedSearchForm');
3816 for(i=0; i<form.elements.length; i++) {
3817 if(form.elements[i].type != 'button') {
3818 form.elements[i].value = '';
3824 //////////////////////////////////////////////////////////////////////////////
3827 //////////////////////////////////////////////////////////////////////////////
3830 /******************************************************************************
3831 * USER SIGNATURES calls stolen from Users module
3832 *****************************************************************************/
3833 createSignature : function(record, the_user_id) {
3834 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3836 URL += "&record="+record;
3838 if(the_user_id != "") {
3839 URL += "&the_user_id="+the_user_id;
3841 var windowName = 'email_signature';
3842 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3844 var win = window.open(URL, windowName, windowFeatures);
3845 if(win && win.focus) {
3846 // put the focus on the popup if the browser supports the focus() method
3851 deleteSignature : function() {
3852 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3853 overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3854 var singature_id = document.getElementById('signature_id').value;
3855 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3859 saveOptionsGeneral : function(displayMessage) {
3860 var formObject = document.getElementById('formEmailSettingsGeneral');
3861 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3862 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3865 YAHOO.util.Connect.setForm(formObject);
3866 SE.composeLayout.emailTemplates = null;
3868 AjaxObject.target = 'frameFlex';
3869 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3872 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3874 SE.settings.settingsDialog.hide();
3878 * Shows settings container screen
3880 showSettings : function() {
3881 if(!SE.settings.settingsDialog) {
3882 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3888 constraintoviewport: true
3890 dlg.showEvent.subscribe( function (){
3891 var el = this.element;
3892 var viewH = YAHOO.util.Dom.getViewportHeight();
3893 if (this.header && el && viewH - 50 < el.clientHeight) {
3894 var body = this.header.nextElementSibling;
3895 body.style.overflow = "auto";
3896 body.style.height = (viewH - 50) + "px";
3899 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3900 dlg.setBody('<div id="settingsTabDiv"/>');
3901 dlg.beforeRenderEvent.subscribe(function() {
3902 var dd = new YAHOO.util.DDProxy(dlg.element);
3903 dd.setHandleElId(dlg.header);
3904 dd.on('endDragEvent', function() {
3910 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3911 var tabContent = Dom.get("tab_general");
3912 tp.addTab(new YAHOO.widget.Tab({
3913 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3915 content : tabContent.innerHTML,
3916 id : "generalSettings",
3919 tabContent.parentNode.removeChild(tabContent);
3920 tabContent = Dom.get("tab_accounts");
3921 var accountTab = new YAHOO.widget.Tab({
3922 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3924 content : tabContent.innerHTML,
3925 id : "accountSettings"
3927 tp.addTab(accountTab);
3928 tabContent.parentNode.removeChild(tabContent);
3930 tp.appendTo(dlg.body);
3933 SE.settings.settingsDialog.show();
3934 SE.folders.lazyLoadSettings();
3935 SE.accounts.lazyLoad();
3939 lazyLoadRules : function() {
3940 if(false/*!SE.settings.rules*/) {
3941 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3946 //// END SE.settings
3947 ///////////////////////////////////////////////////////////////////////////////
3950 /******************************************************************************
3952 *****************************************************************************/
3953 function removeHiddenNodes(nodes, grid) {
3955 for(var i = nodes.length - 1; i > -1; i--) {
3956 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3957 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3963 function strpad(val) {
3964 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3967 function refreshTodos() {
3968 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3969 AjaxObject.target = 'todo';
3970 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3973 /******************************************************************************
3974 * MUST STAY IN GLOBAL NAMESPACE
3975 *****************************************************************************/
3976 function refresh_signature_list(signature_id, signature_name) {
3977 var field=document.getElementById('signature_id');
3979 for (var i=0; i < field.options.length; i++) {
3980 if (field.options[i].value == signature_id) {
3981 if (field.options[i].selected==false) {
3982 field.options[i].selected=true;
3987 //add item to selection list.
3989 var newElement=document.createElement('option');
3990 newElement.text=signature_name;
3991 newElement.value=signature_id;
3992 field.options.add(newElement);
3993 newElement.selected=true;
3996 //enable the edit button.
3997 var field1=document.getElementById('edit_sig');
3998 field1.style.visibility="inherit";
3999 var deleteButt = document.getElementById('delete_sig');
4000 deleteButt.style.visibility="inherit";
4003 function setDefaultSigId(id) {
4004 var checkbox = document.getElementById("signature_default");
4005 var default_sig = document.getElementById("signatureDefault");
4007 if(checkbox.checked) {
4008 default_sig.value = id;
4010 default_sig.value = "";
4014 function setSigEditButtonVisibility() {
4015 var field = document.getElementById('signature_id');
4016 var editButt = document.getElementById('edit_sig');
4017 var deleteButt = document.getElementById('delete_sig');
4018 if(field.value != '') {
4019 editButt.style.visibility = "inherit";
4020 deleteButt.style.visibility = "inherit";
4022 editButt.style.visibility = "hidden";
4023 deleteButt.style.visibility = "hidden";
4025 }// End of File modules/Emails/javascript/EmailUI.js
4027 /*********************************************************************************
4028 * SugarCRM is a customer relationship management program developed by
4029 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4031 * This program is free software; you can redistribute it and/or modify it under
4032 * the terms of the GNU Affero General Public License version 3 as published by the
4033 * Free Software Foundation with the addition of the following permission added
4034 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4035 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4036 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4038 * This program is distributed in the hope that it will be useful, but WITHOUT
4039 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4040 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4043 * You should have received a copy of the GNU Affero General Public License along with
4044 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4045 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4048 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4049 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4051 * The interactive user interfaces in modified source and object code versions
4052 * of this program must display Appropriate Legal Notices, as required under
4053 * Section 5 of the GNU Affero General Public License version 3.
4055 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4056 * these Appropriate Legal Notices must retain the display of the "Powered by
4057 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4058 * technical reasons, the Appropriate Legal Notices must display the words
4059 * "Powered by SugarCRM".
4060 ********************************************************************************/
4063 var sw = YAHOO.SUGAR,
4064 Event = YAHOO.util.Event,
4065 Connect = YAHOO.util.Connect,
4066 Dom = YAHOO.util.Dom
4069 ///////////////////////////////////////////////////////////////////////////////
4072 _contactCache : new Array(), // cache of contacts
4073 _dd : new Array(), // filtered list, same format as _contactCache
4074 _ddLists : new Array(), // list of Lists
4075 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4076 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4077 clickBubble : true, // hack to get around onclick event bubbling
4079 relatedBeanType : '',
4082 itemSpacing : 'white-space:nowrap; padding:2px;',
4088 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4090 initFixForDatatableSort: function () {
4091 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4092 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4093 var oColumn = this._oColumnSet.getColumn(column);
4096 // Validate TD element
4097 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4099 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4101 // Validate TH element
4103 elCell = this.getThEl(column);
4106 var allColumns = this._oColumnSet.flat;
4107 for(var i=0, len=allColumns.length; i<len; i++) {
4108 if(allColumns[i].getThEl().id === elCell.id) {
4109 oColumn = allColumns[i];
4120 cancelEdit : function() {
4121 if(this.editContactDialog)
4122 this.editContactDialog.hide();
4123 if(this.editMailingListDialog)
4124 this.editMailingListDialog.hide();
4128 * Clears filter form
4130 clear : function() {
4131 var t = document.getElementById('contactsFilter');
4137 * handle context-menu Compose-to call
4138 * @param string type 'contacts' or 'lists'
4140 composeTo : function(type, waited) {
4141 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4142 if (activePanel.substring(0, 10) != "composeTab") {
4143 SE.composeLayout.c0_composeNewEmail();
4144 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4145 SE.contextMenus.contactsContextMenu.hide();
4148 var idx = activePanel.substring(10);
4151 // determine if we have a selection to work with
4152 if(type == 'contacts') {
4153 var ids = SE.contactView.getSelectedRows();
4154 for (var i in ids) {
4155 rows[i] = SE.contactView.getRecord(ids[i]);
4157 removeHiddenNodes(rows, SE.contactView);
4161 if(rows.length > 0) {
4162 SE.composeLayout.handleDrop(
4163 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4164 null, rows, 'addressTO' + idx );
4166 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4170 editContact : function() {
4171 SE.contextMenus.contactsContextMenu.hide();
4172 var element = SE.contactView.getSelectedNodes()[0];
4174 if (element.className.indexOf('address-contact') > -1) {
4175 elementId = element.id;
4176 } else if (element.className.indexOf('address-exp-contact') > -1) {
4177 elementId = element.id.substring(2);
4183 * Filters contact entries based on user input
4185 filter : function(inputEl) {
4186 var ret = new Object();
4187 var re = new RegExp(inputEl.value, "gi");
4189 for(var i in this._contactCache) {
4190 if(this._contactCache[i].name.match(re)) {
4191 ret[i] = this._contactCache[i];
4195 this.buildContactList(ret);
4198 fullForm : function(id, module) {
4199 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4203 * returns a formatted email address from the addressBook cache
4205 getFormattedAddress : function(id) {
4206 var o = this._contactCache[id];
4207 var primaryEmail = '';
4209 for(var i=0; i<o.email.length; i++) {
4210 var currentEmail = o.email[i].email_address;
4212 if(o.email[i].primary_address == 1) {
4213 primaryEmail = o.email[i].email_address;
4217 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4218 var name = new String(o.name);
4219 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4220 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4226 * Sets up async call to query for matching contacts, users, etc.
4228 searchContacts : function() {
4229 var fn = document.getElementById('input_searchField').value;
4230 var pe = document.getElementById('input_searchPerson').value;
4232 var rb = document.getElementById('hasRelatedBean').checked;
4235 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4236 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4237 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4238 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4240 this.addressBookDataModel.params['related_bean_id'] = '';
4243 this.addressBookDataModel.params['search_field'] = fn;
4244 this.addressBookDataModel.params['person'] = pe;
4245 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4246 this.grid._oDataSource = this.addressBookDataModel;
4247 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4251 * Clear Search Crieteria For Addressbook
4253 clearAddressBookSearch : function() {
4254 document.getElementById('input_searchField').value = "";
4255 document.getElementById('input_searchPerson').selectedIndex = 0;
4259 * Opens modal select window to add contacts to addressbook
4261 selectContactsDialogue : function(destId) {
4262 if(!this.contactsDialogue) {
4263 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4267 constraintoviewport: true,
4269 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4270 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4272 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4274 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4275 dlg.setBody(body.innerHTML);
4276 dlg.renderEvent.subscribe(function() {
4277 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4278 if (iev && !SUGAR.isIE) {
4279 this.body.style.width = "950px";
4284 dlg.beforeRenderEvent.subscribe(function() {
4285 var dd = new YAHOO.util.DDProxy(dlg.element);
4286 dd.setHandleElId(dlg.header);
4287 dd.on('endDragEvent', function() {
4293 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4295 var tabContent = SUGAR.util.getAndRemove("searchForm");
4296 tp.addTab(new YAHOO.widget.Tab({
4297 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4299 content : tabContent.innerHTML,
4300 id : "addressSearchTab",
4304 var addListenerFields = ['input_searchPerson','input_searchField' ]
4305 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4306 if (e.keyCode == 13) {
4307 YAHOO.util.Event.stopEvent(e);
4308 SUGAR.email2.addressBook.searchContacts();
4312 this.contactsDialogue.render();
4315 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4316 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4320 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4321 var idx = activePanel.substring(10);
4323 SE.addressBook.idx = idx;
4326 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4327 document.getElementById('relatedBeanColumn').style.display = '';
4328 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4329 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4330 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4331 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4332 SE.addressBook.relatedBeanType = relatedBeanType;
4334 document.getElementById('relatedBeanColumn').style.display = 'none';
4335 document.getElementById('hasRelatedBean').checked = false;
4338 if (!SE.addressBook.grid)
4340 if (hasRelatedBeanId) {
4341 document.getElementById('hasRelatedBean').checked = true;
4343 AddressSearchGridInit();
4344 SE.addressBook.relatedBeanId = relatedBeanId;
4348 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4350 SE.addressBook.relatedBeanId = relatedBeanId;
4351 document.getElementById('hasRelatedBean').checked = true;
4353 if (document.getElementById('hasRelatedBean').checked == true)
4355 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4356 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4358 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4359 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4361 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4362 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4363 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4366 //Remove any lingering rows in the result set table if the module was closed.
4367 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4369 SE.addressBook.populateResulstTableEmailAddresses();
4371 this.contactsDialogue.show();
4374 * Clear all email addresses from result table.
4377 clearAllEmailAddressFieldsFromResultTable: function () {
4378 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4379 //Unhighlight any rows currently selected if the emails were cleared.
4380 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4381 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4384 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4385 * results table. This function is called when the address book is displayed.
4387 populateResulstTableEmailAddresses: function () {
4389 var idx = SE.addressBook.idx;
4390 var emailFields = ['to','cc','bcc'];
4392 for(var k=0;k<emailFields.length;k++)
4394 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4395 var allEmails = document.getElementById(elKey).value;
4399 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4401 for (var i=0; i<formatedEmails.length; i++)
4403 var t_name = formatedEmails[i].name;
4404 var t_emailAddr = formatedEmails[i].email_address;
4405 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4407 t_name = displayEmail = t_emailAddr;
4409 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4410 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4411 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4417 * Checks all entries in the result table against a particular email address, returning true
4418 * if the email address is found, false otherwise.
4420 doesEmailAdddressExistInResultTable: function(emailAddress)
4422 if(trim(emailAddress) == '')
4425 var emailAddressFound = false;
4426 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4427 for (var i=0; i < contacts.length; i++)
4429 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4430 //If we are adding to cc or bcc fields, make them visible.
4431 if(data.email_address == emailAddress)
4433 emailAddressFound = true;
4438 return emailAddressFound;
4441 * Takes all email addresses that the users wishes to add from the address book and populates the To
4442 * fields on the compose tab.
4444 populateEmailAddressFieldsFromResultTable: function()
4446 //Clear the fields first, all email addresses are stored in the address book
4447 var idx = SE.addressBook.idx;
4448 var emailFields = ['to','cc','bcc'];
4449 for(var k=0;k<emailFields.length;k++)
4451 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4452 document.getElementById(elKey).value = "";
4455 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4456 for (var i=0; i < contacts.length; i++)
4458 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4460 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4461 //If we are adding to cc or bcc fields, make them visible.
4462 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4463 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4464 //Construct the target id
4465 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4467 var target = document.getElementById(target_id);
4468 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4471 //Delete all rows from the result set table
4472 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4475 SE.addressBook.contactsDialogue.hide()
4478 * Insert contacts into the result table.
4480 insertContactToResultTable : function(event,address_type) {
4482 var contactsDialogue = SE.addressBook.contactsDialogue;
4483 var contacts = SE.addressBook.grid.getSelectedRows();
4485 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4486 for (var i = 0; i < rows.length; i++)
4488 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4490 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4491 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4492 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4493 rows[i].setData("selected",true);
4496 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4497 for (var i = 0; i < checkBoxes.length; i++) {
4498 checkBoxes[i].checked = false;
4504 insertContactRowToResultTable : function(rowId, addressType) {
4505 var data = SE.addressBook.grid.getRecord(rowId).getData();
4506 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4508 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4509 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4510 if(addressType == null)
4511 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4512 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});
4515 * Remove a row from the gridsResult table.
4517 removeRowFromGridResults : function(rowId,emailAddress)
4519 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4520 for (var i=0; i < contacts.length; i++)
4522 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4523 var data = rec.getData();
4524 if(data.email_address == emailAddress)
4526 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4531 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4534 * Translates between the addressType To|Cc|Bcc labels/keys.
4536 translateAddresType: function(addressType,fromKey)
4538 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4539 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4540 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4541 var mappingObject = {};
4544 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4547 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4548 mappingObject[displayCc] = 'cc';
4549 mappingObject[displayBcc] = 'bcc';
4552 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4558 toggleSearchRowIcon : function(rowId,show)
4562 var idToShow = rowId + '_add_img';
4563 var idToHide = rowId + '_rm_img';
4567 var idToShow = rowId + '_rm_img';
4568 var idToHide = rowId + '_add_img';
4572 Dom.addClass(idToHide, "yui-hidden");
4573 Dom.removeClass(idToShow, "yui-hidden");
4576 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4578 doesGridResultsEntryExist: function(emailAddrs)
4581 var contactExists = false;
4582 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4583 for (var i=0; i < contacts.length; i++)
4585 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4586 if(data.email_address == emailAddrs)
4588 contactExists = true;
4592 return contactExists;
4596 * adds an email address to a string, but first checks if it exists
4597 * @param string concat The string we are appending email addresses to
4598 * @param string addr Email address to add
4601 smartAddEmailAddressToComposeField : function(concat, addr) {
4602 var re = new RegExp(addr);
4604 if(!concat.match(re)) {
4606 concat += "; " + addr;
4615 //// END ADDRESS BOOK
4616 ///////////////////////////////////////////////////////////////////////////////
4620 ///////////////////////////////////////////////////////////////////////////////
4623 * Auto-complete object
4627 delimChar : [";", ","],
4631 prehighlightClassName : "yui-ac-prehighlight",
4634 instances : new Array(),
4637 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4638 * @param object Contact from AddressBook
4641 getPrimaryAddress : function(contact) {
4642 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4644 for(var eIndex in contact.email) {
4645 address = contact.email[eIndex].email_address;
4646 if(contact.email[eIndex].primary_address == 1) {
4647 return contact.email[eIndex].email_address;
4655 * initializes autocomplete widgets for a given compose view
4658 init : function(idx) {
4659 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4660 "queryMatchContains" : false,
4661 "queryMatchSubset" : true
4664 this.instances[idx] = {
4671 // instantiate the autoComplete widgets
4672 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4673 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4674 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4676 // enable hiding of interfering textareas
4677 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4678 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4679 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4681 // enable reshowing of hidden textareas
4682 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4683 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4684 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4686 // enable refreshes of contact lists
4687 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4688 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4689 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4692 refreshDataSource : function(sType, aArgs) {
4693 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4695 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4697 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4698 idx = textBoxId.substr(9);
4700 idx = textBoxId.substr(10);
4703 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4704 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4705 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4709 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4711 returnDataSource : function(contacts) {
4712 var ret = new Array();
4713 for(var id in contacts) {
4714 if (contacts[id].name) {
4715 var primary = this.getPrimaryAddress(contacts[id]);
4717 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4718 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4720 for(var emailIndex in contacts[id].email) {
4721 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4730 * Hides address textareas to prevent autocomplete dropdown from being obscured
4732 toggleTextareaHide : function(sType, aArgs) {
4733 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4737 if(textBoxId.indexOf("addressTO") > -1) {
4739 } else if(textBoxId.indexOf("addressCC") > -1) {
4742 idx = textBoxId.substr(9);
4744 // follow through if not BCC
4746 var cc = document.getElementById("addressCC" + idx);
4747 var bcc = document.getElementById("addressBCC" + idx);
4751 cc.style.visibility = 'hidden';
4753 bcc.style.visibility = 'hidden';
4760 * Redisplays the textareas after an address is commited
4762 toggleTextareaShow : function(sType, aArgs) {
4763 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4767 if(textBoxId.indexOf("addressTO") > -1) {
4769 } else if(textBoxId.indexOf("addressCC") > -1) {
4772 idx = textBoxId.substr(9);
4774 // follow through if not BCC
4776 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4777 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4782 //// END AUTOCOMPLETE
4783 ///////////////////////////////////////////////////////////////////////////////
4785 ///////////////////////////////////////////////////////////////////////////////
4788 * expands the options sidebar
4790 SE.composeLayout = {
4791 currentInstanceId : 0,
4794 outboundAccountErrors : null,
4795 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4797 showAddressDetails : function(e) {
4798 var linkElement = document.getElementById("More"+e.id);
4799 var spanElement = document.getElementById("Detail"+e.id);
4800 var emailAddressList = e.value;
4801 if(e.value.length > 96)
4803 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4804 var displayArray = [];
4805 for (var i=0; i<resultArray.length; i++)
4807 var t_name = resultArray[i].name;
4808 var t_emailAddr = resultArray[i].email_address;
4810 displayArray.push('<br/><' + t_emailAddr + '>');
4812 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4815 var result = displayArray.join('<br/>');
4817 linkElement.style.display = "inline";
4818 linkElement.style.height="10px";
4819 linkElement.style.overflow="visible";
4820 spanElement.innerHTML = result;
4823 linkElement.style.display = "none";
4828 * Given a string of email address, return an array containing the name portion (if available)
4829 * and email portion.
4831 _getEmailArrayFromString : function (emailAddressList){
4834 while ((results = reg.exec(emailAddressList)) != null)
4836 orignial = results[0];
4837 parsedResult = results[0].replace(';', ':::::');
4838 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4842 while ((results = reg.exec(emailAddressList)) != null)
4844 orignial = results[0];
4845 parsedResult = results[0].replace(',', ':::::');
4846 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4848 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4849 var emailArr = emailAddressList.split(":::::");
4850 var resultsArray = [];
4852 for (var i=0; i<emailArr.length; i++)
4854 var rposition = emailArr[i].indexOf('<');
4855 var lposition = emailArr[i].indexOf('>');
4857 if(trim(emailArr[i]) != '')
4859 if(rposition != -1 && lposition != -1)
4861 var t_name = emailArr[i].substr(0, rposition-1);
4862 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4863 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4867 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4871 return resultsArray;
4873 ///////////////////////////////////////////////////////////////////////////
4876 * Prepare bucket DIV and yui-ext tab panels
4878 _0_yui : function() {
4879 var idx = this.currentInstanceId;
4881 var composeTab = new YAHOO.SUGAR.ClosableTab({
4882 label: mod_strings.LNK_NEW_SEND_EMAIL,
4884 content : "<div id='htmleditordiv" + idx + "'/>",
4885 id : "composeTab" + idx,
4886 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4889 SE.innerLayout.addTab(composeTab);
4891 // get template engine with template
4892 if (!SE.composeLayout.composeTemplate) {
4893 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4896 // create Tab inner layout
4897 var composePanel = this.getComposeLayout();
4898 composePanel.getUnitByPosition("right").collapse();
4899 composePanel.autoSize();
4903 * Generate the quick compose layout
4904 * @method getQuickComposeLayout
4905 * @param {Pannel} parentPanel Parent pannel
4906 * @param {Object} o Options
4909 getQuickComposeLayout : function (parentPanel,o) {
4910 var idx = SE.composeLayout.currentInstanceId;
4912 //Before rendering the parent pannel we need to initalize the grid layout
4913 parentPanel.beforeRenderEvent.subscribe(function() {
4915 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4916 SE.composeLayout._createComposeLayout(idx);
4917 SE.composeLayout[idx].set('height', 350);
4918 SE.composeLayout[idx].render();
4922 //Wait until the Compose Layout has rendered, then add the
4923 //options tab and perform the tiny initialization.
4924 parentPanel.renderEvent.subscribe(function() {
4926 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4927 SE.composeLayout._initComposeOptionTabs(idx);
4928 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4929 //Initialize tinyMCE
4930 if (!SUGAR.util.isTouchScreen())
4931 SE.composeLayout._1_tiny();
4932 //Init templates and address book
4933 SE.composeLayout._2_final();
4935 SE.composeLayout.quickCreateComposePackage(o);
4940 //Check if we have the div override for the shortcut bar
4941 if(typeof o.menu_id != 'undefined') {
4942 parentPanel.render(o.menu_id);
4944 parentPanel.render(document.body);
4947 return SE.composeLayout[idx];
4950 * Fill in all fields into the quick compose layout.
4951 * @method quickCreateComposePackage
4952 * @param {Object} o Options
4955 quickCreateComposePackage: function(o)
4957 //If we have a compose package fill in defaults.
4958 if (typeof(o.composePackage) != 'undefined')
4960 composePackage = o.composePackage; //Set the compose data object
4961 //Hijack this method called by composePackage as it's not need for quick creates.
4962 SE.composeLayout.c0_composeNewEmail = function(){};
4963 SE.composeLayout.composePackage(); //Fill in defaults.
4966 getComposeLayout : function() {
4967 var idx = SE.composeLayout.currentInstanceId;
4969 this._createComposeLayout(idx);
4970 SE.composeLayout[idx].render();
4971 this._initComposeOptionTabs(idx);
4973 return SE.composeLayout[idx];
4977 * Create the layout manager for the compose window.
4979 _createComposeLayout : function(idx)
4981 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
4982 parent: SE.complexLayout,
4992 SE.composeLayout.composeTemplate.exec({
4993 'app_strings':app_strings,
4994 'mod_strings':mod_strings,
4996 'linkbeans_options' : linkBeans,
4997 'idx' : SE.composeLayout.currentInstanceId
5008 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5011 header: app_strings.LBL_EMAIL_OPTIONS
5017 * Create compose tab which will populate the 'right' container in the compose window.
5019 _initComposeOptionTabs : function(idx)
5021 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5022 var tab = new YAHOO.widget.Tab({
5023 label: app_strings.LBL_EMAIL_ATTACHMENT,
5025 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5026 id : "divAttachments" + idx,
5030 tab.layout = SE.composeLayout[idx];
5032 tab.on("activeChange", function(o){
5034 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5040 tab = new YAHOO.widget.Tab({
5041 label: app_strings.LBL_EMAIL_OPTIONS,
5043 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5044 id : "divOptions" + idx,
5048 tab.layout = SE.composeLayout[idx];
5049 tab.on("activeChange", function(o){
5051 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5056 SE.composeLayout[idx].autoSize = function() {
5057 var pEl = this.get("element").parentNode.parentNode.parentNode;
5058 this.set("height", pEl.clientHeight-30);
5062 SE.composeLayout[idx].rightTabs = cTabs;
5064 isParentTypeValid : function(idx) {
5065 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5066 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5067 if (trim(parentTypeValue) == ""){
5068 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5074 isParentTypeAndNameValid : function(idx) {
5075 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5076 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5077 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5078 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5079 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5080 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5086 callopenpopupForEmail2 : function(idx,options) {
5088 var formName = 'emailCompose' + idx;
5090 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5091 formName = options.form_name;
5093 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5094 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5095 if (!SE.composeLayout.isParentTypeValid(idx)) {
5098 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5100 call_back_function:"SE.composeLayout.popupAddEmail",
5102 field_to_name_array:{
5103 id:'data_parent_id' + idx,
5104 name:'data_parent_name' + idx,
5109 popupAddEmail : function(o)
5111 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5112 var data = o.name_to_value_array;
5113 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5114 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5116 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5117 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5124 _1_tiny : function() {
5125 var idx = SE.composeLayout.currentInstanceId;
5126 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5127 SE.tinyInstances[elId] = { };
5128 SE.tinyInstances[elId].ready = false;
5129 var t = tinyMCE.getInstanceById(elId);
5131 if(typeof(t) == 'undefined') {
5132 tinyMCE.execCommand('mceAddControl', false, elId);
5133 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5134 SE.composeLayout.resizeEditor(idx);
5135 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
5140 resizeEditor : function(idx)
5142 var cof = Dom.get('composeOverFrame' + idx);
5143 var head = Dom.get('composeHeaderTable' + idx);
5144 var targetHeight = cof.clientHeight - head.clientHeight;
5145 var instance = tinyMCE.get(SE.tinyInstances.currentHtmleditor);
5147 var parentEl = Dom.get(instance.editorId + '_parent');
5148 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5149 var contentEl = instance.contentAreaContainer;
5150 var iFrame = contentEl.firstChild;
5151 var tinMceToolbarOffset = 18;
5152 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5156 * Initializes d&d, auto-complete, email templates
5158 _2_final : function() {
5159 var idx = SE.composeLayout.currentInstanceId;
5161 if(this.emailTemplates) {
5162 this.setComposeOptions(idx);
5164 //populate email template cache
5165 AjaxObject.target = '';
5166 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5169 // handle drop targets for addressBook
5170 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5171 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5172 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5173 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5175 // auto-complete setup
5176 SE.autoComplete.init(idx);
5179 document.getElementById("addressTO" + idx).focus();
5183 * hide tinyMCE tool bar if send email as plaintext is checked
5185 renderTinyMCEToolBar : function (idx, hide) {
5187 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5189 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5193 c1_composeEmail : function(isReplyForward, retry) {
5197 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5198 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5203 if(isReplyForward) {
5204 this.replyForwardEmailStage2();
5210 * takes draft info and prepopulates
5212 c0_composeDraft : function() {
5213 this.getNewInstanceId();
5215 document.getElementById('_blank').innerHTML = '';
5216 var idx = SE.composeLayout.currentInstanceId;
5217 SE.composeLayout.draftObject = new Object();
5218 SE.composeLayout.draftObject.id = idx;
5219 SE.composeLayout.draftObject.isDraft = true;
5220 SE.composeLayout.currentInstanceId = idx;
5221 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5222 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5223 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5225 SE.composeLayout._0_yui();
5226 SE.composeLayout._1_tiny();
5229 SE.composeLayout._2_final();
5231 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5232 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5236 * Strip & Prep editor hidden fields
5238 c0_composeNewEmail : function() {
5239 this.getNewInstanceId();
5240 this.c1_composeEmail(false);
5244 * Sends async request to get the compose view.
5245 * Requests come from "reply" or "forwards"
5247 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5248 SE.composeLayout.replyForwardObj = new Object();
5249 SE.composeLayout.replyForwardObj.ieId = ieId;
5250 SE.composeLayout.replyForwardObj.uid = uid;
5251 SE.composeLayout.replyForwardObj.mbox = mbox;
5252 SE.composeLayout.replyForwardObj.type = type;
5254 if(mbox == 'sugar::Emails') {
5255 SE.composeLayout.replyForwardObj.sugarEmail = true;
5258 SE.composeLayout.getNewInstanceId();
5259 SE.composeLayout.c1_composeEmail(true);
5261 //// END COMPOSE FLOW
5262 ///////////////////////////////////////////////////////////////////////////
5265 * Called when a contact, email, or mailinglist is dropped
5266 * into one of the compose fields.
5268 handleDrop : function (source, event, data, target) {
5271 target = event.getTarget();
5273 data.nodes = [data.nodes];
5277 target = document.getElementById(target);
5281 if (target.id.indexOf('address') > -1) {
5282 // dropped onto email to/cc/bcc field
5283 for(var i in nodes) {
5284 var node = nodes[i].getData();
5286 if (node[1].indexOf('contact') > -1) {
5287 email = SE.addressBook.getFormattedAddress(node[0]);
5288 } else if (node[1].indexOf('address-email') > -1){
5289 email = node[3].replace(/ /gi, '');
5290 email = email.replace('<', '<').replace('>', '>');
5291 var tr = source.getTrEl(nodes[i]);
5292 while (tr && !Dom.hasClass(tr, "address-contact")) {
5293 tr = source.getPreviousTrEl(tr);
5295 var CID = source.getRecord(tr).getData()[0];
5296 var o = SE.addressBook._contactCache[CID];
5297 var name = new String(o.name);
5298 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5299 email = finalName + email;
5301 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5307 /*/////////////////////////////////////////////////////////////////////////////
5308 /// EMAIL TEMPLATE CODE
5310 applyEmailTemplate : function (idx, id) {
5313 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5314 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5315 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5317 // id is selected index of email template drop-down
5318 if(id == '' || id == "0") {
5319 YAHOO.SUGAR.MessageBox.show({
5324 if(btn=='no'){return;};
5325 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5332 YAHOO.SUGAR.MessageBox.show({
5337 if(btn=='no'){return;};
5338 SUGAR.email2.composeLayout.processResult(idx, id);},
5344 processNoneResult : function(idx, id) {
5345 var tiny = SE.util.getTiny('htmleditor' + idx);
5346 var tinyHTML = tiny.getContent();
5347 var openTag = '<div><span><span>';
5348 var htmllow = tinyHTML.toLowerCase();
5349 var start = htmllow.indexOf(openTag);
5351 tinyHTML = tinyHTML.substr(start);
5352 tiny.setContent(tinyHTML);
5354 tiny.setContent('');
5358 processResult : function(idx , id){
5359 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5361 // get attachments if any
5362 AjaxObject.target = '';
5363 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5366 appendEmailTemplateJSON : function() {
5367 var idx = SE.composeLayout.currentInstanceId; // post increment
5369 // query based on template, contact_id0,related_to
5370 //jchi 09/10/2008 refix #7743
5371 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5372 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5375 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,'"');
5377 // cn: bug 14361 - text-only templates don't fill compose screen
5379 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/>");
5382 var tiny = SE.util.getTiny('htmleditor' + idx);
5383 var tinyHTML = tiny.getContent();
5384 var openTag = '<div><span><span>';
5385 var closeTag = '</span></span></div>';
5386 var htmllow = tinyHTML.toLowerCase();
5387 var start = htmllow.indexOf(openTag);
5389 var htmlPart2 = tinyHTML.substr(start);
5390 tinyHTML = text + htmlPart2;
5391 tiny.setContent(tinyHTML);
5393 tiny.setContent(text);
5398 * Writes out the signature in the email editor
5400 setSignature : function(idx) {
5403 var hide = document.getElementById('setEditor' + idx).checked;
5404 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5405 //wait for signatures to load before trying to set them
5406 if (!SE.composeLayout.signatures) {
5407 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5412 var sel = document.getElementById('signatures' + idx);
5414 var sel = document.getElementById('signature_id');
5415 idx = SE.tinyInstances.currentHtmleditor;
5418 //Ensure that the tinyMCE html has been rendered.
5419 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5420 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5427 signature = sel.options[sel.selectedIndex].value;
5432 var openTag = '<div><span><span>';
5433 var closeTag = '</span></span></div>';
5434 var t = SE.util.getTiny('htmleditor' + idx);
5436 if(typeof(t) != 'undefined')
5438 t.contentDocument = t.contentWindow.document;
5439 var html = t.getContent();
5444 var htmllow = html.toLowerCase();
5445 var start = htmllow.indexOf(openTag);
5446 var end = htmllow.indexOf(closeTag) + closeTag.length;
5448 // selected "none" - remove signature from email
5449 if(signature == '') {
5451 var htmlPart1 = html.substr(0, start);
5452 var htmlPart2 = html.substr(end, html.length);
5454 html = htmlPart1 + htmlPart2;
5457 SE.signatures.lastAttemptedLoad = '';
5461 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5462 SE.signatures.lastAttemptedLoad = '';
5464 SE.signatures.lastAttemptedLoad = signature;
5466 if(typeof(SE.signatures[signature]) == 'undefined') {
5468 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5469 SE.signatures.targetInstance = (idx) ? idx : "";
5470 AjaxObject.target = '';
5471 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5473 var newSignature = this.prepareSignature(SE.signatures[signature]);
5475 // clear out old signature
5476 if(SE.signatures.lastAttemptedLoad && start > -1) {
5477 var htmlPart1 = html.substr(0, start);
5478 var htmlPart2 = html.substr(end, html.length);
5480 html = htmlPart1 + htmlPart2;
5484 start = html.indexOf('<div><hr></div>');
5485 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5486 var htmlPart1 = html.substr(0, start);
5487 var htmlPart2 = html.substr(start, html.length);
5488 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5489 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5490 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5492 var newHtml = html + openTag + newSignature + closeTag;
5494 //tinyMCE.setContent(newHtml);
5495 t.setContent(newHtml);
5499 prepareSignature : function(str) {
5500 var signature = new String(str);
5502 signature = signature.replace(/</gi, '<');
5503 signature = signature.replace(/>/gi, '>');
5509 showAttachmentPanel : function(idx) {
5510 var east = SE.composeLayout[idx].getUnitByPosition("right");
5511 var tabs = SE.composeLayout[idx].rightTabs;
5513 tabs.set("activeTab", tabs.getTab(0));
5517 * expands sidebar and displays options panel
5519 showOptionsPanel : function(idx) {
5520 var east = SE.composeLayout[idx].getUnitByPosition("right");
5521 var tabs = SE.composeLayout[idx].rightTabs;
5523 tabs.set("activeTab", tabs.getTab(1));
5527 * Selects the Contacts tab
5529 showContactsPanel : function() {
5530 SE.complexLayout.regions.west.showPanel("contactsTab");
5534 * Generates fields for Select Document
5536 addDocumentField : function(idx) {
5537 var basket = document.getElementById('addedDocuments' + idx);
5539 var index = (basket.childNodes.length / 7) - 1;
5546 var test = document.getElementById('documentId' + idx + index);
5548 while(test != null) {
5550 test = document.getElementById('documentId' + idx + index);
5553 var documentCup = document.createElement("div");
5554 documentCup.id = 'documentCup' + idx + index;
5555 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5556 // document id field
5557 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5558 // document name field
5559 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5561 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5562 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5563 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5565 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5566 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5567 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5570 basket.appendChild(documentCup);
5571 //basket.innerHTML += out;
5576 * Makes async call to save a draft of the email
5577 * @param int Instance index
5579 saveDraft : function(tinyInstance) {
5580 this.sendEmail(tinyInstance, true);
5583 selectDocument : function(target) {
5584 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5585 windowName = 'selectDocument';
5586 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5588 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5590 // put the focus on the popup if the browser supports the focus() method
5596 * Modal popup for file attachment dialogue
5598 addFileField : function() {
5599 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5600 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5604 constraintoviewport: true,
5606 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5607 fn:function(){SE.addFileDialog.hide();}
5610 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5611 SE.addFileDialog.render();
5612 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5614 Dom.removeClass("addFileDialog", "yui-hidden");
5616 SE.addFileDialog.show();
5620 * Async upload of file to temp dir
5622 uploadAttachment : function() {
5623 if(document.getElementById('email_attachment').value != "") {
5624 var formObject = document.getElementById('uploadAttachment');
5625 YAHOO.util.Connect.setForm(formObject, true, true);
5626 AjaxObject.target = '';
5627 AjaxObject.startRequest(callbackUploadAttachment, null);
5629 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5634 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5635 * @param string target in focus compose layout
5637 setDocument : function(idx, target, documentId, documentName, docRevId) {
5638 // fields are named/id'd [fieldName][instanceId][index]
5639 var addedDocs = document.getElementById("addedDocuments" + idx);
5640 var docId = document.getElementById('documentId' + idx + target);
5641 var docName = document.getElementById('documentName' + idx + target);
5642 var docRevisionId = document.getElementById('document' + idx + target);
5643 docId.value = documentId;
5644 docName.value = documentName;
5645 docRevisionId.value = docRevId;
5649 * Removes the bucket div containing the document input fields
5651 deleteDocumentField : function(documentCup) {
5652 var f0 = document.getElementById(documentCup);
5653 f0.parentNode.removeChild(f0);
5657 * Removes a Template Attachment field
5661 deleteTemplateAttachmentField : function(idx, index) {
5662 // create not-in-array values for removal filtering
5663 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5669 r += document.getElementById('templateAttachmentId' + idx + index).value;
5670 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5672 var target = 'templateAttachmentCup' + idx + index;
5673 d = document.getElementById(target);
5674 d.parentNode.removeChild(d);
5678 * Async removal of uploaded temp file
5679 * @param string index Should be a concatenation of idx and index
5682 deleteUploadAttachment : function(index, file) {
5683 var d = document.getElementById('email_attachment_bucket' + index);
5684 d.parentNode.removeChild(d);
5686 // make async call to delete cached file
5687 AjaxObject.target = '';
5688 AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5692 * Attaches files coming from Email Templates
5694 addTemplateAttachmentField : function(idx) {
5696 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5698 var basket = document.getElementById('addedTemplateAttachments' + idx);
5701 var index = basket.childNodes.length;
5708 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5710 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5711 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5712 idx + "\",\"" + index + "\");'/>" +
5714 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5715 // templateAttachment field
5716 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5718 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5720 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5721 "<br id='br" + index + "></br>" +
5722 "<br id='brdoc" + index + "></br>" +
5724 basket.innerHTML = basket.innerHTML + out;
5730 * Sends one email via async call
5731 * @param int idx Editor instance ID
5732 * @param bool isDraft
5734 sendEmail : function(idx, isDraft) {
5736 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5737 var obAccountID = document.getElementById('addressFrom' + idx).value;
5739 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5741 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5746 var form = document.getElementById('emailCompose' + idx);
5747 var composeOptionsFormName = "composeOptionsForm" + idx;
5748 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5749 var html = t.getContent();
5750 var subj = document.getElementById('emailSubject' + idx).value;
5751 var to = trim(document.getElementById('addressTO' + idx).value);
5752 var cc = trim(document.getElementById('addressCC' + idx).value);
5753 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5754 var email_id = document.getElementById('email_id' + idx).value;
5755 var composeType = document.getElementById('composeType').value;
5756 var parent_type = document.getElementById("parent_type").value;
5757 var parent_id = document.getElementById("parent_id").value;
5759 var el_uid = document.getElementById("uid");
5760 var uid = (el_uid == null) ? '' : el_uid.value;
5762 var el_ieId = document.getElementById("ieId");
5763 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5765 var el_mbox = document.getElementById("mbox");
5766 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5768 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5769 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5773 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5776 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5777 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5778 parent_id = parentIdValue;
5779 parent_type = parentTypeValue;
5781 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5782 // baseline viability check
5784 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5785 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5787 } else if(subj == '' && !isDraft) {
5788 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5791 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5793 } else if(html == '' && !isDraft) {
5794 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5799 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5800 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5801 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5802 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5803 html = html.replace(/</ig, "sugarLessThan");
5804 html = html.replace(/>/ig, "sugarGreaterThan");
5806 form.sendDescription.value = html;
5807 form.sendSubject.value = subj;
5808 form.sendTo.value = to;
5809 form.sendCc.value = cc;
5810 form.sendBcc.value = bcc;
5811 form.email_id.value = email_id;
5812 form.composeType.value = composeType;
5813 form.composeLayoutId.value = 'composeLayout' + idx;
5814 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5815 form.saveToSugar.value = 1;
5816 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5817 form.parent_type.value = parent_type;
5818 form.parent_id.value = parent_id;
5819 form.uid.value = uid;
5820 form.ieId.value = ieId;
5821 form.mbox.value = mbox;
5823 // email attachments
5824 var addedFiles = document.getElementById('addedFiles' + idx);
5826 for(i=0; i<addedFiles.childNodes.length; i++) {
5827 var bucket = addedFiles.childNodes[i];
5829 for(j=0; j<bucket.childNodes.length; j++) {
5830 var node = bucket.childNodes[j];
5831 var nName = new String(node.name);
5833 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5834 if(form.attachments.value != '') {
5835 form.attachments.value += "::";
5837 form.attachments.value += node.value;
5844 var addedDocs = document.getElementById('addedDocuments' + idx);
5846 for(i=0; i<addedDocs.childNodes.length; i++) {
5847 var cNode = addedDocs.childNodes[i];
5848 for(j=0; j<cNode.childNodes.length; j++) {
5849 var node = cNode.childNodes[j];
5850 var nName = new String(node.name);
5851 if(node.type == 'hidden' && nName.match(/documentId/)) {
5852 if(form.documents.value != '') {
5853 form.documents.value += "::";
5855 form.documents.value += node.value;
5861 // template attachments
5862 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5863 if(addedTemplateAttachments) {
5864 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5865 var cNode = addedTemplateAttachments.childNodes[i];
5866 for(j=0; j<cNode.childNodes.length; j++) {
5867 var node = cNode.childNodes[j];
5868 var nName = new String(node.name);
5869 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5870 if(form.templateAttachments.value != "") {
5871 form.templateAttachments.value += "::";
5873 form.templateAttachments.value += node.value;
5879 // remove attachments
5880 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5882 YAHOO.util.Connect.setForm(form);
5884 AjaxObject.target = 'frameFlex';
5886 // sending a draft email
5887 if(!isDraft && in_draft) {
5889 SE.listView.removeRowByUid(email_id);
5892 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5893 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5895 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5899 * Handles clicking the email address link from a given view
5901 composePackage : function() {
5902 if(composePackage != null) {
5903 SE.composeLayout.c0_composeNewEmail();
5906 if(composePackage.to_email_addrs) {
5907 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5909 if (composePackage.subject != null && composePackage.subject.length > 0) {
5910 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5913 //If no parent fields are set in the composePackage, ensure they are cleared.
5914 var parentFields = ['parent_type','parent_name','parent_id'];
5915 for(var i=0;i<parentFields.length;i++)
5917 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5918 composePackage[parentFields[i]] = "";
5921 document.getElementById("parent_type").value = composePackage.parent_type;
5922 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5923 document.getElementById("parent_id").value = composePackage.parent_id;
5924 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5925 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5927 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5928 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5930 if (composePackage.body != null && composePackage.body.length > 0) {
5931 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5932 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5933 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5935 if (composePackage.attachments != null) {
5936 SE.composeLayout.loadAttachments(composePackage.attachments);
5939 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5940 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5941 SE.util.emptySelectOptions(addressFrom);
5942 var fromAccountOpts = composePackage.fromAccounts.data;
5943 for(i=0; i<fromAccountOpts.length; i++) {
5944 var key = fromAccountOpts[i].value;
5945 var display = fromAccountOpts[i].text;
5946 var opt = new Option(display, key);
5947 if (fromAccountOpts[i].selected) {
5948 opt.selected = true;
5950 addressFrom.options.add(opt);
5957 setContentOnThisTiny : function() {
5958 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5959 var tinyHTML = tiny.getContent();
5960 composePackage.body = decodeURI(encodeURI(composePackage.body));
5961 // cn: bug 14361 - text-only templates don't fill compose screen
5962 if(composePackage.body == '') {
5963 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
5965 //Flag determines if we should clear the tiny contents or just append
5966 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5967 SE.composeLayout.tinyHTML = '';
5969 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
5971 tiny.setContent(SE.composeLayout.tinyHTML);
5972 //Indicate that the contents has been loaded successfully.
5973 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5976 * Confirms closure of a compose screen if "x" is clicked
5978 confirmClose : function(panel) {
5979 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
5980 SE.composeLayout.closeCompose(panel.id);
5988 * forces close of a compose screen
5990 forceCloseCompose : function(id) {
5991 SE.composeLayout.closeCompose(id);
5993 // handle flow back to originating view
5994 if(composePackage) {
5995 // check if it's a module we need to return to
5996 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
5997 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
5998 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
5999 window.location = url;
6006 * closes the editor that just sent email
6007 * @param string id ID of composeLayout tab
6009 closeCompose : function(id) {
6010 // destroy tinyMCE instance
6011 var idx = id.substr(13, id.length);
6012 var instanceId = "htmleditor" + idx;
6013 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6015 // nullify DOM and namespace values.
6017 SE.composeLayout[idx] = null;
6018 SE.tinyInstances[instanceId] = null;
6019 var tabsArray = SE.innerLayout.get("tabs");
6020 for (i = 0 ; i < tabsArray.length ; i++) {
6021 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6022 tabsArray[i].close();
6026 //SE.innerLayout.getTab(idx).close();
6030 * Enable the quick search for the compose relate field or search tab
6032 enableQuickSearchRelate: function(idx,overides){
6034 if(typeof overides != 'undefined')
6036 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6037 var newModule = document.getElementById(newModuleID).value;
6038 var formName = overides['formName'];
6039 var fieldName = overides['fieldName'];
6040 var fieldId = overides['fieldId'];
6041 var fullName = formName + "_" + fieldName;
6042 var postBlurFunction = null;
6046 var newModule = document.getElementById('data_parent_type'+idx).value;
6047 var formName = 'emailCompose'+idx;
6048 var fieldName = 'data_parent_name'+idx;
6049 var fieldId = 'data_parent_id'+idx;
6050 var fullName = formName + "_" + fieldName;
6051 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6054 if(typeof sqs_objects == 'undefined')
6055 window['sqs_objects'] = new Array;
6057 window['sqs_objects'][fullName] = {
6060 modules:[newModule],
6062 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6063 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6064 post_onblur_function: postBlurFunction,
6065 order:"name","limit":"30","no_match_text":"No Match"};
6068 if(typeof QSProcessedFieldsArray != 'undefined')
6069 QSProcessedFieldsArray[fullName] = false;
6070 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6071 QSFieldsArray[fullName].destroy();
6072 delete QSFieldsArray[fullName];
6074 if (Dom.get(fullName + "_results")) {
6075 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6081 qsAddAddress : function(o) {
6082 if (o.name != "" && o.email1 != "")
6084 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6085 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6089 * Returns a new instance ID, 0-index
6091 getNewInstanceId : function() {
6092 this.currentInstanceId = this.currentInstanceId + 1;
6093 return this.currentInstanceId;
6097 * 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.
6099 loadAttachments : function(result) {
6100 var idx = SE.composeLayout.currentInstanceId;
6102 if(typeof(result) == 'object') {
6103 //jchi #20680. Clean the former template attachments;
6104 var basket = document.getElementById('addedTemplateAttachments' + idx);
6105 if(basket.innerHTML != ''){
6106 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6108 basket.innerHTML = '';
6113 if(typeof result[i] == 'object') {
6114 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6115 var bean = result[i];
6116 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6117 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6124 * fills drop-down values for email templates and signatures
6126 setComposeOptions : function(idx) {
6127 // send from accounts
6128 var addressFrom = document.getElementById('addressFrom' + idx);
6130 if (addressFrom.options.length <= 0) {
6131 SE.util.emptySelectOptions(addressFrom);
6132 var fromAccountOpts = SE.composeLayout.fromAccounts;
6133 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6134 var key = fromAccountOpts[id].value;
6135 var display = fromAccountOpts[id].text;
6136 var is_default = false;
6137 if(key == SUGAR.default_inbound_accnt_id)
6139 var opt = new Option(display, key);
6140 addressFrom.options.add(opt);
6141 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6146 var et = document.getElementById('email_template' + idx);
6147 SE.util.emptySelectOptions(et);
6149 for(var key in this.emailTemplates) { // iterate through assoc array
6150 var display = this.emailTemplates[key];
6151 var opt = new Option(display, key);
6152 et.options.add(opt);
6156 var sigs = document.getElementById('signatures' + idx);
6157 SE.util.emptySelectOptions(sigs);
6159 for(var key in this.signatures) { // iterate through assoc array
6160 var display = this.signatures[key];
6161 var opt = new Option(display, key);
6163 if(key == SE.userPrefs.signatures.signature_default) {
6164 opt.selected = true;
6167 sigs.options.add(opt);
6170 // html/plain email?
6171 var htmlEmail = document.getElementById('setEditor' + idx);
6172 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6173 htmlEmail.checked = true;
6175 htmlEmail.checked = false;
6178 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6182 * After compose screen is rendered, async call to get email body from Sugar
6184 replyForwardEmailStage2 : function() {
6185 SE.util.clearHiddenFieldValues('emailUIForm');
6186 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6188 var ieId = SE.composeLayout.replyForwardObj.ieId;
6189 var uid = SE.composeLayout.replyForwardObj.uid;
6190 var mbox = SE.composeLayout.replyForwardObj.mbox;
6191 var type = SE.composeLayout.replyForwardObj.type;
6192 var idx = SE.composeLayout.currentInstanceId;
6194 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6196 document.getElementById('emailSubject' + idx).value = type;
6197 document.getElementById('emailUIAction').value = 'composeEmail';
6198 document.getElementById('composeType').value = type;
6199 document.getElementById('ieId').value = ieId;
6200 document.getElementById('uid').value = uid;
6201 document.getElementById('mbox').value = mbox;
6202 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6203 var formObject = document.getElementById('emailUIForm');
6204 YAHOO.util.Connect.setForm(formObject);
6206 var sendType = type;
6207 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6211 * Show the hidden cc or bcc fields
6213 showHiddenAddress: function(addrType,idx){
6215 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6216 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6217 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6218 this[addrType+'Hidden'+idx] = false;
6220 //After bcc or cc is added, move options below last addr field
6221 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6223 //If both cc and bcc hidden, remove the empty row containing text.
6224 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6225 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6226 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6228 SE.composeLayout.resizeEditor(idx);
6231 * Hide the cc and bcc fields if they were shown.
6233 hideHiddenAddresses: function(idx){
6235 var addrTypes = ['cc','bcc'];
6236 for(var i = 0;i<addrTypes.length;i++)
6238 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6239 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6240 this[addrTypes[i] + 'Hidden'+idx] = true
6243 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6244 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6245 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6249 //// END SE.composeLayout
6250 ///////////////////////////////////////////////////////////////////////////////
6251 ///////////////////////////////////////////////////////////////////////////////
6255 * Cleans serialized UID lists of duplicates
6259 cleanUids : function(str) {
6260 var seen = new Object();
6262 var arr = new String(str).split(",");
6264 for(var i=0; i<arr.length; i++) {
6269 clean += (clean != "") ? "," : "";
6271 seen[arr[i]] = true;
6278 * Clears hidden field values
6279 * @param string id ID of form element to clear
6281 clearHiddenFieldValues : function(id) {
6282 var form = document.getElementById(id);
6284 for(i=0; i<form.elements.length; i++) {
6285 if(form.elements[i].type == 'hidden') {
6286 var e = form.elements[i];
6287 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6295 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6297 emptySelectOptions : function(el) {
6299 for(i=el.childNodes.length - 1; i >= 0; i--) {
6300 if(el.childNodes[i]) {
6301 el.removeChild(el.childNodes[i]);
6308 * Returns the MBOX path in the manner php_imap expects:
6309 * ie: INBOX.DEBUG.test
6310 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6312 generateMboxPath : function(str) {
6313 var ex = str.split("::");
6315 /* we have a serialized MBOX path */
6319 for(var i=0; i<ex.length; i++) {
6320 if(ex[i] == 'INBOX') {
6332 /* we have a Sugar folder GUID - do nothing */
6340 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6341 * @param HTMLElement el
6342 * @return string GUID of found element or empty on failure
6344 getGuidFromElement : function(el) {
6350 for(var i=0; i<iterations; i++) {
6352 if(el.id.match(SE.reGUID)) {
6364 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6367 getPanelId : function() {
6368 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6372 * wrapper to handle weirdness with IE
6373 * @param string instanceId
6374 * @return tinyMCE Controller object
6376 getTiny : function(instanceId) {
6377 if(instanceId == '') {
6381 var t = tinyMCE.getInstanceById(instanceId);
6385 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6391 * Simple check for MSIE browser
6395 var nav = new String(navigator.appVersion);
6396 if(nav.match(/MSIE/)) {
6403 * Recursively removes an element from the DOM
6404 * @param HTMLElement
6406 removeElementRecursive : function(el) {
6407 this.emptySelectOptions(el);
6414 sleep : function(secs) {
6415 setTimeout("void(0);", secs);
6419 * Converts a <select> element to an Ext.form.combobox
6421 convertSelect : function(select) {
6422 alert('in convertSelect');
6423 if (typeof(select) == "string") {
6424 select = document.getElementById(select);
6428 findChildNode : function (parent, property, value) {
6429 for (i in parent.children) {
6430 var child = parent.children[i];
6431 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6433 var searchChild = SE.util.findChildNode(child, property, value);
6440 cascadeNodes : function (parent, fn, scope, args) {
6441 for (i in parent.children) {
6442 var child = parent.children[i];
6443 var s = scope ? scope : child;
6444 var a = args ? args : child;
6446 SE.util.cascadeNodes(child, fn, scope, args);
6453 ///////////////////////////////////////////////////////////////////////////////
6456 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6458 /*********************************************************************************
6459 * SugarCRM is a customer relationship management program developed by
6460 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6462 * This program is free software; you can redistribute it and/or modify it under
6463 * the terms of the GNU Affero General Public License version 3 as published by the
6464 * Free Software Foundation with the addition of the following permission added
6465 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6466 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6467 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6469 * This program is distributed in the hope that it will be useful, but WITHOUT
6470 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6471 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6474 * You should have received a copy of the GNU Affero General Public License along with
6475 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6476 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6479 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6480 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6482 * The interactive user interfaces in modified source and object code versions
6483 * of this program must display Appropriate Legal Notices, as required under
6484 * Section 5 of the GNU Affero General Public License version 3.
6486 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6487 * these Appropriate Legal Notices must retain the display of the "Powered by
6488 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6489 * technical reasons, the Appropriate Legal Notices must display the words
6490 * "Powered by SugarCRM".
6491 ********************************************************************************/
6494 if (typeof console == "undefined")
6495 console = { log: function(o) {alert(o)} };
6499 currentRequestObject : null,
6500 //timeout : 30000, // 30 second timeout default
6501 timeout : 9999999999, // 30 second timeout default
6503 trail : new Array(),
6507 _reset : function() {
6508 this.timeout = 30000;
6509 this.forceAbort = false;
6512 folderRenameCleanup : function() {
6513 SUGAR.email2.folders.setSugarFolders();
6516 fullSyncCleanup : function(o) {
6517 this.folders.checkMailCleanup(o);
6518 SUGAR.email2.settings.settingsDialog.hide();
6523 composeCache : function(o) {
6524 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6525 // get email templates and user signatures
6526 var ret = JSON.parse(o.responseText);
6528 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6529 SUGAR.email2.composeLayout.signatures = ret.signatures;
6530 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6532 SUGAR.email2.composeLayout.setComposeOptions(idx);
6534 //Set the error array so we can notify the user when they try to hit send if any errors
6535 //are present. We will also notify them now (after hitting compose button).
6536 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6539 //if error element is returning an array, then check the length to make sure we have error messages
6540 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6541 //add error messages for display
6542 for(i in ret.errorArray)
6543 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6544 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6545 //if error element is returning an object, and the object value is not empty or null, then display error message
6546 for(i in ret.errorArray)
6547 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6550 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6552 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6554 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6560 handleDeleteSignature : function(o) {
6562 var ret = JSON.parse(o.responseText);
6563 SUGAR.email2.composeLayout.signatures = ret.signatures;
6564 var field = document.getElementById('signature_id');
6565 SUGAR.email2.util.emptySelectOptions(field);
6567 for(var i in ret.signatures) { // iterate through assoc array
6568 var opt = new Option(ret.signatures[i], i);
6569 field.options.add(opt);
6571 setSigEditButtonVisibility();
6576 handleDeleteReturn : function(o) {
6577 // force refresh ListView
6579 if(document.getElementById('focusEmailMbox')) {
6580 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6583 // need to display success message before calling next async call?
6584 document.getElementById(this.target).innerHTML = o.responseText;
6589 handleFailure : function(o) {
6591 overlay('Exception occurred...', o.statusText, 'alert');
6594 handleReplyForward : function(o) {
6595 var a = JSON.parse(o.responseText);
6597 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6599 document.getElementById('email_id' + idx).value = a.uid;
6600 document.getElementById('emailSubject' + idx).value = a.name;
6601 document.getElementById('addressTO' + idx).value = a.from;
6602 document.getElementById('uid' + idx).value = a.uid;
6604 document.getElementById('addressCC' + idx).value = a.cc;
6605 SE.composeLayout.showHiddenAddress('cc', idx);
6609 document.getElementById('type' + idx).value = a.type;
6612 // apply attachment values
6613 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6615 setTimeout("callbackReplyForward.finish(globalA);", 500);
6618 handleReplyForwardForDraft : function(o) {
6619 var a = JSON.parse(o.responseText);
6621 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6623 document.getElementById('email_id' + idx).value = a.uid;
6624 document.getElementById('emailSubject' + idx).value = a.name;
6625 document.getElementById('addressTO' + idx).value = a.to;
6628 document.getElementById('addressCC' + idx).value = a.cc;
6629 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6633 document.getElementById('addressBCC' + idx).value = a.bcc;
6634 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6639 document.getElementById('type' + idx).value = a.type;
6643 // apply attachment values
6644 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6646 setTimeout("callbackReplyForward.finish(globalA);", 500);
6651 handleSuccess : function(o) {
6652 document.getElementById(this.target).innerHTML = o.responseText;
6658 ieDeleteSuccess : function(o) {
6661 var ret = JSON.parse(o.responseText);
6663 SUGAR.email2.accounts.refreshInboundAccountTable();
6664 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6665 SUGAR.email2.accounts.rebuildFolderList();
6671 ieSaveSuccess : function(o) {
6672 document.getElementById('saveButton').disabled = false;
6673 var a = JSON.parse(o.responseText);
6676 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6677 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6679 resp = JSON.parse(o.responseText);
6680 SUGAR.email2.accounts.refreshInboundAccountTable();
6681 SUGAR.email2.accounts.refreshOuboundAccountTable();
6682 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6683 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6687 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6694 loadAttachments : function(o) {
6695 var result = JSON.parse(o.responseText);
6697 SUGAR.email2.composeLayout.loadAttachments(result);
6702 loadSignature : function(o) {
6703 var ret = JSON.parse(o.responseText);
6704 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6705 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6709 * Follow up to mark email read|unread|flagged
6711 markEmailCleanup : function(o) {
6712 var ret = JSON.parse(o.responseText);
6713 if (!ret['status']) {
6715 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6717 SUGAR.email2.contextMenus.markEmailCleanup();
6723 rebuildShowFolders : function(o) {
6724 var t = JSON.parse(o.responseText);
6725 var show = document.getElementById('ieAccountListShow');
6727 SUGAR.email2.util.emptySelectOptions(show);
6729 for(i=0; i<t.length; i++) { // iterate through assoc array
6730 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6731 opt.selected = t[i].selected;
6732 show.options.add(opt);
6735 SUGAR.email2.accounts.renderTree();
6739 saveListViewSortOrderPart2 : function() {
6740 // create the JSON string the func expects
6741 focusFolderPath = '[ "Home", "' + ieName + '"';
6743 var f = new String(focusFolder);
6744 var fEx = f.split('.');
6746 for(i=0; i<fEx.length; i++) {
6747 focusFolderPath += ', "' + fEx[i] +'"'
6750 focusFolderPath += ']';
6752 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6753 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6759 sendEmailCleanUp : function(o) {
6761 var ret = JSON.parse(o.responseText);
6763 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6764 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6765 } else if (o.responseText) {
6766 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6769 if (typeof(SE.grid) != 'undefined')
6770 SE.listView.refreshGrid();
6771 //Disabled while address book is disabled
6773 //If this call back was initiated by quick compose from a Detail View page, refresh the
6774 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6775 //close the shortcut bar menu
6776 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6777 if(action_sugar_grp1 == 'DetailView') {
6778 showSubPanel('history',null,true);
6779 } else if(action_sugar_grp1 == 'quickcreate') {
6780 closeEmailOverlay();
6786 ieSendSuccess : function(o) {
6788 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6793 settingsFolderRefresh : function(o) {
6794 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6795 var ret = JSON.parse(o.responseText);
6796 var user = document.getElementById('userFolders');
6798 SUGAR.email2.util.emptySelectOptions(user);
6800 for(i=0; i<ret.userFolders.length; i++) {
6801 var display = ret.userFolders[i].name;
6802 var value = ret.userFolders[i].id;
6803 var selected = (ret.userFolders[i].selected != "") ? true : false;
6804 var opt = new Option(display, value, selected);
6805 opt.selected = selected;
6806 user.options.add(opt);
6812 startRequest : function(callback, args, forceAbort) {
6813 if(this.currentRequestObject != null) {
6814 if(this.forceAbort == true) {
6815 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6818 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6822 requestInProgress : function() {
6823 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6828 updateFolderSubscriptions : function() {
6829 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6830 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6836 updateFrameFolder : function() {
6837 SUGAR.email2.folders.checkEmailAccounts();
6842 updateUserPrefs : function(o) {
6843 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6844 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6849 uploadAttachmentSuccessful : function(o) {
6851 document.getElementById('email_attachment').value = '';
6853 var ret = JSON.parse(o.responseText);
6854 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6855 var overall = document.getElementById('addedFiles' + idx);
6856 var index = overall.childNodes.length;
6858 "<div id='email_attachment_bucket" + idx + index + "'>" +
6860 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6861 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6862 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6864 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6865 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6867 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6869 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6872 overall.innerHTML += out;
6873 if(SUGAR.email2.util.isIe()) {
6874 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6878 SUGAR.email2.addFileDialog.hide();
6879 // focus attachments
6880 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6885 ///////////////////////////////////////////////////////////////////////////
6886 //// PER MODULE CALLBACK OBJECTS
6887 AjaxObject.accounts = {
6888 saveOutboundCleanup : function(o) {
6889 SUGAR.email2.accounts.refreshOuboundAccountTable();
6890 SUGAR.email2.accounts.outboundDialog.hide();
6891 var id = o.responseText;
6892 SUGAR.email2.accounts.newAddedOutboundId = id;
6894 saveDefaultOutboundCleanup: function(o){
6897 callbackEditOutbound : {
6898 success : function(o)
6900 var ret = JSON.parse(o.responseText);
6902 SUGAR.email2.accounts.showAddSmtp();
6905 document.getElementById("mail_id").value = ret.id;
6906 document.getElementById("type").value = ret.type;
6907 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6908 document.getElementById("mail_name").value = ret.name;
6909 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6910 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6911 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6912 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6913 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6914 SUGAR.email2.accounts.smtp_authenticate_field_display();
6915 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6917 if(ret.type == 'system-override') {
6918 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6919 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6922 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6923 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6925 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6928 failure : AjaxObject.handleFailure,
6929 timeout : AjaxObject.timeout,
6932 callbackDeleteOutbound : {
6933 success : function(o) {
6934 var ret = JSON.parse(o.responseText);
6937 if(confirm(ret.error_message))
6939 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6940 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6948 SUGAR.email2.accounts.refreshOuboundAccountTable();
6952 failure : AjaxObject.handleFailure,
6953 timeout : AjaxObject.timeout,
6957 callbackCheckMailProgress : {
6958 success : function(o) {
6959 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6960 SUGAR.email2.accounts.totalMsgCount = -1;
6963 //Check for server timeout / errors
6964 var ret = JSON.parse(o.responseText);
6967 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6969 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6970 SUGAR.email2.accounts.totalMsgCount = -1;
6971 //SUGAR.email2.folders.rebuildFolders();
6975 var currIeId = ret['ieid'];
6978 var serverCount = ret.count;
6980 if (ret['status'] == 'done') {
6981 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
6982 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
6986 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
6987 //Go to next account
6988 currIeId = SUGAR.email2.accounts.ieIds[i+1];
6990 SUGAR.email2.accounts.totalMsgCount = -1;
6995 else if (ret.mbox && ret.totalcount && ret.count) {
6996 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
6997 if (ret.count >= ret.totalcount) {
7000 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7001 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7004 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7005 SUGAR.email2.accounts.totalMsgCount = -1;
7010 SUGAR.email2.accounts.totalMsgCount = -1;
7012 SUGAR.email2.folders.rebuildFolders();
7013 SE.listView.refreshGrid();
7014 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7015 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7016 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7017 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7019 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7020 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7021 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7022 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7023 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7026 failure : AjaxObject.handleFailure,
7027 timeout : AjaxObject.timeout,
7032 ///////////////////////////////////////////////////////////////////////////////
7034 AjaxObject.composeLayout = {
7036 * Populates the record id
7038 saveDraftCleanup : function(o) {
7040 var ret = JSON.parse(o.responseText);
7042 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7043 else if (o.responseText)
7044 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7048 AjaxObject.composeLayout.callback = {
7050 success : AjaxObject.composeLayout.saveDraftCleanup,
7051 failure : AjaxObject.handleFailure,
7052 timeout : AjaxObject.timeout,
7057 AjaxObject.detailView = {
7059 * Pops-up a printable view of an email
7061 displayPrintable : function(o) {
7062 var ret = JSON.parse(o.responseText);
7063 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7064 // 2 below must be in global context
7066 meta['panelId'] = SUGAR.email2.util.getPanelId();
7067 email = ret.meta.email;
7068 if (typeof(email.cc) == 'undefined') {
7072 var out = displayTemplate.exec({
7073 'app_strings' : app_strings,
7077 'email' : meta.email
7080 // open popup window
7081 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7082 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7084 popup.document.write(out);
7085 popup.document.close();
7089 * Takes formatted response and creates a modal pop-over containing a title and content
7091 displayView : function(o) {
7092 var SED = SUGAR.email2.detailView;
7093 var ret = JSON.parse(o.responseText);
7095 if(!SED.viewDialog) {
7096 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7100 constraintoviewport: true,
7103 SED.viewDialog.renderEvent.subscribe(function() {
7104 var content = this.body.firstChild;
7105 var viewH = YAHOO.util.Dom.getViewportHeight();
7107 this.body.style.overflow = "auto";
7108 this.body.style.width = "800px";
7109 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7113 SED.viewDialog.setHeader(ret.title);
7114 SED.viewDialog.setBody(ret.html);
7115 SED.viewDialog.render();
7116 SED.viewDialog.show();
7120 * Generates a modal popup to populate with the contents of bean's full EditView
7122 showQuickCreateForm : function(o) {
7123 var SED = SUGAR.email2.detailView;
7124 var ret = JSON.parse(o.responseText);
7126 if(!SED.quickCreateDialog) {
7127 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7131 constraintoviewport: true,
7135 SED.quickCreateDialog.renderEvent.subscribe(function() {
7136 var viewH = YAHOO.util.Dom.getViewportHeight();
7138 for (var i in this.body.childNodes) {
7139 if (this.body.childNodes[i].clientHeight) {
7140 contH += this.body.childNodes[i].clientHeight;
7141 } else if (this.body.childNodes[i].offsetHeight) {
7142 contH += this.body.childNodes[i].offsetHeight;
7145 this.body.style.width = "800px";
7146 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7147 this.body.style.overflow = "auto";
7148 }, SED.quickCreateDialog);
7150 SED.quickCreateDialog.hideEvent.subscribe(function(){
7151 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7152 /*for(var qsField in qsFields){
7153 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7154 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7157 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7160 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7162 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7163 SED.quickCreateDialog.render();
7164 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7166 SED.quickCreateDialog.ieId = ret.ieId;
7167 SED.quickCreateDialog.uid = ret.uid;
7168 SED.quickCreateDialog.mbox = ret.mbox;
7169 SED.quickCreateDialog.qcmodule = ret.module;
7171 SED.quickCreateDialog.show();
7173 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7175 editForm.module.value = 'Emails';
7176 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7177 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7178 var instId = ret.module + count;
7179 SED.quickCreateEmailsToAdd = ret.emailAddress;
7180 SED.quickCreateEmailCallback = function(instId, tableId) {
7181 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7182 if (typeof(eaw) == "undefined")
7183 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7184 + instId + "','" + tableId + "');", 100);
7185 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7187 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7188 + instId + "','" + tableId + "');", 100);
7192 saveQuickCreateForm : function(o) {
7194 SUGAR.email2.detailView.quickCreateDialog.hide();
7195 validate['EditView'] = [ ];
7198 saveQuickCreateFormAndReply : function(o) {
7200 var ret = JSON.parse(o.responseText);
7201 SUGAR.email2.detailView.quickCreateDialog.hide();
7202 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7203 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7205 var emailID = ret.id;
7206 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7208 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7210 //Cean the validate cache to prevent errors on the next call
7211 validate['EditView'] = [ ];
7214 saveQuickCreateFormAndAddToAddressBook : function(o) {
7216 SUGAR.email2.detailView.quickCreateDialog.hide();
7217 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7218 validate['EditView'] = [ ];
7221 handleAssignmentDialogAssignAction : function() {
7224 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7226 var dist = 'direct';
7230 var found_teams = false;
7231 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7232 if(!found_teams && assign_user_id == '' )
7234 alert(warning_message);
7238 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7240 for(i=0; i<emailUids.length; i++) {
7242 uids += app_strings.LBL_EMAIL_DELIMITER;
7244 uids += emailUids[i];
7247 var row = SUGAR.email2.grid.getSelectedRows()[0];
7248 var data = SUGAR.email2.grid.getRecord(row).getData();
7249 var ieid = data.ieId;
7250 var mbox = data.mbox;
7251 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7252 SUGAR.email2.contextMenus.assignToDialogue.hide();
7253 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7257 handleAssignmentDialogDeleteAction : function() {
7258 // TO pass list of UIDS/emailIds
7259 var uids = SUGAR.email2.listView.getUidsFromSelection();
7260 var row = SUGAR.email2.grid.getSelections()[0];
7261 var ieid = row.data.ieId;
7262 var mbox = row.data.mbox;
7263 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7264 SUGAR.email2.contextMenus.assignmentDialog.hide();
7265 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7271 showEmailDetailView : function(o) {
7273 var SED = SUGAR.email2.detailView;
7274 var ret = JSON.parse(o.responseText);
7276 if(!SED.quickCreateDialog) {
7277 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7281 constraintoviewport: true,
7283 autofillheight: "body",
7286 SED.quickCreateDialog.renderEvent.subscribe(function() {
7287 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7289 for (var i in this.body.childNodes) {
7290 if (this.body.childNodes[i].offsetHeight)
7291 contH += this.body.childNodes[i].offsetHeight;
7293 this.body.style.overflow = "auto";
7294 this.body.style.width = "800px";
7295 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7297 }, SED.quickCreateDialog);
7299 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7300 SED.quickCreateDialog.setBody(ret.html);
7301 SED.quickCreateDialog.render();
7302 SUGAR.util.evalScript(ret.html);
7303 SED.quickCreateDialog.show();
7306 showAssignmentDialogWithData : function(o) {
7307 var SEC = SUGAR.email2.contextMenus;
7309 var ret = JSON.parse(o.responseText);
7310 if (!SEC.assignmentDialog) {
7311 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7314 constraintoviewport: true,
7317 SEC.assignmentDialog.setBody("");
7318 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7319 SEC.assignmentDialog.renderEvent.subscribe(function() {
7320 var iev = YAHOO.util.Dom.get("Distribute");
7322 this.body.style.width = "700px";
7324 }, SEC.assignmentDialog);
7325 SEC.assignmentDialog.render();
7327 SEC.assignmentDialog.setBody(ret);
7328 SEC.assignmentDialog.render();
7330 SEC.assignmentDialog.show();
7331 SUGAR.util.evalScript(ret);
7334 showImportForm : function(o) {
7335 var SED = SUGAR.email2.detailView;
7336 var ret = JSON.parse(o.responseText);
7338 document.getElementById('quickCreateContent').innerHTML = "";
7344 if(!SED.importDialog) {
7345 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7349 constraintoviewport: true,
7351 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7352 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7356 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7357 SED.importDialog.setBody("");
7358 SED.importDialog.hideEvent.subscribe(function(){
7359 for(var i in QSFieldsArray) {
7360 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7361 QSFieldsArray[i].destroy();
7362 delete QSFieldsArray[i];
7364 if (QSProcessedFieldsArray[i]) {
7365 QSProcessedFieldsArray[i] = false;
7369 SED.importDialog.renderEvent.subscribe(function() {
7370 var iev = YAHOO.util.Dom.get("ImportEditView");
7372 //this.body.style.height = (iev.clientHeight + 10) + "px";
7373 this.body.style.width = "600px";
7375 }, SED.importDialog);
7376 SED.importDialog.render();
7378 SED.importDialog.setBody(ret.html);
7379 SED.importDialog.ret = ret;
7380 SUGAR.util.evalScript(ret.html);
7381 SED.importDialog.render();
7383 SED.importDialog.show();
7384 SED.importDialog.focusFirstButton();
7386 getImportAction : function(ret) {
7387 if (!check_form('ImportEditView')) return false;
7388 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7389 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7393 var editView = document.getElementById('ImportEditView');
7394 if (editView.assigned_user_id != null) {
7395 get = get + "&user_id=" + editView.assigned_user_id.value
7396 //var user_id = editView.assigned_user_id.value;
7398 var parent_id = editView.parent_id.value;
7399 var parent_type = editView.parent_type.value;
7400 var row = SUGAR.email2.grid.getSelectedRows()[0];
7401 row = SUGAR.email2.grid.getRecord(row);
7402 var data = row.getData();
7403 var ieId = data.ieId;
7404 var mbox = data.mbox;
7405 var serverDelete = editView.serverDelete.checked;
7406 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7408 for(i=0; i<emailUids.length; i++) {
7410 uids += app_strings.LBL_EMAIL_DELIMITER;
7412 uids += emailUids[i];
7415 var action = 'importEmail&uid=';
7417 action = 'moveEmails';
7418 action = action + '&sourceFolder=' + ret['srcFolder'];
7419 action = action + '&sourceIeId=' + ret['srcIeId'];
7420 action = action + '&destinationFolder=' + ret['dstFolder'];
7421 action = action + '&destinationIeId=' + ret['dstIeId'];
7422 action = action + '&emailUids=';
7424 if (action.search(/importEmail/) != -1) {
7425 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7427 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7430 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7431 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7432 SUGAR.email2.detailView.importDialog.hide();
7433 document.getElementById('importDialogContent').innerHTML = "";
7436 showRelateForm : function(o) {
7437 var SED = SUGAR.email2.detailView;
7438 var ret = JSON.parse(o.responseText);
7439 document.getElementById('quickCreateContent').innerHTML = "";
7444 dialog_loaded = true;
7446 if(!SED.relateDialog) {
7447 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7452 constraintoviewport: true,
7454 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7455 if (!check_form('RelateEditView')) return false;
7457 var editView = document.getElementById('RelateEditView');
7458 var parent_id = editView.parent_id.value;
7459 var parent_type = editView.parent_type.value;
7460 var row = SUGAR.email2.grid.getSelectedRows()[0];
7461 row = SUGAR.email2.grid.getRecord(row);
7462 var ieId = row.getData().ieId;
7463 var mbox = row.getData().mbox;
7464 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7466 for(i=0; i<emailUids.length; i++) {
7468 uids += app_strings.LBL_EMAIL_DELIMITER;
7470 uids += emailUids[i];
7472 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7473 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7474 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7475 SED.relateDialog.hide();
7476 document.getElementById('relateDialogContent').innerHTML = "";
7481 SED.relateDialog.hideEvent.subscribe(function(){
7482 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7483 QSFieldsArray['ImportEditView_parent_name'].destroy();
7484 delete QSFieldsArray['ImportEditView_parent_name'];
7486 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7487 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7491 SED.relateDialog.renderEvent.subscribe(function() {
7492 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7494 for (var i in this.body.childNodes) {
7495 if (this.body.childNodes[i].clientHeight)
7496 contH += this.body.childNodes[i].clientHeight;
7498 }, SED.relateDialog);
7499 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7502 SED.relateDialog.setBody(ret.html);
7503 SED.relateDialog.render();
7504 SUGAR.util.evalScript(ret.html);
7505 SED.relateDialog.show();
7509 * DetailView callbacks
7511 AjaxObject.detailView.callback = {
7513 success : function(o) {
7515 var ret = JSON.parse(o.responseText);
7516 SUGAR.email2.detailView.consumeMetaDetail(ret);
7518 argument: [targetDiv],
7519 failure : AjaxObject.handleFailure,
7524 success : function(o) {
7526 var ret = JSON.parse(o.responseText);
7527 SUGAR.email2.detailView.consumeMetaPreview(ret);
7529 failure : AjaxObject.handleFailure,
7534 success : AjaxObject.detailView.displayPrintable,
7535 failure : AjaxObject.handleFailure,
7536 timeout : AjaxObject.timeout,
7540 success : AjaxObject.detailView.displayView,
7541 failure : AjaxObject.handleFailure,
7542 timeout : AjaxObject.timeout,
7551 AjaxObject.folders = {
7553 * check-mail post actions
7555 checkMailCleanup : function(o) {
7557 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7559 // refresh focus ListView
7560 SE.listView.refreshGrid();
7561 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7566 rebuildFolders : function(o) {
7569 var data = JSON.parse(o.responseText);
7571 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7572 SUGAR.email2.folders.setSugarFolders();
7575 AjaxObject.folders.callback = {
7577 success : AjaxObject.folders.checkMailCleanup,
7578 failure : AjaxObject.handleFailure,
7579 timeout : 600000, // 5 mins
7584 AjaxObject.rules = {
7585 loadRulesForSettings : function(o) {
7586 document.getElementById("rulesListCell").innerHTML = o.responseText;
7587 // assume we have the class we need
7588 SUGAR.routing.getStrings();
7589 SUGAR.routing.getDependentDropdowns();
7592 //// END PER MODULE CALLBACK OBJECTS
7593 ///////////////////////////////////////////////////////////////////////////
7597 success : AjaxObject.handleSuccess,
7598 failure : AjaxObject.handleFailure,
7599 timeout : AjaxObject.timeout,
7602 var callbackAccount = {
7603 success : AjaxObject.ieSaveSuccess,
7604 failure : AjaxObject.handleFailure,
7605 timeout : AjaxObject.timeout,
7608 var callbackAccountDelete = {
7609 success : AjaxObject.ieDeleteSuccess,
7610 failure : AjaxObject.handleFailure,
7611 timeout : AjaxObject.timeout,
7614 var callbackOutboundTest = {
7615 success : AjaxObject.ieSendSuccess,
7616 failure : AjaxObject.handleFailure,
7617 timeout : AjaxObject.timeout,
7623 var callbackTeamInfoForSettings = {
7624 success : function (o) {
7625 var data = JSON.parse(o.responseText);
7626 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7628 failure : AjaxObject.handleFailure,
7629 timeout : AjaxObject.timeout,
7634 var callbackStatusForImport = {
7635 success : function (o) {
7637 if (o.responseText != "") {
7638 var statusString = "";
7639 var data = JSON.parse(o.responseText);
7640 for(i=0; i<data.length; i++) {
7641 statusString = statusString + data[i] + '<br/>';
7643 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7645 SE.listView.refreshGrid();
7648 failure : AjaxObject.handleFailure,
7649 timeout : AjaxObject.timeout,
7653 var callbackComposeCache = {
7654 success : AjaxObject.composeCache,
7655 failure : AjaxObject.handleFailure,
7656 timeout : AjaxObject.timeout,
7659 var callbackDelete = {
7660 success : AjaxObject.handleDeleteReturn,
7661 failure : AjaxObject.handleFailure,
7662 timeout : AjaxObject.timeout,
7665 var callbackEmailDetailMultiple = {
7666 success : function(o) {
7668 var retMulti = JSON.parse(o.responseText);
7669 var ret = new Object();
7671 for(var i=0; i<retMulti.length; i++) {
7674 SUGAR.email2._setDetailCache(ret);
7675 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7678 failure : AjaxObject.handleFailure,
7682 var callbackListViewSortOrderChange = {
7683 success : AjaxObject.saveListViewSortOrderPart2,
7684 failure : AjaxObject.handleFailure,
7685 timeout : AjaxObject.timeout,
7687 argument : [ieId, ieName, focusFolder]
7689 var callbackEmptyTrash = {
7690 success : function(o) {
7692 AjaxObject.folderRenameCleanup;
7694 failure : AjaxObject.handleFailure,
7695 timeout : AjaxObject.timeout,
7698 var callbackClearCacheFiles = {
7699 success : function(o) {
7702 failure : AjaxObject.handleFailure,
7703 timeout : AjaxObject.timeout,
7706 var callbackFolderRename = {
7707 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7708 failure : AjaxObject.handleFailure,
7709 timeout : AjaxObject.timeout,
7712 var callbackFolderDelete = {
7713 success : function(o) {
7714 var ret = JSON.parse(o.responseText);
7716 if (ret.folder_id) {
7717 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7719 SUGAR.email2.tree.removeNode(node, true);
7720 } else if (ret.ieId && ret.mbox) {
7721 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7723 SUGAR.email2.tree.removeNode(node, true);
7726 //SUGAR.email2.folders.loadSettingFolder();
7729 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7732 failure : AjaxObject.handleFailure,
7733 timeout : AjaxObject.timeout,
7736 var callbackFolderSave = {
7737 success : function(o) {
7738 var ret = JSON.parse(o.responseText);
7740 switch(ret.action) {
7741 case 'newFolderSave':
7742 SUGAR.email2.folders.rebuildFolders();
7746 failure : AjaxObject.handleFailure,
7747 timeout : AjaxObject.timeout,
7750 var callbackFolderSubscriptions = {
7751 success : AjaxObject.updateFolderSubscriptions,
7752 failure : AjaxObject.handleFailure,
7753 timeout : AjaxObject.timeout,
7756 var callbackFolderUpdate = {
7757 success : AjaxObject.updateFrameFolder,
7758 failure : AjaxObject.handleFailure,
7759 timeout : AjaxObject.timeout,
7762 var callbackFolders = {
7763 success : AjaxObject.folders.rebuildFolders,
7764 //success : void(true),
7765 failure : AjaxObject.handleFailure,
7766 timeout : AjaxObject.timeout,
7769 var callbackFullSync = {
7770 success : AjaxObject.fullSyncCleanup,
7771 failure : AjaxObject.handleFailure,
7772 timeout : 9999999999999,
7775 var callbackGeneric = {
7776 success : function() {
7779 failure : AjaxObject.handleFailure,
7780 timeout : AjaxObject.timeout,
7783 var callbackIeAccountRetrieve = {
7784 success : function(o) {
7785 // return JSON encoding
7787 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7788 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7790 failure : AjaxObject.handleFailure,
7791 timeout : AjaxObject.timeout,
7794 var callbackImportOneEmail = {
7795 success : AjaxObject.detailView.showImportForm,
7796 failure : AjaxObject.handleFailure,
7797 timeout : AjaxObject.timeout,
7800 var callbackRelateEmail = {
7801 success : AjaxObject.detailView.showRelateForm,
7802 failure : AjaxObject.handleFailure,
7803 timeout : AjaxObject.timeout,
7806 var callbackEmailDetailView = {
7807 success : AjaxObject.detailView.showEmailDetailView,
7808 failure : AjaxObject.handleFailure,
7809 timeout : AjaxObject.timeout,
7812 var callbackAssignmentDialog = {
7813 success : AjaxObject.detailView.showAssignmentDialogWithData,
7814 failure : AjaxObject.handleFailure,
7815 timeout : AjaxObject.timeout,
7818 var callbackAssignmentAction = {
7819 success : function(o) {
7820 SE.listView.refreshGrid();
7822 if(o.responseText != '') {
7823 overlay('Assignment action result', o.responseText, 'alert');
7826 failure : AjaxObject.handleFailure,
7827 timeout : AjaxObject.timeout,
7830 var callbackMoveEmails = {
7831 success : function(o) {
7832 SE.listView.refreshGrid();
7834 if(o.responseText != '') {
7835 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7838 failure : AjaxObject.handleFailure,
7839 timeout : AjaxObject.timeout,
7842 var callbackLoadAttachments = {
7843 success : AjaxObject.loadAttachments,
7844 failure : AjaxObject.handleFailure,
7845 timeout : AjaxObject.timeout,
7848 var callbackLoadRules = {
7849 success : AjaxObject.rules.loadRulesForSettings,
7850 failure : AjaxObject.handleFailure,
7851 timeout : AjaxObject.timeout,
7854 var callbackLoadSignature = {
7855 success : AjaxObject.loadSignature,
7856 failure : AjaxObject.handleFailure,
7857 timeout : AjaxObject.timeout,
7860 var callbackDeleteSignature = {
7861 success : AjaxObject.handleDeleteSignature,
7862 failure : AjaxObject.handleFailure,
7863 timeout : AjaxObject.timeout,
7866 /*var callbackMoveEmails = {
7867 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7868 failure : AjaxObject.handleFailure,
7869 timeout : AjaxObject.timeout,
7872 var callbackOutboundSave = {
7873 success : AjaxObject.accounts.saveOutboundCleanup,
7874 failure : AjaxObject.handleFailure,
7875 timeout : AjaxObject.timeout,
7878 var callbackDefaultOutboundSave = {
7879 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7880 failure : AjaxObject.handleFailure,
7881 timeout : AjaxObject.timeout,
7884 var callbackQuickCreate = {
7885 success : AjaxObject.detailView.showQuickCreateForm,
7886 failure : AjaxObject.handleFailure,
7887 timeout : AjaxObject.timeout,
7890 var callbackQuickCreateSave = {
7891 success : AjaxObject.detailView.saveQuickCreateForm,
7892 failure : AjaxObject.handleFailure,
7893 timeout : AjaxObject.timeout,
7896 var callbackQuickCreateSaveAndAddToAddressBook = {
7897 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7898 failure : AjaxObject.handleFailure,
7899 timeout : AjaxObject.timeout,
7902 var callbackQuickCreateSaveAndReply = {
7903 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7904 failure : AjaxObject.handleFailure,
7905 timeout : AjaxObject.timeout,
7908 var callbackQuickCreateSaveAndReplyCase = {
7909 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7910 failure : AjaxObject.handleFailure,
7911 timeout : AjaxObject.timeout,
7914 var callbackRebuildShowAccountList = {
7915 success : AjaxObject.rebuildShowFolders,
7916 failure : AjaxObject.handleFailure,
7917 timeout : AjaxObject.timeout,
7921 var callbackRefreshSugarFolders = {
7922 success : function(o) {
7923 var t = JSON.parse(o.responseText);
7924 SUGAR.email2.folders.setSugarFoldersEnd(t);
7926 failure : AjaxObject.handleFailure,
7927 timeout : AjaxObject.timeout,
7930 var callbackReplyForward = {
7931 success : AjaxObject.handleReplyForward,
7932 finish : function(a, retryCount) {
7933 if (typeof(retryCount) == 'undefined') {
7938 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7939 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7941 var html = t.getContent();
7943 if (a.type != 'draft') {
7944 if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7945 html += " <div><hr></div>" + a.description;
7947 html = " <div><hr></div>" + a.description + html;
7950 html = a.description;
7953 t.setContent(html);//
7956 if (retryCount < 5) {
7957 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7961 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7962 if (tabArray != null && tabArray.length > 0) {
7963 for (i = 0 ; i < tabArray.length ; i++) {
7964 var tabObject = tabArray[i];
7965 if (tabObject.get("id") == ("composeTab" + idx)) {
7966 var tabLabel = a.name;
7967 if (tabLabel != null && tabLabel.length > 25) {
7968 tabLabel = tabLabel.substring(0, 25) + "...";
7970 tabObject.get("labelEl").firstChild.data = tabLabel;
7976 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
7977 if (a.parent_name != null && a.parent_name != "") {
7978 document.getElementById('data_parent_name' + idx).value = a.parent_name;
7980 if (a.parent_type != null && a.parent_type != "") {
7981 document.getElementById('data_parent_type' + idx).value = a.parent_type;
7983 if (a.parent_id != null && a.parent_id != "") {
7984 document.getElementById('data_parent_id' + idx).value = a.parent_id;
7986 if (a.fromAccounts.status) {
7987 var addressFrom = document.getElementById('addressFrom' + idx);
7988 SUGAR.email2.util.emptySelectOptions(addressFrom);
7989 var fromAccountOpts = a.fromAccounts.data;
7990 for(i=0; i<fromAccountOpts.length; i++) {
7991 var key = fromAccountOpts[i].value;
7992 var display = fromAccountOpts[i].text;
7993 var opt = new Option(display, key);
7994 if (fromAccountOpts[i].selected) {
7995 opt.selected = true;
7997 addressFrom.options.add(opt);
8003 failure : AjaxObject.handleFailure,
8004 timeout : AjaxObject.timeout,
8006 argument : [sendType]
8008 var callbackSendEmail = {
8009 success : AjaxObject.sendEmailCleanUp,
8010 failure : AjaxObject.handleFailure,
8011 timeout : AjaxObject.timeout,
8014 var callbackSettings = {
8015 success : AjaxObject.updateUserPrefs,
8016 failure : AjaxObject.handleFailure,
8017 timeout : AjaxObject.timeout,
8020 var callbackSettingsFolderRefresh = {
8021 success : AjaxObject.settingsFolderRefresh,
8022 failure : AjaxObject.handleFailure,
8023 timeout : AjaxObject.timeout,
8026 var callbackLoadSettingFolder = {
8027 success : function(o) {
8028 AjaxObject.settingsFolderRefresh(o);
8029 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8031 failure : AjaxObject.handleFailure,
8032 timeout : AjaxObject.timeout,
8036 var callbackUploadAttachment = {
8037 success : AjaxObject.uploadAttachmentSuccessful,
8038 upload : AjaxObject.uploadAttachmentSuccessful,
8039 failure : AjaxObject.handleFailure,
8040 timeout : AjaxObject.timeout,
8043 var callbackUserPrefs = {
8044 success : function(o) {
8045 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8047 failure : AjaxObject.handleFailure,
8048 timeout : AjaxObject.timeout,
8052 var callbackContextmenus = {
8054 success : AjaxObject.markEmailCleanup,
8055 failure : AjaxObject.handleFailure,
8056 timeout : AjaxObject.timeout,
8061 var callbackCheckEmail2 = {
8062 success : function(o) {
8063 var ret = JSON.parse(o.responseText);
8064 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8068 failure : AjaxObject.handleFailure,
8069 timeout : AjaxObject.timeout,
8071 }// End of File modules/Emails/javascript/ajax.js
8073 /*********************************************************************************
8074 * SugarCRM is a customer relationship management program developed by
8075 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8077 * This program is free software; you can redistribute it and/or modify it under
8078 * the terms of the GNU Affero General Public License version 3 as published by the
8079 * Free Software Foundation with the addition of the following permission added
8080 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8081 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8082 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8084 * This program is distributed in the hope that it will be useful, but WITHOUT
8085 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8086 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8089 * You should have received a copy of the GNU Affero General Public License along with
8090 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8091 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8094 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8095 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8097 * The interactive user interfaces in modified source and object code versions
8098 * of this program must display Appropriate Legal Notices, as required under
8099 * Section 5 of the GNU Affero General Public License version 3.
8101 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8102 * these Appropriate Legal Notices must retain the display of the "Powered by
8103 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8104 * technical reasons, the Appropriate Legal Notices must display the words
8105 * "Powered by SugarCRM".
8106 ********************************************************************************/
8108 function gridInit() {
8109 if(SUGAR.email2.grid) {
8110 SUGAR.email2.grid.destroy();
8116 var Ck = YAHOO.util.Cookie;
8117 var widths = [ 10, 10, 150, 250, 175, 125 ];
8119 if (Ck.get("EmailGridWidths")) {
8120 for (var i=0; i < widths.length; i++) {
8121 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8124 for (var i=0; i < widths.length; i++) {
8125 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8129 // changes "F" to an icon
8130 function flaggedIcon(cell, record, column, value) {
8132 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8135 // changes "A" to replied icon
8136 function repliedIcon(cell, record, column, value) {
8138 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8141 function attachIcon(cell, record, column, value) {
8143 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8150 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8155 formatter: attachIcon,
8159 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8164 formatter: flaggedIcon,
8168 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8173 formatter: repliedIcon,
8177 label: app_strings.LBL_EMAIL_FROM,
8184 label: app_strings.LBL_EMAIL_SUBJECT,
8191 label: mod_strings.LBL_LIST_DATE,
8198 label: app_strings.LBL_EMAIL_TO,
8234 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8235 responseType: YAHOO.util.DataSource.TYPE_JSON,
8237 resultsList: 'Email',
8238 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8239 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8245 action : "EmailUIAjax",
8246 emailUIAction : "getMessageList",
8249 forceRefresh : "false"
8251 if(lazyLoadFolder != null) {
8252 params['mbox'] = lazyLoadFolder.folder;
8253 params['ieId'] = lazyLoadFolder.ieId;
8254 //Check if the folder is a Sugar Folder
8255 var test = new String(lazyLoadFolder.folder);
8256 if(test.match(/SUGAR\./)) {
8257 params['emailUIAction'] = 'getMessageListSugarFolders';
8258 params['mbox'] = test.substr(6);
8261 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8264 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8265 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8267 paginator: new YAHOO.widget.Paginator({
8268 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8269 containers : ["dt-pag-nav"],
8270 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8271 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8272 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8273 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8274 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8276 initialRequest:SUGAR.util.paramsToUrl(params),
8283 //Override Paging request construction
8284 grid.set("generateRequest", function(oState, oSelf) {
8285 oState = oState || {pagination:null, sortedBy:null};
8286 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8287 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8288 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8289 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8290 // Build the request
8292 SUGAR.util.paramsToUrl(oSelf.params) +
8295 "&start=" + startIndex +
8296 ((results !== null) ? "&limit=" + results : "");
8301 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8302 oPayload = oPayload || { };
8304 oPayload.totalRecords = oResponse.meta.total;
8305 oPayload.unreadRecords = oResponse.meta.unread;
8307 var tabObject = SE.innerLayout.get("tabs")[0];
8309 if (this.params.mbox != null) {
8310 mboxTitle = this.params.mbox;
8312 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8313 tabObject.get("labelEl").firstChild.data = tabtext;
8316 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8318 node.data.unseen = oResponse.meta.unread;
8319 SE.accounts.renderTree();
8325 var resize = grid.resizeGrid = function () {
8326 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8327 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8329 grid.convertDDRows = function() {
8330 var rowEl = this.getFirstTrEl();
8331 while (rowEl != null) {
8332 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8333 rowEl = this.getNextTrEl(rowEl);
8338 grid.on("columnResizeEvent", function(o) {
8339 //Find the index of the column
8340 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8341 for (var i=0; i < colSet.length; i++) {
8342 if (o.column == colSet[i]) {
8343 //Store it in the cookie
8344 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8347 //this.resizeGrid();
8350 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8351 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8352 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8354 SUGAR.email2.listViewLayout.on("render", resize);
8357 //Setup the default load parameters
8358 SUGAR.email2.grid.params = params;
8360 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8361 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8362 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8369 function initRowDD() {
8370 var sg = SUGAR.email2.grid,
8371 Dom = YAHOO.util.Dom;
8372 sg.DDRow = function(oDataTable, oRecord, elTr) {
8373 if(oDataTable && oRecord && elTr) {
8374 this.ddtable = oDataTable;
8375 this.table = oDataTable.getTableEl();
8378 this.newIndex = null;
8380 this.initFrame(); // Needed for DDProxy
8381 this.invalidHandleTypes = {};
8385 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8386 _resizeProxy: function() {
8387 this.constructor.superclass._resizeProxy.apply(this, arguments);
8388 var dragEl = this.getDragEl(),
8390 var xy = Dom.getXY(el);
8392 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8393 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8394 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8395 Dom.setStyle(dragEl, 'display', "");
8398 startDrag: function(x, y) {
8399 //Check if we should be dragging a set of rows rather than just the one.
8400 var selectedRows = this.ddtable.getSelectedRows();
8401 var iSelected = false;
8402 for (var i in selectedRows) {
8403 if (this.rowEl.id == selectedRows[i]) {
8410 for (var i in selectedRows) {
8411 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8414 this.rows = [this.row];
8415 this.ddtable.unselectAllRows();
8416 this.ddtable.selectRow(this.row);
8419 //Initialize the dragable proxy
8420 var dragEl = this.getDragEl();
8421 var clickEl = this.getEl();
8422 Dom.setStyle(clickEl, "opacity", "0.25");
8423 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8424 Dom.addClass(dragEl, "yui-dt-liner");
8425 Dom.setStyle(dragEl, "opacity", "0.5");
8426 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8427 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8428 Dom.setStyle(dragEl, "border", "2px solid gray");
8431 clickValidator: function(e) {
8432 if (this.row.getData()[0] == " ")
8434 var target = YAHOO.util.Event.getTarget(e);
8435 return ( this.isValidHandleChild(target) &&
8436 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8439 * This funciton checks that the target of the drag is a table row in this
8440 * DDGroup and simply moves the sourceEL to that location as a preview.
8442 onDragOver: function(ev, id) {
8443 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8444 if (node && node != this.targetNode) {
8445 this.targetNode = node;
8446 SUGAR.email2.folders.unhighliteAll();
8451 onDragOut: function(e, id) {
8452 if (this.targetNode) {
8453 SUGAR.email2.folders.unhighliteAll();
8454 this.targetNode = false;
8457 endDrag: function() {
8458 Dom.setStyle(this.getEl(), "opacity", "");
8459 Dom.setStyle(this.getDragEl(), "display", "none");
8460 if (this.targetNode) {
8461 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8463 SUGAR.email2.folders.unhighliteAll();
8469 function AddressSearchGridInit() {
8470 function moduleIcon(elCell, oRecord, oColumn, oData) {
8471 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8473 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8474 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8476 var checkHeader = '<input type="checkbox" ';
8477 if (SUGAR.email2.util.isIe()) {
8478 checkHeader += 'style="top:-5px" ';
8480 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8485 formatter: selectionCheckBox,
8489 label: mod_strings.LBL_LIST_TYPE,
8491 formatter: moduleIcon,
8495 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8501 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8507 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8508 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8510 resultsList: 'Person',
8511 fields: ['name', 'email', 'bean_id', 'bean_module'],
8512 metaFields: {total: 'TotalCount'}
8514 //enable sorting on the server accross all data
8517 dataModel.params = {
8520 action : "EmailUIAjax",
8521 emailUIAction:"getAddressSearchResults"
8523 var rb = document.getElementById('hasRelatedBean').checked;
8525 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8526 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8527 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8528 dataModel.params['related_bean_id'] = relatedBeanId;
8529 dataModel.params['related_bean_type'] = relatedBeanType;
8530 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8532 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8534 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8535 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8537 paginator: new YAHOO.widget.Paginator({
8539 containers : ["dt-pag-nav-addressbook"],
8540 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8541 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8542 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8543 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8544 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8546 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8550 //Override Paging request construction
8551 grid.set("generateRequest", function(oState, oSelf) {
8552 oState = oState || {pagination:null, sortedBy:null};
8553 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8554 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8555 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8556 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8557 // Build the request
8559 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8560 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8561 ((results !== null) ? "&limit=" + results : "");
8565 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8566 oPayload = oPayload || { };
8567 oPayload.totalRecords = oResponse.meta.total;
8571 grid.clickToggleSelect= function(args) {
8572 var isIE = (args.event.target == null);
8573 var targetElement = isIE ? args.event.srcElement : args.event.target;
8574 if(targetElement.type == null || targetElement.type != 'checkbox') {
8575 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8579 grid.reSelectRowsOnRender = function (){
8580 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8581 for (var i = 0; i < rows.length; i++)
8583 var emailAddress = rows[i].getData("email");
8584 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8587 rows[i].setData("selected", true);
8588 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8592 rows[i].setData("selected", false);
8593 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8597 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8598 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8599 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8600 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8603 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8604 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8606 grid.toggleSelectCheckbox = function(id,checked){
8607 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8608 row.setData("checked",checked);
8610 grid.toggleSelect = function(id, checked) {
8611 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8612 checked = row.getData("selected");
8615 SUGAR.email2.addressBook.grid.selectRow(row);
8616 SE.addressBook.insertContactRowToResultTable(id,null)
8619 SUGAR.email2.addressBook.grid.unselectRow(row);
8620 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8622 row.setData("selected", !checked);
8625 grid.toggleSelectAll = function(checked) {
8626 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8627 for (var i = 0; i < rows.length; i++) {
8628 if (typeof(rows[i]) != "undefined")
8629 rows[i].setData("checked", checked);
8631 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8632 for (var i = 0; i < checkBoxes.length; i++) {
8633 checkBoxes[i].checked = checked;
8637 //Initialize the grid result table.
8638 AddressSearchResultsGridInit();
8644 * Initalize the results table for the address book selection.
8647 function AddressSearchResultsGridInit()
8650 /* Full name sort funciton to compare by last name if available */
8651 var fullNameSort = function(a, b, desc) {
8652 // Deal with empty values
8653 if(!YAHOO.lang.isValue(a))
8654 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8655 else if(!YAHOO.lang.isValue(b))
8658 var aNames = a.getData("name").split(' ');
8659 var bNames = b.getData("name").split(' ');
8661 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8662 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8664 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8668 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8669 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8670 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8672 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})},
8673 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8675 var myDataSource = new YAHOO.util.DataSource([]);
8676 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8677 myDataSource.responseSchema = {
8678 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8681 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8682 width: "350px",height: "250px", MSG_EMPTY: " "});
8684 var highlightEditableCell = function(oArgs) {
8685 var elCell = oArgs.target;
8686 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8687 this.highlightCell(elCell);
8691 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8692 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8693 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8694 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8695 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8697 //Setup the context menus
8698 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8699 var task = p_aArgs[1];
8702 var elRow = this.contextEventTarget;
8703 elRow = p_myDataTable.getTrEl(elRow);
8710 var oRecord = p_myDataTable.getRecord(elRow);
8711 p_myDataTable.deleteRow(elRow);
8712 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8717 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8718 {trigger:gridResults.getTbodyEl()});
8719 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8720 contextMenu.render("addrSearchResultGrid");
8721 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8723 // End of File modules/Emails/javascript/grid.js
8725 /*********************************************************************************
8726 * SugarCRM is a customer relationship management program developed by
8727 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8729 * This program is free software; you can redistribute it and/or modify it under
8730 * the terms of the GNU Affero General Public License version 3 as published by the
8731 * Free Software Foundation with the addition of the following permission added
8732 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8733 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8734 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8736 * This program is distributed in the hope that it will be useful, but WITHOUT
8737 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8738 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8741 * You should have received a copy of the GNU Affero General Public License along with
8742 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8743 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8746 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8747 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8749 * The interactive user interfaces in modified source and object code versions
8750 * of this program must display Appropriate Legal Notices, as required under
8751 * Section 5 of the GNU Affero General Public License version 3.
8753 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8754 * these Appropriate Legal Notices must retain the display of the "Powered by
8755 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8756 * technical reasons, the Appropriate Legal Notices must display the words
8757 * "Powered by SugarCRM".
8758 ********************************************************************************/
8763 function complexLayoutInit() {
8764 var se = SUGAR.email2;
8765 var Dom = YAHOO.util.Dom;
8767 getInnerLayout : function(rows) {
8768 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8769 parent: se.complexLayout,
8775 scroll:false, // grid should autoScroll itself
8777 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8785 body: "<div id='listBottom' />"
8793 body: "<div id='listRight' />",
8794 titlebar: false //,header: "right"
8797 se.complexLayout.on("render", function(){
8798 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8799 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8800 SUGAR.email2.listViewLayout.set("height", height);
8801 SUGAR.email2.listViewLayout.render();
8803 se.listViewLayout.render();
8805 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8806 var rp = se.listViewLayout.resizePreview = function() {
8807 var pre = Dom.get("displayEmailFramePreview");
8809 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8810 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8813 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8814 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8815 se.e2Layout.setPreviewPanel(rows);
8816 se.previewLayout = se.listViewLayout;
8817 return se.listViewLayout;
8820 getInnerLayout2Rows : function() {
8821 return this.getInnerLayout(true);
8823 getInnerLayout2Columns : function() {
8824 return this.getInnerLayout(false);
8828 // initialize state manager, we will use cookies
8829 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8830 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8831 se.complexLayout = new YAHOO.widget.Layout("container", {
8834 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8835 width: Dom.getViewportWidth() - 40,
8839 body: "<div id='emailtabs'></div>"
8844 body: "<div id='lefttabs'></div>",
8854 header: Dom.get('footerLinks').innerHTML,
8861 se.complexLayout.render();
8862 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8863 tp.addTab(new YAHOO.widget.Tab({
8866 content : "<div id='listViewDiv'/>",
8870 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8871 tp.appendTo(centerEl);
8873 tp.get("element").style.borderRight = "1px solid #666"
8875 var listV = this.getInnerLayout2Rows();
8876 listV.set("height", tp.get("element").clientHeight - 25);
8879 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8880 var folderTab = new YAHOO.widget.Tab({
8881 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8883 content : "<div id='emailtree'/>",
8887 folderTab.on("activeChange", function(o){
8889 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8892 se.leftTabs.addTab(folderTab);
8894 var tabContent = SUGAR.util.getAndRemove("searchTab");
8895 var searchTab = new YAHOO.widget.Tab({
8896 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8898 content : tabContent.innerHTML,
8901 searchTab.on("activeChange", function(o){
8904 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8905 //Setup the calendars if needed
8906 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_from", singleClick : true, step : 1, weekNumbers:false});
8907 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_to", singleClick : true, step : 1, weekNumbers:false});
8909 //Initalize sqs object for assigned user name
8910 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
8912 //Attach event handler for when the relate module option is selected for the correct sqs object
8913 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8914 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8915 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
8916 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8918 //If enter key is pressed, perform search
8919 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8920 for(var i=0; i < addKeyPressFields.length;i++)
8922 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8923 if (e.keyCode == 13) {
8924 YAHOO.util.Event.stopEvent(e);
8925 SUGAR.email2.search.searchAdvanced();
8929 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
8931 //Clear parent values if selecting another parent type.
8932 YAHOO.util.Event.addListener('data_parent_type_search','change',
8934 document.getElementById('data_parent_id_search').value ='';
8935 document.getElementById('data_parent_name_search').value ='';
8940 se.leftTabs.addTab(searchTab);
8942 var resizeTabBody = function() {
8943 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8944 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8947 se.complexLayout.on("render", resizeTabBody);
8948 se.leftTabs.on("activeTabChange", resizeTabBody);
8949 //hack to allow left pane scroll bar to fully show
8950 var lefttabsDiv = document.getElementById('lefttabs');
8951 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8952 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8953 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8956 initSQSObject: function(formName,fieldName)
8958 var fullFieldName = formName + '_' + fieldName; //SQS Convention
8959 var resultName = fullFieldName + '_' + 'results';
8961 if (QSFieldsArray[fullFieldName] != null)
8963 QSFieldsArray[fullFieldName].destroy();
8964 delete QSFieldsArray[fullFieldName];
8966 if (QSProcessedFieldsArray[fullFieldName])
8967 QSProcessedFieldsArray[fullFieldName] = false;
8969 if( Dom.get(resultName) )
8971 var obj = document.getElementById(resultName);
8972 obj.parentNode.removeChild(obj);
8975 setPreviewPanel: function(rows) {
8977 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
8978 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
8979 Dom.get("listRight").innerHTML = "";
8980 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
8982 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
8983 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
8984 Dom.get("listBottom").innerHTML = "";
8985 Dom.get("listRight").innerHTML = "<div id='_blank' />";
8992 var myBufferedListenerObject = new Object();
8993 myBufferedListenerObject.refit = function() {
8994 if(SUGAR.email2.grid) {
8995 SUGAR.email2.grid.autoSize();
8998 // End of File modules/Emails/javascript/complexLayout.js
9000 /*********************************************************************************
9001 * SugarCRM is a customer relationship management program developed by
9002 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9004 * This program is free software; you can redistribute it and/or modify it under
9005 * the terms of the GNU Affero General Public License version 3 as published by the
9006 * Free Software Foundation with the addition of the following permission added
9007 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9008 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9009 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9011 * This program is distributed in the hope that it will be useful, but WITHOUT
9012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9013 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9016 * You should have received a copy of the GNU Affero General Public License along with
9017 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9018 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9021 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9022 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9024 * The interactive user interfaces in modified source and object code versions
9025 * of this program must display Appropriate Legal Notices, as required under
9026 * Section 5 of the GNU Affero General Public License version 3.
9028 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9029 * these Appropriate Legal Notices must retain the display of the "Powered by
9030 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9031 * technical reasons, the Appropriate Legal Notices must display the words
9032 * "Powered by SugarCRM".
9033 ********************************************************************************/
9036 /******************************************************************************
9037 * Initialize Email 2.0 Application
9040 //Override Sugar Languge so quick creates work properly
9043 function email2init() {
9046 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9047 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9048 if (!SUGAR.util.isTouchScreen()) {
9050 convert_urls : false,
9051 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9052 width: tinyConfig.width,
9053 theme: tinyConfig.theme,
9054 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9055 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9056 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9057 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9058 plugins : tinyConfig.plugins,
9059 elements : tinyConfig.elements,
9060 language : tinyConfig.language,
9061 extended_valid_elements : tinyConfig.extended_valid_elements,
9062 mode: tinyConfig.mode,
9063 strict_loading_mode : true,
9064 force_br_newlines : true,
9065 forced_root_block : ''
9068 //alert('loadedTiny');
9070 // initialze message overlay
9071 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9081 if (SUGAR.themes.tempHideLeftCol)
9082 SUGAR.themes.tempHideLeftCol();
9084 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9085 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9087 // set defaults for YAHOO.util.DragDropManager
9088 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9090 SUGAR.email2.nextYear = new Date();
9091 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9094 // initialize and display UI framework (complexLayout.js)
9095 complexLayoutInit();
9097 // initialize and display grid (grid.js)
9100 // initialize treeview for folders
9102 SUGAR.email2.folders.rebuildFolders(true);
9105 //Setup the Message Box overlay
9106 /*Ext.MessageBox.maxWidth = 350;
9107 Ext.MessageBox.minProgressWidth = 350;
9109 ///////////////////////////////////////////////////////////////////////////
9112 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9114 var SEC = SUGAR.email2.contextMenus;
9117 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9118 trigger: SUGAR.email2.grid.get("element"),
9121 emailMenu.subscribe("beforeShow", function() {
9122 var oTarget = this.contextEventTarget;
9123 if (typeof(oTarget) == "undefined")
9125 var grid = SUGAR.email2.grid;
9126 var selectedRows = grid.getSelectedRows();
9127 var multipleSelected = (selectedRows.length > 1) ? true: false;
9128 if (!multipleSelected)
9130 grid.unselectAllRows();
9131 grid.selectRow(oTarget);
9132 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9134 else if(multipleSelected)
9136 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9140 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9141 //us to access individual elements easier by name rather than by index
9142 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
9143 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9144 emailMenu.addItems([
9146 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9147 id: 'showDetailView',
9148 onclick: { fn: SEC.showDetailView }
9151 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9152 onclick: { fn: SEC.openMultiple }
9155 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9156 onclick: { fn: SEC.archiveToSugar }
9159 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9161 onclick: { fn: SEC.replyForwardEmailContext }
9164 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9166 onclick: { fn: SEC.replyForwardEmailContext }
9169 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9171 onclick: { fn: SEC.replyForwardEmailContext }
9174 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9176 onclick: { fn: SEC.markDeleted }
9179 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9181 onclick: { fn: SEC.viewPrintable }
9185 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9187 id: "markEmailMenu",
9190 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9191 onclick: { fn: SEC.markUnread }
9194 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9195 onclick: { fn: SEC.markRead }
9198 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9199 onclick: { fn: SEC.markFlagged }
9202 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9203 onclick: { fn: SEC.markUnflagged }
9209 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9211 onclick: { fn: SEC.assignEmailsTo }
9214 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9216 onclick: { fn: SEC.relateTo }
9219 SEC.emailListContextMenu.render();
9221 //Handle the Tree folder menu trigger ourselves
9222 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9226 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9230 SEC.frameFoldersContextMenu.addItems([
9231 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9232 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9233 onclick: { fn: function() {
9234 var node = SUGAR.email2.clickedFolderNode;
9235 if (node.data.ieId) {
9236 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9239 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9240 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9241 onclick: { fn: function() {
9242 var node = SUGAR.email2.clickedFolderNode;
9243 if (node.data.ieId) {
9244 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9248 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9249 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9250 onclick: { fn: SUGAR.email2.folders.folderAdd }
9253 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9254 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9255 onclick: { fn: SUGAR.email2.folders.folderDelete }
9258 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9259 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9260 onclick: { fn: SUGAR.email2.folders.folderRename }
9263 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9264 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9265 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9268 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9269 onclick: { fn: function() {
9270 var node = SUGAR.email2.clickedFolderNode;
9271 if (node.data.ieId) {
9272 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9276 SEC.frameFoldersContextMenu.render();
9278 SEC.initContactsMenu = function() {
9280 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9281 trigger: "contacts",
9284 SEC.contactsContextMenu.addItems([
9286 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9287 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9290 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9291 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9294 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9295 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9296 if (oTarget && !grid.isSelected(oTarget)) {
9297 grid.unselectAllRows();
9298 grid.selectRow(oTarget);
9301 SEC.contactsContextMenu.render();
9305 // set auto-check timer
9306 SUGAR.email2.folders.startCheckTimer();
9307 // check if we're coming from an email-link click
9308 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9310 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9312 //Init fix for YUI 2.7.0 datatable sort.
9313 SUGAR.email2.addressBook.initFixForDatatableSort();
9316 function createTreePanel(treeData, params) {
9317 var tree = new YAHOO.widget.TreeView(params.id);
9318 var root = tree.getRoot();
9320 //if (treeData.nodes && treeData[0].id == "Home")
9321 // treeData = treeData[0];
9323 addChildNodes(root, treeData);
9328 function addChildNodes(parentNode, parentData) {
9329 var Ck = YAHOO.util.Cookie;
9330 var nextyear = SUGAR.email2.nextYear;
9331 var nodes = parentData.nodes || parentData.children;
9333 if (typeof(nodes[i]) == 'object') {
9334 if (nodes[i].data) {
9335 nodes[i].data.href = '#';
9336 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9337 node.action = nodes[i].data.action;
9339 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9340 addChildNodes(parentNode, nodes[i]);
9343 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9344 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9346 nodes[i].className = nodes[i].cls;
9348 nodes[i].href = "#";
9349 if (nodes[i].text) nodes[i].label = nodes[i].text;
9350 //Override YUI child node creation
9351 if (nodes[i].children) {
9352 nodes[i].nodes = nodes[i].children;
9353 nodes[i].children = [ ];
9355 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9358 if (typeof(nodes[i].nodes) == 'object') {
9359 addChildNodes(node, nodes[i]);
9366 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9368 function email2treeinit(tree, treedata, treediv, params) {
9369 //ensure the tree data is not corrupt
9373 if (SUGAR.email2.tree) {
9374 SUGAR.email2.tree.destroy();
9375 SUGAR.email2.tree = null;
9378 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9382 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9383 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9384 tree.subscribe("expandComplete", function(node){
9385 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9386 for (var i in node.children) {
9387 SE.accounts.setupDDTarget(node.children[i]);
9390 tree.setCollapseAnim("TVSlideOut");
9391 tree.setExpandAnim("TVSlideIn");
9392 var root = tree.root;
9393 while (root.hasChildren()) {
9394 var node = root.children[0];
9396 tree.removeNode(root.children[0], false);
9398 addChildNodes(root, treedata);
9400 SUGAR.email2.accounts.renderTree();
9403 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9404 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9408 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9409 startDrag: function(x, y) {
9410 var Dom = YAHOO.util.Dom;
9411 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9414 var dragEl = this.getDragEl();
9415 var clickEl = this.getEl();
9416 Dom.setStyle(clickEl, "color", "#AAA");
9417 Dom.setStyle(clickEl, "opacity", "0.25");
9418 dragEl.innerHTML = clickEl.innerHTML;
9420 Dom.addClass(dragEl, "ygtvcell");
9421 Dom.addClass(dragEl, "ygtvcontent");
9422 Dom.addClass(dragEl, "folderDragProxy");
9423 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9424 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9425 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9426 Dom.setStyle(dragEl, "opacity", "0.5");
9427 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9430 onDragOver: function(ev, id) {
9431 var Dom = YAHOO.util.Dom;
9432 if (id != this.dragId)
9434 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9435 if(node.data.cls != "sugarFolder") {
9436 SUGAR.email2.folders.unhighliteAll();
9440 this.targetNode = node;
9441 SUGAR.email2.folders.unhighliteAll();
9446 onDragOut: function(e, id) {
9447 if (this.targetNode) {
9448 SUGAR.email2.folders.unhighliteAll();
9449 this.targetNode = false;
9450 this.dragId = false;
9454 endDrag: function() {
9455 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9456 if (this.targetNode) {
9457 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9460 });// End of File modules/Emails/javascript/init.js
9462 /*********************************************************************************
9463 * SugarCRM is a customer relationship management program developed by
9464 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9466 * This program is free software; you can redistribute it and/or modify it under
9467 * the terms of the GNU Affero General Public License version 3 as published by the
9468 * Free Software Foundation with the addition of the following permission added
9469 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9470 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9471 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9473 * This program is distributed in the hope that it will be useful, but WITHOUT
9474 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9475 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9478 * You should have received a copy of the GNU Affero General Public License along with
9479 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9480 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9483 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9484 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9486 * The interactive user interfaces in modified source and object code versions
9487 * of this program must display Appropriate Legal Notices, as required under
9488 * Section 5 of the GNU Affero General Public License version 3.
9490 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9491 * these Appropriate Legal Notices must retain the display of the "Powered by
9492 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9493 * technical reasons, the Appropriate Legal Notices must display the words
9494 * "Powered by SugarCRM".
9495 ********************************************************************************/
9497 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9498 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9499 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9500 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9501 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9502 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9503 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9504 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9505 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9506 ' <input type="hidden" id="composeType" name="composeType">' +
9507 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9508 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9509 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9510 ' <input type="hidden" id="sendTo" name="sendTo">' +
9511 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9512 ' <input type="hidden" id="sendCc" name="sendCc">' +
9513 ' <input type="hidden" id="setEditor" name="setEditor">' +
9514 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9515 ' <input type="hidden" id="parent_id" name="parent_id">' +
9516 ' <input type="hidden" id="parent_type" name="parent_type">' +
9517 ' <input type="hidden" id="attachments" name="attachments">' +
9518 ' <input type="hidden" id="documents" name="documents">' +
9519 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9520 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9521 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9522 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9524 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9525 ' <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>' +
9526 ' <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>' +
9527 ' <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>' +
9528 ' <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>' +
9529 '</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>' +
9530 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9531 '<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>' +
9532 ' </td></tr></tbody></table></th>' +
9536 ' <div style="margin:5px;">' +
9537 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9539 ' <td class="emailUILabel" NOWRAP >' +
9540 ' {app_strings.LBL_EMAIL_FROM}:' +
9542 ' <td class="emailUIField" NOWRAP>' +
9544 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9549 ' <td class="emailUILabel" NOWRAP>' +
9550 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9551 ' {app_strings.LBL_EMAIL_TO}:' +
9554 ' <td class="emailUIField" NOWRAP>' +
9555 ' <div class="ac_autocomplete">' +
9556 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9557 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9558 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9562 ' <tr id="add_addr_options_tr{idx}">' +
9563 ' <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>'+
9565 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9566 ' <td class="emailUILabel" NOWRAP>' +
9567 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9568 ' {app_strings.LBL_EMAIL_CC}:' +
9571 ' <td class="emailUIField" NOWRAP>' +
9572 ' <div class="ac_autocomplete">' +
9573 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9574 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9575 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9579 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9580 ' <td class="emailUILabel" NOWRAP>' +
9581 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9582 ' {app_strings.LBL_EMAIL_BCC}:' +
9585 ' <td class="emailUIField" NOWRAP>' +
9586 ' <div class="ac_autocomplete">' +
9587 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9588 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9589 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9594 ' <td class="emailUILabel" NOWRAP width="1%">' +
9595 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9597 ' <td class="emailUIField" NOWRAP width="99%">' +
9598 ' <div class="ac_autocomplete">' +
9599 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9608 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9609 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9610 ' <div style="padding:5px;">' +
9611 ' <table cellpadding="2" cellspacing="0" border="0">' +
9614 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9621 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9622 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9634 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9641 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9642 ' <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>' +
9654 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9661 ' <div id="addedTemplateAttachments{idx}"></div>' +
9668 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9669 ' <div style="padding:5px;">' +
9670 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9671 ' <table border="0" width="100%">' +
9673 ' <td NOWRAP style="padding:2px;">' +
9674 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9678 ' <td NOWRAP style="padding:2px;">' +
9679 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9684 ' <table border="0" width="100%">' +
9686 ' <td NOWRAP style="padding:2px;">' +
9687 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9691 ' <td NOWRAP style="padding:2px;">' +
9692 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9696 ' <table border="0" width="100%">' +
9698 ' <td NOWRAP style="padding:2px;">' +
9699 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9700 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9708 // End of File modules/Emails/javascript/composeEmailTemplate.js
9710 /*********************************************************************************
9711 * SugarCRM is a customer relationship management program developed by
9712 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9714 * This program is free software; you can redistribute it and/or modify it under
9715 * the terms of the GNU Affero General Public License version 3 as published by the
9716 * Free Software Foundation with the addition of the following permission added
9717 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9718 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9719 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9721 * This program is distributed in the hope that it will be useful, but WITHOUT
9722 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9723 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9726 * You should have received a copy of the GNU Affero General Public License along with
9727 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9728 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9731 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9732 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9734 * The interactive user interfaces in modified source and object code versions
9735 * of this program must display Appropriate Legal Notices, as required under
9736 * Section 5 of the GNU Affero General Public License version 3.
9738 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9739 * these Appropriate Legal Notices must retain the display of the "Powered by
9740 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9741 * technical reasons, the Appropriate Legal Notices must display the words
9742 * "Powered by SugarCRM".
9743 ********************************************************************************/
9745 SUGAR.email2.templates['displayOneEmail'] =
9746 '<div class="emailDetailTable" style="height:100%">' +
9747 '<div id="viewMenuDiv{idx}"></div>' +
9748 '<div width="100%" class="displayEmailValue">' +
9749 ' <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>' +
9750 ' <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>' +
9751 ' <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>' +
9752 ' <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>' +
9753 ' <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>' +
9754 ' <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>' +
9755 ' <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>' +
9756 ' <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>' +
9757 ' <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>' +
9759 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9761 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9762 ' {app_strings.LBL_EMAIL_FROM}:' +
9764 ' <td width="99%" class="displayEmailValue">' +
9765 ' {email.from_addr}' +
9769 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9770 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9772 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9773 ' <b>{email.name}</b>' +
9777 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9778 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9780 ' <td class="displayEmailValue">' +
9781 ' {email.date_start} {email.time_start}' +
9785 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9786 ' {app_strings.LBL_EMAIL_TO}:' +
9788 ' <td class="displayEmailValue">' +
9789 ' {email.toaddrs}' +
9792 ' <tr>{meta.cc}</tr>' +
9793 ' <tr>{email.attachments}</tr>' +
9795 ' <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>' +
9796 //' {email.description}' +
9798 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9800 /*********************************************************************************
9801 * SugarCRM is a customer relationship management program developed by
9802 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9804 * This program is free software; you can redistribute it and/or modify it under
9805 * the terms of the GNU Affero General Public License version 3 as published by the
9806 * Free Software Foundation with the addition of the following permission added
9807 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9808 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9809 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9811 * This program is distributed in the hope that it will be useful, but WITHOUT
9812 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9813 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9816 * You should have received a copy of the GNU Affero General Public License along with
9817 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9818 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9821 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9822 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9824 * The interactive user interfaces in modified source and object code versions
9825 * of this program must display Appropriate Legal Notices, as required under
9826 * Section 5 of the GNU Affero General Public License version 3.
9828 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9829 * these Appropriate Legal Notices must retain the display of the "Powered by
9830 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9831 * technical reasons, the Appropriate Legal Notices must display the words
9832 * "Powered by SugarCRM".
9833 ********************************************************************************/
9835 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9836 '<body onload="javascript:window.print();">' +
9840 ' font-family: helvetica, impact, sans-serif;' +
9841 ' font-size : 12pt;' +
9848 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9851 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9853 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9854 ' {app_strings.LBL_EMAIL_FROM}:' +
9856 ' <td width="99%" class="displayEmailValue">' +
9857 ' {email.from_name} <{email.from_addr}>' +
9861 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9862 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9864 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9865 ' <b>{email.name}</b>' +
9869 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9870 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9872 ' <td class="displayEmailValue">' +
9873 ' {email.date_start} {email.time_start}' +
9877 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9878 ' {app_strings.LBL_EMAIL_TO}:' +
9880 ' <td class="displayEmailValue">' +
9881 ' {email.toaddrs}' +
9885 ' {email.attachments}' +
9891 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9893 ' <td style="border-top: 1px solid #333;">' +
9894 ' <div style="padding:5px;">' +
9895 '{email.description}' +
9905 // End of File modules/Emails/javascript/viewPrintable.js
9907 /*********************************************************************************
9908 * SugarCRM is a customer relationship management program developed by
9909 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9911 * This program is free software; you can redistribute it and/or modify it under
9912 * the terms of the GNU Affero General Public License version 3 as published by the
9913 * Free Software Foundation with the addition of the following permission added
9914 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9915 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9916 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9918 * This program is distributed in the hope that it will be useful, but WITHOUT
9919 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9920 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9923 * You should have received a copy of the GNU Affero General Public License along with
9924 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9925 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9928 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9929 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9931 * The interactive user interfaces in modified source and object code versions
9932 * of this program must display Appropriate Legal Notices, as required under
9933 * Section 5 of the GNU Affero General Public License version 3.
9935 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9936 * these Appropriate Legal Notices must retain the display of the "Powered by
9937 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9938 * technical reasons, the Appropriate Legal Notices must display the words
9939 * "Powered by SugarCRM".
9940 ********************************************************************************/
9941 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9942 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;}
9943 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');}
9944 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;}}
9945 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9946 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9947 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}
9948 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="";}}
9949 this.oldValue="";}});if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9950 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];}}}
9951 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]];}
9952 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
9953 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9954 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js