2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
5 * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6 * dragged element is inserted before the dragged-over element.
8 * @extends YAHOO.util.DDProxy
10 * @param {String} id the id of the linked element
11 * @param {String} sGroup the group of related DragDrop objects
13 function ygDDList(id, sGroup) {
16 this.init(id, sGroup);
18 //this.logger = new ygLogger("ygDDList");
21 var s = this.getDragEl().style;
22 s.borderColor = "transparent";
23 s.backgroundColor = "#f6f5e5";
25 s.filter = "alpha(opacity=76)";
28 ygDDList.prototype = new YAHOO.util.DDProxy();
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
33 ygDDList.prototype.startDrag = function(x, y) {
34 //this.logger.debug(this.id + " startDrag");
36 var dragEl = this.getDragEl();
37 var clickEl = this.getEl();
39 dragEl.innerHTML = clickEl.innerHTML;
40 dragElObjects = dragEl.getElementsByTagName('object');
43 dragEl.className = clickEl.className;
44 dragEl.style.color = clickEl.style.color;
45 dragEl.style.border = "1px solid #aaa";
47 // save the style of the object
48 clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
50 this.borderDiv = document.createElement('div'); // create a div to display border
51 this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52 this.borderDiv.style.border = '2px dashed #cccccc';
54 for(i in clickEl.childNodes) { // hide contents of the target elements contents
55 if(typeof clickEl.childNodes[i].style != 'undefined') {
56 this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57 clickEl.childNodes[i].style.display = 'none';
61 clickEl.appendChild(this.borderDiv);
64 ygDDList.prototype.endDrag = function(e) {
65 // disable moving the linked element
66 var clickEl = this.getEl();
68 clickEl.removeChild(this.borderDiv); // remove border div
70 for(i in clickEl.childNodes) { // show target elements contents
71 if(typeof clickEl.childNodes[i].style != 'undefined') {
72 clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
77 clickEl.style.height = this.clickHeight;
79 clickEl.style.height = '';
82 clickEl.style.border = this.clickBorder;
84 clickEl.style.border = '';
86 dragEl = this.getDragEl();
87 dragEl.innerHTML = '';
92 ygDDList.prototype.afterEndDrag = function(e) {
96 ygDDList.prototype.onDrag = function(e, id) {
100 ygDDList.prototype.onDragOver = function(e, id) {
101 // this.logger.debug(this.id.toString() + " onDragOver " + id);
104 if ("string" == typeof id) {
105 el = YAHOO.util.DDM.getElement(id);
107 el = YAHOO.util.DDM.getBestMatch(id).getEl();
110 dragEl = this.getDragEl();
111 elRegion = YAHOO.util.Dom.getRegion(el);
113 // this.logger.debug('id: ' + el.id);
114 // this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 // this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116 var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 // this.logger.debug('mid: ' + mid);
119 // this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " < " + mid);
120 // this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
122 if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123 var el2 = this.getEl();
124 var p = el.parentNode;
125 p.insertBefore(el2, el);
127 if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128 var el2 = this.getEl();
129 var p = el.parentNode;
130 p.insertBefore(el2, el.nextSibling);
134 ygDDList.prototype.onDragEnter = function(e, id) {
135 // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136 // this.getDragEl().style.border = "1px solid #449629";
139 ygDDList.prototype.onDragOut = function(e, id) {
140 // I need to know when we are over nothing
141 // this.getDragEl().style.border = "1px solid #964428";
144 /////////////////////////////////////////////////////////////////////////////
146 function ygDDListBoundary(id, sGroup) {
148 this.init(id, sGroup);
149 //this.logger = new ygLogger("ygDDListBoundary");
150 this.isBoundary = true;
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
157 /*********************************************************************************
158 * SugarCRM Community Edition is a customer relationship management program developed by
159 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
161 * This program is free software; you can redistribute it and/or modify it under
162 * the terms of the GNU Affero General Public License version 3 as published by the
163 * Free Software Foundation with the addition of the following permission added
164 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
168 * This program is distributed in the hope that it will be useful, but WITHOUT
169 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
173 * You should have received a copy of the GNU Affero General Public License along with
174 * this program; if not, see http://www.gnu.org/licenses or write to the Free
175 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
178 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
181 * The interactive user interfaces in modified source and object code versions
182 * of this program must display Appropriate Legal Notices, as required under
183 * Section 5 of the GNU Affero General Public License version 3.
185 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186 * these Appropriate Legal Notices must retain the display of the "Powered by
187 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188 * technical reasons, the Appropriate Legal Notices must display the words
189 * "Powered by SugarCRM".
190 ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span> </span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&themeName=Sugar&imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace(''',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&!(/_email_widget_add/.test(elm.id.toLowerCase()))&&/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(YAHOO.env.ua.ie){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)};if(YAHOO.env.ua.ie){var emailcontainer=Dom.getAncestorByTagName(insertInto,'span');var listeners=YAHOO.util.Event.getListeners(emailcontainer);if(typeof listeners!='undefined'&&listeners instanceof Array){for(var i=0;i<listeners.length;++i){var listener=listeners[i];YAHOO.util.Event.addListener(newContent,listener.type,listener.fn,listener.obj,listener.adjust);}}}
216 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));}
217 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
218 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
219 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));}}
220 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
221 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
222 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
223 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
224 if(YAHOO.env.ua.ie){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;}}
225 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
226 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();
227 // End of File include/SugarEmailAddress/SugarEmailAddress.js
229 /*********************************************************************************
230 * SugarCRM Community Edition is a customer relationship management program developed by
231 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
233 * This program is free software; you can redistribute it and/or modify it under
234 * the terms of the GNU Affero General Public License version 3 as published by the
235 * Free Software Foundation with the addition of the following permission added
236 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
237 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
238 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
240 * This program is distributed in the hope that it will be useful, but WITHOUT
241 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
242 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
245 * You should have received a copy of the GNU Affero General Public License along with
246 * this program; if not, see http://www.gnu.org/licenses or write to the Free
247 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
250 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
251 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
253 * The interactive user interfaces in modified source and object code versions
254 * of this program must display Appropriate Legal Notices, as required under
255 * Section 5 of the GNU Affero General Public License version 3.
257 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
258 * these Appropriate Legal Notices must retain the display of the "Powered by
259 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
260 * technical reasons, the Appropriate Legal Notices must display the words
261 * "Powered by SugarCRM".
262 ********************************************************************************/
263 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)
264 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_","_")]);}
265 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
266 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;}
267 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();}
268 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';}
269 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='';}
270 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();',100);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',100);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
271 this.js_more();this.js_more();}
272 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
273 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
274 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);}}}
275 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
276 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';}
277 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);}}
278 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);}}}
279 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++;}}}
280 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
281 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='';}}
283 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;}
285 if(!has_primary){return false;}
287 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);}}}
288 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;}}}}
289 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;}
290 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();}}}}
291 if(noAdd){enableQS(false);}
292 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);}}}
294 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
295 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=='';}
297 SUGAR.collection.safe_clone=function(e,recursive)
298 {if(e.nodeName=="#text")
299 {return document.createTextNode(e.data);}
300 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];if(SUGAR.isIE7&&e.tagName.toLowerCase()=='input')
301 {var properties=['class','style','name','type','valign','border','width','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}else{var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}
302 for(var i in properties)
303 {if(e[properties[i]])
304 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
305 newNode[properties[i]]=e[properties[i]];}}
307 {for(var i in e.childNodes)
308 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
309 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
311 // End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
313 /*********************************************************************************
314 * SugarCRM Community Edition is a customer relationship management program developed by
315 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
317 * This program is free software; you can redistribute it and/or modify it under
318 * the terms of the GNU Affero General Public License version 3 as published by the
319 * Free Software Foundation with the addition of the following permission added
320 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
321 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
322 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
324 * This program is distributed in the hope that it will be useful, but WITHOUT
325 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
326 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
329 * You should have received a copy of the GNU Affero General Public License along with
330 * this program; if not, see http://www.gnu.org/licenses or write to the Free
331 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
334 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
335 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
337 * The interactive user interfaces in modified source and object code versions
338 * of this program must display Appropriate Legal Notices, as required under
339 * Section 5 of the GNU Affero General Public License version 3.
341 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
342 * these Appropriate Legal Notices must retain the display of the "Powered by
343 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
344 * technical reasons, the Appropriate Legal Notices must display the words
345 * "Powered by SugarCRM".
346 ********************************************************************************/
347 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);}
348 return s;},init:function(){if(Rot13.map!=null)
349 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
350 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
351 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
352 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='';}
353 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='';}
354 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='';}}
356 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName,ie_id)
357 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
358 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id:'';URL='index.php?'
359 +'module='+module_name
362 +'&target='+pageTarget
363 +'&target1='+pageTarget
364 +'&server_url='+mail_server
365 +'&email_user='+words[0]
366 +'&protocol='+protocol
368 +'&email_password='+words[1]
369 +'&mailbox='+words[2]
372 +'&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)
373 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
374 this.body.style.width=w}}
375 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
376 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();}
377 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'));}
378 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
379 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
380 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
381 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
382 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";}
384 alert(out);return false;}else{return true;}}
385 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?'
386 +'module='+module_name
389 +'&target='+pageTarget
390 +'&target1='+pageTarget
391 +'&server_url='+mail_server
392 +'&email_user='+words[0]
393 +'&protocol='+protocol
395 +'&email_password='+words[1]
396 +'&mailbox='+words[2]
398 +'&personal='+isPersonal
399 +'&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)
400 this.body.style.width=w}}
401 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();}
402 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;}}}
403 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';}}}
404 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='';}
405 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";}}
406 // End of File modules/InboundEmail/InboundEmail.js
408 /*********************************************************************************
409 * SugarCRM Community Edition is a customer relationship management program developed by
410 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
412 * This program is free software; you can redistribute it and/or modify it under
413 * the terms of the GNU Affero General Public License version 3 as published by the
414 * Free Software Foundation with the addition of the following permission added
415 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
416 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
417 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
419 * This program is distributed in the hope that it will be useful, but WITHOUT
420 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
421 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
424 * You should have received a copy of the GNU Affero General Public License along with
425 * this program; if not, see http://www.gnu.org/licenses or write to the Free
426 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
429 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
430 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
432 * The interactive user interfaces in modified source and object code versions
433 * of this program must display Appropriate Legal Notices, as required under
434 * Section 5 of the GNU Affero General Public License version 3.
436 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
437 * these Appropriate Legal Notices must retain the display of the "Powered by
438 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
439 * technical reasons, the Appropriate Legal Notices must display the words
440 * "Powered by SugarCRM".
441 ********************************************************************************/
444 cache : new Object(),
445 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
446 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
449 currentHtmleditor : ''
453 * preserves hits from email server
455 _setDetailCache : function(ret) {
457 var compKey = ret.meta.mbox + ret.meta.uid;
459 if(!SUGAR.email2.cache[compKey]) {
460 SUGAR.email2.cache[compKey] = ret;
465 autoSetLayout : function() {
466 var c = document.getElementById('container');
467 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
468 //Ensure a minimum height.
469 tHeight = Math.max(tHeight, 550);
470 c.style.height = tHeight + "px";
471 SUGAR.email2.complexLayout.set('height', tHeight);
472 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
473 SUGAR.email2.complexLayout.render();
474 SUGAR.email2.listViewLayout.resizePreview();
479 * Shows overlay progress message
481 function overlayModal(title, body) {
482 overlay(title, body);
484 function overlay(reqtitle, body, type, additconfig) {
486 if (typeof(additconfig) == "object") {
487 var config = additconfig;
490 config.title = reqtitle;
492 YAHOO.SUGAR.MessageBox.show(config);
495 function hideOverlay() {
496 YAHOO.SUGAR.MessageBox.hide();
498 // End of File modules/Emails/javascript/EmailUIShared.js
500 /*********************************************************************************
501 * SugarCRM Community Edition is a customer relationship management program developed by
502 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
504 * This program is free software; you can redistribute it and/or modify it under
505 * the terms of the GNU Affero General Public License version 3 as published by the
506 * Free Software Foundation with the addition of the following permission added
507 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
508 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
509 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
511 * This program is distributed in the hope that it will be useful, but WITHOUT
512 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
513 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
516 * You should have received a copy of the GNU Affero General Public License along with
517 * this program; if not, see http://www.gnu.org/licenses or write to the Free
518 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
521 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
522 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
524 * The interactive user interfaces in modified source and object code versions
525 * of this program must display Appropriate Legal Notices, as required under
526 * Section 5 of the GNU Affero General Public License version 3.
528 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
529 * these Appropriate Legal Notices must retain the display of the "Powered by
530 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
531 * technical reasons, the Appropriate Legal Notices must display the words
532 * "Powered by SugarCRM".
533 ********************************************************************************/
537 var sw = YAHOO.SUGAR,
538 Event = YAHOO.util.Event,
539 Connect = YAHOO.util.Connect,
543 ///////////////////////////////////////////////////////////////////////////////
546 outboundDialog : null,
547 inboundAccountEditDialog : null,
548 inboundAccountsSettingsTable : null,
549 outboundAccountsSettingsTable : null,
550 testOutboundDialog : null,
551 errorStyle : 'input-error',
553 newAddedOutboundId : '',
556 * makes async call to retrieve an outbound instance for editting
559 editOutbound : function(obi) {
561 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
564 deleteOutbound : function(obi) {
566 if(obi.match(/^(add|line|sendmail)+/)) {
567 alert('Invalid Operation');
569 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
570 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
574 getReplyAddress : function() {
577 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
578 var addy = SE.userPrefs.current_user.emailAddresses[i];
580 if(addy.primary_address == "1") {
581 primary = addy.email_address;
584 if(addy.reply_to == "1") {
585 return addy.email_address;
593 * Called on "Accounts" tab activation event
595 lazyLoad : function() {
597 this._setupInboundAccountTable();
598 this._setupOutboundAccountTable();
602 _setupInboundAccountTable: function()
604 //Setup the inbound mail settings
605 if(!this.inboundAccountsSettingsTable)
607 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
608 var clckEvent = oColumn.key;
610 var is_group = oRecord.getData("is_group");
613 if(oColumn.key == 'edit')
615 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
616 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
618 else if(oColumn.key == 'delete')
620 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
621 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
623 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
627 this.showBoolean = function(el, oRecord, oColumn, oData)
629 var is_group = oRecord.getData("is_group");
630 var bChecked = oData;
631 bChecked = (bChecked) ? " checked" : "";
634 el.innerHTML = "<input type=\"radio\"" + bChecked +
635 " name=\"col" + oColumn.getId() + "-radio\"" +
636 " class=\"yui-dt-radio\">";
641 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
642 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
644 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
645 '<img border="0" src="themes/default/images/helpInline.gif">' +
646 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
649 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
650 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
651 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
652 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
653 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
654 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
655 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
656 this.ieDataSource = new YAHOO.util.DataSource(query);
657 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
658 this.ieDataSource.responseSchema = {
659 resultsList: "account_list",
660 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
662 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
663 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
665 var elCheckbox = oArgs.target;
666 var oColumn = this.getColumn(elCheckbox);
667 if(oColumn.key == 'is_active')
669 var oRecord = this.getRecord(elCheckbox);
670 oRecord.setData("is_active",elCheckbox.checked);
671 var t_id = oRecord.getData('id');
672 var isGroupFolder = oRecord.getData('has_groupfolder');
675 SUGAR.email2.folders.updateSubscriptions();
677 SUGAR.email2.folders.setFolderSelection();
681 var lastDefaultSelectedId = "";
682 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
684 var elRadio = oArgs.target;
685 var oColumn = this.getColumn(elRadio);
686 if(oColumn.key == 'is_default')
688 var oRecord = this.getRecord(elRadio);
689 var t_id = oRecord.getData('id');
690 var t_isGroup = oRecord.getData('is_group');
691 if(t_id != lastDefaultSelectedId && !t_isGroup)
693 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
694 lastDefaultSelectedId = t_id;
695 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
698 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
703 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
704 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
707 _setupOutboundAccountTable: function()
709 if(!this.outboundAccountsSettingsTable)
711 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
712 var clckEvent = oColumn.key;
714 var isEditable = oRecord.getData("is_editable");
715 var type = oRecord.getData("type");
718 if(oColumn.key == 'edit')
720 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
721 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
723 else if(oColumn.key == 'delete' && type == 'user')
725 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
726 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
729 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
733 //Custom formatter to display any error messages.
734 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
736 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
737 SUGAR.email2.composeLayout.outboundAccountErrors = {};
739 var id = oRecord.getData('id');
740 var message = oRecord.getData("errors");
743 elLiner.innerHTML = '<span class="required">' + message + '</span>';
744 //Add the id and message for all outbound accounts.
745 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
749 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
750 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
753 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
754 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
756 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
757 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
758 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
759 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
761 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
762 this.obDataSource = new YAHOO.util.DataSource(query);
763 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
764 this.obDataSource.responseSchema = {
766 resultsList: "outbound_account_list",
767 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
770 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
773 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
774 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
775 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
779 * Displays a modal diaglogue to edit outbound account settings
781 showEditInboundAccountDialogue : function(clear) {
783 if(!this.inboundAccountEditDialog) {
784 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
788 constraintoviewport: true,
792 EAD.showEvent.subscribe(function() {
793 var el = this.element;
794 var viewH = YAHOO.util.Dom.getViewportHeight();
795 if (this.header && el && viewH - 50 < el.clientHeight) {
796 var body = this.header.nextElementSibling;
797 body.style.overflow = "hidden";
798 body.style.height = "100%";
801 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
802 Dom.removeClass("editAccountDialogue", "yui-hidden");
806 if(clear == undefined || clear == true)
808 SE.accounts.clearInboundAccountEditScreen();
809 //Set default protocol to IMAP when creating new records
810 document.forms['ieAccount'].elements['protocol'].value = "imap";
811 SE.accounts.setPortDefault();
814 //Check if we should display username/password fields for outbound account if errors were detected.
815 this.checkOutBoundSelection();
817 this.inboundAccountEditDialog.render();
818 this.inboundAccountEditDialog.show();
819 SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
823 * Set all fields on the outbound edit form to either enabled/disabled
824 * except for the username/password.
827 toggleOutboundAccountDisabledFields: function(disable)
829 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
830 for(var i=0;i<fields.length;i++)
832 document.getElementById(fields[i]).disabled = disable;
835 Dom.addClass("mail_smtpssl_row", "yui-hidden");
837 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
841 * Refresh the inbound accounts table.
843 refreshInboundAccountTable : function()
845 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
847 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
848 scope: this.inboundAccountsSettingsTable }
852 * Refresh the outbound accounts table.
854 refreshOuboundAccountTable : function()
856 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
858 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
859 scope: this.outboundAccountsSettingsTable }
863 * Displays a modal diaglogue to add a SMTP server
865 showAddSmtp : function() {
866 // lazy load dialogue
867 if(!this.outboundDialog) {
868 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
872 constraintoviewport: true,
876 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
877 this.outboundDialog.hideEvent.subscribe(function(){
878 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
879 var out = Dom.get("outbound_email");
880 if (out && out.value == "SYSTEM_ADD")
882 out.value = out.options[0].value;
884 //Check if we should display username/password for system account.
885 SE.accounts.checkOutBoundSelection();
889 Dom.removeClass("outboundDialog", "yui-hidden");
893 var form = document.getElementById('outboundEmailForm');
894 for(i=0; i<form.elements.length; i++) {
895 if(form.elements[i].name == 'mail_smtpport') {
896 form.elements[i].value = 25;
897 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
898 form.elements[i].value = '';
899 } else if(form.elements[i].type == 'checkbox') {
900 form.elements[i].checked = false;
903 //Render the SMTP buttons
904 if ( !SUGAR.smtpButtonGroup ) {
905 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
906 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
908 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
909 document.getElementById('smtp_settings').style.display = '';
910 form.mail_smtptype.value = e.newValue.get('value');
912 YAHOO.widget.Button.addHiddenFieldsToForm(form);
914 //Hide Username/Password
915 SUGAR.email2.accounts.smtp_authenticate_field_display();
916 //Unset readonly fields
917 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
918 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
919 this.outboundDialog.render();
920 this.outboundDialog.show();
924 * Accounts' Advanced Settings view toggle
926 toggleAdv : function() {
927 var adv = document.getElementById("ie_adv");
928 if(adv.style.display == 'none') {
929 adv.style.display = "";
931 adv.style.display = 'none';
935 smtp_authenticate_field_display : function() {
936 var smtpauth_req = document.getElementById("mail_smtpauth_req");
937 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
938 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
941 smtp_setDefaultSMTPPort : function() {
942 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
944 if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
945 document.getElementById("mail_smtpport").value = '465';
947 if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
948 document.getElementById("mail_smtpport").value = '25';
953 * Changes the display used in the outbound email SMTP dialog to match the
955 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
957 document.getElementById("smtpButtonGroupTD").style.display = '';
958 document.getElementById("chooseEmailProviderTD").style.display = '';
959 document.getElementById("mailsettings1").style.display = '';
960 document.getElementById("mailsettings2").style.display = '';
961 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
962 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
963 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
964 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
968 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
969 document.getElementById("mail_smtpport").value = '465';
970 document.getElementById("mail_smtpauth_req").checked = true;
971 var ssl = document.getElementById("mail_smtpssl");
972 for(var j=0;j<ssl.options.length;j++) {
973 if(ssl.options[j].text == 'SSL') {
974 ssl.options[j].selected = true;
978 document.getElementById("mailsettings1").style.display = 'none';
979 document.getElementById("mailsettings2").style.display = 'none';
980 document.getElementById("mail_smtppass_label").innerHTML =
981 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
982 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
985 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
986 document.getElementById("mail_smtpport").value = '587';
987 document.getElementById("mail_smtpauth_req").checked = true;
988 var ssl = document.getElementById("mail_smtpssl");
989 for(var j=0;j<ssl.options.length;j++) {
990 if(ssl.options[j].text == 'TLS') {
991 ssl.options[j].selected = true;
995 document.getElementById("mailsettings1").style.display = 'none';
996 document.getElementById("mailsettings2").style.display = 'none';
997 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
998 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
1001 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
1002 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
1003 document.getElementById("mail_smtpserver").value = '';
1005 document.getElementById("mail_smtpport").value = '25';
1006 document.getElementById("mail_smtpauth_req").checked = true;
1007 document.getElementById("mailsettings1").style.display = '';
1008 document.getElementById("mailsettings2").style.display = '';
1009 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1010 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1011 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1012 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1015 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1017 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1018 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1019 document.getElementById("mailsettings2").style.display = 'none';
1022 SUGAR.email2.accounts.smtp_authenticate_field_display();
1023 SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1027 * Fill the gmail default values for inbound accounts.
1029 fillInboundGmailDefaults: function () {
1031 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1032 document.forms['ieAccount'].elements['ssl'].checked = true;
1033 document.forms['ieAccount'].elements['protocol'].value = "imap";
1034 SUGAR.email2.accounts.setPortDefault();
1035 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1038 * Sets Port field to selected protocol and SSL settings defaults
1040 setPortDefault : function() {
1041 var prot = document.getElementById('protocol');
1042 var ssl = document.getElementById('ssl');
1043 var port = document.getElementById('port');
1044 var stdPorts= new Array("110", "143", "993", "995");
1045 var stdBool = new Boolean(false);
1046 var mailboxdiv = document.getElementById("mailboxdiv");
1047 var trashFolderdiv = document.getElementById("trashFolderdiv");
1048 var sentFolderdiv = document.getElementById("sentFolderdiv");
1049 var monitoredFolder = document.getElementById("subscribeFolderButton");
1050 if(port.value == '') {
1051 stdBool.value = true;
1053 for(i=0; i<stdPorts.length; i++) {
1054 if(stdPorts[i] == port.value) {
1055 stdBool.value = true;
1060 if(stdBool.value == true) {
1061 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1063 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1065 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1067 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1072 if (prot.value == 'imap') {
1073 mailboxdiv.style.display = "";
1074 trashFolderdiv.style.display = "";
1075 sentFolderdiv.style.display = "";
1076 monitoredFolder.style.display = "";
1077 if (document.getElementById('mailbox').value == "") {
1078 document.getElementById('mailbox').value = "INBOX";
1081 mailboxdiv.style.display = "none";
1082 trashFolderdiv.style.display = "none";
1083 sentFolderdiv.style.display = "none";
1084 monitoredFolder.style.display = "none";
1085 document.getElementById('mailbox').value = "";
1090 * Draws/removes red boxes around required fields.
1092 ieAccountError : function(style) {
1093 document.getElementById('server_url').className = style;
1094 document.getElementById('email_user').className = style;
1095 document.getElementById('email_password').className = style;
1096 document.getElementById('protocol').className = style;
1097 document.getElementById('port').className = style;
1100 checkOutBoundSelection: function() {
1101 var select = Dom.get('outbound_email');
1102 if (!select || select.selectedIndex == -1) { return; }
1104 var v = select.options[select.selectedIndex].value;
1108 select.options[select.selectedIndex].selected = false;
1109 v = select.options[0].value;
1111 else if (v == 'SYSTEM_ADD')
1112 SUGAR.email2.accounts.showAddSmtp();
1114 var foundError = false;
1115 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1116 for(i in errorAccounts)
1125 //Should username/password fields for outbound account.
1127 this.toggleInboundOutboundFields(true);
1129 this.toggleInboundOutboundFields(false);
1134 toggleInboundOutboundFields : function (display)
1138 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1139 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1143 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1144 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1148 * rebuilds the select options for mailer options
1150 rebuildMailerOptions : function() {
1151 var select = document.forms['ieAccount'].elements['outbound_email'];
1152 SE.util.emptySelectOptions(select);
1154 //Get the available sugar mailers
1155 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1157 for(i=0;i<a_outbound.length;i++)
1159 var t_record = a_outbound[i];
1160 var key = t_record.getData('id');
1161 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1163 var opt = new Option(display, key);
1164 select.options.add(opt);
1165 if (key == SE.accounts.newAddedOutboundId) {
1166 select.options.selectedIndex = i;
1170 select.options.add(new Option('',''));
1171 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1172 //Hide/Show username password fields if necessary.
1173 SE.accounts.checkOutBoundSelection();
1176 * Empties all the fields in the accounts edit view
1178 clearInboundAccountEditScreen:function() {
1180 document.getElementById('ie_id').value = '';
1181 document.getElementById('ie_name').value = '';
1182 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1183 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1184 document.getElementById('reply_to_addr').value = '';
1185 document.getElementById('server_url').value = '';
1186 document.getElementById('email_user').value = '';
1187 document.getElementById('email_password').value = '';
1188 document.getElementById('port').value = '';
1189 document.getElementById('inbound_mail_smtpuser').value = '';
1190 document.getElementById('inbound_mail_smtppass').value = '';
1191 document.ieAccount.protocol.options[0].selected = true;
1193 document.getElementById('ssl').checked = false;
1194 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1198 * Populates an account's fields in Settings->Accounts
1200 fillIeAccount:function(jsonstr) {
1201 var o = YAHOO.lang.JSON.parse(jsonstr);
1203 document.getElementById('ie_id').value = o.id;
1204 document.getElementById('ie_name').value = o.name;
1205 if (o.stored_options != null) {
1206 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1207 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1208 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1209 if (o.stored_options.trashFolder != null) {
1210 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1212 if (o.stored_options.sentFolder != null) {
1213 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1216 document.getElementById('server_url').value = o.server_url;
1217 document.getElementById('email_user').value = o.email_user;
1218 document.getElementById('port').value = o.port;
1219 document.getElementById('group_id').value = o.group_id;
1220 document.getElementById('mailbox').value = o.mailbox;
1226 if(typeof(o.service[2]) != 'undefined') {
1227 document.getElementById('ssl').checked = true;
1231 if(document.getElementById('protocol').value != o.protocol) {
1232 var prot = document.getElementById('protocol');
1233 for(i=0; i<prot.options.length; i++) {
1234 if(prot.options[i].value == o.service[3]) {
1235 prot.options[i].selected = true;
1236 this.setPortDefault();
1240 // handle SMTP selection
1241 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1242 var opts = document.getElementById('outbound_email').options;
1243 for(i=0; i<opts.length; i++) {
1244 if(opts[i].value == o.stored_options.outbound_email) {
1245 opts[i].selected = true;
1251 deleteIeAccount : function(IeAccountID,IeGroupID) {
1252 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1254 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1256 AjaxObject.target = 'frameFlex';
1257 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1258 SUGAR.email2.accounts.refreshInboundAccountTable();
1262 // Null check for Outbound Settings.
1263 checkOutboundSettings: function() {
1264 var errorMessage = '';
1265 var isError = false;
1266 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1267 var mailName = document.getElementById('mail_name').value;
1268 var smtpServer = document.getElementById('mail_smtpserver').value;
1269 var smtpPort = document.getElementById('mail_smtpport').value;
1271 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1272 if(trim(mailName) == '') {
1274 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1276 if(trim(smtpServer) == '') {
1278 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1280 if(trim(smtpPort) == '') {
1282 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1284 if(mailsmtpauthreq.checked) {
1285 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1287 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1292 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1299 testOutboundSettings: function() {
1300 var errorMessage = '';
1301 var isError = false;
1302 var fromAddress = document.getElementById("outboundtest_from_address").value;
1303 if (trim(fromAddress) == "") {
1304 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1305 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1309 else if (!isValidEmail(fromAddress)) {
1310 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1311 overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1315 //Hide the dialogue and show an in progress indicator.
1316 SE.accounts.testOutboundDialog.hide();
1317 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1319 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1320 //nothing is sent in the request.
1321 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1322 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1324 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1325 if(outboundType == 'system-override')
1326 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1328 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1329 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1333 testOutboundSettingsDialog: function() {
1334 //Ensure that all settings are correct before proceeding to send test email.
1335 if(!SE.accounts.checkOutboundSettings())
1338 // lazy load dialogue
1339 if(!SE.accounts.testOutboundDialog) {
1340 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1344 constraintoviewport: true,
1348 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1349 Dom.removeClass("testOutboundDialog", "yui-hidden");
1351 SE.accounts.testOutboundDialog.render();
1352 SE.accounts.testOutboundDialog.show();
1356 * Saves Outbound email settings
1358 saveOutboundSettings : function() {
1359 if(SE.accounts.checkOutboundSettings()) {
1360 //Enable the form fields for the post.
1361 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1362 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1363 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1369 saveIeAccount : function() {
1371 //Before saving check if there are any error messages associated with the outbound account.
1372 var outboundID = document.getElementById('outbound_email').value;
1374 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1375 'validateSMTPCreds':true}) )
1377 document.getElementById('saveButton').disabled = true;
1379 overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1381 var formObject = document.getElementById('ieAccount');
1382 YAHOO.util.Connect.setForm(formObject);
1384 AjaxObject._reset();
1385 AjaxObject.target = 'frameFlex';
1386 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1390 testSettings : function() {
1391 form = document.getElementById('ieAccount');
1393 if(SE.accounts.checkIeCreds()) {
1394 ie_test_open_popup_with_submit("InboundEmail", "Popup", "Popup", 400, 300, trim(form.server_url.value), form.protocol.value, trim(form.port.value), trim(form.email_user.value), Rot13.write(form.email_password.value), trim(form.mailbox.value), form.ssl.checked, true, "ieAccount", form.ie_id.value);
1398 getFoldersListForInboundAccountForEmail2 : function() {
1399 form = document.getElementById('ieAccount');
1400 if(SE.accounts.checkIeCreds()) {
1401 var mailBoxValue = form.mailbox.value;
1402 if (form.searchField.value.length > 0) {
1405 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 );
1410 checkIeCreds : function(validateRules) {
1411 if(typeof(validateRules) == 'undefined')
1414 var errors = new Array();
1415 var out = new String();
1417 var ie_name = Dom.get('ie_name').value;
1418 var fromAddress = Dom.get('ie_from_addr').value;
1419 var server_url = Dom.get('server_url').value;
1420 var email_user = Dom.get('email_user').value;
1421 var email_password = Dom.get('email_password').value;
1422 var protocol = Dom.get('protocol').value;
1423 var port = Dom.get('port').value;
1424 var oe = Dom.get('outbound_email');
1426 // Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
1427 // other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
1428 // return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
1429 var oe_value = (typeof(oe.options[oe.selectedIndex]) === 'undefined' || typeof(oe.options[oe.selectedIndex]) === 'unknown' || typeof(oe.options[oe.selectedIndex]) === null) ? "" : oe.options[oe.selectedIndex].value;
1431 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1432 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1434 //If the username and password were provided then ignore the error messge
1436 var outboundCredentialsFound = false;
1438 if(outboundUserName != "" && outboundPass != "")
1439 outboundCredentialsFound = true;
1441 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1443 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1444 && validateSMTPCreds)
1446 if(trim(outboundUserName) == "") {
1447 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1449 if(trim(outboundPass) == "") {
1450 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1454 if(trim(ie_name) == "") {
1455 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1458 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1460 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1461 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1466 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1467 || trim(oe_value) == "SYSTEM_ADD") ) {
1468 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1470 if(trim(server_url) == "") {
1471 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1473 if(trim(email_user) == "") {
1474 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1476 if(protocol == "") {
1477 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1479 if (protocol == 'imap') {
1480 var mailbox = document.getElementById('mailbox').value;
1481 if (trim(mailbox) == "") {
1482 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1484 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1485 var trashFolder = document.getElementById('trashFolder').value;
1486 if (trim(trashFolder) == "") {
1487 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1492 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1495 if(errors.length > 0) {
1496 out = app_strings.LBL_EMAIL_ERROR_DESC;
1497 for(i=0; i<errors.length; i++) {
1512 getIeAccount : function(ieId) {
1516 overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1517 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1519 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1523 * Iterates through TreeView nodes to apply styles dependent nature of node
1525 renderTree:function() {
1526 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1530 //Sets the style for any nodes that need it.
1531 setNodeStyle : function(node) {
1532 if (!node.data.origText) {
1533 node.data.origText = node.data.text;
1536 if (typeof(node.data.unseen) != 'undefined') {
1537 if (node.data.unseen > 0) {
1538 node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
1539 // Add bold style to label, kinda hacky
1540 node.labelStyle += " ygtvlabelbold";
1543 node.setUpLabel(node.data.origText);
1546 node.setUpLabel(node.data.origText);
1548 SE.accounts.setupDDTarget(node);
1551 setupDDTarget : function(node) {
1552 if (node.ddTarget) {
1553 node.ddTarget.removeFromGroup();
1554 delete node.ddTarget;
1556 var id = node.getElId();
1557 var num = id.substring(4);
1558 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1559 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1560 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1562 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1564 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1565 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1570 * Async call to rebuild the folder list. After a folder delete or account delete
1572 rebuildFolderList : function() {
1573 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1574 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1578 * Returns the number of remote accounts the user has active.
1580 getAccountCount : function() {
1583 for(i=0; i<tree._nodes.length; i++) {
1584 var node = tree._nodes[i];
1586 if(typeof(node) != 'undefined' && node.data.ieId) {
1594 ///////////////////////////////////////////////////////////////////////////////
1599 ///////////////////////////////////////////////////////////////////////////////
1600 //// CONTEXT MENU CALLS
1603 assignToDialogue : null,
1605 * Archives from context menu
1607 * @param string ieId
1608 * @param string folder
1610 _archiveToSugar : function(uids, ieId, folder) {
1613 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1614 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1617 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1621 * Archives from context menu
1623 archiveToSugar : function(menuItem) {
1624 SE.contextMenus.emailListContextMenu.hide();
1626 var rows = SE.grid.getSelectedRows();
1628 /* iterate through available rows JIC a row is deleted - use first available */
1629 for(var i=0; i<rows.length; i++) {
1630 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1632 var data = SE.grid.getRecord(rows[0]).getData();
1633 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1637 * Popup the printable version and start system's print function.
1639 viewPrintable : function(menuItem) {
1640 var rows = SE.grid.getSelectedRows();
1641 var data = SE.grid.getRecord(rows[0]).getData();
1642 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1646 * Marks email flagged on mail server
1648 markRead : function(type, contextMenuId) {
1649 SE.contextMenus.markEmail('read');
1653 * Assign this emails to people based on assignment rules
1655 assignEmailsTo : function(type, contextMenuId) {
1656 if(!SE.contextMenus.assignToDialogue)
1658 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1662 constraintoviewport: true,
1666 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1670 Dom.removeClass("assignToDiv", "yui-hidden");
1671 SE.contextMenus.assignToDialogue.render();
1672 SE.contextMenus.assignToDialogue.show();
1676 * Marks email flagged on mail server
1678 markFlagged : function(contextMenuId) {
1679 SE.contextMenus.markEmail('flagged');
1683 * Marks email unflagged on mail server
1685 markUnflagged : function(contextMenuId) {
1686 SE.contextMenus.markEmail('unflagged');
1690 * Marks email unread on mail server
1692 markUnread : function() {
1693 SE.contextMenus.markEmail('unread');
1697 * Deletes an email from context menu
1699 markDeleted : function() {
1700 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1701 document.getElementById('_blank').innerHTML = "";
1702 SE.contextMenus.markEmail('deleted');
1707 * generic call API to apply a flag to emails on the server and on sugar
1708 * @param string type "read" | "unread" | "flagged" | "deleted"
1710 markEmail : function(type) {
1711 SE.contextMenus.emailListContextMenu.hide();
1713 //var dm = SE.grid.getStore();
1714 //var uids = SE.grid.getSelectedRowIds();
1715 //var indexes = SE.grid.getSelectedRowIndexes();
1716 var rows = SE.grid.getSelectedRows();
1717 if (rows.length == 0)
1718 rows = [SE.contextMenus.currentRow];
1721 for(var i=0; i<rows.length; i++) {
1722 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1725 ser = YAHOO.lang.JSON.stringify(ser);
1727 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1728 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1734 if(type == 'read' || type == 'deleted') {
1736 for(var j=0; j<rows.length; j++) {
1737 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1739 SE.grid.getRecord(rows[j]).setData("seen", "1");
1742 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1744 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1745 var unseenCount = node.data.unseen;
1746 if (isNaN(unseenCount)) {
1749 var finalCount = parseInt(unseenCount) - count;
1750 node.data.unseen = finalCount;
1752 SE.accounts.renderTree();
1754 } else if(type == 'unread') {
1756 for(var j=0; j<rows.length; j++) {
1757 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1762 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1763 var unseenCount = node.data.unseen;
1764 if (isNaN(unseenCount)) {
1767 var finalCount = parseInt(unseenCount) + count;
1768 node.data.unseen = finalCount;
1769 SE.accounts.renderTree();
1772 if (type == 'unread') {
1773 for(var i=0; i<rows.length; i++) {
1774 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1778 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1779 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1783 * refreshes the ListView to show changes to cache
1785 markEmailCleanup : function() {
1786 SE.accounts.renderTree();
1788 SE.listView.refreshGrid();
1791 showAssignmentDialog : function() {
1792 if (SE.contextMenus.assignmentDialog == null) {
1793 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1795 SE.contextMenus.assignmentDialog.show();
1800 * shows the import dialog with only relate visible.
1802 relateTo : function() {
1803 SE.contextMenus.emailListContextMenu.hide();
1805 var rows = SE.grid.getSelectedRows();
1806 var data = SE.grid.getRecord(rows[0]).getData();
1807 var ieId = data.ieId;
1808 var folder = data.mbox;
1810 /* iterate through available rows JIC a row is deleted - use first available */
1811 for(var i=0; i<rows.length; i++) {
1812 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1814 var ser = YAHOO.lang.JSON.stringify(uids);
1816 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1820 * shows the import dialog with only relate visible.
1822 showDetailView : function() {
1823 SE.contextMenus.emailListContextMenu.hide();
1824 var rows = SE.grid.getSelectedRows();
1825 if (rows.length > 1) {
1826 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1829 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1830 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1831 /* iterate through available rows JIC a row is deleted - use first available */
1832 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1833 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1839 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1840 overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1841 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1845 * Opens multiple messages from ListView context click
1847 openMultiple : function() {
1848 SE.contextMenus.emailListContextMenu.hide();
1850 var rows = SE.grid.getSelectedRows();
1851 var uids = SE.listView.getUidsFromSelection();
1853 if(uids.length > 0) {
1854 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1855 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1856 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1861 * Replies/forwards email
1863 replyForwardEmailContext : function() {
1864 SE.contextMenus.emailListContextMenu.hide();
1866 var indexes = SE.grid.getSelectedRows();
1867 //var dm = SE.grid.getDataModel();
1870 for(var i=0; i<indexes.length; i++) {
1871 var row = SE.grid.getRecord(indexes[i]).getData();
1872 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1876 //show menu functions
1877 showEmailsListMenu : function(grid, row) {
1879 var data = row.getData();
1880 var draft = (data.type == "draft");
1881 var menu = SE.contextMenus.emailListContextMenu;
1886 if (data.mbox == 'sugar::Emails')
1887 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1889 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1891 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1892 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1893 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1894 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1896 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1899 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1901 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1902 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1903 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1904 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1905 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1908 if (data.mbox == "sugar::Emails")
1910 //Allow users to reassign imported emails
1911 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1912 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1913 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1914 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1918 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1919 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1923 showFolderMenu : function(grid, rowIndex, event) {
1925 var coords = event.getXY();
1926 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1930 SE.contextMenus.dv = {
1931 archiveToSugar : function(contextMenuId) {
1933 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1936 replyForwardEmailContext : function(all) {
1937 SE.contextMenus.detailViewContextMenu.hide();
1946 //// END SE.contextMenus
1947 ///////////////////////////////////////////////////////////////////////////////
1951 ///////////////////////////////////////////////////////////////////////////////
1954 consumeMetaDetail : function(ret) {
1955 // handling if the Email drafts
1956 if(ret.type == 'draft') {
1957 SE.composeLayout.c0_composeDraft();
1962 // cache contents browser-side
1963 SE._setDetailCache(ret);
1965 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1966 // 2 below must be in global context
1968 meta['panelId'] = SE.util.getPanelId();
1970 email = ret.meta.email;
1971 var out = displayTemplate.exec({
1972 'app_strings' : app_strings,
1974 'idx' : targetDiv.id,
1976 'email' : meta.email,
1977 'linkBeans' : linkBeans
1979 var tabLabel = meta.email.name;
1980 if (tabLabel != null && tabLabel.length > 25) {
1981 tabLabel = tabLabel.substring(0, 25) + "...";
1983 targetDiv.set("label", tabLabel);
1984 targetDiv.set("content", out);
1986 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1987 if (SUGAR.email2.util.isIe()) {
1988 displayEmailFrameDiv.style.height = "390px";
1990 displayEmailFrameDiv.style.height = "410px";
1993 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1994 displayFrame.contentWindow.document.write(email.description);
1995 displayFrame.contentWindow.document.close();
1997 // hide archive links
1998 if(ret.meta.is_sugarEmail) {
1999 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
2000 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
2002 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
2003 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
2008 consumeMetaPreview : function(ret) {
2009 // cache contents browser-side
2010 SE._setDetailCache(ret);
2014 var currrow = SE.grid.getLastSelectedRecord();
2015 currrow = SE.grid.getRecord(currrow);
2017 document.getElementById('_blank').innerHTML = '';
2020 // handling if the Email drafts
2021 if(ret.type == 'draft'){
2022 if (currrow.getData().uid == ret.uid) {
2023 SE.composeLayout.c0_composeDraft();
2028 if (currrow.getData().uid != ret.meta.uid) {
2032 // remove loading sprite
2033 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2034 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2036 meta['panelId'] = SE.util.getPanelId();
2037 email = ret.meta.email;
2039 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2040 'app_strings' : app_strings,
2044 'email' :meta.email,
2045 'linkBeans' : linkBeans
2047 // document.getElementById('_blank').innerHTML = meta.email;
2048 /* displayTemplate.append('_blank', {
2049 'app_strings' : app_strings,
2053 'email' :meta.email,
2054 'linkBeans' : linkBeans
2057 var displayFrame = document.getElementById('displayEmailFramePreview');
2058 displayFrame.contentWindow.document.write(email.description);
2059 displayFrame.contentWindow.document.close();
2061 SE.listViewLayout.resizePreview();
2063 // hide archive links
2064 if(ret.meta.is_sugarEmail) {
2065 document.getElementById("archiveEmailPreview").innerHTML = " ";
2066 document.getElementById("btnEmailViewPreview").style.display = "none";
2067 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2069 //hide view relationship link
2070 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2075 * wraps emailDelete() for single messages, comes from preview or tab
2077 emailDeleteSingle : function(ieId, uid, mbox) {
2078 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2079 // find active panel and close if the user double clicked the email to view.
2080 var activeTabId = SE.util.getPanelId();
2081 if(activeTabId != 'Preview')
2082 SE.innerLayout.get("activeTab").close();
2084 document.getElementById('_blank').innerHTML = "";
2087 uid = YAHOO.lang.JSON.stringify(ser);
2088 this.emailDelete(ieId, uid, mbox);
2093 * Sends async call to delete a given message
2096 emailDelete : function(ieId, uid, mbox) {
2097 overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2098 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2099 uid + "&ieId=" + ieId + "&folder=" + mbox);
2103 * retrieves one email to display in the preview pane.
2105 getEmailPreview : function() {
2106 var row = SUGAR.email2.listView.currentRow;
2107 var data = row.getData();
2108 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2109 var setRead = (data['seen'] == 0) ? true : false;
2110 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2111 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2116 * Imports one email into Sugar
2118 importEmail : function(ieId, uid, mbox) {
2119 SE.util.clearHiddenFieldValues('emailUIForm');
2121 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2123 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2124 AjaxObject.target = '';
2125 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2129 * Populates the frameFlex div with the contents of an email
2131 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2132 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2134 var mboxStr = new String(mbox);
2135 var compKey = mbox + uid;
2137 if(setRead == true) {
2138 SE.listView.boldUnreadRows()
2139 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2142 if(destination == SE.innerLayout) {
2144 * loading email into a tab, peer with ListView
2145 * targetDiv must remain in the global namespace as it is used by AjaxObject
2147 //Check if we already have a tab of the email open
2148 var tabs = SE.innerLayout.get("tabs");
2149 for (var t in tabs) {
2150 if (tabs[t].id && tabs[t].id == uid) {
2151 SE.innerLayout.set("activeTab", tabs[t]);
2156 targetDiv = new YAHOO.SUGAR.ClosableTab({
2157 label: loadingSprite,
2163 SE.innerLayout.addTab(targetDiv);
2165 // use cache if available
2166 if(SE.cache[compKey]) {
2167 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2169 // open email as peer-tab to listView
2170 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2171 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2174 // loading email into preview pane
2175 document.getElementById('_blank').innerHTML = loadingSprite;
2177 // use cache if available
2178 if(SE.cache[compKey]) {
2179 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2181 AjaxObject.forceAbort = true;
2182 // open in preview window
2183 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2184 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2189 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2191 if(mboxStr.substring(0,7) == 'sugar::') {
2192 // display an email from Sugar
2193 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2195 // display an email from an email server
2196 document.getElementById('emailUIAction').value = 'getSingleMessage';
2198 document.getElementById('mbox').value = mbox;
2199 document.getElementById('ieId').value = ieId;
2200 document.getElementById('uid').value = uid;
2202 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2204 AjaxObject.forceAbort = true;
2205 AjaxObject.target = '_blank';
2206 AjaxObject.startRequest(callback, null);
2210 * Retrieves multiple emails for DetailView
2212 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2213 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2214 SE.util.clearHiddenFieldValues('emailUIForm');
2216 var mboxStr = new String(mbox);
2218 uids = SE.util.cleanUids(uids);
2220 if(mboxStr.substring(0,7) == 'sugar::') {
2221 // display an email from Sugar
2222 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2223 document.getElementById('uid').value = uids;
2225 // display an email from an email server
2226 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2227 document.getElementById('mbox').value = mbox;
2228 document.getElementById('ieId').value = ieId;
2229 document.getElementById('uid').value = uids;
2232 var formObject = document.getElementById('emailUIForm');
2233 YAHOO.util.Connect.setForm(formObject);
2235 AjaxObject.target = 'frameFlex';
2236 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2238 if(setRead == true) {
2239 var c = uids.split(",");
2240 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2245 * Makes async call to get QuickCreate form
2246 * Renders a modal edit view for a given module
2248 quickCreate : function(module, ieId, uid, mailbox) {
2249 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2251 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2252 get += "&sugarEmail=true";
2255 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2259 * Makes async call to save a quick create
2262 saveQuickCreate : function(action) {
2263 var qcd = SE.detailView.quickCreateDialog;
2264 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2265 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2266 var theCallback = callbackQuickCreateSave;
2267 var accountType = '&sugarEmail=true';
2268 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2269 accountType = '&ieId=' + qcd.ieId;
2272 if (action == 'reply') {
2273 theCallback = callbackQuickCreateSaveAndReply;
2274 } else if (action == true) {
2275 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2277 formObject.action.value = 'EmailUIAjax';
2278 YAHOO.util.Connect.setForm(formObject);
2279 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2280 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2281 accountType + '&mbox=' + qcd.mbox);
2286 * Code to show/hide long list of email address in DetailView
2288 showCroppedEmailList : function(el) {
2289 el.style.display = 'none';
2290 el.previousSibling.style.display = 'inline'
2292 showFullEmailList : function(el) {
2293 el.style.display = 'none';
2294 el.nextSibling.style.display = 'inline';
2298 * Shows the QuickCreate overlay
2299 * @param string ieId
2301 * @param string mailbox
2303 showQuickCreate : function(ieId, uid, mailbox) {
2304 var panelId = SE.util.getPanelId();
2305 var context = document.getElementById("quickCreateSpan" + panelId);
2307 if (!SE.detailView.cqMenus)
2308 SE.detailView.cqMenus = {};
2310 if (SE.detailView.cqMenus[context])
2311 SE.detailView.cqMenus[context].destroy();
2313 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2315 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2318 for (var i=0; i < this.qcmodules.length; i++) {
2319 var module = this.qcmodules[i];
2321 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2324 onclick: { fn: function() {
2325 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2331 menu.render(document.body);
2336 * Displays the "View" submenu in the detailView
2337 * @param string ieId
2339 * @param string mailbox
2341 showViewMenu : function(ieId, uid, mailbox) {
2342 var panelId = SE.util.getPanelId();
2343 var context = "btnEmailView" + panelId;
2344 if (!SE.detailView.viewMenus)
2345 SE.detailView.viewMenus = {};
2347 if (SE.detailView.viewMenus[context])
2348 SE.detailView.viewMenus[context].destroy();
2350 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2352 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2356 (ieId == 'null' || ieId == null) ?
2357 //No ieId - Sugar Email
2359 text: app_strings.LBL_EMAIL_VIEW_RAW,
2360 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2363 //IeID exists, on a remote server
2365 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2366 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2368 text: app_strings.LBL_EMAIL_VIEW_RAW,
2369 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2372 menu.render(document.body);
2377 //#23108 jchi@07/17/2008
2378 menu.render('quickCreateSpan'+ panelId);*/
2379 //this.viewMenu = menu;
2380 //this.viewMenu.show(context);
2383 * Makes async call to get an email's headers
2385 viewHeaders : function(ieId, uid, mailbox) {
2386 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2387 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2391 * Makes async call to get a printable version
2393 viewPrintable : function(ieId, uid, mailbox) {
2394 if(mailbox == 'sugar::Emails') {
2395 // display an email from Sugar
2396 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2398 // display an email from an email server
2399 var emailUIAction = '&emailUIAction=getSingleMessage';
2402 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2403 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2407 * Makes async call to get an email's raw source
2409 viewRaw : function(ieId, uid, mailbox) {
2410 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2411 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2415 * Display all email addresses in detailview.
2417 displayAllAddrs : function(el) {
2418 el.style.display = 'none';
2419 Dom.getNextSibling(el).style.display = 'inline';
2422 //// END SE.detailView
2423 ///////////////////////////////////////////////////////////////////////////////
2427 ///////////////////////////////////////////////////////////////////////////////
2430 contextMenuFocus : new Object(),
2433 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2434 * SugarFolder ID - folder strings
2436 _createFolderId : function(node) {
2442 if(node.data.ieId) {
2443 /* we have a local Sugar folder */
2444 if(node.data.ieId == 'folder') {
2445 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2446 } else if(node.data.ieId.match(SE.reGUID)) {
2447 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2456 addChildNode : function(parentNode, childNode) {
2457 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2458 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2459 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2461 if(childNode.nodes) {
2462 if(childNode.nodes.length > 0) {
2463 for(j=0; j<childNode.nodes.length; j++) {
2464 var newChildNode = childNode.nodes[j];
2465 this.addChildNode(node, newChildNode);
2472 * Builds and returns a new TreeView Node
2473 * @param string name
2475 * @param int is_group
2478 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2479 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2481 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2482 node.expanded = expanded;
2483 node.data = new Object;
2484 node.data['id'] = id;
2485 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2486 node.data['label'] = name;
2487 node.data['ieId'] = 'folder';
2488 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2489 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2490 node.data['unseen'] = unseen;
2495 * ensures that a new folder has a valid name
2497 checkFolderName : function(name) {
2501 this.folderAdd(name);
2505 * Pings email servers for new email - forces refresh of folder pane
2507 checkEmailAccounts : function() {
2508 this.checkEmailAccountsSilent(true);
2511 checkEmailAccountsSilent : function(showOverlay) {
2512 if(typeof(SE.folders.checkingMail)) {
2513 clearTimeout(SE.folders.checkingMail);
2516 // don't stomp an on-going request
2517 if(AjaxObject.currentRequestObject.conn == null) {
2519 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2520 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2522 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2524 // wait 5 secs before trying again.
2525 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2530 * Starts check of all email Accounts using a loading bar for large POP accounts
2532 startEmailAccountCheck : function() {
2533 // don't do two checks at the same time
2534 if(!AjaxObject.requestInProgress()) {
2535 overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2536 SE.accounts.ieIds = SE.folders.getIeIds();
2537 if (SE.accounts.ieIds.length > 0) {
2538 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2539 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2544 // wait 5 secs before trying again.
2545 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2550 * Checks a single Account check based on passed ieId
2552 startEmailCheckOneAccount : function(ieId, synch) {
2559 var node = SE.clickedFolderNode;
2560 if (node && !synch) {
2561 mbox = node.data.mbox;
2563 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2564 SE.accounts.ieIds = [ieId];
2565 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2566 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2571 * Empties trash for subscribed accounts
2573 emptyTrash : function() {
2574 SE.contextMenus.frameFoldersContextMenu.hide();
2575 overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2576 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2580 * Clears Cache files of the inboundemail account
2582 clearCacheFiles : function(ieId) {
2583 SE.contextMenus.frameFoldersContextMenu.hide();
2584 overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2585 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2590 * Returns an array of all the active accounts in the folder view
2592 getIeIds : function() {
2594 var root = SE.tree.getRoot();
2595 for(i=0; i < root.children.length; i++) {
2596 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2597 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2598 ieIds.push(root.children[i].children[0].data.ieId);
2605 * loads folder lists in Settings->Folders
2607 lazyLoadSettings : function() {
2608 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2609 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2613 * After the add new folder is done via folders tab on seetings, this function should get called
2614 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2616 loadSettingFolder : function() {
2617 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2618 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2622 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2624 removeSugarFolders : function() {
2626 var root = tree.getRoot();
2627 var folder = SE.util.findChildNode(root, "ieId", "folder");
2629 tree.removeNode(folder);
2630 folder = SE.util.findChildNode(root, "ieId", "folder");
2632 if (!root.childrenRendered) {
2633 root.childrenRendered = true;
2637 rebuildFolders : function(silent) {
2638 if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2639 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2645 * Updates TreeView with Sugar Folders
2647 setSugarFolders : function(delay) {
2648 this.removeSugarFolders();
2649 //AjaxObject.forceAbort = true;
2650 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2654 * Takes async data object and creates the sugar folders in TreeView
2656 setSugarFoldersEnd : function(o) {
2657 var root = SE.tree.getRoot();
2658 addChildNodes(root, {nodes: o});
2659 SE.accounts.renderTree();
2660 //If nothing is loaded in the grid, load "My Inbox"
2661 if (SE.grid.params.ieId == "undefined") {
2662 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2666 startCheckTimer : function() {
2667 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2668 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2670 if(typeof(SE.folders.checkTimer) != 'undefined') {
2671 clearTimeout(SE.folders.checkTimer);
2674 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2675 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2677 SE.userPrefs.emailSettings.firstAutoCheck = true;
2678 SE.folders.checkEmailAccountsSilent(false);
2684 * makes an async call to save user preference and refresh folder view
2685 * @param object SELECT list object
2687 setFolderSelection : function() {
2688 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2690 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2691 var a_active_accnts = "";
2692 for(i=0;i<a_rs.length;i++)
2694 var t_record = a_rs[i];
2695 var is_active = t_record.getData('is_active');
2697 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2700 if(a_active_accnts == "")
2701 a_active_accnts = "&ieIdShow[]=";
2703 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2705 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2709 * makes async call to save user preference for a given node's open state
2710 * @param object node YUI TextNode object
2712 setOpenState : function(node) {
2713 SE.util.clearHiddenFieldValues('emailUIForm');
2714 var nodePath = node.data.id;
2715 var nodeParent = node.parent;
2717 while(nodeParent != null) {
2718 // root node has no ID param
2719 if(nodeParent.data != null) {
2720 nodePath = nodeParent.data.id + "::" + nodePath;
2723 var nodeParent = nodeParent.parent;
2726 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2727 document.getElementById('focusFolder').value = nodePath;
2729 if(node.expanded == true) {
2730 document.getElementById('focusFolderOpen').value = 'open';
2732 document.getElementById('focusFolderOpen').value = 'closed';
2735 var formObject = document.getElementById('emailUIForm');
2736 YAHOO.util.Connect.setForm(formObject);
2738 AjaxObject.startRequest(null, null);
2741 getNodeFromMboxPath : function(path) {
2742 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2743 var a = YAHOO.lang.JSON.parse(path);
2745 var node = tree.getRoot();
2748 while(i < a.length) {
2749 node = this.getChildNodeFromLabel(node, a[i]);
2756 getChildNodeFromLabel : function(node, nodeLabel) {
2757 for(i=0; i<node.children.length; i++) {
2758 if(node.children[i].data.id == nodeLabel) {
2759 return node.children[i];
2765 * returns the node that presumably under the user's right-click
2767 getNodeFromContextMenuFocus : function() {
2768 //// get the target(parent) node
2769 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2771 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2773 // filter local folders
2774 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2775 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2776 if(target.id == '') {
2777 target = target.parentNode;
2784 var targetNode = document.getElementById(target.id);
2785 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2788 var matches = re.exec(targetNode.id);
2790 return document.getElementById(ygtvlabelel1);
2796 // usually parent node
2797 matches = re.exec(targetNode.parentNode.id);
2804 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2805 parentNode.expand();
2811 * Decrements the Unread Email count in folder text
2812 * @param string ieId ID to look for
2813 * @param string mailbox name
2814 * @param count how many to decrement
2816 decrementUnreadCount : function(ieId, mbox, count) {
2821 if(mbox.indexOf("sugar::") === 0) {
2822 var node = this.getNodeFromId(ieId);
2824 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2827 var unseen = node.data.unseen;
2829 var check = unseen - count;
2830 var finalCount = (check >= 0) ? check : 0;
2831 node.data.unseen = finalCount;
2833 SE.accounts.renderTree();
2838 * gets the TreeView node with a given ID/ieId
2839 * @param string id ID to look for
2840 * @return object Node
2842 getNodeFromId : function(id) {
2843 SE.folders.focusNode = null;
2844 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2845 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2846 SE.folders.focusNode = this;
2850 return SE.folders.focusNode;
2854 * Uses ieId and mailbox to try to find a node in the tree
2856 getNodeFromIeIdAndMailbox : function(id, mbox) {
2857 SE.folders.focusNode = null;
2858 if (mbox == "sugar::Emails") {
2862 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2863 if (varsarray instanceof Array) {
2864 if (this.data.ieId && this.data.ieId == varsarray[0]
2865 && this.data.mbox == varsarray[1]) {
2866 SE.folders.focusNode = this;
2870 if (this.data.ieId && this.data.ieId == varsarray) {
2871 SE.folders.focusNode = this;
2875 }, null, [id, mbox]);
2876 return SE.folders.focusNode;
2879 unhighliteAll : function() {
2880 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2884 * Displays a short form
2886 folderAdd : function() {
2887 SE.contextMenus.frameFoldersContextMenu.hide();
2889 var node = SE.clickedFolderNode;
2891 if(node != null && node.data) {
2892 overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2893 app_strings.LBL_EMAIL_SETTINGS_NAME,
2894 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2896 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2900 folderAddRegisterEnter : function() {
2901 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2902 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2903 this.buttons[1].handler);
2905 this.enterKeyListener.enable();
2908 folderRemoveRegisterEnter : function() {
2909 this.enterKeyListener.disable();
2912 folderAddXmlCall : function(name) {
2913 if (trim(name) == "") {
2914 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2917 name = escape(name);
2921 var parentNode = SE.clickedFolderNode;
2923 this.contextMenuFocus = parentNode;
2925 if(parentNode.data.ieId) {
2926 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2930 if(type == 'imap') {
2931 // make an IMAP folder
2932 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2933 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2934 } else if(type == 'sugar') {
2935 // make a Sugar folder
2936 if(SE.folders.isUniqueFolderName(name)) {
2937 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2938 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2940 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2941 SE.folders.folderAdd();
2945 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2948 // hide add-folder diaglogue
2949 SE.e2overlay.hide();
2953 * Removes either an IMAP folder or a Sugar Folder
2955 folderDelete : function() {
2956 SE.contextMenus.frameFoldersContextMenu.hide();
2958 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2960 var parentNode = SE.clickedFolderNode;
2962 if(parentNode != null && parentNode.data) {
2963 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2964 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2968 AjaxObject.target = 'frameFlex';
2970 if(parentNode.data.ieId != 'folder') {
2971 // delete an IMAP folder
2972 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2974 // delete a sugar folder
2975 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2977 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2978 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2980 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2986 * Rename folder form
2989 folderRename : function() {
2990 SE.contextMenus.frameFoldersContextMenu.hide();
2991 var node = SE.clickedFolderNode;
2994 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2995 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2999 overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
3000 app_strings.LBL_EMAIL_SETTINGS_NAME,
3002 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
3004 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
3009 * fills an Object with key-value pairs of available folders
3011 getAvailableFoldersObject : function() {
3012 var ret = new Object();
3013 var tree = SE.tree.root;
3016 for(var i=0; i<tree.children.length; i++) {
3017 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3020 ret['none'] = app_strings.LBL_NONE;
3027 * Fills in key-value pairs for dependent dropdowns
3028 * @param object ret Associative array
3029 * @param object node TreeView node in focus
3030 * @param string currentPath Built up path thus far
3031 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3033 getFolderFromChild : function(ret, node, currentPath, spacer) {
3034 if(node.data != null && node.depth > 0) {
3035 /* handle visual separtors differentiating b/t mailserver and local */
3036 if(node.data.ieId && node.data.ieId == 'folder') {
3037 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3041 ret['spacer0'] = spacer;
3042 } else if(ret.spacer0 != spacer) {
3043 ret['spacer1'] = spacer
3046 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3047 var depthMarker = currentPath;
3048 var retIndex = SE.folders._createFolderId(node);
3049 ret[retIndex] = depthMarker + theLabel;
3052 if(node.children != null) {
3054 currentPath += theLabel + "/";
3057 for(var i=0; i<node.children.length; i++) {
3058 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3066 * Wrapper to refresh folders tree
3068 getFolders : function() {
3069 SE.accounts.rebuildFolderList();
3073 * handles events around folder-rename input field changes
3074 * @param object YUI event object
3076 handleEnter : function(e) {
3077 switch(e.browserEvent.type) {
3079 e.preventDefault(); // click in text field
3083 SE.folders.submitFolderRename(e);
3087 var kc = e.browserEvent.keyCode;
3091 SE.folders.submitFolderRename(e);
3095 e.preventDefault(e);
3096 SE.folders.cancelFolderRename(e);
3103 * Called when a node is clicked on in the folder tree
3104 * @param node, The node clicked on
3105 * @param e, The click event
3107 handleClick : function(o) {
3109 //If the click was on a sugar folder
3110 if (node.data.ieId == "folder") {
3111 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3114 SE.listView.populateListFrame(node, node.data.ieId, false);
3116 //eval(node.data.click);
3121 * Called when a node is right-clicked on in the folder tree
3123 handleRightClick : function(e) {
3124 YAHOO.util.Event.preventDefault(e);
3126 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3127 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3129 //If the click was on a sugar folder
3130 SE.clickedFolderNode = node;
3131 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3132 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3133 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3134 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3135 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3136 menu.getItem(3).cfg.setProperty("disabled", false);
3137 menu.getItem(4).cfg.setProperty("disabled", false);
3138 menu.getItem(5).cfg.setProperty("disabled", false);
3139 menu.getItem(6).cfg.setProperty("disabled", true);
3141 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3142 menu.getItem(0).cfg.setProperty("disabled", true);
3143 menu.getItem(1).cfg.setProperty("disabled", true);
3144 menu.getItem(2).cfg.setProperty("disabled", true);
3145 menu.getItem(3).cfg.setProperty("disabled", true);
3146 menu.getItem(4).cfg.setProperty("disabled", true);
3148 if (node.data.protocol != null) {
3149 menu.getItem(6).cfg.setProperty("disabled", false);
3151 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3152 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3153 //Sent or Draft folders
3154 menu.getItem(3).cfg.setProperty("disabled", true);
3155 menu.getItem(4).cfg.setProperty("disabled", true);
3156 menu.getItem(5).cfg.setProperty("disabled", true);
3159 //For group with auto inbound, disable everything.
3160 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3162 menu.getItem(0).cfg.setProperty("disabled", true);
3163 menu.getItem(1).cfg.setProperty("disabled", true);
3164 menu.getItem(2).cfg.setProperty("disabled", true);
3165 menu.getItem(3).cfg.setProperty("disabled", true);
3166 menu.getItem(4).cfg.setProperty("disabled", true);
3167 menu.getItem(5).cfg.setProperty("disabled", true);
3168 menu.getItem(6).cfg.setProperty("disabled", true);
3171 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3176 * Called when a row is dropped on a node
3178 handleDrop : function(rows, targetFolder) {
3179 var rowData = rows[0].getData();
3180 if (rowData.mbox != targetFolder.data.mbox) {
3181 var srcIeId = rowData.ieId;
3182 var srcFolder = rowData.mbox;
3183 var destIeId = targetFolder.data.ieId;
3184 var destFolder = targetFolder.data.mbox;
3186 for(var i=0; i<rows.length; i++) {
3187 uids[i] = rows[i].getData().uid;
3189 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3194 * Called when something is dragged over a Folder Node
3196 dragOver : function(dragObject) {
3201 * Determines if a folder name is unique to the folder tree
3202 * @param string name
3204 isUniqueFolderName : function(name) {
3205 uniqueFolder = true;
3206 var root = SE.tree.getRoot();
3207 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3208 if (this.attributes && this.attributes.ieId == "folder") {
3209 if (this.attributes.text == name) {
3210 uniqueFolder = false;
3215 return uniqueFolder;
3219 * Makes async call to rename folder in focus
3220 * @param object e Event Object
3222 submitFolderRename : function(newName) {
3223 if (trim(newName) == "") {
3224 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3227 newName = escape(newName);
3228 var node = SE.clickedFolderNode;
3229 var origName = node.data.text
3231 if (newName == origName) {
3234 if(SE.folders.isUniqueFolderName(newName)) {
3235 overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3236 if (node.data.ieId == "folder") {
3238 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3241 //IMAP folder or POP mailbox
3242 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3243 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3244 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3248 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3253 moveFolder : function(folderId, parentFolderId) {
3254 if (folderId != parentFolderId)
3256 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3257 + folderId + "&newParentId=" + parentFolderId);
3262 * makes async call to do a full synchronization of all accounts
3264 synchronizeAccounts : function() {
3265 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3266 overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3267 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3272 * Updates user's folder subscriptsion (Sugar only)
3273 * @param object SELECT DOM object in focus
3274 * @param string type of Folder selection
3276 updateSubscriptions : function() {
3277 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3281 select = document.getElementById('userFolders');
3283 for(i=0; i<select.options.length; i++) {
3284 var opt = select.options[i];
3285 if(opt.selected && opt.value != "") {
3289 active += opt.value;
3293 //Add the group folder ids.
3294 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3295 for(i=0; i<group_folders.length; i++)
3297 active += ("::" + group_folders[i]);
3300 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3303 * Updates user's group folder subscriptsion (Sugar only)
3304 * @param ieID The group folder to add to the tree view
3306 retrieveGroupFolderSubscriptions : function() {
3308 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3309 var activeGroupFolders = "";
3310 var activeGroupIds = [];
3311 for(i=0;i<a_rs.length;i++)
3313 var t_record = a_rs[i];
3314 var is_active = t_record.getData('is_active');
3315 var isGroupFolder = t_record.getData('has_groupfolder');
3316 var ieID = t_record.getData('id');
3320 activeGroupIds.push(ieID);
3324 return activeGroupIds;
3329 SE.folders.checkEmail2 = function() {
3330 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3332 //// END FOLDERS OBJECT
3333 ///////////////////////////////////////////////////////////////////////////////
3336 ///////////////////////////////////////////////////////////////////////////////
3339 * Keypress Event capture and processing
3342 overall : function(e) {
3343 switch(e.charCode) {
3345 if(e.ctrlKey || e.altKey) {
3346 var focusRegion = SE.innerLayout.regions.center;
3347 if(focusRegion.activePanel.closable == true) {
3348 focusRegion.remove(focusRegion.activePanel);
3356 ///////////////////////////////////////////////////////////////////////////////
3359 ///////////////////////////////////////////////////////////////////////////////
3362 * ListView object methods and attributes
3368 * Fills the ListView pane with detected messages.
3370 populateListFrame : function(node, ieId, forceRefresh) {
3371 SE.innerLayout.selectTab(0);
3372 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3374 Dom.get('_blank').innerHTML = "";
3375 SE.grid.params['emailUIAction'] = 'getMessageList';
3376 SE.grid.params['mbox'] = node.data.mbox;
3377 SE.grid.params['ieId'] = ieId;
3378 forcePreview = true; // loads the preview pane with first item in grid
3379 SE.listView.refreshGrid();
3383 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3385 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3386 SE.innerLayout.selectTab(0);
3387 Dom.get('_blank').innerHTML = "";
3388 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3389 SE.grid.params['ieId'] = node.data.id;
3390 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3391 SE.listView.refreshGrid();
3395 * Sets sort order as user preference
3398 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3400 ieName = ieNamePassed;
3401 focusFolder = focusFolderPassed;
3403 SE.util.clearHiddenFieldValues('emailUIForm');
3404 var previousSort = document.getElementById('sortBy').value;
3406 document.getElementById('sortBy').value = sortBy;
3407 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3408 document.getElementById('focusFolder').value = focusFolder;
3409 document.getElementById('ieId').value = ieId;
3411 if(sortBy == previousSort) {
3412 document.getElementById('reverse').value = '1';
3415 var formObject = document.getElementById('emailUIForm');
3416 YAHOO.util.Connect.setForm(formObject);
3418 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3423 * Enables click/arrow select of grid items which then populate the preview pane.
3425 selectFirstRow : function() {
3426 SE.grid.selModel.selectFirstRow();
3429 selectLastRow : function() {
3430 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3433 setEmailListStyles : function() {
3434 SE.listView.boldUnreadRows();
3436 var ds = SE.grid.getStore();
3437 if (SE.grid.getSelections().length == 0) {
3438 document.getElementById('_blank').innerHTML = '';
3442 if(typeof(ds.baseParams.mbox) != 'undefined') {
3443 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3444 var cm = SE.grid.getColumnModel();
3445 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3446 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3448 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3449 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3453 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3454 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3457 // 4/20/2007 added to hide overlay after search
3459 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3460 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3461 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3462 if (node) node.data.unseen = unread;
3464 SE.accounts.renderTree();
3467 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3468 if(forcePreview && ds.totalCount > 0) {
3469 SE.detailView.getEmailPreview();
3470 forcePreview = false;
3475 * Removes a row if found via its UID
3477 removeRowByUid : function(uid) {
3478 uid = new String(uid);
3479 uids = uid.split(',');
3480 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3482 for(j=0; j<uids.length; j++) {
3483 var theUid = uids[j];
3484 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3485 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3486 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3492 displaySelectedEmails : function(rows) {
3493 var dm = SE.grid.getDataModel();
3496 for(i=0; i<rows.length; i++) {
3497 var rowIndex = rows[i].rowIndex;
3498 var metadata = dm.data[rowIndex];
3503 uids += metadata[5];
3505 // unbold unseen email
3506 this.unboldRow(rowIndex);
3509 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3513 * exception handler for data load failures
3515 loadException : function(dataModel, ex, response) {
3520 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3521 * @param string sourceIeId Email's source I-E id
3522 * @param string sourceFolder Email's current folder
3523 * @param destinationIeId Destination I-E id
3524 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3526 * @param array emailUids Array of email's UIDs
3528 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3529 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3530 overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3532 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3533 // remove rows from visibility
3534 for(row in selectedRows) {
3535 //SE.grid.getStore().remove(row);
3538 var baseUrl = '&sourceIeId=' + sourceIeId +
3539 '&sourceFolder=' + sourceFolder +
3540 '&destinationIeId=' + destinationIeId +
3541 '&destinationFolder=' + destinationFolder;
3544 for(i=0; i<emailUids.length; i++) {
3546 uids += app_strings.LBL_EMAIL_DELIMITER;
3548 uids += emailUids[i];
3550 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3551 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3553 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3559 * Unbolds text in the grid view to denote read status
3561 markRead : function(index, record) {
3562 // unbold unseen email
3563 var row = SE.grid.getRecord(record);
3564 row.getData().seen = 1;
3565 SE.grid.getTrEl(record).style.fontWeight = "normal";
3569 * grid row output, bolding unread emails
3571 boldUnreadRows : function() {
3572 // bold unread emails
3573 var trEl = SE.grid.getFirstTrEl();
3574 while(trEl != null) {
3575 if(SE.grid.getRecord(trEl).getData().seen == "0")
3576 trEl.style.fontWeight = "bold";
3578 trEl.style.fontWeight = "";
3579 trEl = SE.grid.getNextTrEl(trEl);
3584 * Show preview for an email if 1 and only 1 is selected
3585 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3587 handleRowSelect : function(e) {
3588 if(e.selectedRows.length == 1) {
3589 SE.detailView.getEmailPreview();
3593 handleDrop : function(e, dd, targetId, e2) {
3595 case 'htmleditordiv':
3596 var rows = SE.grid.getSelectedRows();
3597 if(rows.length > 0) {
3598 SE.listView.displaySelectedEmails(rows);
3603 var targetElId = new String(targetId);
3604 var targetIndex = targetElId.replace('ygtvlabelel',"");
3605 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3606 var dm = SE.grid.getDataModel();
3607 var emailUids = new Array();
3608 var destinationIeId = targetNode.data.ieId;
3609 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3612 var rows = SE.grid.getSelectedRows();
3613 // iterate through dragged rows
3614 for(i=0; i<rows.length; i++) {
3615 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3616 var rowIndex = rows[i].rowIndex;
3617 var dataModelRow = dm.data[rowIndex];
3618 var sourceIeId = dataModelRow[7];
3619 var sourceFolder = dataModelRow[6];
3620 emailUids[i] = dataModelRow[5];
3623 // event wrapped call - need FQ
3624 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3625 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3631 * Hack-around to get double-click and single clicks to work on the grid
3632 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3634 handleClick : function(o) {
3635 SUGAR.email2.grid.clearTextSelection();
3637 var el = SUGAR.email2.grid.getSelectedRows();
3639 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3640 if ( el.length == 1)
3643 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3644 SUGAR.email2.listView.currentRowIndex = rowId;
3645 clearTimeout(SUGAR.email2.detailView.previewTimer);
3646 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3651 * Custom handler for double-click/enter
3652 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3654 getEmail : function(e) {
3655 var rows = SE.grid.getSelectedRows();
3656 var row = SE.grid.getRecord(rows[0]).getData();
3658 clearTimeout(SE.detailView.previewTimer);
3659 document.getElementById("_blank").innerHTML = "";
3661 if(row.type != "draft") {
3662 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3664 // circumventing yui-ext tab generation, let callback handler build new view
3665 SE.util.clearHiddenFieldValues('emailUIForm');
3666 //function(uid, mbox, ieId, setRead, destination) {
3667 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3668 document.getElementById('uid').value = row.uid; // uid;
3669 document.getElementById('mbox').value = row.mbox; // mbox;
3670 document.getElementById('ieId').value = row.ieId; // ieId;
3672 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3673 AjaxObject.target = '_blank';
3674 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3679 * Retrieves a row if found via its UID
3683 getRowIndexByUid : function(uid) {
3684 uid = new String(uid);
3685 uids = uid.split(',');
3687 for(j=0; j<uids.length; j++) {
3688 var theUid = uids[j];
3690 for(i=0; i<SE.grid.getStore().data.length; i++) {
3691 if(SE.grid.getStore().data[i].id == theUid) {
3699 * Returns the UID's of the seleted rows
3702 getUidsFromSelection : function() {
3703 var rows = SE.grid.getSelectedRows();
3705 /* iterate through available rows JIC a row is deleted - use first available */
3706 for(var i=0; i<rows.length; i++) {
3707 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3712 refreshGrid : function() {
3713 SE.grid.getDataSource().sendRequest(
3714 SUGAR.util.paramsToUrl(SE.grid.params),
3715 SE.grid.onDataReturnInitializeTable,
3721 //// END SE.listView
3722 ///////////////////////////////////////////////////////////////////////////////
3724 ///////////////////////////////////////////////////////////////////////////////
3728 * sends search criteria
3729 * @param reference element search field
3731 search : function(el) {
3732 var searchCriteria = new String(el.value);
3734 if(searchCriteria == '') {
3735 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3739 var safeCriteria = escape(searchCriteria);
3741 var accountListSearch = document.getElementById('accountListSearch');
3742 //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3744 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3745 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3746 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3747 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3748 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3753 * sends advanced search criteria
3755 searchAdvanced : function() {
3756 var formObject = document.getElementById('advancedSearchForm');
3759 //Set assigned user id to blank if name is not present.
3760 if (formObject.elements['assigned_user_name'].value == "")
3761 formObject.elements['assigned_user_id'].value = "";
3763 for(i=0; i<formObject.elements.length; i++) {
3764 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3767 if(formObject.elements[i].type == 'text') {
3768 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3770 if(formObject.elements[i].type == 'hidden') {
3771 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3773 if(formObject.elements[i].type == 'select-one') {
3774 var el = formObject.elements[i];
3775 var v = el.options[el.selectedIndex].value;
3778 SE.grid.params[el.name] = v;
3781 //Clear previous search results if necessary
3782 if(typeof( SE.grid.params[el.name]) != 'undefined')
3783 delete SE.grid.params[el.name]
3790 if(! this.validateSearchFormInput() )
3793 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3794 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3795 var accountListSearch = document.getElementById('accountListSearch');
3796 SE.listView.refreshGrid();
3798 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3803 * Validates the search form inputs to ensure all parameters are valid
3806 validateSearchFormInput: function()
3808 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3809 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3810 var dateCheck = check_form('advancedSearchForm');
3812 //If the parent type is selected ensure the user selected a parent_id.
3813 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3819 * Toggles the advanced options, either hidding or showing the selection.
3821 toggleAdvancedOptions: function()
3823 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3825 for(var i=0;i<el.length;i++)
3827 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3828 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3830 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3834 * clears adv search form fields
3836 searchClearAdvanced : function() {
3837 var form = document.getElementById('advancedSearchForm');
3839 for(i=0; i<form.elements.length; i++) {
3840 if(form.elements[i].type != 'button') {
3841 form.elements[i].value = '';
3847 //////////////////////////////////////////////////////////////////////////////
3850 //////////////////////////////////////////////////////////////////////////////
3853 /******************************************************************************
3854 * USER SIGNATURES calls stolen from Users module
3855 *****************************************************************************/
3856 createSignature : function(record, the_user_id) {
3857 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3859 URL += "&record="+record;
3861 if(the_user_id != "") {
3862 URL += "&the_user_id="+the_user_id;
3864 var windowName = 'email_signature';
3865 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3867 var win = window.open(URL, windowName, windowFeatures);
3868 if(win && win.focus) {
3869 // put the focus on the popup if the browser supports the focus() method
3874 deleteSignature : function() {
3875 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3876 overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3877 var singature_id = document.getElementById('signature_id').value;
3878 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3882 saveOptionsGeneral : function(displayMessage) {
3883 var formObject = document.getElementById('formEmailSettingsGeneral');
3884 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3885 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3888 YAHOO.util.Connect.setForm(formObject);
3889 SE.composeLayout.emailTemplates = null;
3891 AjaxObject.target = 'frameFlex';
3892 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3895 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3897 SE.settings.settingsDialog.hide();
3901 * Shows settings container screen
3903 showSettings : function() {
3904 if(!SE.settings.settingsDialog) {
3905 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3911 constraintoviewport: true
3913 dlg.showEvent.subscribe( function (){
3914 var el = this.element;
3915 var viewH = YAHOO.util.Dom.getViewportHeight();
3916 if (this.header && el && viewH - 50 < el.clientHeight) {
3917 var body = this.header.nextElementSibling;
3918 body.style.overflow = "auto";
3919 body.style.height = (viewH - 50) + "px";
3922 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3923 dlg.setBody('<div id="settingsTabDiv"/>');
3924 dlg.beforeRenderEvent.subscribe(function() {
3925 var dd = new YAHOO.util.DDProxy(dlg.element);
3926 dd.setHandleElId(dlg.header);
3927 dd.on('endDragEvent', function() {
3933 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3934 var tabContent = Dom.get("tab_general");
3935 tp.addTab(new YAHOO.widget.Tab({
3936 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3938 content : tabContent.innerHTML,
3939 id : "generalSettings",
3942 tabContent.parentNode.removeChild(tabContent);
3943 tabContent = Dom.get("tab_accounts");
3944 var accountTab = new YAHOO.widget.Tab({
3945 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3947 content : tabContent.innerHTML,
3948 id : "accountSettings"
3950 tp.addTab(accountTab);
3951 tabContent.parentNode.removeChild(tabContent);
3953 tp.appendTo(dlg.body);
3956 SE.settings.settingsDialog.show();
3957 SE.folders.lazyLoadSettings();
3958 SE.accounts.lazyLoad();
3962 lazyLoadRules : function() {
3963 if(false/*!SE.settings.rules*/) {
3964 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3969 //// END SE.settings
3970 ///////////////////////////////////////////////////////////////////////////////
3973 /******************************************************************************
3975 *****************************************************************************/
3976 function removeHiddenNodes(nodes, grid) {
3978 for(var i = nodes.length - 1; i > -1; i--) {
3979 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3980 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3986 function strpad(val) {
3987 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3990 function refreshTodos() {
3991 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3992 AjaxObject.target = 'todo';
3993 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3996 /******************************************************************************
3997 * MUST STAY IN GLOBAL NAMESPACE
3998 *****************************************************************************/
3999 function refresh_signature_list(signature_id, signature_name) {
4000 var field=document.getElementById('signature_id');
4002 for (var i=0; i < field.options.length; i++) {
4003 if (field.options[i].value == signature_id) {
4004 if (field.options[i].selected==false) {
4005 field.options[i].selected=true;
4010 //add item to selection list.
4012 var newElement=document.createElement('option');
4013 newElement.text=signature_name;
4014 newElement.value=signature_id;
4015 field.options.add(newElement);
4016 newElement.selected=true;
4019 //enable the edit button.
4020 var field1=document.getElementById('edit_sig');
4021 field1.style.visibility="inherit";
4022 var deleteButt = document.getElementById('delete_sig');
4023 deleteButt.style.visibility="inherit";
4026 function setDefaultSigId(id) {
4027 var checkbox = document.getElementById("signature_default");
4028 var default_sig = document.getElementById("signatureDefault");
4030 if(checkbox.checked) {
4031 default_sig.value = id;
4033 default_sig.value = "";
4037 function setSigEditButtonVisibility() {
4038 var field = document.getElementById('signature_id');
4039 var editButt = document.getElementById('edit_sig');
4040 var deleteButt = document.getElementById('delete_sig');
4041 if(field.value != '') {
4042 editButt.style.visibility = "inherit";
4043 deleteButt.style.visibility = "inherit";
4045 editButt.style.visibility = "hidden";
4046 deleteButt.style.visibility = "hidden";
4048 }// End of File modules/Emails/javascript/EmailUI.js
4050 /*********************************************************************************
4051 * SugarCRM Community Edition is a customer relationship management program developed by
4052 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4054 * This program is free software; you can redistribute it and/or modify it under
4055 * the terms of the GNU Affero General Public License version 3 as published by the
4056 * Free Software Foundation with the addition of the following permission added
4057 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4058 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4059 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4061 * This program is distributed in the hope that it will be useful, but WITHOUT
4062 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4063 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4066 * You should have received a copy of the GNU Affero General Public License along with
4067 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4068 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4071 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4072 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4074 * The interactive user interfaces in modified source and object code versions
4075 * of this program must display Appropriate Legal Notices, as required under
4076 * Section 5 of the GNU Affero General Public License version 3.
4078 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4079 * these Appropriate Legal Notices must retain the display of the "Powered by
4080 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4081 * technical reasons, the Appropriate Legal Notices must display the words
4082 * "Powered by SugarCRM".
4083 ********************************************************************************/
4086 var sw = YAHOO.SUGAR,
4087 Event = YAHOO.util.Event,
4088 Connect = YAHOO.util.Connect,
4089 Dom = YAHOO.util.Dom
4092 ///////////////////////////////////////////////////////////////////////////////
4095 _contactCache : new Array(), // cache of contacts
4096 _dd : new Array(), // filtered list, same format as _contactCache
4097 _ddLists : new Array(), // list of Lists
4098 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4099 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4100 clickBubble : true, // hack to get around onclick event bubbling
4102 relatedBeanType : '',
4105 itemSpacing : 'white-space:nowrap; padding:2px;',
4111 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4113 initFixForDatatableSort: function () {
4114 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4115 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4116 var oColumn = this._oColumnSet.getColumn(column);
4119 // Validate TD element
4120 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4122 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4124 // Validate TH element
4126 elCell = this.getThEl(column);
4129 var allColumns = this._oColumnSet.flat;
4130 for(var i=0, len=allColumns.length; i<len; i++) {
4131 if(allColumns[i].getThEl().id === elCell.id) {
4132 oColumn = allColumns[i];
4143 cancelEdit : function() {
4144 if(this.editContactDialog)
4145 this.editContactDialog.hide();
4146 if(this.editMailingListDialog)
4147 this.editMailingListDialog.hide();
4151 * Clears filter form
4153 clear : function() {
4154 var t = document.getElementById('contactsFilter');
4160 * handle context-menu Compose-to call
4161 * @param string type 'contacts' or 'lists'
4163 composeTo : function(type, waited) {
4164 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4165 if (activePanel.substring(0, 10) != "composeTab") {
4166 SE.composeLayout.c0_composeNewEmail();
4167 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4168 SE.contextMenus.contactsContextMenu.hide();
4171 var idx = activePanel.substring(10);
4174 // determine if we have a selection to work with
4175 if(type == 'contacts') {
4176 var ids = SE.contactView.getSelectedRows();
4177 for (var i in ids) {
4178 rows[i] = SE.contactView.getRecord(ids[i]);
4180 removeHiddenNodes(rows, SE.contactView);
4184 if(rows.length > 0) {
4185 SE.composeLayout.handleDrop(
4186 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4187 null, rows, 'addressTO' + idx );
4189 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4193 editContact : function() {
4194 SE.contextMenus.contactsContextMenu.hide();
4195 var element = SE.contactView.getSelectedNodes()[0];
4197 if (element.className.indexOf('address-contact') > -1) {
4198 elementId = element.id;
4199 } else if (element.className.indexOf('address-exp-contact') > -1) {
4200 elementId = element.id.substring(2);
4206 * Filters contact entries based on user input
4208 filter : function(inputEl) {
4209 var ret = new Object();
4210 var re = new RegExp(inputEl.value, "gi");
4212 for(var i in this._contactCache) {
4213 if(this._contactCache[i].name.match(re)) {
4214 ret[i] = this._contactCache[i];
4218 this.buildContactList(ret);
4221 fullForm : function(id, module) {
4222 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4226 * returns a formatted email address from the addressBook cache
4228 getFormattedAddress : function(id) {
4229 var o = this._contactCache[id];
4230 var primaryEmail = '';
4232 for(var i=0; i<o.email.length; i++) {
4233 var currentEmail = o.email[i].email_address;
4235 if(o.email[i].primary_address == 1) {
4236 primaryEmail = o.email[i].email_address;
4240 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4241 var name = new String(o.name);
4242 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4243 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4249 * Sets up async call to query for matching contacts, users, etc.
4251 searchContacts : function() {
4252 var fn = document.getElementById('input_searchField').value;
4253 var pe = document.getElementById('input_searchPerson').value;
4255 var rb = document.getElementById('hasRelatedBean').checked;
4258 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4259 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4260 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4261 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4263 this.addressBookDataModel.params['related_bean_id'] = '';
4266 this.addressBookDataModel.params['search_field'] = fn;
4267 this.addressBookDataModel.params['person'] = pe;
4268 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4269 this.grid._oDataSource = this.addressBookDataModel;
4270 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4274 * Clear Search Crieteria For Addressbook
4276 clearAddressBookSearch : function() {
4277 document.getElementById('input_searchField').value = "";
4278 document.getElementById('input_searchPerson').selectedIndex = 0;
4282 * Opens modal select window to add contacts to addressbook
4284 selectContactsDialogue : function(destId) {
4285 if(!this.contactsDialogue) {
4286 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4290 constraintoviewport: true,
4292 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4293 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4295 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4297 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4298 dlg.setBody(body.innerHTML);
4299 dlg.renderEvent.subscribe(function() {
4300 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4301 if (iev && !SUGAR.isIE) {
4302 this.body.style.width = "950px";
4307 dlg.beforeRenderEvent.subscribe(function() {
4308 var dd = new YAHOO.util.DDProxy(dlg.element);
4309 dd.setHandleElId(dlg.header);
4310 dd.on('endDragEvent', function() {
4316 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4318 var tabContent = SUGAR.util.getAndRemove("searchForm");
4319 tp.addTab(new YAHOO.widget.Tab({
4320 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4322 content : tabContent.innerHTML,
4323 id : "addressSearchTab",
4327 var addListenerFields = ['input_searchPerson','input_searchField' ]
4328 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4329 if (e.keyCode == 13) {
4330 YAHOO.util.Event.stopEvent(e);
4331 SUGAR.email2.addressBook.searchContacts();
4335 this.contactsDialogue.render();
4338 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4339 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4343 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4344 var idx = activePanel.substring(10);
4346 SE.addressBook.idx = idx;
4349 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4350 document.getElementById('relatedBeanColumn').style.display = '';
4351 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4352 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4353 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4354 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4355 SE.addressBook.relatedBeanType = relatedBeanType;
4357 document.getElementById('relatedBeanColumn').style.display = 'none';
4358 document.getElementById('hasRelatedBean').checked = false;
4361 if (!SE.addressBook.grid)
4363 if (hasRelatedBeanId) {
4364 document.getElementById('hasRelatedBean').checked = true;
4366 AddressSearchGridInit();
4367 SE.addressBook.relatedBeanId = relatedBeanId;
4371 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4373 SE.addressBook.relatedBeanId = relatedBeanId;
4374 document.getElementById('hasRelatedBean').checked = true;
4376 if (document.getElementById('hasRelatedBean').checked == true)
4378 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4379 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4381 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4382 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4384 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4385 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4386 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4389 //Remove any lingering rows in the result set table if the module was closed.
4390 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4392 SE.addressBook.populateResulstTableEmailAddresses();
4394 this.contactsDialogue.show();
4397 * Clear all email addresses from result table.
4400 clearAllEmailAddressFieldsFromResultTable: function () {
4401 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4402 //Unhighlight any rows currently selected if the emails were cleared.
4403 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4404 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4407 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4408 * results table. This function is called when the address book is displayed.
4410 populateResulstTableEmailAddresses: function () {
4412 var idx = SE.addressBook.idx;
4413 var emailFields = ['to','cc','bcc'];
4415 for(var k=0;k<emailFields.length;k++)
4417 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4418 var allEmails = document.getElementById(elKey).value;
4422 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4424 for (var i=0; i<formatedEmails.length; i++)
4426 var t_name = formatedEmails[i].name;
4427 var t_emailAddr = formatedEmails[i].email_address;
4428 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4430 t_name = displayEmail = t_emailAddr;
4432 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4433 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4434 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4440 * Checks all entries in the result table against a particular email address, returning true
4441 * if the email address is found, false otherwise.
4443 doesEmailAdddressExistInResultTable: function(emailAddress)
4445 if(trim(emailAddress) == '')
4448 var emailAddressFound = false;
4449 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4450 for (var i=0; i < contacts.length; i++)
4452 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4453 //If we are adding to cc or bcc fields, make them visible.
4454 if(data.email_address == emailAddress)
4456 emailAddressFound = true;
4461 return emailAddressFound;
4464 * Takes all email addresses that the users wishes to add from the address book and populates the To
4465 * fields on the compose tab.
4467 populateEmailAddressFieldsFromResultTable: function()
4469 //Clear the fields first, all email addresses are stored in the address book
4470 var idx = SE.addressBook.idx;
4471 var emailFields = ['to','cc','bcc'];
4472 for(var k=0;k<emailFields.length;k++)
4474 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4475 document.getElementById(elKey).value = "";
4478 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4479 for (var i=0; i < contacts.length; i++)
4481 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4483 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4484 //If we are adding to cc or bcc fields, make them visible.
4485 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4486 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4487 //Construct the target id
4488 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4490 var target = document.getElementById(target_id);
4491 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4494 //Delete all rows from the result set table
4495 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4498 SE.addressBook.contactsDialogue.hide()
4501 * Insert contacts into the result table.
4503 insertContactToResultTable : function(event,address_type) {
4505 var contactsDialogue = SE.addressBook.contactsDialogue;
4506 var contacts = SE.addressBook.grid.getSelectedRows();
4508 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4509 for (var i = 0; i < rows.length; i++)
4511 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4513 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4514 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4515 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4516 rows[i].setData("selected",true);
4519 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4520 for (var i = 0; i < checkBoxes.length; i++) {
4521 checkBoxes[i].checked = false;
4527 insertContactRowToResultTable : function(rowId, addressType) {
4528 var data = SE.addressBook.grid.getRecord(rowId).getData();
4529 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4531 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4532 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4533 if(addressType == null)
4534 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4535 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});
4538 * Remove a row from the gridsResult table.
4540 removeRowFromGridResults : function(rowId,emailAddress)
4542 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4543 for (var i=0; i < contacts.length; i++)
4545 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4546 var data = rec.getData();
4547 if(data.email_address == emailAddress)
4549 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4554 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4557 * Translates between the addressType To|Cc|Bcc labels/keys.
4559 translateAddresType: function(addressType,fromKey)
4561 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4562 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4563 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4564 var mappingObject = {};
4567 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4570 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4571 mappingObject[displayCc] = 'cc';
4572 mappingObject[displayBcc] = 'bcc';
4575 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4581 toggleSearchRowIcon : function(rowId,show)
4585 var idToShow = rowId + '_add_img';
4586 var idToHide = rowId + '_rm_img';
4590 var idToShow = rowId + '_rm_img';
4591 var idToHide = rowId + '_add_img';
4595 Dom.addClass(idToHide, "yui-hidden");
4596 Dom.removeClass(idToShow, "yui-hidden");
4599 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4601 doesGridResultsEntryExist: function(emailAddrs)
4604 var contactExists = false;
4605 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4606 for (var i=0; i < contacts.length; i++)
4608 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4609 if(data.email_address == emailAddrs)
4611 contactExists = true;
4615 return contactExists;
4619 * adds an email address to a string, but first checks if it exists
4620 * @param string concat The string we are appending email addresses to
4621 * @param string addr Email address to add
4624 smartAddEmailAddressToComposeField : function(concat, addr) {
4625 var re = new RegExp(addr);
4627 if(!concat.match(re)) {
4629 concat += "; " + addr;
4638 //// END ADDRESS BOOK
4639 ///////////////////////////////////////////////////////////////////////////////
4643 ///////////////////////////////////////////////////////////////////////////////
4646 * Auto-complete object
4650 delimChar : [";", ","],
4654 prehighlightClassName : "yui-ac-prehighlight",
4657 instances : new Array(),
4660 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4661 * @param object Contact from AddressBook
4664 getPrimaryAddress : function(contact) {
4665 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4667 for(var eIndex in contact.email) {
4668 address = contact.email[eIndex].email_address;
4669 if(contact.email[eIndex].primary_address == 1) {
4670 return contact.email[eIndex].email_address;
4678 * initializes autocomplete widgets for a given compose view
4681 init : function(idx) {
4682 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4683 "queryMatchContains" : false,
4684 "queryMatchSubset" : true
4687 this.instances[idx] = {
4694 // instantiate the autoComplete widgets
4695 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4696 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4697 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4699 // enable hiding of interfering textareas
4700 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4701 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4702 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4704 // enable reshowing of hidden textareas
4705 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4706 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4707 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4709 // enable refreshes of contact lists
4710 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4711 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4712 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4715 refreshDataSource : function(sType, aArgs) {
4716 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4718 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4720 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4721 idx = textBoxId.substr(9);
4723 idx = textBoxId.substr(10);
4726 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4727 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4728 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4732 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4734 returnDataSource : function(contacts) {
4735 var ret = new Array();
4736 for(var id in contacts) {
4737 if (contacts[id].name) {
4738 var primary = this.getPrimaryAddress(contacts[id]);
4740 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4741 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4743 for(var emailIndex in contacts[id].email) {
4744 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4753 * Hides address textareas to prevent autocomplete dropdown from being obscured
4755 toggleTextareaHide : function(sType, aArgs) {
4756 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4760 if(textBoxId.indexOf("addressTO") > -1) {
4762 } else if(textBoxId.indexOf("addressCC") > -1) {
4765 idx = textBoxId.substr(9);
4767 // follow through if not BCC
4769 var cc = document.getElementById("addressCC" + idx);
4770 var bcc = document.getElementById("addressBCC" + idx);
4774 cc.style.visibility = 'hidden';
4776 bcc.style.visibility = 'hidden';
4783 * Redisplays the textareas after an address is commited
4785 toggleTextareaShow : function(sType, aArgs) {
4786 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4790 if(textBoxId.indexOf("addressTO") > -1) {
4792 } else if(textBoxId.indexOf("addressCC") > -1) {
4795 idx = textBoxId.substr(9);
4797 // follow through if not BCC
4799 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4800 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4805 //// END AUTOCOMPLETE
4806 ///////////////////////////////////////////////////////////////////////////////
4808 ///////////////////////////////////////////////////////////////////////////////
4811 * expands the options sidebar
4813 SE.composeLayout = {
4814 currentInstanceId : 0,
4817 outboundAccountErrors : null,
4818 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4820 showAddressDetails : function(e) {
4821 var linkElement = document.getElementById("More"+e.id);
4822 var spanElement = document.getElementById("Detail"+e.id);
4823 var emailAddressList = e.value;
4824 if(e.value.length > 96)
4826 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4827 var displayArray = [];
4828 for (var i=0; i<resultArray.length; i++)
4830 var t_name = resultArray[i].name;
4831 var t_emailAddr = resultArray[i].email_address;
4833 displayArray.push('<br/><' + t_emailAddr + '>');
4835 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4838 var result = displayArray.join('<br/>');
4840 linkElement.style.display = "inline";
4841 linkElement.style.height="10px";
4842 linkElement.style.overflow="visible";
4843 spanElement.innerHTML = result;
4846 linkElement.style.display = "none";
4851 * Given a string of email address, return an array containing the name portion (if available)
4852 * and email portion.
4854 _getEmailArrayFromString : function (emailAddressList){
4857 while ((results = reg.exec(emailAddressList)) != null)
4859 orignial = results[0];
4860 parsedResult = results[0].replace(';', ':::::');
4861 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4865 while ((results = reg.exec(emailAddressList)) != null)
4867 orignial = results[0];
4868 parsedResult = results[0].replace(',', ':::::');
4869 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4871 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4872 var emailArr = emailAddressList.split(":::::");
4873 var resultsArray = [];
4875 for (var i=0; i<emailArr.length; i++)
4877 var rposition = emailArr[i].indexOf('<');
4878 var lposition = emailArr[i].indexOf('>');
4880 if(trim(emailArr[i]) != '')
4882 if(rposition != -1 && lposition != -1)
4884 var t_name = emailArr[i].substr(0, rposition-1);
4885 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4886 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4890 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4894 return resultsArray;
4896 ///////////////////////////////////////////////////////////////////////////
4899 * Prepare bucket DIV and yui-ext tab panels
4901 _0_yui : function() {
4902 var idx = this.currentInstanceId;
4904 var composeTab = new YAHOO.SUGAR.ClosableTab({
4905 label: mod_strings.LNK_NEW_SEND_EMAIL,
4907 content : "<div id='htmleditordiv" + idx + "'/>",
4908 id : "composeTab" + idx,
4909 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4912 SE.innerLayout.addTab(composeTab);
4914 // get template engine with template
4915 if (!SE.composeLayout.composeTemplate) {
4916 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4919 // create Tab inner layout
4920 var composePanel = this.getComposeLayout();
4921 composePanel.getUnitByPosition("right").collapse();
4922 composePanel.autoSize();
4926 * Generate the quick compose layout
4927 * @method getQuickComposeLayout
4928 * @param {Pannel} parentPanel Parent pannel
4929 * @param {Object} o Options
4932 getQuickComposeLayout : function (parentPanel,o) {
4933 var idx = SE.composeLayout.currentInstanceId;
4935 //Before rendering the parent pannel we need to initalize the grid layout
4936 parentPanel.beforeRenderEvent.subscribe(function() {
4938 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4939 SE.composeLayout._createComposeLayout(idx);
4940 SE.composeLayout[idx].set('height', 350);
4941 SE.composeLayout[idx].render();
4945 //Wait until the Compose Layout has rendered, then add the
4946 //options tab and perform the tiny initialization.
4947 parentPanel.renderEvent.subscribe(function() {
4949 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4950 SE.composeLayout._initComposeOptionTabs(idx);
4951 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4952 //Initialize tinyMCE
4953 SE.composeLayout._1_tiny(false);
4955 //Init templates and address book
4956 SE.composeLayout._2_final();
4958 SE.composeLayout.quickCreateComposePackage(o);
4963 //Check if we have the div override for the shortcut bar
4964 if(typeof o.menu_id != 'undefined') {
4965 parentPanel.render(o.menu_id);
4967 parentPanel.render(document.body);
4970 return SE.composeLayout[idx];
4973 * Fill in all fields into the quick compose layout.
4974 * @method quickCreateComposePackage
4975 * @param {Object} o Options
4978 quickCreateComposePackage: function(o)
4980 //If we have a compose package fill in defaults.
4981 if (typeof(o.composePackage) != 'undefined')
4983 composePackage = o.composePackage; //Set the compose data object
4984 //Hijack this method called by composePackage as it's not need for quick creates.
4985 SE.composeLayout.c0_composeNewEmail = function(){};
4986 SE.composeLayout.composePackage(); //Fill in defaults.
4989 getComposeLayout : function() {
4990 var idx = SE.composeLayout.currentInstanceId;
4992 this._createComposeLayout(idx);
4993 SE.composeLayout[idx].render();
4994 this._initComposeOptionTabs(idx);
4996 return SE.composeLayout[idx];
5000 * Create the layout manager for the compose window.
5002 _createComposeLayout : function(idx)
5004 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
5005 parent: SE.complexLayout,
5015 SE.composeLayout.composeTemplate.exec({
5016 'app_strings':app_strings,
5017 'mod_strings':mod_strings,
5019 'linkbeans_options' : linkBeans,
5020 'idx' : SE.composeLayout.currentInstanceId
5031 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5034 header: app_strings.LBL_EMAIL_OPTIONS
5040 * Create compose tab which will populate the 'right' container in the compose window.
5042 _initComposeOptionTabs : function(idx)
5044 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5045 var tab = new YAHOO.widget.Tab({
5046 label: app_strings.LBL_EMAIL_ATTACHMENT,
5048 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5049 id : "divAttachments" + idx,
5053 tab.layout = SE.composeLayout[idx];
5055 tab.on("activeChange", function(o){
5057 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5063 tab = new YAHOO.widget.Tab({
5064 label: app_strings.LBL_EMAIL_OPTIONS,
5066 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5067 id : "divOptions" + idx,
5071 tab.layout = SE.composeLayout[idx];
5072 tab.on("activeChange", function(o){
5074 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5079 SE.composeLayout[idx].autoSize = function() {
5080 var pEl = this.get("element").parentNode.parentNode.parentNode;
5081 this.set("height", pEl.clientHeight-30);
5085 SE.composeLayout[idx].rightTabs = cTabs;
5087 isParentTypeValid : function(idx) {
5088 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5089 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5090 if (trim(parentTypeValue) == ""){
5091 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5097 isParentTypeAndNameValid : function(idx) {
5098 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5099 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5100 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5101 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5102 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5103 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5109 callopenpopupForEmail2 : function(idx,options) {
5111 var formName = 'emailCompose' + idx;
5113 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5114 formName = options.form_name;
5116 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5117 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5118 if (!SE.composeLayout.isParentTypeValid(idx)) {
5121 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5123 call_back_function:"SE.composeLayout.popupAddEmail",
5125 field_to_name_array:{
5126 id:'data_parent_id' + idx,
5127 name:'data_parent_name' + idx,
5132 popupAddEmail : function(o)
5134 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5135 var data = o.name_to_value_array;
5136 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5137 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5139 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5140 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5147 _1_tiny : function(isReplyForward) {
5148 var idx = SE.composeLayout.currentInstanceId;
5149 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5150 SE.tinyInstances[elId] = { };
5151 SE.tinyInstances[elId].ready = false;
5153 if (!SUGAR.util.isTouchScreen()) {
5154 var t = tinyMCE.getInstanceById(elId);
5156 if(typeof(t) == 'undefined') {
5157 if (!SUGAR.util.isTouchScreen()) {
5158 tinyMCE.execCommand('mceAddControl', false, elId);
5160 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5161 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
5166 resizeEditorSetSignature : function(idx,setSignature)
5168 var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5170 if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
5171 setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+isReplyForward+"');",500);
5175 SE.composeLayout.resizeEditor(idx);
5177 setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
5182 resizeEditor : function(idx)
5184 var cof = Dom.get('composeOverFrame' + idx);
5185 var head = Dom.get('composeHeaderTable' + idx);
5186 var targetHeight = cof.clientHeight - head.clientHeight;
5187 var instance = SE.util.getTiny('htmleditor' + idx);
5190 var parentEl = Dom.get(instance.editorId + '_parent');
5191 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5192 var contentEl = instance.contentAreaContainer;
5193 var iFrame = contentEl.firstChild;
5194 var tinMceToolbarOffset = 18;
5195 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5198 setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
5203 * Initializes d&d, auto-complete, email templates
5205 _2_final : function() {
5206 var idx = SE.composeLayout.currentInstanceId;
5208 if(this.emailTemplates) {
5209 this.setComposeOptions(idx);
5211 //populate email template cache
5212 AjaxObject.target = '';
5213 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5216 // handle drop targets for addressBook
5217 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5218 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5219 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5220 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5222 // auto-complete setup
5223 SE.autoComplete.init(idx);
5226 document.getElementById("addressTO" + idx).focus();
5230 * hide tinyMCE tool bar if send email as plaintext is checked
5232 renderTinyMCEToolBar : function (idx, hide) {
5234 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5236 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5240 c1_composeEmail : function(isReplyForward, retry) {
5244 if (!SUGAR.util.isTouchScreen() && (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined')){
5245 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5247 this._1_tiny(isReplyForward);
5250 if(isReplyForward) {
5251 this.replyForwardEmailStage2();
5257 * takes draft info and prepopulates
5259 c0_composeDraft : function() {
5260 this.getNewInstanceId();
5262 document.getElementById('_blank').innerHTML = '';
5263 var idx = SE.composeLayout.currentInstanceId;
5264 SE.composeLayout.draftObject = new Object();
5265 SE.composeLayout.draftObject.id = idx;
5266 SE.composeLayout.draftObject.isDraft = true;
5267 SE.composeLayout.currentInstanceId = idx;
5268 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5269 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5270 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5272 SE.composeLayout._0_yui();
5273 SE.composeLayout._1_tiny(true);
5276 SE.composeLayout._2_final();
5278 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5279 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5283 * Strip & Prep editor hidden fields
5285 c0_composeNewEmail : function() {
5286 this.getNewInstanceId();
5287 this.c1_composeEmail(false);
5291 * Sends async request to get the compose view.
5292 * Requests come from "reply" or "forwards"
5294 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5295 SE.composeLayout.replyForwardObj = new Object();
5296 SE.composeLayout.replyForwardObj.ieId = ieId;
5297 SE.composeLayout.replyForwardObj.uid = uid;
5298 SE.composeLayout.replyForwardObj.mbox = mbox;
5299 SE.composeLayout.replyForwardObj.type = type;
5301 if(mbox == 'sugar::Emails') {
5302 SE.composeLayout.replyForwardObj.sugarEmail = true;
5305 SE.composeLayout.getNewInstanceId();
5306 SE.composeLayout.c1_composeEmail(true);
5308 //// END COMPOSE FLOW
5309 ///////////////////////////////////////////////////////////////////////////
5312 * Called when a contact, email, or mailinglist is dropped
5313 * into one of the compose fields.
5315 handleDrop : function (source, event, data, target) {
5318 target = event.getTarget();
5320 data.nodes = [data.nodes];
5324 target = document.getElementById(target);
5328 if (target.id.indexOf('address') > -1) {
5329 // dropped onto email to/cc/bcc field
5330 for(var i in nodes) {
5331 var node = nodes[i].getData();
5333 if (node[1].indexOf('contact') > -1) {
5334 email = SE.addressBook.getFormattedAddress(node[0]);
5335 } else if (node[1].indexOf('address-email') > -1){
5336 email = node[3].replace(/ /gi, '');
5337 email = email.replace('<', '<').replace('>', '>');
5338 var tr = source.getTrEl(nodes[i]);
5339 while (tr && !Dom.hasClass(tr, "address-contact")) {
5340 tr = source.getPreviousTrEl(tr);
5342 var CID = source.getRecord(tr).getData()[0];
5343 var o = SE.addressBook._contactCache[CID];
5344 var name = new String(o.name);
5345 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5346 email = finalName + email;
5348 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5354 /*/////////////////////////////////////////////////////////////////////////////
5355 /// EMAIL TEMPLATE CODE
5357 applyEmailTemplate : function (idx, id) {
5360 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5361 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5362 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5365 var to_addr = document.getElementById('addressTO'+idx);
5366 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
5368 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5369 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5372 // id is selected index of email template drop-down
5373 if(id == '' || id == "0") {
5374 YAHOO.SUGAR.MessageBox.show({
5379 if(btn=='no'){return;};
5380 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5387 YAHOO.SUGAR.MessageBox.show({
5392 if(btn=='no'){return;};
5393 SUGAR.email2.composeLayout.processResult(idx, id);},
5399 processNoneResult : function(idx, id) {
5400 var tiny = SE.util.getTiny('htmleditor' + idx);
5401 var tinyHTML = tiny.getContent();
5402 var openTag = '<div><span><span>';
5403 var htmllow = tinyHTML.toLowerCase();
5404 var start = htmllow.indexOf(openTag);
5406 tinyHTML = tinyHTML.substr(start);
5407 tiny.setContent(tinyHTML);
5409 tiny.setContent('');
5413 processResult : function(idx , id){
5414 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5416 // get attachments if any
5417 AjaxObject.target = '';
5418 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5421 appendEmailTemplateJSON : function() {
5422 var idx = SE.composeLayout.currentInstanceId; // post increment
5424 // query based on template, contact_id0,related_to
5425 //jchi 09/10/2008 refix #7743
5426 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5427 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5430 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,'"');
5432 // cn: bug 14361 - text-only templates don't fill compose screen
5434 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/>");
5437 var tiny = SE.util.getTiny('htmleditor' + idx);
5438 var tinyHTML = tiny.getContent();
5439 var openTag = '<div><span><span>';
5440 var closeTag = '</span></span></div>';
5441 var htmllow = tinyHTML.toLowerCase();
5442 var start = htmllow.indexOf(openTag);
5444 var htmlPart2 = tinyHTML.substr(start);
5445 tinyHTML = text + htmlPart2;
5446 tiny.setContent(tinyHTML);
5448 tiny.setContent(text);
5453 * Writes out the signature in the email editor
5455 setSignature : function(idx) {
5458 var hide = document.getElementById('setEditor' + idx).checked;
5459 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5460 //wait for signatures to load before trying to set them
5461 if (!SE.composeLayout.signatures) {
5462 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5467 var sel = document.getElementById('signatures' + idx);
5469 var sel = document.getElementById('signature_id');
5470 idx = SE.tinyInstances.currentHtmleditor;
5473 //Ensure that the tinyMCE html has been rendered.
5474 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5475 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5482 signature = sel.options[sel.selectedIndex].value;
5487 var openTag = '<div><span><span>';
5488 var closeTag = '</span></span></div>';
5489 var t = tinyMCE.getInstanceById('htmleditor' + idx);
5491 if(typeof(t) != 'undefined')
5493 t.contentDocument = t.contentWindow.document;
5494 var html = t.getContent();
5501 var htmllow = html.toLowerCase();
5502 var start = htmllow.indexOf(openTag);
5503 var end = htmllow.indexOf(closeTag) + closeTag.length;
5505 // selected "none" - remove signature from email
5506 if(signature == '') {
5508 var htmlPart1 = html.substr(0, start);
5509 var htmlPart2 = html.substr(end, html.length);
5511 html = htmlPart1 + htmlPart2;
5514 SE.signatures.lastAttemptedLoad = '';
5518 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5519 SE.signatures.lastAttemptedLoad = '';
5521 SE.signatures.lastAttemptedLoad = signature;
5523 if(typeof(SE.signatures[signature]) == 'undefined') {
5525 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5526 SE.signatures.targetInstance = (idx) ? idx : "";
5527 AjaxObject.target = '';
5528 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5530 var newSignature = this.prepareSignature(SE.signatures[signature]);
5532 // clear out old signature
5533 if(SE.signatures.lastAttemptedLoad && start > -1) {
5534 var htmlPart1 = html.substr(0, start);
5535 var htmlPart2 = html.substr(end, html.length);
5537 html = htmlPart1 + htmlPart2;
5541 start = html.indexOf('<div><hr></div>');
5542 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5543 var htmlPart1 = html.substr(0, start);
5544 var htmlPart2 = html.substr(start, html.length);
5545 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5546 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5547 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5549 var newHtml = html + openTag + newSignature + closeTag;
5551 //tinyMCE.setContent(newHtml);
5552 t.setContent(newHtml);
5556 prepareSignature : function(str) {
5557 var signature = new String(str);
5559 signature = signature.replace(/</gi, '<');
5560 signature = signature.replace(/>/gi, '>');
5566 showAttachmentPanel : function(idx) {
5567 var east = SE.composeLayout[idx].getUnitByPosition("right");
5568 var tabs = SE.composeLayout[idx].rightTabs;
5570 tabs.set("activeTab", tabs.getTab(0));
5574 * expands sidebar and displays options panel
5576 showOptionsPanel : function(idx) {
5577 var east = SE.composeLayout[idx].getUnitByPosition("right");
5578 var tabs = SE.composeLayout[idx].rightTabs;
5580 tabs.set("activeTab", tabs.getTab(1));
5584 * Selects the Contacts tab
5586 showContactsPanel : function() {
5587 SE.complexLayout.regions.west.showPanel("contactsTab");
5591 * Generates fields for Select Document
5593 addDocumentField : function(idx) {
5594 var basket = document.getElementById('addedDocuments' + idx);
5596 var index = (basket.childNodes.length / 7) - 1;
5603 var test = document.getElementById('documentId' + idx + index);
5605 while(test != null) {
5607 test = document.getElementById('documentId' + idx + index);
5610 var documentCup = document.createElement("div");
5611 documentCup.id = 'documentCup' + idx + index;
5612 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5613 // document id field
5614 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5615 // document name field
5616 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5618 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5619 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5620 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5622 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5623 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5624 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5627 basket.appendChild(documentCup);
5628 //basket.innerHTML += out;
5633 * Makes async call to save a draft of the email
5634 * @param int Instance index
5636 saveDraft : function(tinyInstance) {
5637 this.sendEmail(tinyInstance, true);
5640 selectDocument : function(target) {
5641 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5642 windowName = 'selectDocument';
5643 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5645 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5647 // put the focus on the popup if the browser supports the focus() method
5653 * Modal popup for file attachment dialogue
5655 addFileField : function() {
5656 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5657 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5661 constraintoviewport: true,
5663 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5664 fn:function(){SE.addFileDialog.hide();}
5667 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5668 SE.addFileDialog.render();
5669 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5671 Dom.removeClass("addFileDialog", "yui-hidden");
5673 SE.addFileDialog.show();
5677 * Async upload of file to temp dir
5679 uploadAttachment : function() {
5680 if(document.getElementById('email_attachment').value != "") {
5681 var formObject = document.getElementById('uploadAttachment');
5682 YAHOO.util.Connect.setForm(formObject, true, true);
5683 AjaxObject.target = '';
5684 AjaxObject.startRequest(callbackUploadAttachment, null);
5686 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5691 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5692 * @param string target in focus compose layout
5694 setDocument : function(idx, target, documentId, documentName, docRevId) {
5695 // fields are named/id'd [fieldName][instanceId][index]
5696 var addedDocs = document.getElementById("addedDocuments" + idx);
5697 var docId = document.getElementById('documentId' + idx + target);
5698 var docName = document.getElementById('documentName' + idx + target);
5699 var docRevisionId = document.getElementById('document' + idx + target);
5700 docId.value = documentId;
5701 docName.value = documentName;
5702 docRevisionId.value = docRevId;
5706 * Removes the bucket div containing the document input fields
5708 deleteDocumentField : function(documentCup) {
5709 var f0 = document.getElementById(documentCup);
5710 f0.parentNode.removeChild(f0);
5714 * Removes a Template Attachment field
5718 deleteTemplateAttachmentField : function(idx, index) {
5719 // create not-in-array values for removal filtering
5720 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5726 r += document.getElementById('templateAttachmentId' + idx + index).value;
5727 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5729 var target = 'templateAttachmentCup' + idx + index;
5730 d = document.getElementById(target);
5731 d.parentNode.removeChild(d);
5735 * Async removal of uploaded temp file
5736 * @param string index Should be a concatenation of idx and index
5739 deleteUploadAttachment : function(index, file) {
5740 var d = document.getElementById('email_attachment_bucket' + index);
5741 d.parentNode.removeChild(d);
5743 // make async call to delete cached file
5744 AjaxObject.target = '';
5745 AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5749 * Attaches files coming from Email Templates
5751 addTemplateAttachmentField : function(idx) {
5753 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5755 var basket = document.getElementById('addedTemplateAttachments' + idx);
5758 var index = basket.childNodes.length;
5765 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5767 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5768 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5769 idx + "\",\"" + index + "\");'/>" +
5771 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5772 // templateAttachment field
5773 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5775 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5777 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5778 "<br id='br" + index + "></br>" +
5779 "<br id='brdoc" + index + "></br>" +
5781 basket.innerHTML = basket.innerHTML + out;
5787 * Sends one email via async call
5788 * @param int idx Editor instance ID
5789 * @param bool isDraft
5791 sendEmail : function(idx, isDraft) {
5793 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5794 var obAccountID = document.getElementById('addressFrom' + idx).value;
5796 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5798 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5803 var form = document.getElementById('emailCompose' + idx);
5804 var composeOptionsFormName = "composeOptionsForm" + idx;
5807 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5808 if (t != null || typeof(t) != "undefined") {
5809 var html = t.getContent();
5811 var html = "<p>" + document.getElementById('htmleditor' + idx).value + "</p>";
5814 var subj = document.getElementById('emailSubject' + idx).value;
5815 var to = trim(document.getElementById('addressTO' + idx).value);
5816 var cc = trim(document.getElementById('addressCC' + idx).value);
5817 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5818 var email_id = document.getElementById('email_id' + idx).value;
5819 var composeType = document.getElementById('composeType').value;
5820 var parent_type = document.getElementById("parent_type").value;
5821 var parent_id = document.getElementById("parent_id").value;
5823 var el_uid = document.getElementById("uid");
5824 var uid = (el_uid == null) ? '' : el_uid.value;
5826 var el_ieId = document.getElementById("ieId");
5827 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5829 var el_mbox = document.getElementById("mbox");
5830 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5832 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5833 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5837 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5840 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5841 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5842 parent_id = parentIdValue;
5843 parent_type = parentTypeValue;
5845 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5846 // baseline viability check
5848 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5849 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5851 } else if(subj == '' && !isDraft) {
5852 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5855 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5857 } else if(html == '' && !isDraft) {
5858 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5863 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5864 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5865 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5866 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5867 html = html.replace(/</ig, "sugarLessThan");
5868 html = html.replace(/>/ig, "sugarGreaterThan");
5870 form.sendDescription.value = html;
5871 form.sendSubject.value = subj;
5872 form.sendTo.value = to;
5873 form.sendCc.value = cc;
5874 form.sendBcc.value = bcc;
5875 form.email_id.value = email_id;
5876 form.composeType.value = composeType;
5877 form.composeLayoutId.value = 'composeLayout' + idx;
5878 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5879 form.saveToSugar.value = 1;
5880 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5881 form.parent_type.value = parent_type;
5882 form.parent_id.value = parent_id;
5883 form.uid.value = uid;
5884 form.ieId.value = ieId;
5885 form.mbox.value = mbox;
5887 // email attachments
5888 var addedFiles = document.getElementById('addedFiles' + idx);
5890 for(i=0; i<addedFiles.childNodes.length; i++) {
5891 var bucket = addedFiles.childNodes[i];
5893 for(j=0; j<bucket.childNodes.length; j++) {
5894 var node = bucket.childNodes[j];
5895 var nName = new String(node.name);
5897 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5898 if(form.attachments.value != '') {
5899 form.attachments.value += "::";
5901 form.attachments.value += node.value;
5908 var addedDocs = document.getElementById('addedDocuments' + idx);
5910 for(i=0; i<addedDocs.childNodes.length; i++) {
5911 var cNode = addedDocs.childNodes[i];
5912 for(j=0; j<cNode.childNodes.length; j++) {
5913 var node = cNode.childNodes[j];
5914 var nName = new String(node.name);
5915 if(node.type == 'hidden' && nName.match(/documentId/)) {
5916 if(form.documents.value != '') {
5917 form.documents.value += "::";
5919 form.documents.value += node.value;
5925 // template attachments
5926 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5927 if(addedTemplateAttachments) {
5928 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5929 var cNode = addedTemplateAttachments.childNodes[i];
5930 for(j=0; j<cNode.childNodes.length; j++) {
5931 var node = cNode.childNodes[j];
5932 var nName = new String(node.name);
5933 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5934 if(form.templateAttachments.value != "") {
5935 form.templateAttachments.value += "::";
5937 form.templateAttachments.value += node.value;
5943 // remove attachments
5944 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5946 YAHOO.util.Connect.setForm(form);
5948 AjaxObject.target = 'frameFlex';
5950 // sending a draft email
5951 if(!isDraft && in_draft) {
5953 SE.listView.removeRowByUid(email_id);
5956 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5957 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5959 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5963 * Handles clicking the email address link from a given view
5965 composePackage : function() {
5966 if(composePackage != null) {
5967 SE.composeLayout.c0_composeNewEmail();
5970 if(composePackage.to_email_addrs) {
5971 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5973 if (composePackage.subject != null && composePackage.subject.length > 0) {
5974 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5977 //If no parent fields are set in the composePackage, ensure they are cleared.
5978 var parentFields = ['parent_type','parent_name','parent_id'];
5979 for(var i=0;i<parentFields.length;i++)
5981 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5982 composePackage[parentFields[i]] = "";
5985 document.getElementById("parent_type").value = composePackage.parent_type;
5986 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5987 document.getElementById("parent_id").value = composePackage.parent_id;
5988 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5989 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5991 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5992 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5994 if (composePackage.body != null && composePackage.body.length > 0) {
5995 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5996 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5997 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5999 if (composePackage.attachments != null) {
6000 SE.composeLayout.loadAttachments(composePackage.attachments);
6003 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
6004 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
6005 SE.util.emptySelectOptions(addressFrom);
6006 var fromAccountOpts = composePackage.fromAccounts.data;
6007 for(i=0; i<fromAccountOpts.length; i++) {
6008 var key = fromAccountOpts[i].value;
6009 var display = fromAccountOpts[i].text;
6010 var opt = new Option(display, key);
6011 if (fromAccountOpts[i].selected) {
6012 opt.selected = true;
6014 addressFrom.options.add(opt);
6021 setContentOnThisTiny : function() {
6022 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6023 var tinyHTML = tiny.getContent();
6024 composePackage.body = decodeURI(encodeURI(composePackage.body));
6025 // cn: bug 14361 - text-only templates don't fill compose screen
6026 if(composePackage.body == '') {
6027 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
6029 //Flag determines if we should clear the tiny contents or just append
6030 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
6031 SE.composeLayout.tinyHTML = '';
6033 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
6035 tiny.setContent(SE.composeLayout.tinyHTML);
6036 //Indicate that the contents has been loaded successfully.
6037 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
6040 * Confirms closure of a compose screen if "x" is clicked
6042 confirmClose : function(panel) {
6043 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6044 SE.composeLayout.closeCompose(panel.id);
6052 * forces close of a compose screen
6054 forceCloseCompose : function(id) {
6055 SE.composeLayout.closeCompose(id);
6057 // handle flow back to originating view
6058 if(composePackage) {
6059 // check if it's a module we need to return to
6060 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6061 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6062 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6063 window.location = url;
6070 * closes the editor that just sent email
6071 * @param string id ID of composeLayout tab
6073 closeCompose : function(id) {
6074 // destroy tinyMCE instance
6075 var idx = id.substr(13, id.length);
6076 var instanceId = "htmleditor" + idx;
6077 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6079 // nullify DOM and namespace values.
6081 SE.composeLayout[idx] = null;
6082 SE.tinyInstances[instanceId] = null;
6083 var tabsArray = SE.innerLayout.get("tabs");
6084 for (i = 0 ; i < tabsArray.length ; i++) {
6085 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6086 tabsArray[i].close();
6090 //SE.innerLayout.getTab(idx).close();
6094 * Enable the quick search for the compose relate field or search tab
6096 enableQuickSearchRelate: function(idx,overides){
6098 if(typeof overides != 'undefined')
6100 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6101 var newModule = document.getElementById(newModuleID).value;
6102 var formName = overides['formName'];
6103 var fieldName = overides['fieldName'];
6104 var fieldId = overides['fieldId'];
6105 var fullName = formName + "_" + fieldName;
6106 var postBlurFunction = null;
6110 var newModule = document.getElementById('data_parent_type'+idx).value;
6111 var formName = 'emailCompose'+idx;
6112 var fieldName = 'data_parent_name'+idx;
6113 var fieldId = 'data_parent_id'+idx;
6114 var fullName = formName + "_" + fieldName;
6115 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6118 if(typeof sqs_objects == 'undefined')
6119 window['sqs_objects'] = new Array;
6121 window['sqs_objects'][fullName] = {
6124 modules:[newModule],
6126 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6127 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6128 post_onblur_function: postBlurFunction,
6129 order:"name","limit":"30","no_match_text":"No Match"};
6132 if(typeof QSProcessedFieldsArray != 'undefined')
6133 QSProcessedFieldsArray[fullName] = false;
6134 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6135 QSFieldsArray[fullName].destroy();
6136 delete QSFieldsArray[fullName];
6138 if (Dom.get(fullName + "_results")) {
6139 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6145 qsAddAddress : function(o) {
6146 if (o.name != "" && o.email1 != "")
6148 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6149 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6153 * Returns a new instance ID, 0-index
6155 getNewInstanceId : function() {
6156 this.currentInstanceId = this.currentInstanceId + 1;
6157 return this.currentInstanceId;
6161 * 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.
6163 loadAttachments : function(result) {
6164 var idx = SE.composeLayout.currentInstanceId;
6166 if(typeof(result) == 'object') {
6167 //jchi #20680. Clean the former template attachments;
6168 var basket = document.getElementById('addedTemplateAttachments' + idx);
6169 if(basket.innerHTML != ''){
6170 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6172 basket.innerHTML = '';
6177 if(typeof result[i] == 'object') {
6178 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6179 var bean = result[i];
6180 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6181 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6188 * fills drop-down values for email templates and signatures
6190 setComposeOptions : function(idx) {
6191 // send from accounts
6192 var addressFrom = document.getElementById('addressFrom' + idx);
6194 if (addressFrom.options.length <= 0) {
6195 SE.util.emptySelectOptions(addressFrom);
6196 var fromAccountOpts = SE.composeLayout.fromAccounts;
6197 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6198 var key = fromAccountOpts[id].value;
6199 var display = fromAccountOpts[id].text;
6200 var is_default = false;
6201 if(key == SUGAR.default_inbound_accnt_id)
6203 var opt = new Option(display, key);
6204 addressFrom.options.add(opt);
6205 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6210 var et = document.getElementById('email_template' + idx);
6211 SE.util.emptySelectOptions(et);
6213 for(var key in this.emailTemplates) { // iterate through assoc array
6214 var display = this.emailTemplates[key];
6215 var opt = new Option(display, key);
6216 et.options.add(opt);
6220 var sigs = document.getElementById('signatures' + idx);
6221 SE.util.emptySelectOptions(sigs);
6223 for(var key in this.signatures) { // iterate through assoc array
6224 var display = this.signatures[key];
6225 var opt = new Option(display, key);
6227 if(key == SE.userPrefs.signatures.signature_default) {
6228 opt.selected = true;
6231 sigs.options.add(opt);
6234 // html/plain email?
6235 var htmlEmail = document.getElementById('setEditor' + idx);
6236 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6237 htmlEmail.checked = true;
6239 htmlEmail.checked = false;
6242 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6246 * After compose screen is rendered, async call to get email body from Sugar
6248 replyForwardEmailStage2 : function() {
6249 SE.util.clearHiddenFieldValues('emailUIForm');
6250 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6252 var ieId = SE.composeLayout.replyForwardObj.ieId;
6253 var uid = SE.composeLayout.replyForwardObj.uid;
6254 var mbox = SE.composeLayout.replyForwardObj.mbox;
6255 var type = SE.composeLayout.replyForwardObj.type;
6256 var idx = SE.composeLayout.currentInstanceId;
6258 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6260 document.getElementById('emailSubject' + idx).value = type;
6261 document.getElementById('emailUIAction').value = 'composeEmail';
6262 document.getElementById('composeType').value = type;
6263 document.getElementById('ieId').value = ieId;
6264 document.getElementById('uid').value = uid;
6265 document.getElementById('mbox').value = mbox;
6266 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6267 var formObject = document.getElementById('emailUIForm');
6268 YAHOO.util.Connect.setForm(formObject);
6270 var sendType = type;
6271 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6275 * Show the hidden cc or bcc fields
6277 showHiddenAddress: function(addrType,idx){
6279 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6280 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6281 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6282 this[addrType+'Hidden'+idx] = false;
6284 //After bcc or cc is added, move options below last addr field
6285 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6287 //If both cc and bcc hidden, remove the empty row containing text.
6288 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6289 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6290 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6292 // SE.composeLayout.resizeEditor(idx);
6295 * Hide the cc and bcc fields if they were shown.
6297 hideHiddenAddresses: function(idx){
6299 var addrTypes = ['cc','bcc'];
6300 for(var i = 0;i<addrTypes.length;i++)
6302 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6303 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6304 this[addrTypes[i] + 'Hidden'+idx] = true
6307 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6308 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6309 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6313 //// END SE.composeLayout
6314 ///////////////////////////////////////////////////////////////////////////////
6315 ///////////////////////////////////////////////////////////////////////////////
6319 * Cleans serialized UID lists of duplicates
6323 cleanUids : function(str) {
6324 var seen = new Object();
6326 var arr = new String(str).split(",");
6328 for(var i=0; i<arr.length; i++) {
6333 clean += (clean != "") ? "," : "";
6335 seen[arr[i]] = true;
6342 * Clears hidden field values
6343 * @param string id ID of form element to clear
6345 clearHiddenFieldValues : function(id) {
6346 var form = document.getElementById(id);
6348 for(i=0; i<form.elements.length; i++) {
6349 if(form.elements[i].type == 'hidden') {
6350 var e = form.elements[i];
6351 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6359 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6361 emptySelectOptions : function(el) {
6363 for(i=el.childNodes.length - 1; i >= 0; i--) {
6364 if(el.childNodes[i]) {
6365 el.removeChild(el.childNodes[i]);
6372 * Returns the MBOX path in the manner php_imap expects:
6373 * ie: INBOX.DEBUG.test
6374 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6376 generateMboxPath : function(str) {
6377 var ex = str.split("::");
6379 /* we have a serialized MBOX path */
6383 for(var i=0; i<ex.length; i++) {
6384 if(ex[i] == 'INBOX') {
6396 /* we have a Sugar folder GUID - do nothing */
6404 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6405 * @param HTMLElement el
6406 * @return string GUID of found element or empty on failure
6408 getGuidFromElement : function(el) {
6414 for(var i=0; i<iterations; i++) {
6416 if(el.id.match(SE.reGUID)) {
6428 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6431 getPanelId : function() {
6432 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6436 * wrapper to handle weirdness with IE
6437 * @param string instanceId
6438 * @return tinyMCE Controller object
6440 getTiny : function(instanceId) {
6441 if(instanceId == '') {
6445 var t = tinyMCE.getInstanceById(instanceId);
6449 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6455 * Simple check for MSIE browser
6459 var nav = new String(navigator.appVersion);
6460 if(nav.match(/MSIE/)) {
6467 * Recursively removes an element from the DOM
6468 * @param HTMLElement
6470 removeElementRecursive : function(el) {
6471 this.emptySelectOptions(el);
6478 sleep : function(secs) {
6479 setTimeout("void(0);", secs);
6483 * Converts a <select> element to an Ext.form.combobox
6485 convertSelect : function(select) {
6486 alert('in convertSelect');
6487 if (typeof(select) == "string") {
6488 select = document.getElementById(select);
6492 findChildNode : function (parent, property, value) {
6493 for (i in parent.children) {
6494 var child = parent.children[i];
6495 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6497 var searchChild = SE.util.findChildNode(child, property, value);
6504 cascadeNodes : function (parent, fn, scope, args) {
6505 for (i in parent.children) {
6506 var child = parent.children[i];
6507 var s = scope ? scope : child;
6508 var a = args ? args : child;
6510 SE.util.cascadeNodes(child, fn, scope, args);
6517 ///////////////////////////////////////////////////////////////////////////////
6520 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6522 /*********************************************************************************
6523 * SugarCRM Community Edition is a customer relationship management program developed by
6524 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6526 * This program is free software; you can redistribute it and/or modify it under
6527 * the terms of the GNU Affero General Public License version 3 as published by the
6528 * Free Software Foundation with the addition of the following permission added
6529 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6530 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6531 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6533 * This program is distributed in the hope that it will be useful, but WITHOUT
6534 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6535 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6538 * You should have received a copy of the GNU Affero General Public License along with
6539 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6540 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6543 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6544 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6546 * The interactive user interfaces in modified source and object code versions
6547 * of this program must display Appropriate Legal Notices, as required under
6548 * Section 5 of the GNU Affero General Public License version 3.
6550 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6551 * these Appropriate Legal Notices must retain the display of the "Powered by
6552 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6553 * technical reasons, the Appropriate Legal Notices must display the words
6554 * "Powered by SugarCRM".
6555 ********************************************************************************/
6558 if (typeof console == "undefined")
6559 console = { log: function(o) {alert(o)} };
6563 currentRequestObject : null,
6564 //timeout : 30000, // 30 second timeout default
6565 timeout : 9999999999, // 30 second timeout default
6567 trail : new Array(),
6571 _reset : function() {
6572 this.timeout = 30000;
6573 this.forceAbort = false;
6576 folderRenameCleanup : function() {
6577 SUGAR.email2.folders.setSugarFolders();
6580 fullSyncCleanup : function(o) {
6581 this.folders.checkMailCleanup(o);
6582 SUGAR.email2.settings.settingsDialog.hide();
6587 composeCache : function(o) {
6588 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6589 // get email templates and user signatures
6590 var ret = YAHOO.lang.JSON.parse(o.responseText);
6592 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6593 SUGAR.email2.composeLayout.signatures = ret.signatures;
6594 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6596 SUGAR.email2.composeLayout.setComposeOptions(idx);
6598 //Set the error array so we can notify the user when they try to hit send if any errors
6599 //are present. We will also notify them now (after hitting compose button).
6600 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6603 //if error element is returning an array, then check the length to make sure we have error messages
6604 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6605 //add error messages for display
6606 for(i in ret.errorArray)
6607 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6608 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6609 //if error element is returning an object, and the object value is not empty or null, then display error message
6610 for(i in ret.errorArray)
6611 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6614 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6616 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6618 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6624 handleDeleteSignature : function(o) {
6626 var ret = YAHOO.lang.JSON.parse(o.responseText);
6627 SUGAR.email2.composeLayout.signatures = ret.signatures;
6628 var field = document.getElementById('signature_id');
6629 SUGAR.email2.util.emptySelectOptions(field);
6631 for(var i in ret.signatures) { // iterate through assoc array
6632 var opt = new Option(ret.signatures[i], i);
6633 field.options.add(opt);
6635 setSigEditButtonVisibility();
6640 handleDeleteReturn : function(o) {
6641 // force refresh ListView
6643 if(document.getElementById('focusEmailMbox')) {
6644 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6647 // need to display success message before calling next async call?
6648 document.getElementById(this.target).innerHTML = o.responseText;
6653 handleFailure : function(o) {
6655 overlay('Exception occurred...', o.statusText, 'alert');
6656 if(document.getElementById('saveButton')) {
6657 document.getElementById('saveButton').disabled = false;
6661 handleReplyForward : function(o) {
6662 var a = YAHOO.lang.JSON.parse(o.responseText);
6664 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6666 document.getElementById('email_id' + idx).value = a.uid;
6667 document.getElementById('emailSubject' + idx).value = a.name;
6668 document.getElementById('addressTO' + idx).value = a.from;
6669 document.getElementById('uid' + idx).value = a.uid;
6671 document.getElementById('addressCC' + idx).value = a.cc;
6672 SE.composeLayout.showHiddenAddress('cc', idx);
6676 document.getElementById('type' + idx).value = a.type;
6679 // apply attachment values
6680 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6682 setTimeout("callbackReplyForward.finish(globalA);", 500);
6685 handleReplyForwardForDraft : function(o) {
6686 var a = YAHOO.lang.JSON.parse(o.responseText);
6688 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6690 document.getElementById('email_id' + idx).value = a.uid;
6691 document.getElementById('emailSubject' + idx).value = a.name;
6692 document.getElementById('addressTO' + idx).value = a.to;
6695 document.getElementById('addressCC' + idx).value = a.cc;
6696 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6700 document.getElementById('addressBCC' + idx).value = a.bcc;
6701 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6706 document.getElementById('type' + idx).value = a.type;
6710 // apply attachment values
6711 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6713 setTimeout("callbackReplyForward.finish(globalA);", 500);
6718 handleSuccess : function(o) {
6719 document.getElementById(this.target).innerHTML = o.responseText;
6725 ieDeleteSuccess : function(o) {
6728 SUGAR.email2.accounts.refreshInboundAccountTable();
6729 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6730 SUGAR.email2.accounts.rebuildFolderList();
6735 ieSaveSuccess : function(o) {
6736 document.getElementById('saveButton').disabled = false;
6737 var a = YAHOO.lang.JSON.parse(o.responseText);
6740 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6741 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6743 resp = YAHOO.lang.JSON.parse(o.responseText);
6744 SUGAR.email2.accounts.refreshInboundAccountTable();
6745 SUGAR.email2.accounts.refreshOuboundAccountTable();
6746 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6747 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6751 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6758 loadAttachments : function(o) {
6759 var result = YAHOO.lang.JSON.parse(o.responseText);
6761 SUGAR.email2.composeLayout.loadAttachments(result);
6766 loadSignature : function(o) {
6767 var ret = YAHOO.lang.JSON.parse(o.responseText);
6768 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6769 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6773 * Follow up to mark email read|unread|flagged
6775 markEmailCleanup : function(o) {
6776 var ret = YAHOO.lang.JSON.parse(o.responseText);
6777 if (!ret['status']) {
6779 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6781 SUGAR.email2.contextMenus.markEmailCleanup();
6787 rebuildShowFolders : function(o) {
6788 var t = YAHOO.lang.JSON.parse(o.responseText);
6789 var show = document.getElementById('ieAccountListShow');
6791 SUGAR.email2.util.emptySelectOptions(show);
6793 for(i=0; i<t.length; i++) { // iterate through assoc array
6794 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6795 opt.selected = t[i].selected;
6796 show.options.add(opt);
6799 SUGAR.email2.accounts.renderTree();
6803 saveListViewSortOrderPart2 : function() {
6804 // create the JSON string the func expects
6805 focusFolderPath = '[ "Home", "' + ieName + '"';
6807 var f = new String(focusFolder);
6808 var fEx = f.split('.');
6810 for(i=0; i<fEx.length; i++) {
6811 focusFolderPath += ', "' + fEx[i] +'"'
6814 focusFolderPath += ']';
6816 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6817 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6823 sendEmailCleanUp : function(o) {
6828 ret = YAHOO.lang.JSON.parse(o.responseText);
6829 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6830 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6832 if (o.responseText) {
6833 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6835 // Else we have an error here.
6838 if (typeof(SE.grid) != 'undefined')
6839 SE.listView.refreshGrid();
6840 //Disabled while address book is disabled
6842 //If this call back was initiated by quick compose from a Detail View page, refresh the
6843 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6844 //close the shortcut bar menu
6845 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6846 if(action_sugar_grp1 == 'DetailView') {
6847 showSubPanel('history',null,true);
6848 } else if(action_sugar_grp1 == 'quickcreate') {
6849 closeEmailOverlay();
6855 ieSendSuccess : function(o) {
6857 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6862 settingsFolderRefresh : function(o) {
6863 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6864 var ret = YAHOO.lang.JSON.parse(o.responseText);
6865 var user = document.getElementById('userFolders');
6867 SUGAR.email2.util.emptySelectOptions(user);
6869 for(i=0; i<ret.userFolders.length; i++) {
6870 var display = ret.userFolders[i].name;
6871 var value = ret.userFolders[i].id;
6872 var selected = (ret.userFolders[i].selected != "") ? true : false;
6873 var opt = new Option(display, value, selected);
6874 opt.selected = selected;
6875 user.options.add(opt);
6881 startRequest : function(callback, args, forceAbort) {
6882 if(this.currentRequestObject != null) {
6883 if(this.forceAbort == true) {
6884 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6887 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6891 requestInProgress : function() {
6892 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6897 updateFolderSubscriptions : function() {
6898 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6899 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6905 updateFrameFolder : function() {
6906 SUGAR.email2.folders.checkEmailAccounts();
6911 updateUserPrefs : function(o) {
6912 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
6913 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6918 uploadAttachmentSuccessful : function(o) {
6920 document.getElementById('email_attachment').value = '';
6922 var ret = YAHOO.lang.JSON.parse(o.responseText);
6923 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6924 var overall = document.getElementById('addedFiles' + idx);
6925 var index = overall.childNodes.length;
6927 "<div id='email_attachment_bucket" + idx + index + "'>" +
6929 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6930 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6931 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6933 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6934 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6936 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6938 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6941 overall.innerHTML += out;
6942 if(SUGAR.email2.util.isIe()) {
6943 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6947 SUGAR.email2.addFileDialog.hide();
6948 // focus attachments
6949 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6954 ///////////////////////////////////////////////////////////////////////////
6955 //// PER MODULE CALLBACK OBJECTS
6956 AjaxObject.accounts = {
6957 saveOutboundCleanup : function(o) {
6958 SUGAR.email2.accounts.refreshOuboundAccountTable();
6959 SUGAR.email2.accounts.outboundDialog.hide();
6960 var id = o.responseText;
6961 SUGAR.email2.accounts.newAddedOutboundId = id;
6963 saveDefaultOutboundCleanup: function(o){
6966 callbackEditOutbound : {
6967 success : function(o)
6969 var ret = YAHOO.lang.JSON.parse(o.responseText);
6971 SUGAR.email2.accounts.showAddSmtp();
6974 document.getElementById("mail_id").value = ret.id;
6975 document.getElementById("type").value = ret.type;
6976 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6977 document.getElementById("mail_name").value = ret.name;
6978 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6979 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6980 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6981 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6982 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6983 SUGAR.email2.accounts.smtp_authenticate_field_display();
6984 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6986 if(ret.type == 'system-override') {
6987 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6988 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6991 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6992 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6994 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6997 failure : AjaxObject.handleFailure,
6998 timeout : AjaxObject.timeout,
7001 callbackDeleteOutbound : {
7002 success : function(o) {
7003 var ret = YAHOO.lang.JSON.parse(o.responseText);
7006 if(confirm(ret.error_message))
7008 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
7009 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
7017 SUGAR.email2.accounts.refreshOuboundAccountTable();
7021 failure : AjaxObject.handleFailure,
7022 timeout : AjaxObject.timeout,
7026 callbackCheckMailProgress : {
7027 success : function(o) {
7028 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
7029 SUGAR.email2.accounts.totalMsgCount = -1;
7032 //Check for server timeout / errors
7033 var ret = YAHOO.lang.JSON.parse(o.responseText);
7036 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
7038 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7039 SUGAR.email2.accounts.totalMsgCount = -1;
7040 //SUGAR.email2.folders.rebuildFolders();
7044 var currIeId = ret['ieid'];
7047 var serverCount = ret.count;
7049 if (ret['status'] == 'done') {
7050 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7051 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7055 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7056 //Go to next account
7057 currIeId = SUGAR.email2.accounts.ieIds[i+1];
7059 SUGAR.email2.accounts.totalMsgCount = -1;
7064 else if (ret.mbox && ret.totalcount && ret.count) {
7065 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7066 if (ret.count >= ret.totalcount) {
7069 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7070 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7073 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7074 SUGAR.email2.accounts.totalMsgCount = -1;
7079 SUGAR.email2.accounts.totalMsgCount = -1;
7081 SUGAR.email2.folders.rebuildFolders();
7082 SE.listView.refreshGrid();
7083 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7084 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7085 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7086 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7088 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7089 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7090 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7091 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7092 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7095 failure : AjaxObject.handleFailure,
7096 timeout : AjaxObject.timeout,
7101 ///////////////////////////////////////////////////////////////////////////////
7103 AjaxObject.composeLayout = {
7105 * Populates the record id
7107 saveDraftCleanup : function(o) {
7112 ret = YAHOO.lang.JSON.parse(o.responseText);
7113 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7115 if (o.responseText) {
7116 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7122 AjaxObject.composeLayout.callback = {
7124 success : AjaxObject.composeLayout.saveDraftCleanup,
7125 failure : AjaxObject.handleFailure,
7126 timeout : AjaxObject.timeout,
7131 AjaxObject.detailView = {
7133 * Pops-up a printable view of an email
7135 displayPrintable : function(o) {
7136 var ret = YAHOO.lang.JSON.parse(o.responseText);
7137 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7138 // 2 below must be in global context
7140 meta['panelId'] = SUGAR.email2.util.getPanelId();
7141 email = ret.meta.email;
7142 if (typeof(email.cc) == 'undefined') {
7146 var out = displayTemplate.exec({
7147 'app_strings' : app_strings,
7151 'email' : meta.email
7154 // open popup window
7155 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7156 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7158 popup.document.write(out);
7159 popup.document.close();
7163 * Takes formatted response and creates a modal pop-over containing a title and content
7165 displayView : function(o) {
7166 var SED = SUGAR.email2.detailView;
7167 var ret = YAHOO.lang.JSON.parse(o.responseText);
7169 if(!SED.viewDialog) {
7170 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7174 constraintoviewport: true,
7177 SED.viewDialog.renderEvent.subscribe(function() {
7178 var content = this.body.firstChild;
7179 var viewH = YAHOO.util.Dom.getViewportHeight();
7181 this.body.style.overflow = "auto";
7182 this.body.style.width = "800px";
7183 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7187 SED.viewDialog.setHeader(ret.title);
7188 SED.viewDialog.setBody(ret.html);
7189 SED.viewDialog.render();
7190 SED.viewDialog.show();
7194 * Generates a modal popup to populate with the contents of bean's full EditView
7196 showQuickCreateForm : function(o) {
7197 var SED = SUGAR.email2.detailView;
7198 var ret = YAHOO.lang.JSON.parse(o.responseText);
7200 if(!SED.quickCreateDialog) {
7201 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7205 constraintoviewport: true,
7209 SED.quickCreateDialog.renderEvent.subscribe(function() {
7210 var viewH = YAHOO.util.Dom.getViewportHeight();
7212 for (var i in this.body.childNodes) {
7213 if (this.body.childNodes[i].clientHeight) {
7214 contH += this.body.childNodes[i].clientHeight;
7215 } else if (this.body.childNodes[i].offsetHeight) {
7216 contH += this.body.childNodes[i].offsetHeight;
7219 this.body.style.width = "800px";
7220 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7221 this.body.style.overflow = "auto";
7222 }, SED.quickCreateDialog);
7224 SED.quickCreateDialog.hideEvent.subscribe(function(){
7225 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7226 /*for(var qsField in qsFields){
7227 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7228 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7231 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7234 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7236 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7237 SED.quickCreateDialog.render();
7238 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7240 SED.quickCreateDialog.ieId = ret.ieId;
7241 SED.quickCreateDialog.uid = ret.uid;
7242 SED.quickCreateDialog.mbox = ret.mbox;
7243 SED.quickCreateDialog.qcmodule = ret.module;
7245 SED.quickCreateDialog.show();
7247 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7249 editForm.module.value = 'Emails';
7250 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7251 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7252 var instId = ret.module + count;
7253 SED.quickCreateEmailsToAdd = ret.emailAddress;
7254 SED.quickCreateEmailCallback = function(instId, tableId) {
7255 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7256 if (typeof(eaw) == "undefined")
7257 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7258 + instId + "','" + tableId + "');", 100);
7259 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7261 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7262 + instId + "','" + tableId + "');", 100);
7266 saveQuickCreateForm : function(o) {
7268 SUGAR.email2.detailView.quickCreateDialog.hide();
7269 validate['EditView'] = [ ];
7272 saveQuickCreateFormAndReply : function(o) {
7274 var ret = YAHOO.lang.JSON.parse(o.responseText);
7275 SUGAR.email2.detailView.quickCreateDialog.hide();
7276 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7277 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7279 var emailID = ret.id;
7280 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7282 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7284 //Cean the validate cache to prevent errors on the next call
7285 validate['EditView'] = [ ];
7288 saveQuickCreateFormAndAddToAddressBook : function(o) {
7290 SUGAR.email2.detailView.quickCreateDialog.hide();
7291 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7292 validate['EditView'] = [ ];
7295 handleAssignmentDialogAssignAction : function() {
7298 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7300 var dist = 'direct';
7304 var found_teams = false;
7305 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7306 if(!found_teams && assign_user_id == '' )
7308 alert(warning_message);
7312 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7314 for(i=0; i<emailUids.length; i++) {
7316 uids += app_strings.LBL_EMAIL_DELIMITER;
7318 uids += emailUids[i];
7321 var row = SUGAR.email2.grid.getSelectedRows()[0];
7322 var data = SUGAR.email2.grid.getRecord(row).getData();
7323 var ieid = data.ieId;
7324 var mbox = data.mbox;
7325 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7326 SUGAR.email2.contextMenus.assignToDialogue.hide();
7327 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7331 handleAssignmentDialogDeleteAction : function() {
7332 // TO pass list of UIDS/emailIds
7333 var uids = SUGAR.email2.listView.getUidsFromSelection();
7334 var row = SUGAR.email2.grid.getSelections()[0];
7335 var ieid = row.data.ieId;
7336 var mbox = row.data.mbox;
7337 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7338 SUGAR.email2.contextMenus.assignmentDialog.hide();
7339 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7345 showEmailDetailView : function(o) {
7347 var SED = SUGAR.email2.detailView;
7348 var ret = YAHOO.lang.JSON.parse(o.responseText);
7350 if(!SED.quickCreateDialog) {
7351 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7355 constraintoviewport: true,
7357 autofillheight: "body",
7360 SED.quickCreateDialog.renderEvent.subscribe(function() {
7361 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7363 for (var i in this.body.childNodes) {
7364 if (this.body.childNodes[i].offsetHeight)
7365 contH += this.body.childNodes[i].offsetHeight;
7367 this.body.style.overflow = "auto";
7368 this.body.style.width = "800px";
7369 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7371 }, SED.quickCreateDialog);
7373 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7374 SED.quickCreateDialog.setBody(ret.html);
7375 SED.quickCreateDialog.render();
7376 SUGAR.util.evalScript(ret.html);
7377 SED.quickCreateDialog.show();
7380 showAssignmentDialogWithData : function(o) {
7381 var SEC = SUGAR.email2.contextMenus;
7383 var ret = YAHOO.lang.JSON.parse(o.responseText);
7384 if (!SEC.assignmentDialog) {
7385 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7388 constraintoviewport: true,
7391 SEC.assignmentDialog.setBody("");
7392 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7393 SEC.assignmentDialog.renderEvent.subscribe(function() {
7394 var iev = YAHOO.util.Dom.get("Distribute");
7396 this.body.style.width = "700px";
7398 }, SEC.assignmentDialog);
7399 SEC.assignmentDialog.render();
7401 SEC.assignmentDialog.setBody(ret);
7402 SEC.assignmentDialog.render();
7404 SEC.assignmentDialog.show();
7405 SUGAR.util.evalScript(ret);
7408 showImportForm : function(o) {
7409 var SED = SUGAR.email2.detailView;
7410 var ret = YAHOO.lang.JSON.parse(o.responseText);
7412 document.getElementById('quickCreateContent').innerHTML = "";
7418 if(!SED.importDialog) {
7419 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7423 constraintoviewport: true,
7425 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7426 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7430 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7431 SED.importDialog.setBody("");
7432 SED.importDialog.hideEvent.subscribe(function(){
7433 for(var i in QSFieldsArray) {
7434 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7435 QSFieldsArray[i].destroy();
7436 delete QSFieldsArray[i];
7438 if (QSProcessedFieldsArray[i]) {
7439 QSProcessedFieldsArray[i] = false;
7443 SED.importDialog.renderEvent.subscribe(function() {
7444 var iev = YAHOO.util.Dom.get("ImportEditView");
7446 //this.body.style.height = (iev.clientHeight + 10) + "px";
7447 this.body.style.width = "600px";
7449 }, SED.importDialog);
7450 SED.importDialog.render();
7452 SED.importDialog.setBody(ret.html);
7453 SED.importDialog.ret = ret;
7454 SUGAR.util.evalScript(ret.html);
7455 SED.importDialog.render();
7457 SED.importDialog.show();
7458 SED.importDialog.focusFirstButton();
7460 getImportAction : function(ret) {
7461 if (!check_form('ImportEditView')) return false;
7462 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7463 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7467 var editView = document.getElementById('ImportEditView');
7468 if (editView.assigned_user_id != null) {
7469 get = get + "&user_id=" + editView.assigned_user_id.value
7470 //var user_id = editView.assigned_user_id.value;
7472 var parent_id = editView.parent_id.value;
7473 var parent_type = editView.parent_type.value;
7474 var row = SUGAR.email2.grid.getSelectedRows()[0];
7475 row = SUGAR.email2.grid.getRecord(row);
7476 var data = row.getData();
7477 var ieId = data.ieId;
7478 var mbox = data.mbox;
7479 var serverDelete = editView.serverDelete.checked;
7480 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7482 for(i=0; i<emailUids.length; i++) {
7484 uids += app_strings.LBL_EMAIL_DELIMITER;
7486 uids += emailUids[i];
7489 var action = 'importEmail&uid=';
7491 action = 'moveEmails';
7492 action = action + '&sourceFolder=' + ret['srcFolder'];
7493 action = action + '&sourceIeId=' + ret['srcIeId'];
7494 action = action + '&destinationFolder=' + ret['dstFolder'];
7495 action = action + '&destinationIeId=' + ret['dstIeId'];
7496 action = action + '&emailUids=';
7498 if (action.search(/importEmail/) != -1) {
7499 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7501 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7504 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7505 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7506 SUGAR.email2.detailView.importDialog.hide();
7507 document.getElementById('importDialogContent').innerHTML = "";
7510 showRelateForm : function(o) {
7511 var SED = SUGAR.email2.detailView;
7512 var ret = YAHOO.lang.JSON.parse(o.responseText);
7513 document.getElementById('quickCreateContent').innerHTML = "";
7518 dialog_loaded = true;
7520 if(!SED.relateDialog) {
7521 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7526 constraintoviewport: true,
7528 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7529 if (!check_form('RelateEditView')) return false;
7531 var editView = document.getElementById('RelateEditView');
7532 var parent_id = editView.parent_id.value;
7533 var parent_type = editView.parent_type.value;
7534 var row = SUGAR.email2.grid.getSelectedRows()[0];
7535 row = SUGAR.email2.grid.getRecord(row);
7536 var ieId = row.getData().ieId;
7537 var mbox = row.getData().mbox;
7538 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7540 for(i=0; i<emailUids.length; i++) {
7542 uids += app_strings.LBL_EMAIL_DELIMITER;
7544 uids += emailUids[i];
7546 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7547 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7548 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7549 SED.relateDialog.hide();
7550 document.getElementById('relateDialogContent').innerHTML = "";
7555 SED.relateDialog.hideEvent.subscribe(function(){
7556 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7557 QSFieldsArray['ImportEditView_parent_name'].destroy();
7558 delete QSFieldsArray['ImportEditView_parent_name'];
7560 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7561 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7565 SED.relateDialog.renderEvent.subscribe(function() {
7566 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7568 for (var i in this.body.childNodes) {
7569 if (this.body.childNodes[i].clientHeight)
7570 contH += this.body.childNodes[i].clientHeight;
7572 }, SED.relateDialog);
7573 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7576 SED.relateDialog.setBody(ret.html);
7577 SED.relateDialog.render();
7578 SUGAR.util.evalScript(ret.html);
7579 SED.relateDialog.show();
7583 * DetailView callbacks
7585 AjaxObject.detailView.callback = {
7587 success : function(o) {
7589 var ret = YAHOO.lang.JSON.parse(o.responseText);
7590 SUGAR.email2.detailView.consumeMetaDetail(ret);
7592 argument: [targetDiv],
7593 failure : AjaxObject.handleFailure,
7598 success : function(o) {
7600 var ret = YAHOO.lang.JSON.parse(o.responseText);
7601 SUGAR.email2.detailView.consumeMetaPreview(ret);
7603 failure : AjaxObject.handleFailure,
7608 success : AjaxObject.detailView.displayPrintable,
7609 failure : AjaxObject.handleFailure,
7610 timeout : AjaxObject.timeout,
7614 success : AjaxObject.detailView.displayView,
7615 failure : AjaxObject.handleFailure,
7616 timeout : AjaxObject.timeout,
7625 AjaxObject.folders = {
7627 * check-mail post actions
7629 checkMailCleanup : function(o) {
7631 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7633 // refresh focus ListView
7634 SE.listView.refreshGrid();
7635 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7640 rebuildFolders : function(o) {
7643 var data = YAHOO.lang.JSON.parse(o.responseText);
7645 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7646 SUGAR.email2.folders.setSugarFolders();
7649 AjaxObject.folders.callback = {
7651 success : AjaxObject.folders.checkMailCleanup,
7652 failure : AjaxObject.handleFailure,
7653 timeout : 600000, // 5 mins
7658 AjaxObject.rules = {
7659 loadRulesForSettings : function(o) {
7660 document.getElementById("rulesListCell").innerHTML = o.responseText;
7661 // assume we have the class we need
7662 SUGAR.routing.getStrings();
7663 SUGAR.routing.getDependentDropdowns();
7666 //// END PER MODULE CALLBACK OBJECTS
7667 ///////////////////////////////////////////////////////////////////////////
7671 success : AjaxObject.handleSuccess,
7672 failure : AjaxObject.handleFailure,
7673 timeout : AjaxObject.timeout,
7676 var callbackAccount = {
7677 success : AjaxObject.ieSaveSuccess,
7678 failure : AjaxObject.handleFailure,
7679 timeout : AjaxObject.timeout,
7682 var callbackAccountDelete = {
7683 success : AjaxObject.ieDeleteSuccess,
7684 failure : AjaxObject.handleFailure,
7685 timeout : AjaxObject.timeout,
7688 var callbackOutboundTest = {
7689 success : AjaxObject.ieSendSuccess,
7690 failure : AjaxObject.handleFailure,
7691 timeout : AjaxObject.timeout,
7697 var callbackTeamInfoForSettings = {
7698 success : function (o) {
7699 var data = YAHOO.lang.JSON.parse(o.responseText);
7700 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7702 failure : AjaxObject.handleFailure,
7703 timeout : AjaxObject.timeout,
7708 var callbackStatusForImport = {
7709 success : function (o) {
7711 if (o.responseText != "") {
7712 var statusString = "";
7713 var data = YAHOO.lang.JSON.parse(o.responseText);
7714 for(i=0; i<data.length; i++) {
7715 statusString = statusString + data[i] + '<br/>';
7717 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7719 SE.listView.refreshGrid();
7722 failure : AjaxObject.handleFailure,
7723 timeout : AjaxObject.timeout,
7727 var callbackComposeCache = {
7728 success : AjaxObject.composeCache,
7729 failure : AjaxObject.handleFailure,
7730 timeout : AjaxObject.timeout,
7733 var callbackDelete = {
7734 success : AjaxObject.handleDeleteReturn,
7735 failure : AjaxObject.handleFailure,
7736 timeout : AjaxObject.timeout,
7739 var callbackEmailDetailMultiple = {
7740 success : function(o) {
7742 var retMulti = YAHOO.lang.JSON.parse(o.responseText);
7743 var ret = new Object();
7745 for(var i=0; i<retMulti.length; i++) {
7748 SUGAR.email2._setDetailCache(ret);
7749 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7752 failure : AjaxObject.handleFailure,
7756 var callbackListViewSortOrderChange = {
7757 success : AjaxObject.saveListViewSortOrderPart2,
7758 failure : AjaxObject.handleFailure,
7759 timeout : AjaxObject.timeout,
7761 argument : [ieId, ieName, focusFolder]
7763 var callbackEmptyTrash = {
7764 success : function(o) {
7766 AjaxObject.folderRenameCleanup;
7768 failure : AjaxObject.handleFailure,
7769 timeout : AjaxObject.timeout,
7772 var callbackClearCacheFiles = {
7773 success : function(o) {
7776 failure : AjaxObject.handleFailure,
7777 timeout : AjaxObject.timeout,
7780 var callbackFolderRename = {
7781 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7782 failure : AjaxObject.handleFailure,
7783 timeout : AjaxObject.timeout,
7786 var callbackFolderDelete = {
7787 success : function(o) {
7788 var ret = YAHOO.lang.JSON.parse(o.responseText);
7790 if (ret.folder_id) {
7791 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7793 SUGAR.email2.tree.removeNode(node, true);
7794 } else if (ret.ieId && ret.mbox) {
7795 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7797 SUGAR.email2.tree.removeNode(node, true);
7800 //SUGAR.email2.folders.loadSettingFolder();
7803 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7806 failure : AjaxObject.handleFailure,
7807 timeout : AjaxObject.timeout,
7810 var callbackFolderSave = {
7811 success : function(o) {
7812 var ret = YAHOO.lang.JSON.parse(o.responseText);
7814 switch(ret.action) {
7815 case 'newFolderSave':
7816 SUGAR.email2.folders.rebuildFolders();
7820 failure : AjaxObject.handleFailure,
7821 timeout : AjaxObject.timeout,
7824 var callbackFolderSubscriptions = {
7825 success : AjaxObject.updateFolderSubscriptions,
7826 failure : AjaxObject.handleFailure,
7827 timeout : AjaxObject.timeout,
7830 var callbackFolderUpdate = {
7831 success : AjaxObject.updateFrameFolder,
7832 failure : AjaxObject.handleFailure,
7833 timeout : AjaxObject.timeout,
7836 var callbackFolders = {
7837 success : AjaxObject.folders.rebuildFolders,
7838 //success : void(true),
7839 failure : AjaxObject.handleFailure,
7840 timeout : AjaxObject.timeout,
7843 var callbackFullSync = {
7844 success : AjaxObject.fullSyncCleanup,
7845 failure : AjaxObject.handleFailure,
7846 timeout : 9999999999999,
7849 var callbackGeneric = {
7850 success : function() {
7853 failure : AjaxObject.handleFailure,
7854 timeout : AjaxObject.timeout,
7857 var callbackIeAccountRetrieve = {
7858 success : function(o) {
7859 // return JSON encoding
7861 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7862 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7864 failure : AjaxObject.handleFailure,
7865 timeout : AjaxObject.timeout,
7868 var callbackImportOneEmail = {
7869 success : AjaxObject.detailView.showImportForm,
7870 failure : AjaxObject.handleFailure,
7871 timeout : AjaxObject.timeout,
7874 var callbackRelateEmail = {
7875 success : AjaxObject.detailView.showRelateForm,
7876 failure : AjaxObject.handleFailure,
7877 timeout : AjaxObject.timeout,
7880 var callbackEmailDetailView = {
7881 success : AjaxObject.detailView.showEmailDetailView,
7882 failure : AjaxObject.handleFailure,
7883 timeout : AjaxObject.timeout,
7886 var callbackAssignmentDialog = {
7887 success : AjaxObject.detailView.showAssignmentDialogWithData,
7888 failure : AjaxObject.handleFailure,
7889 timeout : AjaxObject.timeout,
7892 var callbackAssignmentAction = {
7893 success : function(o) {
7894 SE.listView.refreshGrid();
7896 if(o.responseText != '') {
7897 overlay('Assignment action result', o.responseText, 'alert');
7900 failure : AjaxObject.handleFailure,
7901 timeout : AjaxObject.timeout,
7904 var callbackMoveEmails = {
7905 success : function(o) {
7906 SE.listView.refreshGrid();
7908 if(o.responseText != '') {
7909 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7912 failure : AjaxObject.handleFailure,
7913 timeout : AjaxObject.timeout,
7916 var callbackLoadAttachments = {
7917 success : AjaxObject.loadAttachments,
7918 failure : AjaxObject.handleFailure,
7919 timeout : AjaxObject.timeout,
7922 var callbackLoadRules = {
7923 success : AjaxObject.rules.loadRulesForSettings,
7924 failure : AjaxObject.handleFailure,
7925 timeout : AjaxObject.timeout,
7928 var callbackLoadSignature = {
7929 success : AjaxObject.loadSignature,
7930 failure : AjaxObject.handleFailure,
7931 timeout : AjaxObject.timeout,
7934 var callbackDeleteSignature = {
7935 success : AjaxObject.handleDeleteSignature,
7936 failure : AjaxObject.handleFailure,
7937 timeout : AjaxObject.timeout,
7940 /*var callbackMoveEmails = {
7941 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7942 failure : AjaxObject.handleFailure,
7943 timeout : AjaxObject.timeout,
7946 var callbackOutboundSave = {
7947 success : AjaxObject.accounts.saveOutboundCleanup,
7948 failure : AjaxObject.handleFailure,
7949 timeout : AjaxObject.timeout,
7952 var callbackDefaultOutboundSave = {
7953 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7954 failure : AjaxObject.handleFailure,
7955 timeout : AjaxObject.timeout,
7958 var callbackQuickCreate = {
7959 success : AjaxObject.detailView.showQuickCreateForm,
7960 failure : AjaxObject.handleFailure,
7961 timeout : AjaxObject.timeout,
7964 var callbackQuickCreateSave = {
7965 success : AjaxObject.detailView.saveQuickCreateForm,
7966 failure : AjaxObject.handleFailure,
7967 timeout : AjaxObject.timeout,
7970 var callbackQuickCreateSaveAndAddToAddressBook = {
7971 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7972 failure : AjaxObject.handleFailure,
7973 timeout : AjaxObject.timeout,
7976 var callbackQuickCreateSaveAndReply = {
7977 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7978 failure : AjaxObject.handleFailure,
7979 timeout : AjaxObject.timeout,
7982 var callbackQuickCreateSaveAndReplyCase = {
7983 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7984 failure : AjaxObject.handleFailure,
7985 timeout : AjaxObject.timeout,
7988 var callbackRebuildShowAccountList = {
7989 success : AjaxObject.rebuildShowFolders,
7990 failure : AjaxObject.handleFailure,
7991 timeout : AjaxObject.timeout,
7995 var callbackRefreshSugarFolders = {
7996 success : function(o) {
7997 var t = YAHOO.lang.JSON.parse(o.responseText);
7998 SUGAR.email2.folders.setSugarFoldersEnd(t);
8000 failure : AjaxObject.handleFailure,
8001 timeout : AjaxObject.timeout,
8004 var callbackReplyForward = {
8005 success : AjaxObject.handleReplyForward,
8006 finish : function(a, retryCount) {
8007 if (typeof(retryCount) == 'undefined') {
8012 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8013 var t = tinyMCE.getInstanceById('htmleditor' + idx);
8015 var html = t.getContent();
8017 html = " <div><hr></div>" + a.description;
8019 t.setContent(html);//
8021 if (a.type != 'draft') {
8022 // Next step, attach signature
8023 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
8027 if (retryCount < 5) {
8028 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
8032 var tabArray = SUGAR.email2.innerLayout.get("tabs");
8033 if (tabArray != null && tabArray.length > 0) {
8034 for (i = 0 ; i < tabArray.length ; i++) {
8035 var tabObject = tabArray[i];
8036 if (tabObject.get("id") == ("composeTab" + idx)) {
8037 var tabLabel = a.name;
8038 if (tabLabel != null && tabLabel.length > 25) {
8039 tabLabel = tabLabel.substring(0, 25) + "...";
8041 tabObject.get("labelEl").firstChild.data = tabLabel;
8047 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8048 if (a.parent_name != null && a.parent_name != "") {
8049 document.getElementById('data_parent_name' + idx).value = a.parent_name;
8051 if (a.parent_type != null && a.parent_type != "") {
8052 document.getElementById('data_parent_type' + idx).value = a.parent_type;
8054 if (a.parent_id != null && a.parent_id != "") {
8055 document.getElementById('data_parent_id' + idx).value = a.parent_id;
8057 if (a.fromAccounts.status) {
8058 var addressFrom = document.getElementById('addressFrom' + idx);
8059 SUGAR.email2.util.emptySelectOptions(addressFrom);
8060 var fromAccountOpts = a.fromAccounts.data;
8061 for(i=0; i<fromAccountOpts.length; i++) {
8062 var key = fromAccountOpts[i].value;
8063 var display = fromAccountOpts[i].text;
8064 var opt = new Option(display, key);
8065 if (fromAccountOpts[i].selected) {
8066 opt.selected = true;
8068 addressFrom.options.add(opt);
8074 failure : AjaxObject.handleFailure,
8075 timeout : AjaxObject.timeout,
8077 argument : [sendType]
8079 var callbackSendEmail = {
8080 success : AjaxObject.sendEmailCleanUp,
8081 failure : AjaxObject.handleFailure,
8082 timeout : AjaxObject.timeout,
8085 var callbackSettings = {
8086 success : AjaxObject.updateUserPrefs,
8087 failure : AjaxObject.handleFailure,
8088 timeout : AjaxObject.timeout,
8091 var callbackSettingsFolderRefresh = {
8092 success : AjaxObject.settingsFolderRefresh,
8093 failure : AjaxObject.handleFailure,
8094 timeout : AjaxObject.timeout,
8097 var callbackLoadSettingFolder = {
8098 success : function(o) {
8099 AjaxObject.settingsFolderRefresh(o);
8100 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8102 failure : AjaxObject.handleFailure,
8103 timeout : AjaxObject.timeout,
8107 var callbackUploadAttachment = {
8108 success : AjaxObject.uploadAttachmentSuccessful,
8109 upload : AjaxObject.uploadAttachmentSuccessful,
8110 failure : AjaxObject.handleFailure,
8111 timeout : AjaxObject.timeout,
8114 var callbackUserPrefs = {
8115 success : function(o) {
8116 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
8118 failure : AjaxObject.handleFailure,
8119 timeout : AjaxObject.timeout,
8123 var callbackContextmenus = {
8125 success : AjaxObject.markEmailCleanup,
8126 failure : AjaxObject.handleFailure,
8127 timeout : AjaxObject.timeout,
8132 var callbackCheckEmail2 = {
8133 success : function(o) {
8134 var ret = YAHOO.lang.JSON.parse(o.responseText);
8135 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8139 failure : AjaxObject.handleFailure,
8140 timeout : AjaxObject.timeout,
8142 }// End of File modules/Emails/javascript/ajax.js
8144 /*********************************************************************************
8145 * SugarCRM Community Edition is a customer relationship management program developed by
8146 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8148 * This program is free software; you can redistribute it and/or modify it under
8149 * the terms of the GNU Affero General Public License version 3 as published by the
8150 * Free Software Foundation with the addition of the following permission added
8151 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8152 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8153 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8155 * This program is distributed in the hope that it will be useful, but WITHOUT
8156 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8157 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8160 * You should have received a copy of the GNU Affero General Public License along with
8161 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8162 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8165 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8166 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8168 * The interactive user interfaces in modified source and object code versions
8169 * of this program must display Appropriate Legal Notices, as required under
8170 * Section 5 of the GNU Affero General Public License version 3.
8172 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8173 * these Appropriate Legal Notices must retain the display of the "Powered by
8174 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8175 * technical reasons, the Appropriate Legal Notices must display the words
8176 * "Powered by SugarCRM".
8177 ********************************************************************************/
8179 function gridInit() {
8180 if(SUGAR.email2.grid) {
8181 SUGAR.email2.grid.destroy();
8187 var Ck = YAHOO.util.Cookie;
8188 var widths = [ 10, 10, 150, 250, 175, 125 ];
8190 if (Ck.get("EmailGridWidths")) {
8191 for (var i=0; i < widths.length; i++) {
8192 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8195 for (var i=0; i < widths.length; i++) {
8196 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8200 // changes "F" to an icon
8201 function flaggedIcon(cell, record, column, value) {
8203 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8206 // changes "A" to replied icon
8207 function repliedIcon(cell, record, column, value) {
8209 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8212 function attachIcon(cell, record, column, value) {
8214 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8221 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8226 formatter: attachIcon,
8230 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8235 formatter: flaggedIcon,
8239 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8244 formatter: repliedIcon,
8248 label: app_strings.LBL_EMAIL_FROM,
8255 label: app_strings.LBL_EMAIL_SUBJECT,
8262 label: mod_strings.LBL_LIST_DATE,
8269 label: app_strings.LBL_EMAIL_TO,
8305 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8306 responseType: YAHOO.util.DataSource.TYPE_JSON,
8308 resultsList: 'Email',
8309 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8310 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8316 action : "EmailUIAjax",
8317 emailUIAction : "getMessageList",
8320 forceRefresh : "false"
8322 if(lazyLoadFolder != null) {
8323 params['mbox'] = lazyLoadFolder.folder;
8324 params['ieId'] = lazyLoadFolder.ieId;
8325 //Check if the folder is a Sugar Folder
8326 var test = new String(lazyLoadFolder.folder);
8327 if(test.match(/SUGAR\./)) {
8328 params['emailUIAction'] = 'getMessageListSugarFolders';
8329 params['mbox'] = test.substr(6);
8332 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8335 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8336 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8338 paginator: new YAHOO.widget.Paginator({
8339 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8340 containers : ["dt-pag-nav"],
8341 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8342 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8343 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8344 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8345 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8347 initialRequest:SUGAR.util.paramsToUrl(params),
8354 //Override Paging request construction
8355 grid.set("generateRequest", function(oState, oSelf) {
8356 oState = oState || {pagination:null, sortedBy:null};
8357 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8358 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8359 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8360 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8361 // Build the request
8363 SUGAR.util.paramsToUrl(oSelf.params) +
8366 "&start=" + startIndex +
8367 ((results !== null) ? "&limit=" + results : "");
8372 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8373 oPayload = oPayload || { };
8375 oPayload.totalRecords = oResponse.meta.total;
8376 oPayload.unreadRecords = oResponse.meta.unread;
8378 var tabObject = SE.innerLayout.get("tabs")[0];
8380 if (this.params.mbox != null) {
8381 mboxTitle = this.params.mbox;
8383 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8384 tabObject.get("labelEl").firstChild.data = tabtext;
8387 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8389 node.data.unseen = oResponse.meta.unread;
8390 SE.accounts.renderTree();
8396 var resize = grid.resizeGrid = function () {
8397 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8398 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8400 grid.convertDDRows = function() {
8401 var rowEl = this.getFirstTrEl();
8402 while (rowEl != null) {
8403 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8404 rowEl = this.getNextTrEl(rowEl);
8409 grid.on("columnResizeEvent", function(o) {
8410 //Find the index of the column
8411 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8412 for (var i=0; i < colSet.length; i++) {
8413 if (o.column == colSet[i]) {
8414 //Store it in the cookie
8415 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8418 //this.resizeGrid();
8421 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8422 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8423 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8425 SUGAR.email2.listViewLayout.on("render", resize);
8428 //Setup the default load parameters
8429 SUGAR.email2.grid.params = params;
8431 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8432 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8433 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8440 function initRowDD() {
8441 var sg = SUGAR.email2.grid,
8442 Dom = YAHOO.util.Dom;
8443 sg.DDRow = function(oDataTable, oRecord, elTr) {
8444 if(oDataTable && oRecord && elTr) {
8445 this.ddtable = oDataTable;
8446 this.table = oDataTable.getTableEl();
8449 this.newIndex = null;
8451 this.initFrame(); // Needed for DDProxy
8452 this.invalidHandleTypes = {};
8456 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8457 _resizeProxy: function() {
8458 this.constructor.superclass._resizeProxy.apply(this, arguments);
8459 var dragEl = this.getDragEl(),
8461 var xy = Dom.getXY(el);
8463 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8464 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8465 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8466 Dom.setStyle(dragEl, 'display', "");
8469 startDrag: function(x, y) {
8470 //Check if we should be dragging a set of rows rather than just the one.
8471 var selectedRows = this.ddtable.getSelectedRows();
8472 var iSelected = false;
8473 for (var i in selectedRows) {
8474 if (this.rowEl.id == selectedRows[i]) {
8481 for (var i in selectedRows) {
8482 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8485 this.rows = [this.row];
8486 this.ddtable.unselectAllRows();
8487 this.ddtable.selectRow(this.row);
8490 //Initialize the dragable proxy
8491 var dragEl = this.getDragEl();
8492 var clickEl = this.getEl();
8493 Dom.setStyle(clickEl, "opacity", "0.25");
8494 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8495 Dom.addClass(dragEl, "yui-dt-liner");
8496 Dom.setStyle(dragEl, "opacity", "0.5");
8497 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8498 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8499 Dom.setStyle(dragEl, "border", "2px solid gray");
8502 clickValidator: function(e) {
8503 if (this.row.getData()[0] == " ")
8505 var target = YAHOO.util.Event.getTarget(e);
8506 return ( this.isValidHandleChild(target) &&
8507 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8510 * This funciton checks that the target of the drag is a table row in this
8511 * DDGroup and simply moves the sourceEL to that location as a preview.
8513 onDragOver: function(ev, id) {
8514 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8515 if (node && node != this.targetNode) {
8516 this.targetNode = node;
8517 SUGAR.email2.folders.unhighliteAll();
8522 onDragOut: function(e, id) {
8523 if (this.targetNode) {
8524 SUGAR.email2.folders.unhighliteAll();
8525 this.targetNode = false;
8528 endDrag: function() {
8529 Dom.setStyle(this.getEl(), "opacity", "");
8530 Dom.setStyle(this.getDragEl(), "display", "none");
8531 if (this.targetNode) {
8532 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8534 SUGAR.email2.folders.unhighliteAll();
8540 function AddressSearchGridInit() {
8541 function moduleIcon(elCell, oRecord, oColumn, oData) {
8542 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8544 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8545 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8547 var checkHeader = '<input type="checkbox" ';
8548 if (SUGAR.email2.util.isIe()) {
8549 checkHeader += 'style="top:-5px" ';
8551 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8556 formatter: selectionCheckBox,
8560 label: mod_strings.LBL_LIST_TYPE,
8562 formatter: moduleIcon,
8566 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8572 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8578 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8579 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8581 resultsList: 'Person',
8582 fields: ['name', 'email', 'bean_id', 'bean_module'],
8583 metaFields: {total: 'TotalCount'}
8585 //enable sorting on the server accross all data
8588 dataModel.params = {
8591 action : "EmailUIAjax",
8592 emailUIAction:"getAddressSearchResults"
8594 var rb = document.getElementById('hasRelatedBean').checked;
8596 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8597 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8598 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8599 dataModel.params['related_bean_id'] = relatedBeanId;
8600 dataModel.params['related_bean_type'] = relatedBeanType;
8601 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8603 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8605 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8606 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8608 paginator: new YAHOO.widget.Paginator({
8610 containers : ["dt-pag-nav-addressbook"],
8611 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8612 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8613 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8614 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8615 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8617 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8621 //Override Paging request construction
8622 grid.set("generateRequest", function(oState, oSelf) {
8623 oState = oState || {pagination:null, sortedBy:null};
8624 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8625 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8626 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8627 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8628 // Build the request
8630 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8631 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8632 ((results !== null) ? "&limit=" + results : "");
8636 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8637 oPayload = oPayload || { };
8638 oPayload.totalRecords = oResponse.meta.total;
8642 grid.clickToggleSelect= function(args) {
8643 var isIE = (args.event.target == null);
8644 var targetElement = isIE ? args.event.srcElement : args.event.target;
8645 if(targetElement.type == null || targetElement.type != 'checkbox') {
8646 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8650 grid.reSelectRowsOnRender = function (){
8651 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8652 for (var i = 0; i < rows.length; i++)
8654 var emailAddress = rows[i].getData("email");
8655 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8658 rows[i].setData("selected", true);
8659 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8663 rows[i].setData("selected", false);
8664 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8668 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8669 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8670 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8671 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8674 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8675 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8677 grid.toggleSelectCheckbox = function(id,checked){
8678 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8679 row.setData("checked",checked);
8681 grid.toggleSelect = function(id, checked) {
8682 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8683 checked = row.getData("selected");
8686 SUGAR.email2.addressBook.grid.selectRow(row);
8687 SE.addressBook.insertContactRowToResultTable(id,null)
8690 SUGAR.email2.addressBook.grid.unselectRow(row);
8691 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8693 row.setData("selected", !checked);
8696 grid.toggleSelectAll = function(checked) {
8697 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8698 for (var i = 0; i < rows.length; i++) {
8699 if (typeof(rows[i]) != "undefined")
8700 rows[i].setData("checked", checked);
8702 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8703 for (var i = 0; i < checkBoxes.length; i++) {
8704 checkBoxes[i].checked = checked;
8708 //Initialize the grid result table.
8709 AddressSearchResultsGridInit();
8715 * Initalize the results table for the address book selection.
8718 function AddressSearchResultsGridInit()
8721 /* Full name sort funciton to compare by last name if available */
8722 var fullNameSort = function(a, b, desc) {
8723 // Deal with empty values
8724 if(!YAHOO.lang.isValue(a))
8725 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8726 else if(!YAHOO.lang.isValue(b))
8729 var aNames = a.getData("name").split(' ');
8730 var bNames = b.getData("name").split(' ');
8732 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8733 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8735 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8739 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8740 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8741 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8743 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})},
8744 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8746 var myDataSource = new YAHOO.util.DataSource([]);
8747 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8748 myDataSource.responseSchema = {
8749 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8752 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8753 width: "350px",height: "250px", MSG_EMPTY: " "});
8755 var highlightEditableCell = function(oArgs) {
8756 var elCell = oArgs.target;
8757 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8758 this.highlightCell(elCell);
8762 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8763 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8764 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8765 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8766 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8768 //Setup the context menus
8769 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8770 var task = p_aArgs[1];
8773 var elRow = this.contextEventTarget;
8774 elRow = p_myDataTable.getTrEl(elRow);
8781 var oRecord = p_myDataTable.getRecord(elRow);
8782 p_myDataTable.deleteRow(elRow);
8783 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8788 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8789 {trigger:gridResults.getTbodyEl()});
8790 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8791 contextMenu.render("addrSearchResultGrid");
8792 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8794 // End of File modules/Emails/javascript/grid.js
8796 /*********************************************************************************
8797 * SugarCRM Community Edition is a customer relationship management program developed by
8798 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8800 * This program is free software; you can redistribute it and/or modify it under
8801 * the terms of the GNU Affero General Public License version 3 as published by the
8802 * Free Software Foundation with the addition of the following permission added
8803 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8804 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8805 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8807 * This program is distributed in the hope that it will be useful, but WITHOUT
8808 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8809 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8812 * You should have received a copy of the GNU Affero General Public License along with
8813 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8814 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8817 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8818 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8820 * The interactive user interfaces in modified source and object code versions
8821 * of this program must display Appropriate Legal Notices, as required under
8822 * Section 5 of the GNU Affero General Public License version 3.
8824 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8825 * these Appropriate Legal Notices must retain the display of the "Powered by
8826 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8827 * technical reasons, the Appropriate Legal Notices must display the words
8828 * "Powered by SugarCRM".
8829 ********************************************************************************/
8832 /******************************************************************************
8833 * Initialize Email 2.0 Application
8836 //Override Sugar Languge so quick creates work properly
8839 function email2init() {
8842 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
8843 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
8844 if (!SUGAR.util.isTouchScreen()) {
8846 convert_urls : false,
8847 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
8848 width: tinyConfig.width,
8849 theme: tinyConfig.theme,
8850 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
8851 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
8852 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
8853 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
8854 plugins : tinyConfig.plugins,
8855 elements : tinyConfig.elements,
8856 language : tinyConfig.language,
8857 extended_valid_elements : tinyConfig.extended_valid_elements,
8858 mode: tinyConfig.mode,
8859 strict_loading_mode : true,
8860 force_br_newlines : true,
8861 forced_root_block : '',
8862 directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
8866 // initialze message overlay
8867 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
8877 if (SUGAR.themes.tempHideLeftCol)
8878 SUGAR.themes.tempHideLeftCol();
8880 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
8881 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
8883 // set defaults for YAHOO.util.DragDropManager
8884 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
8886 SUGAR.email2.nextYear = new Date();
8887 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
8890 // initialize and display UI framework (complexLayout.js)
8891 complexLayoutInit();
8893 // initialize and display grid (grid.js)
8896 // initialize treeview for folders
8898 SUGAR.email2.folders.rebuildFolders(true);
8901 //Setup the Message Box overlay
8902 /*Ext.MessageBox.maxWidth = 350;
8903 Ext.MessageBox.minProgressWidth = 350;
8905 ///////////////////////////////////////////////////////////////////////////
8908 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
8910 var SEC = SUGAR.email2.contextMenus;
8913 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
8914 trigger: SUGAR.email2.grid.get("element"),
8917 emailMenu.subscribe("beforeShow", function() {
8918 var oTarget = this.contextEventTarget;
8919 if (typeof(oTarget) == "undefined")
8921 var grid = SUGAR.email2.grid;
8922 var selectedRows = grid.getSelectedRows();
8923 var multipleSelected = (selectedRows.length > 1) ? true: false;
8924 if (!multipleSelected)
8926 grid.unselectAllRows();
8927 grid.selectRow(oTarget);
8928 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8930 else if(multipleSelected)
8932 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8936 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
8937 //us to access individual elements easier by name rather than by index
8938 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
8939 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
8940 emailMenu.addItems([
8942 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
8943 id: 'showDetailView',
8944 onclick: { fn: SEC.showDetailView }
8947 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
8948 onclick: { fn: SEC.openMultiple }
8951 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
8952 onclick: { fn: SEC.archiveToSugar }
8955 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
8957 onclick: { fn: SEC.replyForwardEmailContext }
8960 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
8962 onclick: { fn: SEC.replyForwardEmailContext }
8965 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
8967 onclick: { fn: SEC.replyForwardEmailContext }
8970 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
8972 onclick: { fn: SEC.markDeleted }
8975 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
8977 onclick: { fn: SEC.viewPrintable }
8981 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
8983 id: "markEmailMenu",
8986 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
8987 onclick: { fn: SEC.markUnread }
8990 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
8991 onclick: { fn: SEC.markRead }
8994 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
8995 onclick: { fn: SEC.markFlagged }
8998 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
8999 onclick: { fn: SEC.markUnflagged }
9005 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9007 onclick: { fn: SEC.assignEmailsTo }
9010 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9012 onclick: { fn: SEC.relateTo }
9015 SEC.emailListContextMenu.render();
9017 //Handle the Tree folder menu trigger ourselves
9018 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9022 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9026 SEC.frameFoldersContextMenu.addItems([
9027 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9028 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9029 onclick: { fn: function() {
9030 var node = SUGAR.email2.clickedFolderNode;
9031 if (node.data.ieId) {
9032 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9035 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9036 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9037 onclick: { fn: function() {
9038 var node = SUGAR.email2.clickedFolderNode;
9039 if (node.data.ieId) {
9040 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9044 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9045 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9046 onclick: { fn: SUGAR.email2.folders.folderAdd }
9049 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9050 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9051 onclick: { fn: SUGAR.email2.folders.folderDelete }
9054 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9055 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9056 onclick: { fn: SUGAR.email2.folders.folderRename }
9059 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9060 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9061 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9064 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9065 onclick: { fn: function() {
9066 var node = SUGAR.email2.clickedFolderNode;
9067 if (node.data.ieId) {
9068 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9072 SEC.frameFoldersContextMenu.render();
9074 SEC.initContactsMenu = function() {
9076 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9077 trigger: "contacts",
9080 SEC.contactsContextMenu.addItems([
9082 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9083 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9086 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9087 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9090 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9091 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9092 if (oTarget && !grid.isSelected(oTarget)) {
9093 grid.unselectAllRows();
9094 grid.selectRow(oTarget);
9097 SEC.contactsContextMenu.render();
9101 // set auto-check timer
9102 SUGAR.email2.folders.startCheckTimer();
9103 // check if we're coming from an email-link click
9104 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9106 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9108 //Init fix for YUI 2.7.0 datatable sort.
9109 SUGAR.email2.addressBook.initFixForDatatableSort();
9112 function createTreePanel(treeData, params) {
9113 var tree = new YAHOO.widget.TreeView(params.id);
9114 var root = tree.getRoot();
9116 //if (treeData.nodes && treeData[0].id == "Home")
9117 // treeData = treeData[0];
9121 function addChildNodes(parentNode, parentData) {
9122 var Ck = YAHOO.util.Cookie;
9123 var nextyear = SUGAR.email2.nextYear;
9124 var nodes = parentData.nodes || parentData.children;
9126 if (typeof(nodes[i]) == 'object') {
9127 if (nodes[i].data) {
9128 // See comment about href below.
9129 // nodes[i].data.href = '#';
9130 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode);
9131 node.action = nodes[i].data.action;
9133 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9134 addChildNodes(parentNode, nodes[i]);
9137 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9138 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9140 nodes[i].className = nodes[i].cls;
9142 // Previously, span was added in the label so it was rendering in the tree.
9143 // Default behavior is to wrap in span if no href property, and since this href
9144 // doesn't do anything, remove it so that it will be wrapped in spans.
9145 // nodes[i].href = "#";
9146 if (nodes[i].text) nodes[i].label = nodes[i].text;
9147 //Override YUI child node creation
9148 if (nodes[i].children) {
9149 nodes[i].nodes = nodes[i].children;
9150 nodes[i].children = [ ];
9152 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9155 if (typeof(nodes[i].nodes) == 'object') {
9156 addChildNodes(node, nodes[i]);
9163 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9165 function email2treeinit(tree, treedata, treediv, params) {
9166 //ensure the tree data is not corrupt
9170 if (SUGAR.email2.tree) {
9171 SUGAR.email2.tree.destroy();
9172 SUGAR.email2.tree = null;
9175 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9179 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9180 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9181 tree.subscribe("expandComplete", function(node){
9182 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9183 for (var i in node.children) {
9184 SE.accounts.setupDDTarget(node.children[i]);
9187 tree.setCollapseAnim("TVSlideOut");
9188 tree.setExpandAnim("TVSlideIn");
9189 var root = tree.root;
9190 while (root.hasChildren()) {
9191 var node = root.children[0];
9193 tree.removeNode(root.children[0], false);
9195 addChildNodes(root, treedata);
9197 SUGAR.email2.accounts.renderTree();
9200 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9201 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9205 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9206 startDrag: function(x, y) {
9207 var Dom = YAHOO.util.Dom;
9208 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9211 var dragEl = this.getDragEl();
9212 var clickEl = this.getEl();
9213 Dom.setStyle(clickEl, "color", "#AAA");
9214 Dom.setStyle(clickEl, "opacity", "0.25");
9215 dragEl.innerHTML = clickEl.innerHTML;
9217 Dom.addClass(dragEl, "ygtvcell");
9218 Dom.addClass(dragEl, "ygtvcontent");
9219 Dom.addClass(dragEl, "folderDragProxy");
9220 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9221 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9222 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9223 Dom.setStyle(dragEl, "opacity", "0.5");
9224 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9227 onDragOver: function(ev, id) {
9228 var Dom = YAHOO.util.Dom;
9229 if (id != this.dragId)
9231 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9232 if(node.data.cls != "sugarFolder") {
9233 SUGAR.email2.folders.unhighliteAll();
9237 this.targetNode = node;
9238 SUGAR.email2.folders.unhighliteAll();
9243 onDragOut: function(e, id) {
9244 if (this.targetNode) {
9245 SUGAR.email2.folders.unhighliteAll();
9246 this.targetNode = false;
9247 this.dragId = false;
9251 endDrag: function() {
9252 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9253 if (this.targetNode) {
9254 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9257 });// End of File modules/Emails/javascript/init.js
9259 /*********************************************************************************
9260 * SugarCRM Community Edition is a customer relationship management program developed by
9261 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9263 * This program is free software; you can redistribute it and/or modify it under
9264 * the terms of the GNU Affero General Public License version 3 as published by the
9265 * Free Software Foundation with the addition of the following permission added
9266 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9267 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9268 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9270 * This program is distributed in the hope that it will be useful, but WITHOUT
9271 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9272 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9275 * You should have received a copy of the GNU Affero General Public License along with
9276 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9277 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9280 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9281 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9283 * The interactive user interfaces in modified source and object code versions
9284 * of this program must display Appropriate Legal Notices, as required under
9285 * Section 5 of the GNU Affero General Public License version 3.
9287 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9288 * these Appropriate Legal Notices must retain the display of the "Powered by
9289 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9290 * technical reasons, the Appropriate Legal Notices must display the words
9291 * "Powered by SugarCRM".
9292 ********************************************************************************/
9297 function complexLayoutInit() {
9298 var se = SUGAR.email2;
9299 var Dom = YAHOO.util.Dom;
9301 getInnerLayout : function(rows) {
9302 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
9303 parent: se.complexLayout,
9309 scroll:false, // grid should autoScroll itself
9311 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
9319 body: "<div id='listBottom' />"
9327 body: "<div id='listRight' />",
9328 titlebar: false //,header: "right"
9331 se.complexLayout.on("render", function(){
9332 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
9333 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9334 SUGAR.email2.listViewLayout.set("height", height);
9335 SUGAR.email2.listViewLayout.render();
9337 se.listViewLayout.render();
9339 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
9340 var rp = se.listViewLayout.resizePreview = function() {
9341 var pre = Dom.get("displayEmailFramePreview");
9343 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
9344 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
9347 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
9348 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
9349 se.e2Layout.setPreviewPanel(rows);
9350 se.previewLayout = se.listViewLayout;
9351 return se.listViewLayout;
9354 getInnerLayout2Rows : function() {
9355 return this.getInnerLayout(true);
9357 getInnerLayout2Columns : function() {
9358 return this.getInnerLayout(false);
9362 // initialize state manager, we will use cookies
9363 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
9364 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
9365 se.complexLayout = new YAHOO.widget.Layout("container", {
9368 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
9369 width: Dom.getViewportWidth() - 40,
9373 body: "<div id='emailtabs'></div>"
9378 body: "<div id='lefttabs'></div>",
9388 header: Dom.get('footerLinks').innerHTML,
9395 se.complexLayout.render();
9396 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
9397 tp.addTab(new YAHOO.widget.Tab({
9400 content : "<div id='listViewDiv'/>",
9404 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
9405 tp.appendTo(centerEl);
9407 tp.get("element").style.borderRight = "1px solid #666"
9409 var listV = this.getInnerLayout2Rows();
9410 listV.set("height", tp.get("element").clientHeight - 25);
9413 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
9414 var folderTab = new YAHOO.widget.Tab({
9415 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
9417 content : "<div id='emailtree'/>",
9421 folderTab.on("activeChange", function(o){
9423 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
9426 se.leftTabs.addTab(folderTab);
9428 var tabContent = SUGAR.util.getAndRemove("searchTab");
9429 var searchTab = new YAHOO.widget.Tab({
9430 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
9432 content : tabContent.innerHTML,
9435 searchTab.on("activeChange", function(o){
9438 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
9439 //Setup the calendars if needed
9440 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
9441 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
9443 //Initalize sqs object for assigned user name
9444 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
9446 //Attach event handler for when the relate module option is selected for the correct sqs object
9447 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
9448 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
9449 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
9450 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
9452 //If enter key is pressed, perform search
9453 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
9454 for(var i=0; i < addKeyPressFields.length;i++)
9456 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
9457 if (e.keyCode == 13) {
9458 YAHOO.util.Event.stopEvent(e);
9459 SUGAR.email2.search.searchAdvanced();
9463 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
9465 //Clear parent values if selecting another parent type.
9466 YAHOO.util.Event.addListener('data_parent_type_search','change',
9468 document.getElementById('data_parent_id_search').value ='';
9469 document.getElementById('data_parent_name_search').value ='';
9474 se.leftTabs.addTab(searchTab);
9476 var resizeTabBody = function() {
9477 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
9478 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9481 se.complexLayout.on("render", resizeTabBody);
9482 se.leftTabs.on("activeTabChange", resizeTabBody);
9483 //hack to allow left pane scroll bar to fully show
9484 var lefttabsDiv = document.getElementById('lefttabs');
9485 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
9486 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
9487 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
9490 initSQSObject: function(formName,fieldName)
9492 var fullFieldName = formName + '_' + fieldName; //SQS Convention
9493 var resultName = fullFieldName + '_' + 'results';
9495 if (QSFieldsArray[fullFieldName] != null)
9497 QSFieldsArray[fullFieldName].destroy();
9498 delete QSFieldsArray[fullFieldName];
9500 if (QSProcessedFieldsArray[fullFieldName])
9501 QSProcessedFieldsArray[fullFieldName] = false;
9503 if( Dom.get(resultName) )
9505 var obj = document.getElementById(resultName);
9506 obj.parentNode.removeChild(obj);
9509 setPreviewPanel: function(rows) {
9511 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9512 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9513 Dom.get("listRight").innerHTML = "";
9514 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9516 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9517 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9518 Dom.get("listBottom").innerHTML = "";
9519 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9526 var myBufferedListenerObject = new Object();
9527 myBufferedListenerObject.refit = function() {
9528 if(SUGAR.email2.grid) {
9529 SUGAR.email2.grid.autoSize();
9532 // End of File modules/Emails/javascript/complexLayout.js
9534 /*********************************************************************************
9535 * SugarCRM Community Edition is a customer relationship management program developed by
9536 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9538 * This program is free software; you can redistribute it and/or modify it under
9539 * the terms of the GNU Affero General Public License version 3 as published by the
9540 * Free Software Foundation with the addition of the following permission added
9541 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9542 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9543 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9545 * This program is distributed in the hope that it will be useful, but WITHOUT
9546 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9547 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9550 * You should have received a copy of the GNU Affero General Public License along with
9551 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9552 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9555 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9556 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9558 * The interactive user interfaces in modified source and object code versions
9559 * of this program must display Appropriate Legal Notices, as required under
9560 * Section 5 of the GNU Affero General Public License version 3.
9562 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9563 * these Appropriate Legal Notices must retain the display of the "Powered by
9564 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9565 * technical reasons, the Appropriate Legal Notices must display the words
9566 * "Powered by SugarCRM".
9567 ********************************************************************************/
9569 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9570 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9571 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9572 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9573 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9574 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9575 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9576 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9577 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9578 ' <input type="hidden" id="composeType" name="composeType">' +
9579 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9580 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9581 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9582 ' <input type="hidden" id="sendTo" name="sendTo">' +
9583 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9584 ' <input type="hidden" id="sendCc" name="sendCc">' +
9585 ' <input type="hidden" id="setEditor" name="setEditor">' +
9586 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9587 ' <input type="hidden" id="parent_id" name="parent_id">' +
9588 ' <input type="hidden" id="parent_type" name="parent_type">' +
9589 ' <input type="hidden" id="attachments" name="attachments">' +
9590 ' <input type="hidden" id="documents" name="documents">' +
9591 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9592 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9593 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9594 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9596 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9597 ' <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>' +
9598 ' <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>' +
9599 ' <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>' +
9600 ' <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>' +
9601 '</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>' +
9602 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9603 '<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>' +
9604 ' </td></tr></tbody></table></th>' +
9608 ' <div style="margin:5px;">' +
9609 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9611 ' <td class="emailUILabel" NOWRAP >' +
9612 ' {app_strings.LBL_EMAIL_FROM}:' +
9614 ' <td class="emailUIField" NOWRAP>' +
9616 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9621 ' <td class="emailUILabel" NOWRAP>' +
9622 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9623 ' {app_strings.LBL_EMAIL_TO}:' +
9626 ' <td class="emailUIField" NOWRAP>' +
9627 ' <div class="ac_autocomplete">' +
9628 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9629 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9630 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9634 ' <tr id="add_addr_options_tr{idx}">' +
9635 ' <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>'+
9637 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9638 ' <td class="emailUILabel" NOWRAP>' +
9639 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9640 ' {app_strings.LBL_EMAIL_CC}:' +
9643 ' <td class="emailUIField" NOWRAP>' +
9644 ' <div class="ac_autocomplete">' +
9645 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9646 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9647 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9651 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9652 ' <td class="emailUILabel" NOWRAP>' +
9653 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9654 ' {app_strings.LBL_EMAIL_BCC}:' +
9657 ' <td class="emailUIField" NOWRAP>' +
9658 ' <div class="ac_autocomplete">' +
9659 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9660 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9661 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9666 ' <td class="emailUILabel" NOWRAP width="1%">' +
9667 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9669 ' <td class="emailUIField" NOWRAP width="99%">' +
9670 ' <div class="ac_autocomplete">' +
9671 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9680 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9681 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9682 ' <div style="padding:5px;">' +
9683 ' <table cellpadding="2" cellspacing="0" border="0">' +
9686 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9693 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9694 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9706 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9713 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9714 ' <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>' +
9726 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9733 ' <div id="addedTemplateAttachments{idx}"></div>' +
9740 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9741 ' <div style="padding:5px;">' +
9742 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9743 ' <table border="0" width="100%">' +
9745 ' <td NOWRAP style="padding:2px;">' +
9746 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9750 ' <td NOWRAP style="padding:2px;">' +
9751 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9756 ' <table border="0" width="100%">' +
9758 ' <td NOWRAP style="padding:2px;">' +
9759 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9763 ' <td NOWRAP style="padding:2px;">' +
9764 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9768 ' <table border="0" width="100%">' +
9770 ' <td NOWRAP style="padding:2px;">' +
9771 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9772 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9780 // End of File modules/Emails/javascript/composeEmailTemplate.js
9782 /*********************************************************************************
9783 * SugarCRM Community Edition is a customer relationship management program developed by
9784 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9786 * This program is free software; you can redistribute it and/or modify it under
9787 * the terms of the GNU Affero General Public License version 3 as published by the
9788 * Free Software Foundation with the addition of the following permission added
9789 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9790 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9791 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9793 * This program is distributed in the hope that it will be useful, but WITHOUT
9794 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9795 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9798 * You should have received a copy of the GNU Affero General Public License along with
9799 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9800 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9803 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9804 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9806 * The interactive user interfaces in modified source and object code versions
9807 * of this program must display Appropriate Legal Notices, as required under
9808 * Section 5 of the GNU Affero General Public License version 3.
9810 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9811 * these Appropriate Legal Notices must retain the display of the "Powered by
9812 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9813 * technical reasons, the Appropriate Legal Notices must display the words
9814 * "Powered by SugarCRM".
9815 ********************************************************************************/
9817 SUGAR.email2.templates['displayOneEmail'] =
9818 '<div class="emailDetailTable" style="height:100%">' +
9819 '<div id="viewMenuDiv{idx}"></div>' +
9820 '<div width="100%" class="displayEmailValue">' +
9821 ' <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>' +
9822 ' <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>' +
9823 ' <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>' +
9824 ' <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>' +
9825 ' <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>' +
9826 ' <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>' +
9827 ' <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>' +
9828 ' <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>' +
9829 ' <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>' +
9831 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9833 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9834 ' {app_strings.LBL_EMAIL_FROM}:' +
9836 ' <td width="99%" class="displayEmailValue">' +
9837 ' {email.from_addr}' +
9841 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9842 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9844 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9845 ' <b>{email.name}</b>' +
9849 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9850 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9852 ' <td class="displayEmailValue">' +
9853 ' {email.date_start} {email.time_start}' +
9857 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9858 ' {app_strings.LBL_EMAIL_TO}:' +
9860 ' <td class="displayEmailValue">' +
9861 ' {email.toaddrs}' +
9864 ' <tr>{meta.cc}</tr>' +
9865 ' <tr>{email.attachments}</tr>' +
9867 ' <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>' +
9868 //' {email.description}' +
9870 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9872 /*********************************************************************************
9873 * SugarCRM Community Edition is a customer relationship management program developed by
9874 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9876 * This program is free software; you can redistribute it and/or modify it under
9877 * the terms of the GNU Affero General Public License version 3 as published by the
9878 * Free Software Foundation with the addition of the following permission added
9879 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9880 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9881 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9883 * This program is distributed in the hope that it will be useful, but WITHOUT
9884 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9885 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9888 * You should have received a copy of the GNU Affero General Public License along with
9889 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9890 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9893 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9894 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9896 * The interactive user interfaces in modified source and object code versions
9897 * of this program must display Appropriate Legal Notices, as required under
9898 * Section 5 of the GNU Affero General Public License version 3.
9900 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9901 * these Appropriate Legal Notices must retain the display of the "Powered by
9902 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9903 * technical reasons, the Appropriate Legal Notices must display the words
9904 * "Powered by SugarCRM".
9905 ********************************************************************************/
9907 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9908 '<body onload="javascript:window.print();">' +
9912 ' font-family: helvetica, impact, sans-serif;' +
9913 ' font-size : 12pt;' +
9920 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9923 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9925 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9926 ' {app_strings.LBL_EMAIL_FROM}:' +
9928 ' <td width="99%" class="displayEmailValue">' +
9929 ' {email.from_name} <{email.from_addr}>' +
9933 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9934 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9936 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9937 ' <b>{email.name}</b>' +
9941 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9942 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9944 ' <td class="displayEmailValue">' +
9945 ' {email.date_start} {email.time_start}' +
9949 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9950 ' {app_strings.LBL_EMAIL_TO}:' +
9952 ' <td class="displayEmailValue">' +
9953 ' {email.toaddrs}' +
9957 ' {email.attachments}' +
9963 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9965 ' <td style="border-top: 1px solid #333;">' +
9966 ' <div style="padding:5px;">' +
9967 '{email.description}' +
9977 // End of File modules/Emails/javascript/viewPrintable.js
9979 /*********************************************************************************
9980 * SugarCRM Community Edition is a customer relationship management program developed by
9981 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9983 * This program is free software; you can redistribute it and/or modify it under
9984 * the terms of the GNU Affero General Public License version 3 as published by the
9985 * Free Software Foundation with the addition of the following permission added
9986 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9987 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9988 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9990 * This program is distributed in the hope that it will be useful, but WITHOUT
9991 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9992 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9995 * You should have received a copy of the GNU Affero General Public License along with
9996 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9997 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
10000 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
10001 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
10003 * The interactive user interfaces in modified source and object code versions
10004 * of this program must display Appropriate Legal Notices, as required under
10005 * Section 5 of the GNU Affero General Public License version 3.
10007 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
10008 * these Appropriate Legal Notices must retain the display of the "Powered by
10009 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
10010 * technical reasons, the Appropriate Legal Notices must display the words
10011 * "Powered by SugarCRM".
10012 ********************************************************************************/
10013 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
10014 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;}
10015 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');}
10016 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;}}
10017 if(QSProcessedFieldsArray[qs_index_id]){continue;}
10018 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
10019 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}
10020 if(!loaded){QSProcessedFieldsArray[qs_index_id]=true;qsFields[qsField].form_id=form_id;var sqs=sqs_objects[qs_index_id];var resultDiv=document.createElement('div');resultDiv.id=combo_id+"_results";Dom.insertAfter(resultDiv,qsFields[qsField]);var fields=qs_obj.field_list.slice();fields[fields.length]="module";var ds=new YAHOO.util.DataSource("index.php?",{responseType:YAHOO.util.XHRDataSource.TYPE_JSON,responseSchema:{resultsList:'fields',total:'totalCount',fields:fields,metaNode:"fields",metaFields:{total:'totalCount',fields:"fields"}},connMethodPost:true});var forceSelect=!((qsFields[qsField].form&&typeof(qsFields[qsField].form)=='object'&&qsFields[qsField].form.name=='search_form')||qsFields[qsField].className.match('sqsNoAutofill')!=null);var search=new YAHOO.widget.AutoComplete(qsFields[qsField],resultDiv,ds,{typeAhead:forceSelect,forceSelection:forceSelect,fields:fields,sqs:sqs,animSpeed:0.25,qs_obj:qs_obj,inputElement:qsFields[qsField],generateRequest:function(sQuery){var out=SUGAR.util.paramsToUrl({to_pdf:'true',module:'Home',action:'quicksearchQuery',data:encodeURIComponent(YAHOO.lang.JSON.stringify(this.sqs)),query:sQuery});return out;},setFields:function(data,filter){this.updateFields(data,filter);},updateFields:function(data,filter){for(var i in this.fields){for(var key in this.qs_obj.field_list){if(this.fields[i]==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&this.qs_obj.populate_list[key].match(filter)){var displayValue=data[i].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value=displayValue;}}}},clearFields:function(){for(var key in this.qs_obj.field_list){if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]){document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";}}
10021 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
10022 {search.clearFields=function(){};search.setFields=function(data,filter)
10023 {var label_str='';var label_data_str='';var current_label_data_str='';var label_data_hash=new Array();for(var i in this.fields){for(var key in this.qs_obj.field_list){if(this.fields[i]==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&document.getElementById(this.qs_obj.populate_list[key]+'_label')&&this.qs_obj.populate_list[key].match(filter)){var displayValue=data[i].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');var data_label=document.getElementById(this.qs_obj.populate_list[key]+'_label').innerHTML.replace(/\n/gi,'');label_and_data=data_label+' '+displayValue;if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&!label_data_hash[data_label])
10024 {label_str+=data_label+' \n';label_data_str+=label_and_data+'\n';label_data_hash[data_label]=true;current_label_data_str+=data_label+' '+document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value+'\n';}}}}
10025 if(label_str!=current_label_data_str&¤t_label_data_str!=label_data_str){module_key=(typeof document.forms[form_id].elements['module']!='undefined')?document.forms[form_id].elements['module'].value:'app_strings';warning_label=SUGAR.language.translate(module_key,'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM')+'\n\n'+label_data_str;if(!confirm(warning_label))
10026 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
10027 {if(this.inputElement.id=='shipping_account_name')
10028 {filter=Dom.get('shipping_checkbox').checked?/(account_id|office_phone)/:filter;}else if(this.inputElement.id=='billing_account_name'){filter=Dom.get('shipping_checkbox').checked?filter:/(account_id|office_phone|billing)/;}}else if(Dom.get('alt_checkbox')){filter=Dom.get('alt_checkbox').checked?filter:/^(?!alt)/;}
10029 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
10030 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
10031 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];}}}
10032 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]];}
10033 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});search.typeAheadEvent.subscribe(function(e,args){this.getInputEl().value=this.getInputEl().value.replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
10034 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
10035 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}
10036 // End of File include/javascript/quicksearch.js