2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
5 * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6 * dragged element is inserted before the dragged-over element.
8 * @extends YAHOO.util.DDProxy
10 * @param {String} id the id of the linked element
11 * @param {String} sGroup the group of related DragDrop objects
13 function ygDDList(id, sGroup) {
16 this.init(id, sGroup);
18 //this.logger = new ygLogger("ygDDList");
21 var s = this.getDragEl().style;
22 s.borderColor = "transparent";
23 s.backgroundColor = "#f6f5e5";
25 s.filter = "alpha(opacity=76)";
28 ygDDList.prototype = new YAHOO.util.DDProxy();
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
33 ygDDList.prototype.startDrag = function(x, y) {
34 //this.logger.debug(this.id + " startDrag");
36 var dragEl = this.getDragEl();
37 var clickEl = this.getEl();
39 dragEl.innerHTML = clickEl.innerHTML;
40 dragElObjects = dragEl.getElementsByTagName('object');
43 dragEl.className = clickEl.className;
44 dragEl.style.color = clickEl.style.color;
45 dragEl.style.border = "1px solid #aaa";
47 // save the style of the object
48 clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
50 this.borderDiv = document.createElement('div'); // create a div to display border
51 this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52 this.borderDiv.style.border = '2px dashed #cccccc';
54 for(i in clickEl.childNodes) { // hide contents of the target elements contents
55 if(typeof clickEl.childNodes[i].style != 'undefined') {
56 this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57 clickEl.childNodes[i].style.display = 'none';
61 clickEl.appendChild(this.borderDiv);
64 ygDDList.prototype.endDrag = function(e) {
65 // disable moving the linked element
66 var clickEl = this.getEl();
68 clickEl.removeChild(this.borderDiv); // remove border div
70 for(i in clickEl.childNodes) { // show target elements contents
71 if(typeof clickEl.childNodes[i].style != 'undefined') {
72 clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
77 clickEl.style.height = this.clickHeight;
79 clickEl.style.height = '';
82 clickEl.style.border = this.clickBorder;
84 clickEl.style.border = '';
86 dragEl = this.getDragEl();
87 dragEl.innerHTML = '';
92 ygDDList.prototype.afterEndDrag = function(e) {
96 ygDDList.prototype.onDrag = function(e, id) {
100 ygDDList.prototype.onDragOver = function(e, id) {
101 // this.logger.debug(this.id.toString() + " onDragOver " + id);
104 if ("string" == typeof id) {
105 el = YAHOO.util.DDM.getElement(id);
107 el = YAHOO.util.DDM.getBestMatch(id).getEl();
110 dragEl = this.getDragEl();
111 elRegion = YAHOO.util.Dom.getRegion(el);
113 // this.logger.debug('id: ' + el.id);
114 // this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 // this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116 var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 // this.logger.debug('mid: ' + mid);
119 // this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " < " + mid);
120 // this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
122 if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123 var el2 = this.getEl();
124 var p = el.parentNode;
125 p.insertBefore(el2, el);
127 if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128 var el2 = this.getEl();
129 var p = el.parentNode;
130 p.insertBefore(el2, el.nextSibling);
134 ygDDList.prototype.onDragEnter = function(e, id) {
135 // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136 // this.getDragEl().style.border = "1px solid #449629";
139 ygDDList.prototype.onDragOut = function(e, id) {
140 // I need to know when we are over nothing
141 // this.getDragEl().style.border = "1px solid #964428";
144 /////////////////////////////////////////////////////////////////////////////
146 function ygDDListBoundary(id, sGroup) {
148 this.init(id, sGroup);
149 //this.logger = new ygLogger("ygDDListBoundary");
150 this.isBoundary = true;
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
157 /*********************************************************************************
158 * SugarCRM Community Edition is a customer relationship management program developed by
159 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
161 * This program is free software; you can redistribute it and/or modify it under
162 * the terms of the GNU Affero General Public License version 3 as published by the
163 * Free Software Foundation with the addition of the following permission added
164 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
168 * This program is distributed in the hope that it will be useful, but WITHOUT
169 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
173 * You should have received a copy of the GNU Affero General Public License along with
174 * this program; if not, see http://www.gnu.org/licenses or write to the Free
175 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
178 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
181 * The interactive user interfaces in modified source and object code versions
182 * of this program must display Appropriate Legal Notices, as required under
183 * Section 5 of the GNU Affero General Public License version 3.
185 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186 * these Appropriate Legal Notices must retain the display of the "Powered by
187 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188 * technical reasons, the Appropriate Legal Notices must display the words
189 * "Powered by SugarCRM".
190 ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span> </span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&themeName=Sugar&imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace(''',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML=' ';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};addToValidate(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,'email',this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
216 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
217 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
218 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
219 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
220 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
221 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
222 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
223 if(SUGAR.isIE){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
224 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
225 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();
226 // End of File include/SugarEmailAddress/SugarEmailAddress.js
228 /*********************************************************************************
229 * SugarCRM Community Edition is a customer relationship management program developed by
230 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
232 * This program is free software; you can redistribute it and/or modify it under
233 * the terms of the GNU Affero General Public License version 3 as published by the
234 * Free Software Foundation with the addition of the following permission added
235 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
236 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
237 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
239 * This program is distributed in the hope that it will be useful, but WITHOUT
240 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
241 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
244 * You should have received a copy of the GNU Affero General Public License along with
245 * this program; if not, see http://www.gnu.org/licenses or write to the Free
246 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
249 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
250 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
252 * The interactive user interfaces in modified source and object code versions
253 * of this program must display Appropriate Legal Notices, as required under
254 * Section 5 of the GNU Affero General Public License version 3.
256 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
257 * these Appropriate Legal Notices must retain the display of the "Powered by
258 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
259 * technical reasons, the Appropriate Legal Notices must display the words
260 * "Powered by SugarCRM".
261 ********************************************************************************/
262 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
263 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
264 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
265 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
266 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
267 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
268 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
269 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){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]);}}
270 this.js_more();this.js_more();}
271 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
272 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
273 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);}}}
274 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
275 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';}
276 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);}}
277 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);}}}
278 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++;}}}
279 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
280 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='';}}
282 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;}
284 if(!has_primary){return false;}
286 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);}}}
287 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;}}}}
288 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;}
289 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();}}}}
290 if(noAdd){enableQS(false);}
291 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);}}}
293 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
294 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=='';}
296 SUGAR.collection.safe_clone=function(e,recursive)
297 {if(e.nodeName=="#text")
298 {return document.createTextNode(e.data);}
299 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')
300 {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'];}
301 for(var i in properties)
302 {if(e[properties[i]])
303 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
304 newNode[properties[i]]=e[properties[i]];}}
306 {for(var i in e.childNodes)
307 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
308 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
310 // End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
312 /*********************************************************************************
313 * SugarCRM Community Edition is a customer relationship management program developed by
314 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
316 * This program is free software; you can redistribute it and/or modify it under
317 * the terms of the GNU Affero General Public License version 3 as published by the
318 * Free Software Foundation with the addition of the following permission added
319 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
320 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
321 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
323 * This program is distributed in the hope that it will be useful, but WITHOUT
324 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
325 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
328 * You should have received a copy of the GNU Affero General Public License along with
329 * this program; if not, see http://www.gnu.org/licenses or write to the Free
330 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
333 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
334 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
336 * The interactive user interfaces in modified source and object code versions
337 * of this program must display Appropriate Legal Notices, as required under
338 * Section 5 of the GNU Affero General Public License version 3.
340 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
341 * these Appropriate Legal Notices must retain the display of the "Powered by
342 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
343 * technical reasons, the Appropriate Legal Notices must display the words
344 * "Powered by SugarCRM".
345 ********************************************************************************/
346 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);}
347 return s;},init:function(){if(Rot13.map!=null)
348 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
349 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
350 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
351 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='';}
352 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='';}
353 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='';}}
355 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)
356 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
357 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id:'';URL='index.php?'
358 +'module='+module_name
361 +'&target='+pageTarget
362 +'&target1='+pageTarget
363 +'&server_url='+mail_server
364 +'&email_user='+words[0]
365 +'&protocol='+protocol
367 +'&email_password='+words[1]
368 +'&mailbox='+words[2]
371 +'&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)
372 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
373 this.body.style.width=w}}
374 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
375 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();}
376 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'));}
377 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
378 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
379 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
380 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
381 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";}
383 alert(out);return false;}else{return true;}}
384 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?'
385 +'module='+module_name
388 +'&target='+pageTarget
389 +'&target1='+pageTarget
390 +'&server_url='+mail_server
391 +'&email_user='+words[0]
392 +'&protocol='+protocol
394 +'&email_password='+words[1]
395 +'&mailbox='+words[2]
397 +'&personal='+isPersonal
398 +'&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)
399 this.body.style.width=w}}
400 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();}
401 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;}}}
402 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';}}}
403 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='';}
404 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";}}
405 // End of File modules/InboundEmail/InboundEmail.js
407 /*********************************************************************************
408 * SugarCRM Community Edition is a customer relationship management program developed by
409 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
411 * This program is free software; you can redistribute it and/or modify it under
412 * the terms of the GNU Affero General Public License version 3 as published by the
413 * Free Software Foundation with the addition of the following permission added
414 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
415 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
416 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
418 * This program is distributed in the hope that it will be useful, but WITHOUT
419 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
420 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
423 * You should have received a copy of the GNU Affero General Public License along with
424 * this program; if not, see http://www.gnu.org/licenses or write to the Free
425 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
428 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
429 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
431 * The interactive user interfaces in modified source and object code versions
432 * of this program must display Appropriate Legal Notices, as required under
433 * Section 5 of the GNU Affero General Public License version 3.
435 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
436 * these Appropriate Legal Notices must retain the display of the "Powered by
437 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
438 * technical reasons, the Appropriate Legal Notices must display the words
439 * "Powered by SugarCRM".
440 ********************************************************************************/
443 cache : new Object(),
444 o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
445 reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
448 currentHtmleditor : ''
452 * preserves hits from email server
454 _setDetailCache : function(ret) {
456 var compKey = ret.meta.mbox + ret.meta.uid;
458 if(!SUGAR.email2.cache[compKey]) {
459 SUGAR.email2.cache[compKey] = ret;
464 autoSetLayout : function() {
465 var c = document.getElementById('container');
466 var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
467 //Ensure a minimum height.
468 tHeight = Math.max(tHeight, 550);
469 c.style.height = tHeight + "px";
470 SUGAR.email2.complexLayout.set('height', tHeight);
471 SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
472 SUGAR.email2.complexLayout.render();
473 SUGAR.email2.listViewLayout.resizePreview();
478 * Shows overlay progress message
480 function overlayModal(title, body) {
481 overlay(title, body);
483 function overlay(reqtitle, body, type, additconfig) {
485 if (typeof(additconfig) == "object") {
486 var config = additconfig;
489 config.title = reqtitle;
491 YAHOO.SUGAR.MessageBox.show(config);
494 function hideOverlay() {
495 YAHOO.SUGAR.MessageBox.hide();
497 // End of File modules/Emails/javascript/EmailUIShared.js
499 /*********************************************************************************
500 * SugarCRM Community Edition is a customer relationship management program developed by
501 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
503 * This program is free software; you can redistribute it and/or modify it under
504 * the terms of the GNU Affero General Public License version 3 as published by the
505 * Free Software Foundation with the addition of the following permission added
506 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
507 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
508 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
510 * This program is distributed in the hope that it will be useful, but WITHOUT
511 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
512 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
515 * You should have received a copy of the GNU Affero General Public License along with
516 * this program; if not, see http://www.gnu.org/licenses or write to the Free
517 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
520 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
521 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
523 * The interactive user interfaces in modified source and object code versions
524 * of this program must display Appropriate Legal Notices, as required under
525 * Section 5 of the GNU Affero General Public License version 3.
527 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
528 * these Appropriate Legal Notices must retain the display of the "Powered by
529 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
530 * technical reasons, the Appropriate Legal Notices must display the words
531 * "Powered by SugarCRM".
532 ********************************************************************************/
536 var sw = YAHOO.SUGAR,
537 Event = YAHOO.util.Event,
538 Connect = YAHOO.util.Connect,
542 ///////////////////////////////////////////////////////////////////////////////
545 outboundDialog : null,
546 inboundAccountEditDialog : null,
547 inboundAccountsSettingsTable : null,
548 outboundAccountsSettingsTable : null,
549 testOutboundDialog : null,
550 errorStyle : 'input-error',
552 newAddedOutboundId : '',
555 * makes async call to retrieve an outbound instance for editting
558 editOutbound : function(obi) {
560 AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
563 deleteOutbound : function(obi) {
565 if(obi.match(/^(add|line|sendmail)+/)) {
566 alert('Invalid Operation');
568 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
569 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
573 getReplyAddress : function() {
576 for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
577 var addy = SE.userPrefs.current_user.emailAddresses[i];
579 if(addy.primary_address == "1") {
580 primary = addy.email_address;
583 if(addy.reply_to == "1") {
584 return addy.email_address;
592 * Called on "Accounts" tab activation event
594 lazyLoad : function() {
596 this._setupInboundAccountTable();
597 this._setupOutboundAccountTable();
601 _setupInboundAccountTable: function()
603 //Setup the inbound mail settings
604 if(!this.inboundAccountsSettingsTable)
606 this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
607 var clckEvent = oColumn.key;
609 var is_group = oRecord.getData("is_group");
612 if(oColumn.key == 'edit')
614 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
615 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
617 else if(oColumn.key == 'delete')
619 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
620 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
622 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
626 this.showBoolean = function(el, oRecord, oColumn, oData)
628 var is_group = oRecord.getData("is_group");
629 var bChecked = oData;
630 bChecked = (bChecked) ? " checked" : "";
633 el.innerHTML = "<input type=\"radio\"" + bChecked +
634 " name=\"col" + oColumn.getId() + "-radio\"" +
635 " class=\"yui-dt-radio\">";
640 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
641 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
643 var typeHoverHelp = ' <div id="rollover"><a href="#" class="rollover">'+
644 '<img border="0" src="themes/default/images/helpInline.gif">' +
645 '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
648 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
649 {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
650 {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
651 {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
652 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
653 {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
654 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
655 this.ieDataSource = new YAHOO.util.DataSource(query);
656 this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
657 this.ieDataSource.responseSchema = {
658 resultsList: "account_list",
659 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
661 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
662 this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
664 var elCheckbox = oArgs.target;
665 var oColumn = this.getColumn(elCheckbox);
666 if(oColumn.key == 'is_active')
668 var oRecord = this.getRecord(elCheckbox);
669 oRecord.setData("is_active",elCheckbox.checked);
670 var t_id = oRecord.getData('id');
671 var isGroupFolder = oRecord.getData('has_groupfolder');
674 SUGAR.email2.folders.updateSubscriptions();
676 SUGAR.email2.folders.setFolderSelection();
680 var lastDefaultSelectedId = "";
681 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
683 var elRadio = oArgs.target;
684 var oColumn = this.getColumn(elRadio);
685 if(oColumn.key == 'is_default')
687 var oRecord = this.getRecord(elRadio);
688 var t_id = oRecord.getData('id');
689 var t_isGroup = oRecord.getData('is_group');
690 if(t_id != lastDefaultSelectedId && !t_isGroup)
692 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
693 lastDefaultSelectedId = t_id;
694 AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
697 YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
702 this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
703 this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
706 _setupOutboundAccountTable: function()
708 if(!this.outboundAccountsSettingsTable)
710 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
711 var clckEvent = oColumn.key;
713 var isEditable = oRecord.getData("is_editable");
714 var type = oRecord.getData("type");
717 if(oColumn.key == 'edit')
719 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
720 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
722 else if(oColumn.key == 'delete' && type == 'user')
724 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
725 imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
728 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
732 //Custom formatter to display any error messages.
733 this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
735 if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
736 SUGAR.email2.composeLayout.outboundAccountErrors = {};
738 var id = oRecord.getData('id');
739 var message = oRecord.getData("errors");
742 elLiner.innerHTML = '<span class="required">' + message + '</span>';
743 //Add the id and message for all outbound accounts.
744 SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
748 if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
749 delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
752 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
753 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
755 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
756 {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
757 {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
758 {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
760 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
761 this.obDataSource = new YAHOO.util.DataSource(query);
762 this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
763 this.obDataSource.responseSchema = {
765 resultsList: "outbound_account_list",
766 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
769 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
772 this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
773 this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
774 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
778 * Displays a modal diaglogue to edit outbound account settings
780 showEditInboundAccountDialogue : function(clear) {
782 if(!this.inboundAccountEditDialog) {
783 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
787 constraintoviewport: true,
791 EAD.showEvent.subscribe(function() {
792 var el = this.element;
793 var viewH = YAHOO.util.Dom.getViewportHeight();
794 if (this.header && el && viewH - 50 < el.clientHeight) {
795 var body = this.header.nextElementSibling;
796 body.style.overflow = "hidden";
797 body.style.height = "100%";
800 EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
801 Dom.removeClass("editAccountDialogue", "yui-hidden");
805 if(clear == undefined || clear == true)
807 SE.accounts.clearInboundAccountEditScreen();
808 //Set default protocol to IMAP when creating new records
809 document.forms['ieAccount'].elements['protocol'].value = "imap";
810 SE.accounts.setPortDefault();
813 //Check if we should display username/password fields for outbound account if errors were detected.
814 this.checkOutBoundSelection();
816 this.inboundAccountEditDialog.render();
817 this.inboundAccountEditDialog.show();
818 SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
822 * Set all fields on the outbound edit form to either enabled/disabled
823 * except for the username/password.
826 toggleOutboundAccountDisabledFields: function(disable)
828 var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
829 for(var i=0;i<fields.length;i++)
831 document.getElementById(fields[i]).disabled = disable;
834 Dom.addClass("mail_smtpssl_row", "yui-hidden");
836 Dom.removeClass('mail_smtpssl_row', "yui-hidden");
840 * Refresh the inbound accounts table.
842 refreshInboundAccountTable : function()
844 this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
846 success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
847 scope: this.inboundAccountsSettingsTable }
851 * Refresh the outbound accounts table.
853 refreshOuboundAccountTable : function()
855 this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
857 success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
858 scope: this.outboundAccountsSettingsTable }
862 * Displays a modal diaglogue to add a SMTP server
864 showAddSmtp : function() {
865 // lazy load dialogue
866 if(!this.outboundDialog) {
867 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
871 constraintoviewport: true,
875 this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
876 this.outboundDialog.hideEvent.subscribe(function(){
877 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
878 var out = Dom.get("outbound_email");
879 if (out && out.value == "SYSTEM_ADD")
881 out.value = out.options[0].value;
883 //Check if we should display username/password for system account.
884 SE.accounts.checkOutBoundSelection();
888 Dom.removeClass("outboundDialog", "yui-hidden");
892 var form = document.getElementById('outboundEmailForm');
893 for(i=0; i<form.elements.length; i++) {
894 if(form.elements[i].name == 'mail_smtpport') {
895 form.elements[i].value = 25;
896 } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
897 form.elements[i].value = '';
898 } else if(form.elements[i].type == 'checkbox') {
899 form.elements[i].checked = false;
902 //Render the SMTP buttons
903 if ( !SUGAR.smtpButtonGroup ) {
904 SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
905 SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
907 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
908 document.getElementById('smtp_settings').style.display = '';
909 form.mail_smtptype.value = e.newValue.get('value');
911 YAHOO.widget.Button.addHiddenFieldsToForm(form);
913 //Hide Username/Password
914 SUGAR.email2.accounts.smtp_authenticate_field_display();
915 //Unset readonly fields
916 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
917 SUGAR.email2.accounts.changeEmailScreenDisplay('other');
918 this.outboundDialog.render();
919 this.outboundDialog.show();
923 * Accounts' Advanced Settings view toggle
925 toggleAdv : function() {
926 var adv = document.getElementById("ie_adv");
927 if(adv.style.display == 'none') {
928 adv.style.display = "";
930 adv.style.display = 'none';
934 smtp_authenticate_field_display : function() {
935 var smtpauth_req = document.getElementById("mail_smtpauth_req");
936 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
937 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
940 smtp_setDefaultSMTPPort : function() {
941 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
943 if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
944 document.getElementById("mail_smtpport").value = '465';
946 if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
947 document.getElementById("mail_smtpport").value = '25';
952 * Changes the display used in the outbound email SMTP dialog to match the
954 changeEmailScreenDisplay : function(smtptype, isSystemAccount)
956 document.getElementById("smtpButtonGroupTD").style.display = '';
957 document.getElementById("chooseEmailProviderTD").style.display = '';
958 document.getElementById("mailsettings1").style.display = '';
959 document.getElementById("mailsettings2").style.display = '';
960 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
961 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
962 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
963 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
967 document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
968 document.getElementById("mail_smtpport").value = '465';
969 document.getElementById("mail_smtpauth_req").checked = true;
970 var ssl = document.getElementById("mail_smtpssl");
971 for(var j=0;j<ssl.options.length;j++) {
972 if(ssl.options[j].text == 'SSL') {
973 ssl.options[j].selected = true;
977 document.getElementById("mailsettings1").style.display = 'none';
978 document.getElementById("mailsettings2").style.display = 'none';
979 document.getElementById("mail_smtppass_label").innerHTML =
980 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
981 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
984 document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
985 document.getElementById("mail_smtpport").value = '587';
986 document.getElementById("mail_smtpauth_req").checked = true;
987 var ssl = document.getElementById("mail_smtpssl");
988 for(var j=0;j<ssl.options.length;j++) {
989 if(ssl.options[j].text == 'TLS') {
990 ssl.options[j].selected = true;
994 document.getElementById("mailsettings1").style.display = 'none';
995 document.getElementById("mailsettings2").style.display = 'none';
996 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
997 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
1000 if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
1001 || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
1002 document.getElementById("mail_smtpserver").value = '';
1004 document.getElementById("mail_smtpport").value = '25';
1005 document.getElementById("mail_smtpauth_req").checked = true;
1006 document.getElementById("mailsettings1").style.display = '';
1007 document.getElementById("mailsettings2").style.display = '';
1008 document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1009 document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1010 document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1011 document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1014 if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1016 document.getElementById("smtpButtonGroupTD").style.display = 'none';
1017 document.getElementById("chooseEmailProviderTD").style.display = 'none';
1018 document.getElementById("mailsettings2").style.display = 'none';
1021 SUGAR.email2.accounts.smtp_authenticate_field_display();
1022 SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1026 * Fill the gmail default values for inbound accounts.
1028 fillInboundGmailDefaults: function () {
1030 document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1031 document.forms['ieAccount'].elements['ssl'].checked = true;
1032 document.forms['ieAccount'].elements['protocol'].value = "imap";
1033 SUGAR.email2.accounts.setPortDefault();
1034 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1037 * Sets Port field to selected protocol and SSL settings defaults
1039 setPortDefault : function() {
1040 var prot = document.getElementById('protocol');
1041 var ssl = document.getElementById('ssl');
1042 var port = document.getElementById('port');
1043 var stdPorts= new Array("110", "143", "993", "995");
1044 var stdBool = new Boolean(false);
1045 var mailboxdiv = document.getElementById("mailboxdiv");
1046 var trashFolderdiv = document.getElementById("trashFolderdiv");
1047 var sentFolderdiv = document.getElementById("sentFolderdiv");
1048 var monitoredFolder = document.getElementById("subscribeFolderButton");
1049 if(port.value == '') {
1050 stdBool.value = true;
1052 for(i=0; i<stdPorts.length; i++) {
1053 if(stdPorts[i] == port.value) {
1054 stdBool.value = true;
1059 if(stdBool.value == true) {
1060 if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1062 } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1064 } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1066 } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1071 if (prot.value == 'imap') {
1072 mailboxdiv.style.display = "";
1073 trashFolderdiv.style.display = "";
1074 sentFolderdiv.style.display = "";
1075 monitoredFolder.style.display = "";
1076 if (document.getElementById('mailbox').value == "") {
1077 document.getElementById('mailbox').value = "INBOX";
1080 mailboxdiv.style.display = "none";
1081 trashFolderdiv.style.display = "none";
1082 sentFolderdiv.style.display = "none";
1083 monitoredFolder.style.display = "none";
1084 document.getElementById('mailbox').value = "";
1089 * Draws/removes red boxes around required fields.
1091 ieAccountError : function(style) {
1092 document.getElementById('server_url').className = style;
1093 document.getElementById('email_user').className = style;
1094 document.getElementById('email_password').className = style;
1095 document.getElementById('protocol').className = style;
1096 document.getElementById('port').className = style;
1099 checkOutBoundSelection: function() {
1100 var select = Dom.get('outbound_email');
1101 if (!select || select.selectedIndex == -1) { return; }
1103 var v = select.options[select.selectedIndex].value;
1107 select.options[select.selectedIndex].selected = false;
1108 v = select.options[0].value;
1110 else if (v == 'SYSTEM_ADD')
1111 SUGAR.email2.accounts.showAddSmtp();
1113 var foundError = false;
1114 var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1115 for(i in errorAccounts)
1124 //Should username/password fields for outbound account.
1126 this.toggleInboundOutboundFields(true);
1128 this.toggleInboundOutboundFields(false);
1133 toggleInboundOutboundFields : function (display)
1137 Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1138 Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1142 Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1143 Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1147 * rebuilds the select options for mailer options
1149 rebuildMailerOptions : function() {
1150 var select = document.forms['ieAccount'].elements['outbound_email'];
1151 SE.util.emptySelectOptions(select);
1153 //Get the available sugar mailers
1154 var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1156 for(i=0;i<a_outbound.length;i++)
1158 var t_record = a_outbound[i];
1159 var key = t_record.getData('id');
1160 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1162 var opt = new Option(display, key);
1163 select.options.add(opt);
1164 if (key == SE.accounts.newAddedOutboundId) {
1165 select.options.selectedIndex = i;
1169 select.options.add(new Option('',''));
1170 select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1171 //Hide/Show username password fields if necessary.
1172 SE.accounts.checkOutBoundSelection();
1175 * Empties all the fields in the accounts edit view
1177 clearInboundAccountEditScreen:function() {
1179 document.getElementById('ie_id').value = '';
1180 document.getElementById('ie_name').value = '';
1181 document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1182 document.getElementById('ie_from_addr').value = this.getReplyAddress();
1183 document.getElementById('reply_to_addr').value = '';
1184 document.getElementById('server_url').value = '';
1185 document.getElementById('email_user').value = '';
1186 document.getElementById('email_password').value = '';
1187 document.getElementById('port').value = '';
1188 document.getElementById('inbound_mail_smtpuser').value = '';
1189 document.getElementById('inbound_mail_smtppass').value = '';
1190 document.ieAccount.protocol.options[0].selected = true;
1192 document.getElementById('ssl').checked = false;
1193 SUGAR.util.setEmailPasswordDisplay('email_password', false);
1197 * Populates an account's fields in Settings->Accounts
1199 fillIeAccount:function(jsonstr) {
1200 var o = YAHOO.lang.JSON.parse(jsonstr);
1202 document.getElementById('ie_id').value = o.id;
1203 document.getElementById('ie_name').value = o.name;
1204 if (o.stored_options != null) {
1205 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1206 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1207 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1208 if (o.stored_options.trashFolder != null) {
1209 document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1211 if (o.stored_options.sentFolder != null) {
1212 document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1215 document.getElementById('server_url').value = o.server_url;
1216 document.getElementById('email_user').value = o.email_user;
1217 document.getElementById('port').value = o.port;
1218 document.getElementById('group_id').value = o.group_id;
1219 document.getElementById('mailbox').value = o.mailbox;
1225 if(typeof(o.service[2]) != 'undefined') {
1226 document.getElementById('ssl').checked = true;
1230 if(document.getElementById('protocol').value != o.protocol) {
1231 var prot = document.getElementById('protocol');
1232 for(i=0; i<prot.options.length; i++) {
1233 if(prot.options[i].value == o.service[3]) {
1234 prot.options[i].selected = true;
1235 this.setPortDefault();
1239 // handle SMTP selection
1240 if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1241 var opts = document.getElementById('outbound_email').options;
1242 for(i=0; i<opts.length; i++) {
1243 if(opts[i].value == o.stored_options.outbound_email) {
1244 opts[i].selected = true;
1250 deleteIeAccount : function(IeAccountID,IeGroupID) {
1251 if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1253 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1255 AjaxObject.target = 'frameFlex';
1256 AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1257 SUGAR.email2.accounts.refreshInboundAccountTable();
1261 // Null check for Outbound Settings.
1262 checkOutboundSettings: function() {
1263 var errorMessage = '';
1264 var isError = false;
1265 if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1266 var mailName = document.getElementById('mail_name').value;
1267 var smtpServer = document.getElementById('mail_smtpserver').value;
1268 var smtpPort = document.getElementById('mail_smtpport').value;
1270 var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1271 if(trim(mailName) == '') {
1273 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1275 if(trim(smtpServer) == '') {
1277 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1279 if(trim(smtpPort) == '') {
1281 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1283 if(mailsmtpauthreq.checked) {
1284 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1286 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1291 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1298 testOutboundSettings: function() {
1299 var errorMessage = '';
1300 var isError = false;
1301 var fromAddress = document.getElementById("outboundtest_from_address").value;
1302 if (trim(fromAddress) == "") {
1303 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1304 overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1308 else if (!isValidEmail(fromAddress)) {
1309 errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1310 overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1314 //Hide the dialogue and show an in progress indicator.
1315 SE.accounts.testOutboundDialog.hide();
1316 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1318 //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1319 //nothing is sent in the request.
1320 var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1321 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1323 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1324 if(outboundType == 'system-override')
1325 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1327 var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
1328 AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1332 testOutboundSettingsDialog: function() {
1333 //Ensure that all settings are correct before proceeding to send test email.
1334 if(!SE.accounts.checkOutboundSettings())
1337 // lazy load dialogue
1338 if(!SE.accounts.testOutboundDialog) {
1339 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1343 constraintoviewport: true,
1347 SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1348 Dom.removeClass("testOutboundDialog", "yui-hidden");
1350 SE.accounts.testOutboundDialog.render();
1351 SE.accounts.testOutboundDialog.show();
1355 * Saves Outbound email settings
1357 saveOutboundSettings : function() {
1358 if(SE.accounts.checkOutboundSettings()) {
1359 //Enable the form fields for the post.
1360 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1361 YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1362 AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1368 saveIeAccount : function() {
1370 //Before saving check if there are any error messages associated with the outbound account.
1371 var outboundID = document.getElementById('outbound_email').value;
1373 if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1374 'validateSMTPCreds':true}) )
1376 document.getElementById('saveButton').disabled = true;
1378 overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1380 var formObject = document.getElementById('ieAccount');
1381 YAHOO.util.Connect.setForm(formObject);
1383 AjaxObject._reset();
1384 AjaxObject.target = 'frameFlex';
1385 AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1389 testSettings : function() {
1390 form = document.getElementById('ieAccount');
1392 if(SE.accounts.checkIeCreds()) {
1393 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);
1397 getFoldersListForInboundAccountForEmail2 : function() {
1398 form = document.getElementById('ieAccount');
1399 if(SE.accounts.checkIeCreds()) {
1400 var mailBoxValue = form.mailbox.value;
1401 if (form.searchField.value.length > 0) {
1404 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 );
1409 checkIeCreds : function(validateRules) {
1410 if(typeof(validateRules) == 'undefined')
1413 var errors = new Array();
1414 var out = new String();
1416 var ie_name = Dom.get('ie_name').value;
1417 var fromAddress = Dom.get('ie_from_addr').value;
1418 var server_url = Dom.get('server_url').value;
1419 var email_user = Dom.get('email_user').value;
1420 var email_password = Dom.get('email_password').value;
1421 var protocol = Dom.get('protocol').value;
1422 var port = Dom.get('port').value;
1423 var oe = Dom.get('outbound_email');
1425 // Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
1426 // other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
1427 // return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
1428 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;
1430 var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1431 var outboundPass = Dom.get('inbound_mail_smtppass').value;
1433 //If the username and password were provided then ignore the error messge
1435 var outboundCredentialsFound = false;
1437 if(outboundUserName != "" && outboundPass != "")
1438 outboundCredentialsFound = true;
1440 var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1442 if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1443 && validateSMTPCreds)
1445 if(trim(outboundUserName) == "") {
1446 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1448 if(trim(outboundPass) == "") {
1449 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1453 if(trim(ie_name) == "") {
1454 errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1457 if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1459 if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1460 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1465 if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1466 || trim(oe_value) == "SYSTEM_ADD") ) {
1467 errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1469 if(trim(server_url) == "") {
1470 errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1472 if(trim(email_user) == "") {
1473 errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1475 if(protocol == "") {
1476 errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1478 if (protocol == 'imap') {
1479 var mailbox = document.getElementById('mailbox').value;
1480 if (trim(mailbox) == "") {
1481 errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1483 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1484 var trashFolder = document.getElementById('trashFolder').value;
1485 if (trim(trashFolder) == "") {
1486 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1491 errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1494 if(errors.length > 0) {
1495 out = app_strings.LBL_EMAIL_ERROR_DESC;
1496 for(i=0; i<errors.length; i++) {
1511 getIeAccount : function(ieId) {
1515 overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1516 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1518 AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1522 * Iterates through TreeView nodes to apply styles dependent nature of node
1524 renderTree:function() {
1525 SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1529 //Sets the style for any nodes that need it.
1530 setNodeStyle : function(node) {
1531 if (!node.data.origText) {
1532 node.data.origText = node.data.text;
1535 if (typeof(node.data.unseen) != 'undefined') {
1536 if (node.data.unseen > 0) {
1537 node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
1538 // Add bold style to label, kinda hacky
1539 node.labelStyle += " ygtvlabelbold";
1542 node.setUpLabel(node.data.origText);
1545 node.setUpLabel(node.data.origText);
1547 SE.accounts.setupDDTarget(node);
1550 setupDDTarget : function(node) {
1551 if (node.ddTarget) {
1552 node.ddTarget.removeFromGroup();
1553 delete node.ddTarget;
1555 var id = node.getElId();
1556 var num = id.substring(4);
1557 if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1558 node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1559 node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1561 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1563 else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1564 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1569 * Async call to rebuild the folder list. After a folder delete or account delete
1571 rebuildFolderList : function() {
1572 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1573 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1577 * Returns the number of remote accounts the user has active.
1579 getAccountCount : function() {
1582 for(i=0; i<tree._nodes.length; i++) {
1583 var node = tree._nodes[i];
1585 if(typeof(node) != 'undefined' && node.data.ieId) {
1593 ///////////////////////////////////////////////////////////////////////////////
1598 ///////////////////////////////////////////////////////////////////////////////
1599 //// CONTEXT MENU CALLS
1602 assignToDialogue : null,
1604 * Archives from context menu
1606 * @param string ieId
1607 * @param string folder
1609 _archiveToSugar : function(uids, ieId, folder) {
1612 for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1613 if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1616 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1620 * Archives from context menu
1622 archiveToSugar : function(menuItem) {
1623 SE.contextMenus.emailListContextMenu.hide();
1625 var rows = SE.grid.getSelectedRows();
1627 /* iterate through available rows JIC a row is deleted - use first available */
1628 for(var i=0; i<rows.length; i++) {
1629 uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1631 var data = SE.grid.getRecord(rows[0]).getData();
1632 SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1636 * Popup the printable version and start system's print function.
1638 viewPrintable : function(menuItem) {
1639 var rows = SE.grid.getSelectedRows();
1640 var data = SE.grid.getRecord(rows[0]).getData();
1641 SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1645 * Marks email flagged on mail server
1647 markRead : function(type, contextMenuId) {
1648 SE.contextMenus.markEmail('read');
1652 * Assign this emails to people based on assignment rules
1654 assignEmailsTo : function(type, contextMenuId) {
1655 if(!SE.contextMenus.assignToDialogue)
1657 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1661 constraintoviewport: true,
1665 SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1669 Dom.removeClass("assignToDiv", "yui-hidden");
1670 SE.contextMenus.assignToDialogue.render();
1671 SE.contextMenus.assignToDialogue.show();
1675 * Marks email flagged on mail server
1677 markFlagged : function(contextMenuId) {
1678 SE.contextMenus.markEmail('flagged');
1682 * Marks email unflagged on mail server
1684 markUnflagged : function(contextMenuId) {
1685 SE.contextMenus.markEmail('unflagged');
1689 * Marks email unread on mail server
1691 markUnread : function() {
1692 SE.contextMenus.markEmail('unread');
1696 * Deletes an email from context menu
1698 markDeleted : function() {
1699 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1700 document.getElementById('_blank').innerHTML = "";
1701 SE.contextMenus.markEmail('deleted');
1706 * generic call API to apply a flag to emails on the server and on sugar
1707 * @param string type "read" | "unread" | "flagged" | "deleted"
1709 markEmail : function(type) {
1710 SE.contextMenus.emailListContextMenu.hide();
1712 //var dm = SE.grid.getStore();
1713 //var uids = SE.grid.getSelectedRowIds();
1714 //var indexes = SE.grid.getSelectedRowIndexes();
1715 var rows = SE.grid.getSelectedRows();
1716 if (rows.length == 0)
1717 rows = [SE.contextMenus.currentRow];
1720 for(var i=0; i<rows.length; i++) {
1721 ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1724 ser = YAHOO.lang.JSON.stringify(ser);
1726 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1727 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1733 if(type == 'read' || type == 'deleted') {
1735 for(var j=0; j<rows.length; j++) {
1736 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1738 SE.grid.getRecord(rows[j]).setData("seen", "1");
1741 //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1743 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1744 var unseenCount = node.data.unseen;
1745 if (isNaN(unseenCount)) {
1748 var finalCount = parseInt(unseenCount) - count;
1749 node.data.unseen = finalCount;
1751 SE.accounts.renderTree();
1753 } else if(type == 'unread') {
1755 for(var j=0; j<rows.length; j++) {
1756 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1761 var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1762 var unseenCount = node.data.unseen;
1763 if (isNaN(unseenCount)) {
1766 var finalCount = parseInt(unseenCount) + count;
1767 node.data.unseen = finalCount;
1768 SE.accounts.renderTree();
1771 if (type == 'unread') {
1772 for(var i=0; i<rows.length; i++) {
1773 SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1777 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1778 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1782 * refreshes the ListView to show changes to cache
1784 markEmailCleanup : function() {
1785 SE.accounts.renderTree();
1787 SE.listView.refreshGrid();
1790 showAssignmentDialog : function() {
1791 if (SE.contextMenus.assignmentDialog == null) {
1792 AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1794 SE.contextMenus.assignmentDialog.show();
1799 * shows the import dialog with only relate visible.
1801 relateTo : function() {
1802 SE.contextMenus.emailListContextMenu.hide();
1804 var rows = SE.grid.getSelectedRows();
1805 var data = SE.grid.getRecord(rows[0]).getData();
1806 var ieId = data.ieId;
1807 var folder = data.mbox;
1809 /* iterate through available rows JIC a row is deleted - use first available */
1810 for(var i=0; i<rows.length; i++) {
1811 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1813 var ser = YAHOO.lang.JSON.stringify(uids);
1815 AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1819 * shows the import dialog with only relate visible.
1821 showDetailView : function() {
1822 SE.contextMenus.emailListContextMenu.hide();
1823 var rows = SE.grid.getSelectedRows();
1824 if (rows.length > 1) {
1825 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1828 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1829 var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1830 /* iterate through available rows JIC a row is deleted - use first available */
1831 var uid = SE.grid.getRecord(rows[0]).getData().uid;
1832 SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1838 showEmailDetailViewInPopup : function(ieId,uid, folder) {
1839 overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1840 AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1844 * Opens multiple messages from ListView context click
1846 openMultiple : function() {
1847 SE.contextMenus.emailListContextMenu.hide();
1849 var rows = SE.grid.getSelectedRows();
1850 var uids = SE.listView.getUidsFromSelection();
1852 if(uids.length > 0) {
1853 var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1854 var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1855 SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1860 * Replies/forwards email
1862 replyForwardEmailContext : function() {
1863 SE.contextMenus.emailListContextMenu.hide();
1865 var indexes = SE.grid.getSelectedRows();
1866 //var dm = SE.grid.getDataModel();
1869 for(var i=0; i<indexes.length; i++) {
1870 var row = SE.grid.getRecord(indexes[i]).getData();
1871 SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1875 //show menu functions
1876 showEmailsListMenu : function(grid, row) {
1878 var data = row.getData();
1879 var draft = (data.type == "draft");
1880 var menu = SE.contextMenus.emailListContextMenu;
1885 if (data.mbox == 'sugar::Emails')
1886 folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1888 folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1890 if ( folderNode != null && typeof(folderNode) != "undefined" && typeof(folderNode.data) != "undefined"
1891 && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1892 || (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1893 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1895 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1898 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1900 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1901 menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1902 menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1903 menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1904 menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1907 if (data.mbox == "sugar::Emails")
1909 //Allow users to reassign imported emails
1910 menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1911 menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1912 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1913 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1917 menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1918 menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1922 showFolderMenu : function(grid, rowIndex, event) {
1924 var coords = event.getXY();
1925 SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1929 SE.contextMenus.dv = {
1930 archiveToSugar : function(contextMenuId) {
1932 SE.contextMenus._archiveToSugar(uids, ieId, folder);
1935 replyForwardEmailContext : function(all) {
1936 SE.contextMenus.detailViewContextMenu.hide();
1945 //// END SE.contextMenus
1946 ///////////////////////////////////////////////////////////////////////////////
1950 ///////////////////////////////////////////////////////////////////////////////
1953 consumeMetaDetail : function(ret) {
1954 // handling if the Email drafts
1955 if(ret.type == 'draft') {
1956 SE.composeLayout.c0_composeDraft();
1961 // cache contents browser-side
1962 SE._setDetailCache(ret);
1964 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1965 // 2 below must be in global context
1967 meta['panelId'] = SE.util.getPanelId();
1969 email = ret.meta.email;
1970 var out = displayTemplate.exec({
1971 'app_strings' : app_strings,
1973 'idx' : targetDiv.id,
1975 'email' : meta.email,
1976 'linkBeans' : linkBeans
1978 var tabLabel = meta.email.name;
1979 if (tabLabel != null && tabLabel.length > 25) {
1980 tabLabel = tabLabel.substring(0, 25) + "...";
1982 targetDiv.set("label", tabLabel);
1983 targetDiv.set("content", out);
1985 var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1986 if (SUGAR.email2.util.isIe()) {
1987 displayEmailFrameDiv.style.height = "390px";
1989 displayEmailFrameDiv.style.height = "410px";
1992 var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1993 displayFrame.contentWindow.document.write(email.description);
1994 displayFrame.contentWindow.document.close();
1996 // hide archive links
1997 if(ret.meta.is_sugarEmail) {
1998 document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1999 document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
2001 if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
2002 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
2007 consumeMetaPreview : function(ret) {
2008 // cache contents browser-side
2009 SE._setDetailCache(ret);
2013 var currrow = SE.grid.getLastSelectedRecord();
2014 currrow = SE.grid.getRecord(currrow);
2016 document.getElementById('_blank').innerHTML = '';
2019 // handling if the Email drafts
2020 if(ret.type == 'draft'){
2021 if (currrow.getData().uid == ret.uid) {
2022 SE.composeLayout.c0_composeDraft();
2027 if (currrow.getData().uid != ret.meta.uid) {
2031 // remove loading sprite
2032 document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2033 var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2035 meta['panelId'] = SE.util.getPanelId();
2036 email = ret.meta.email;
2038 document.getElementById('_blank').innerHTML = displayTemplate.exec({
2039 'app_strings' : app_strings,
2043 'email' :meta.email,
2044 'linkBeans' : linkBeans
2046 // document.getElementById('_blank').innerHTML = meta.email;
2047 /* displayTemplate.append('_blank', {
2048 'app_strings' : app_strings,
2052 'email' :meta.email,
2053 'linkBeans' : linkBeans
2056 var displayFrame = document.getElementById('displayEmailFramePreview');
2057 displayFrame.contentWindow.document.write(email.description);
2058 displayFrame.contentWindow.document.close();
2060 SE.listViewLayout.resizePreview();
2062 // hide archive links
2063 if(ret.meta.is_sugarEmail) {
2064 document.getElementById("archiveEmailPreview").innerHTML = " ";
2065 document.getElementById("btnEmailViewPreview").style.display = "none";
2066 document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2068 //hide view relationship link
2069 document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2074 * wraps emailDelete() for single messages, comes from preview or tab
2076 emailDeleteSingle : function(ieId, uid, mbox) {
2077 if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2078 // find active panel and close if the user double clicked the email to view.
2079 var activeTabId = SE.util.getPanelId();
2080 if(activeTabId != 'Preview')
2081 SE.innerLayout.get("activeTab").close();
2083 document.getElementById('_blank').innerHTML = "";
2086 uid = YAHOO.lang.JSON.stringify(ser);
2087 this.emailDelete(ieId, uid, mbox);
2092 * Sends async call to delete a given message
2095 emailDelete : function(ieId, uid, mbox) {
2096 overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2097 AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2098 uid + "&ieId=" + ieId + "&folder=" + mbox);
2102 * retrieves one email to display in the preview pane.
2104 getEmailPreview : function() {
2105 var row = SUGAR.email2.listView.currentRow;
2106 var data = row.getData();
2107 if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2108 var setRead = (data['seen'] == 0) ? true : false;
2109 SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2110 SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2115 * Imports one email into Sugar
2117 importEmail : function(ieId, uid, mbox) {
2118 SE.util.clearHiddenFieldValues('emailUIForm');
2120 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2122 var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2123 AjaxObject.target = '';
2124 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2128 * Populates the frameFlex div with the contents of an email
2130 populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2131 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2133 var mboxStr = new String(mbox);
2134 var compKey = mbox + uid;
2136 if(setRead == true) {
2137 SE.listView.boldUnreadRows()
2138 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2141 if(destination == SE.innerLayout) {
2143 * loading email into a tab, peer with ListView
2144 * targetDiv must remain in the global namespace as it is used by AjaxObject
2146 //Check if we already have a tab of the email open
2147 var tabs = SE.innerLayout.get("tabs");
2148 for (var t in tabs) {
2149 if (tabs[t].id && tabs[t].id == uid) {
2150 SE.innerLayout.set("activeTab", tabs[t]);
2155 targetDiv = new YAHOO.SUGAR.ClosableTab({
2156 label: loadingSprite,
2162 SE.innerLayout.addTab(targetDiv);
2164 // use cache if available
2165 if(SE.cache[compKey]) {
2166 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2168 // open email as peer-tab to listView
2169 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2170 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2173 // loading email into preview pane
2174 document.getElementById('_blank').innerHTML = loadingSprite;
2176 // use cache if available
2177 if(SE.cache[compKey]) {
2178 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2180 AjaxObject.forceAbort = true;
2181 // open in preview window
2182 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2183 // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2188 requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2190 if(mboxStr.substring(0,7) == 'sugar::') {
2191 // display an email from Sugar
2192 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2194 // display an email from an email server
2195 document.getElementById('emailUIAction').value = 'getSingleMessage';
2197 document.getElementById('mbox').value = mbox;
2198 document.getElementById('ieId').value = ieId;
2199 document.getElementById('uid').value = uid;
2201 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2203 AjaxObject.forceAbort = true;
2204 AjaxObject.target = '_blank';
2205 AjaxObject.startRequest(callback, null);
2209 * Retrieves multiple emails for DetailView
2211 populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2212 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2213 SE.util.clearHiddenFieldValues('emailUIForm');
2215 var mboxStr = new String(mbox);
2217 uids = SE.util.cleanUids(uids);
2219 if(mboxStr.substring(0,7) == 'sugar::') {
2220 // display an email from Sugar
2221 document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2222 document.getElementById('uid').value = uids;
2224 // display an email from an email server
2225 document.getElementById('emailUIAction').value = 'getMultipleMessages';
2226 document.getElementById('mbox').value = mbox;
2227 document.getElementById('ieId').value = ieId;
2228 document.getElementById('uid').value = uids;
2231 var formObject = document.getElementById('emailUIForm');
2232 YAHOO.util.Connect.setForm(formObject);
2234 AjaxObject.target = 'frameFlex';
2235 AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2237 if(setRead == true) {
2238 var c = uids.split(",");
2239 SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2244 * Makes async call to get QuickCreate form
2245 * Renders a modal edit view for a given module
2247 quickCreate : function(module, ieId, uid, mailbox) {
2248 var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2250 if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2251 get += "&sugarEmail=true";
2254 AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2258 * Makes async call to save a quick create
2261 saveQuickCreate : function(action) {
2262 var qcd = SE.detailView.quickCreateDialog;
2263 if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2264 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2265 var theCallback = callbackQuickCreateSave;
2266 var accountType = '&sugarEmail=true';
2267 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2268 accountType = '&ieId=' + qcd.ieId;
2271 if (action == 'reply') {
2272 theCallback = callbackQuickCreateSaveAndReply;
2273 } else if (action == true) {
2274 theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2276 formObject.action.value = 'EmailUIAjax';
2277 YAHOO.util.Connect.setForm(formObject);
2278 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2279 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2280 accountType + '&mbox=' + qcd.mbox);
2285 * Code to show/hide long list of email address in DetailView
2287 showCroppedEmailList : function(el) {
2288 el.style.display = 'none';
2289 el.previousSibling.style.display = 'inline'
2291 showFullEmailList : function(el) {
2292 el.style.display = 'none';
2293 el.nextSibling.style.display = 'inline';
2297 * Shows the QuickCreate overlay
2298 * @param string ieId
2300 * @param string mailbox
2302 showQuickCreate : function(ieId, uid, mailbox) {
2303 var panelId = SE.util.getPanelId();
2304 var context = document.getElementById("quickCreateSpan" + panelId);
2306 if (!SE.detailView.cqMenus)
2307 SE.detailView.cqMenus = {};
2309 if (SE.detailView.cqMenus[context])
2310 SE.detailView.cqMenus[context].destroy();
2312 var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2314 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2317 for (var i=0; i < this.qcmodules.length; i++) {
2318 var module = this.qcmodules[i];
2320 text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2323 onclick: { fn: function() {
2324 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2330 menu.render(document.body);
2335 * Displays the "View" submenu in the detailView
2336 * @param string ieId
2338 * @param string mailbox
2340 showViewMenu : function(ieId, uid, mailbox) {
2341 var panelId = SE.util.getPanelId();
2342 var context = "btnEmailView" + panelId;
2343 if (!SE.detailView.viewMenus)
2344 SE.detailView.viewMenus = {};
2346 if (SE.detailView.viewMenus[context])
2347 SE.detailView.viewMenus[context].destroy();
2349 var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2351 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2355 (ieId == 'null' || ieId == null) ?
2356 //No ieId - Sugar Email
2358 text: app_strings.LBL_EMAIL_VIEW_RAW,
2359 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2362 //IeID exists, on a remote server
2364 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2365 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2367 text: app_strings.LBL_EMAIL_VIEW_RAW,
2368 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2371 menu.render(document.body);
2376 //#23108 jchi@07/17/2008
2377 menu.render('quickCreateSpan'+ panelId);*/
2378 //this.viewMenu = menu;
2379 //this.viewMenu.show(context);
2382 * Makes async call to get an email's headers
2384 viewHeaders : function(ieId, uid, mailbox) {
2385 var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2386 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2390 * Makes async call to get a printable version
2392 viewPrintable : function(ieId, uid, mailbox) {
2393 if(mailbox == 'sugar::Emails') {
2394 // display an email from Sugar
2395 var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2397 // display an email from an email server
2398 var emailUIAction = '&emailUIAction=getSingleMessage';
2401 var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2402 AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2406 * Makes async call to get an email's raw source
2408 viewRaw : function(ieId, uid, mailbox) {
2409 var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2410 AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2414 * Display all email addresses in detailview.
2416 displayAllAddrs : function(el) {
2417 el.style.display = 'none';
2418 Dom.getNextSibling(el).style.display = 'inline';
2421 //// END SE.detailView
2422 ///////////////////////////////////////////////////////////////////////////////
2426 ///////////////////////////////////////////////////////////////////////////////
2429 contextMenuFocus : new Object(),
2432 * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2433 * SugarFolder ID - folder strings
2435 _createFolderId : function(node) {
2441 if(node.data.ieId) {
2442 /* we have a local Sugar folder */
2443 if(node.data.ieId == 'folder') {
2444 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2445 } else if(node.data.ieId.match(SE.reGUID)) {
2446 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2455 addChildNode : function(parentNode, childNode) {
2456 var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2457 var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2458 var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2460 if(childNode.nodes) {
2461 if(childNode.nodes.length > 0) {
2462 for(j=0; j<childNode.nodes.length; j++) {
2463 var newChildNode = childNode.nodes[j];
2464 this.addChildNode(node, newChildNode);
2471 * Builds and returns a new TreeView Node
2472 * @param string name
2474 * @param int is_group
2477 buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2478 var node = new YAHOO.widget.TextNode(name, parentNode, true);
2480 //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2481 node.expanded = expanded;
2482 node.data = new Object;
2483 node.data['id'] = id;
2484 node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2485 node.data['label'] = name;
2486 node.data['ieId'] = 'folder';
2487 node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2488 node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2489 node.data['unseen'] = unseen;
2494 * ensures that a new folder has a valid name
2496 checkFolderName : function(name) {
2500 this.folderAdd(name);
2504 * Pings email servers for new email - forces refresh of folder pane
2506 checkEmailAccounts : function() {
2507 this.checkEmailAccountsSilent(true);
2510 checkEmailAccountsSilent : function(showOverlay) {
2511 if(typeof(SE.folders.checkingMail)) {
2512 clearTimeout(SE.folders.checkingMail);
2515 // don't stomp an on-going request
2516 if(AjaxObject.currentRequestObject.conn == null) {
2518 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2519 app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2521 AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2523 // wait 5 secs before trying again.
2524 SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2529 * Starts check of all email Accounts using a loading bar for large POP accounts
2531 startEmailAccountCheck : function() {
2532 // don't do two checks at the same time
2533 if(!AjaxObject.requestInProgress()) {
2534 overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2535 SE.accounts.ieIds = SE.folders.getIeIds();
2536 if (SE.accounts.ieIds.length > 0) {
2537 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2538 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
2543 // wait 5 secs before trying again.
2544 SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2549 * Checks a single Account check based on passed ieId
2551 startEmailCheckOneAccount : function(ieId, synch) {
2558 var node = SE.clickedFolderNode;
2559 if (node && !synch) {
2560 mbox = node.data.mbox;
2562 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2563 SE.accounts.ieIds = [ieId];
2564 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2565 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
2570 * Empties trash for subscribed accounts
2572 emptyTrash : function() {
2573 SE.contextMenus.frameFoldersContextMenu.hide();
2574 overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2575 AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2579 * Clears Cache files of the inboundemail account
2581 clearCacheFiles : function(ieId) {
2582 SE.contextMenus.frameFoldersContextMenu.hide();
2583 overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2584 AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2589 * Returns an array of all the active accounts in the folder view
2591 getIeIds : function() {
2593 var root = SE.tree.getRoot();
2594 for(i=0; i < root.children.length; i++) {
2595 if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2596 (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2597 ieIds.push(root.children[i].children[0].data.ieId);
2604 * loads folder lists in Settings->Folders
2606 lazyLoadSettings : function() {
2607 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2608 AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2612 * After the add new folder is done via folders tab on seetings, this function should get called
2613 * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2615 loadSettingFolder : function() {
2616 AjaxObject.timeout = 300000; // 5 min timeout for long checks
2617 AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2621 * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2623 removeSugarFolders : function() {
2625 var root = tree.getRoot();
2626 var folder = SE.util.findChildNode(root, "ieId", "folder");
2628 tree.removeNode(folder);
2629 folder = SE.util.findChildNode(root, "ieId", "folder");
2631 if (!root.childrenRendered) {
2632 root.childrenRendered = true;
2636 rebuildFolders : function(silent) {
2637 if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2638 AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2644 * Updates TreeView with Sugar Folders
2646 setSugarFolders : function(delay) {
2647 this.removeSugarFolders();
2648 //AjaxObject.forceAbort = true;
2649 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2653 * Takes async data object and creates the sugar folders in TreeView
2655 setSugarFoldersEnd : function(o) {
2656 var root = SE.tree.getRoot();
2657 addChildNodes(root, {nodes: o});
2658 SE.accounts.renderTree();
2659 //If nothing is loaded in the grid, load "My Inbox"
2660 if (SE.grid.params.ieId == "undefined") {
2661 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2665 startCheckTimer : function() {
2666 if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2667 var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2669 if(typeof(SE.folders.checkTimer) != 'undefined') {
2670 clearTimeout(SE.folders.checkTimer);
2673 SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2674 if (!SE.userPrefs.emailSettings.firstAutoCheck)
2676 SE.userPrefs.emailSettings.firstAutoCheck = true;
2677 SE.folders.checkEmailAccountsSilent(false);
2683 * makes an async call to save user preference and refresh folder view
2684 * @param object SELECT list object
2686 setFolderSelection : function() {
2687 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2689 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2690 var a_active_accnts = "";
2691 for(i=0;i<a_rs.length;i++)
2693 var t_record = a_rs[i];
2694 var is_active = t_record.getData('is_active');
2696 a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2699 if(a_active_accnts == "")
2700 a_active_accnts = "&ieIdShow[]=";
2702 var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2704 AjaxObject.startRequest(callbackFolders, urlStandard + query);
2708 * makes async call to save user preference for a given node's open state
2709 * @param object node YUI TextNode object
2711 setOpenState : function(node) {
2712 SE.util.clearHiddenFieldValues('emailUIForm');
2713 var nodePath = node.data.id;
2714 var nodeParent = node.parent;
2716 while(nodeParent != null) {
2717 // root node has no ID param
2718 if(nodeParent.data != null) {
2719 nodePath = nodeParent.data.id + "::" + nodePath;
2722 var nodeParent = nodeParent.parent;
2725 document.getElementById('emailUIAction').value = 'setFolderOpenState';
2726 document.getElementById('focusFolder').value = nodePath;
2728 if(node.expanded == true) {
2729 document.getElementById('focusFolderOpen').value = 'open';
2731 document.getElementById('focusFolderOpen').value = 'closed';
2734 var formObject = document.getElementById('emailUIForm');
2735 YAHOO.util.Connect.setForm(formObject);
2737 AjaxObject.startRequest(null, null);
2740 getNodeFromMboxPath : function(path) {
2741 var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2742 var a = YAHOO.lang.JSON.parse(path);
2744 var node = tree.getRoot();
2747 while(i < a.length) {
2748 node = this.getChildNodeFromLabel(node, a[i]);
2755 getChildNodeFromLabel : function(node, nodeLabel) {
2756 for(i=0; i<node.children.length; i++) {
2757 if(node.children[i].data.id == nodeLabel) {
2758 return node.children[i];
2764 * returns the node that presumably under the user's right-click
2766 getNodeFromContextMenuFocus : function() {
2767 //// get the target(parent) node
2768 var tree = YAHOO.widget.TreeView.trees.frameFolders;
2770 var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2772 // filter local folders
2773 if(target.className == 'localFolder' || target.className == 'groupInbox') {
2774 while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2775 if(target.id == '') {
2776 target = target.parentNode;
2783 var targetNode = document.getElementById(target.id);
2784 re = new RegExp(/ygtv[a-z]*(\d+)/i);
2787 var matches = re.exec(targetNode.id);
2789 return document.getElementById(ygtvlabelel1);
2795 // usually parent node
2796 matches = re.exec(targetNode.parentNode.id);
2803 var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2804 parentNode.expand();
2810 * Decrements the Unread Email count in folder text
2811 * @param string ieId ID to look for
2812 * @param string mailbox name
2813 * @param count how many to decrement
2815 decrementUnreadCount : function(ieId, mbox, count) {
2820 if(mbox.indexOf("sugar::") === 0) {
2821 var node = this.getNodeFromId(ieId);
2823 var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2826 var unseen = node.data.unseen;
2828 var check = unseen - count;
2829 var finalCount = (check >= 0) ? check : 0;
2830 node.data.unseen = finalCount;
2832 SE.accounts.renderTree();
2837 * gets the TreeView node with a given ID/ieId
2838 * @param string id ID to look for
2839 * @return object Node
2841 getNodeFromId : function(id) {
2842 SE.folders.focusNode = null;
2843 SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2844 if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2845 SE.folders.focusNode = this;
2849 return SE.folders.focusNode;
2853 * Uses ieId and mailbox to try to find a node in the tree
2855 getNodeFromIeIdAndMailbox : function(id, mbox) {
2856 SE.folders.focusNode = null;
2857 if (mbox == "sugar::Emails") {
2861 SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2862 if (varsarray instanceof Array) {
2863 if (this.data.ieId && this.data.ieId == varsarray[0]
2864 && this.data.mbox == varsarray[1]) {
2865 SE.folders.focusNode = this;
2869 if (this.data.ieId && this.data.ieId == varsarray) {
2870 SE.folders.focusNode = this;
2874 }, null, [id, mbox]);
2875 return SE.folders.focusNode;
2878 unhighliteAll : function() {
2879 SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2883 * Displays a short form
2885 folderAdd : function() {
2886 SE.contextMenus.frameFoldersContextMenu.hide();
2888 var node = SE.clickedFolderNode;
2890 if(node != null && node.data) {
2891 overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2892 app_strings.LBL_EMAIL_SETTINGS_NAME,
2893 'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2895 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2899 folderAddRegisterEnter : function() {
2900 this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2901 {keys: YAHOO.util.KeyListener.KEY.ENTER},
2902 this.buttons[1].handler);
2904 this.enterKeyListener.enable();
2907 folderRemoveRegisterEnter : function() {
2908 this.enterKeyListener.disable();
2911 folderAddXmlCall : function(name) {
2912 if (trim(name) == "") {
2913 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2916 name = escape(name);
2920 var parentNode = SE.clickedFolderNode;
2922 this.contextMenuFocus = parentNode;
2924 if(parentNode.data.ieId) {
2925 if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2929 if(type == 'imap') {
2930 // make an IMAP folder
2931 post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2932 AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2933 } else if(type == 'sugar') {
2934 // make a Sugar folder
2935 if(SE.folders.isUniqueFolderName(name)) {
2936 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2937 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2939 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2940 SE.folders.folderAdd();
2944 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2947 // hide add-folder diaglogue
2948 SE.e2overlay.hide();
2952 * Removes either an IMAP folder or a Sugar Folder
2954 folderDelete : function() {
2955 SE.contextMenus.frameFoldersContextMenu.hide();
2957 if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2959 var parentNode = SE.clickedFolderNode;
2961 if(parentNode != null && parentNode.data) {
2962 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2963 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2967 AjaxObject.target = 'frameFlex';
2969 if(parentNode.data.ieId != 'folder') {
2970 // delete an IMAP folder
2971 post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2973 // delete a sugar folder
2974 post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2976 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2977 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2979 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2985 * Rename folder form
2988 folderRename : function() {
2989 SE.contextMenus.frameFoldersContextMenu.hide();
2990 var node = SE.clickedFolderNode;
2993 if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2994 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2998 overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2999 app_strings.LBL_EMAIL_SETTINGS_NAME,
3001 {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
3003 alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
3008 * fills an Object with key-value pairs of available folders
3010 getAvailableFoldersObject : function() {
3011 var ret = new Object();
3012 var tree = SE.tree.root;
3015 for(var i=0; i<tree.children.length; i++) {
3016 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3019 ret['none'] = app_strings.LBL_NONE;
3026 * Fills in key-value pairs for dependent dropdowns
3027 * @param object ret Associative array
3028 * @param object node TreeView node in focus
3029 * @param string currentPath Built up path thus far
3030 * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3032 getFolderFromChild : function(ret, node, currentPath, spacer) {
3033 if(node.data != null && node.depth > 0) {
3034 /* handle visual separtors differentiating b/t mailserver and local */
3035 if(node.data.ieId && node.data.ieId == 'folder') {
3036 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3040 ret['spacer0'] = spacer;
3041 } else if(ret.spacer0 != spacer) {
3042 ret['spacer1'] = spacer
3045 var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3046 var depthMarker = currentPath;
3047 var retIndex = SE.folders._createFolderId(node);
3048 ret[retIndex] = depthMarker + theLabel;
3051 if(node.children != null) {
3053 currentPath += theLabel + "/";
3056 for(var i=0; i<node.children.length; i++) {
3057 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3065 * Wrapper to refresh folders tree
3067 getFolders : function() {
3068 SE.accounts.rebuildFolderList();
3072 * handles events around folder-rename input field changes
3073 * @param object YUI event object
3075 handleEnter : function(e) {
3076 switch(e.browserEvent.type) {
3078 e.preventDefault(); // click in text field
3082 SE.folders.submitFolderRename(e);
3086 var kc = e.browserEvent.keyCode;
3090 SE.folders.submitFolderRename(e);
3094 e.preventDefault(e);
3095 SE.folders.cancelFolderRename(e);
3102 * Called when a node is clicked on in the folder tree
3103 * @param node, The node clicked on
3104 * @param e, The click event
3106 handleClick : function(o) {
3108 //If the click was on a sugar folder
3109 if (node.data.ieId == "folder") {
3110 SE.listView.populateListFrameSugarFolder(node, node.id, false);
3113 SE.listView.populateListFrame(node, node.data.ieId, false);
3115 //eval(node.data.click);
3120 * Called when a node is right-clicked on in the folder tree
3122 handleRightClick : function(e) {
3123 YAHOO.util.Event.preventDefault(e);
3125 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3126 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3128 //If the click was on a sugar folder
3129 SE.clickedFolderNode = node;
3130 var inbound = (node.data.ieId && node.data.ieId != 'folder');
3131 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3132 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3133 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3134 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3135 menu.getItem(3).cfg.setProperty("disabled", false);
3136 menu.getItem(4).cfg.setProperty("disabled", false);
3137 menu.getItem(5).cfg.setProperty("disabled", false);
3138 menu.getItem(6).cfg.setProperty("disabled", true);
3140 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3141 menu.getItem(0).cfg.setProperty("disabled", true);
3142 menu.getItem(1).cfg.setProperty("disabled", true);
3143 menu.getItem(2).cfg.setProperty("disabled", true);
3144 menu.getItem(3).cfg.setProperty("disabled", true);
3145 menu.getItem(4).cfg.setProperty("disabled", true);
3147 if (node.data.protocol != null) {
3148 menu.getItem(6).cfg.setProperty("disabled", false);
3150 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3151 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3152 //Sent or Draft folders
3153 menu.getItem(3).cfg.setProperty("disabled", true);
3154 menu.getItem(4).cfg.setProperty("disabled", true);
3155 menu.getItem(5).cfg.setProperty("disabled", true);
3158 //For group with auto inbound, disable everything.
3159 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3161 menu.getItem(0).cfg.setProperty("disabled", true);
3162 menu.getItem(1).cfg.setProperty("disabled", true);
3163 menu.getItem(2).cfg.setProperty("disabled", true);
3164 menu.getItem(3).cfg.setProperty("disabled", true);
3165 menu.getItem(4).cfg.setProperty("disabled", true);
3166 menu.getItem(5).cfg.setProperty("disabled", true);
3167 menu.getItem(6).cfg.setProperty("disabled", true);
3170 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3175 * Called when a row is dropped on a node
3177 handleDrop : function(rows, targetFolder) {
3178 var rowData = rows[0].getData();
3179 if (rowData.mbox != targetFolder.data.mbox) {
3180 var srcIeId = rowData.ieId;
3181 var srcFolder = rowData.mbox;
3182 var destIeId = targetFolder.data.ieId;
3183 var destFolder = targetFolder.data.mbox;
3185 for(var i=0; i<rows.length; i++) {
3186 uids[i] = rows[i].getData().uid;
3188 SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3193 * Called when something is dragged over a Folder Node
3195 dragOver : function(dragObject) {
3200 * Determines if a folder name is unique to the folder tree
3201 * @param string name
3203 isUniqueFolderName : function(name) {
3204 uniqueFolder = true;
3205 var root = SE.tree.getRoot();
3206 SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3207 if (this.attributes && this.attributes.ieId == "folder") {
3208 if (this.attributes.text == name) {
3209 uniqueFolder = false;
3214 return uniqueFolder;
3218 * Makes async call to rename folder in focus
3219 * @param object e Event Object
3221 submitFolderRename : function(newName) {
3222 if (trim(newName) == "") {
3223 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3226 newName = escape(newName);
3227 var node = SE.clickedFolderNode;
3228 var origName = node.data.text
3230 if (newName == origName) {
3233 if(SE.folders.isUniqueFolderName(newName)) {
3234 overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3235 if (node.data.ieId == "folder") {
3237 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3240 //IMAP folder or POP mailbox
3241 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3242 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3243 + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3247 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3252 moveFolder : function(folderId, parentFolderId) {
3253 if (folderId != parentFolderId)
3255 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3256 + folderId + "&newParentId=" + parentFolderId);
3261 * makes async call to do a full synchronization of all accounts
3263 synchronizeAccounts : function() {
3264 if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3265 overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br> <br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3266 AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3271 * Updates user's folder subscriptsion (Sugar only)
3272 * @param object SELECT DOM object in focus
3273 * @param string type of Folder selection
3275 updateSubscriptions : function() {
3276 overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3280 select = document.getElementById('userFolders');
3282 for(i=0; i<select.options.length; i++) {
3283 var opt = select.options[i];
3284 if(opt.selected && opt.value != "") {
3288 active += opt.value;
3292 //Add the group folder ids.
3293 var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3294 for(i=0; i<group_folders.length; i++)
3296 active += ("::" + group_folders[i]);
3299 AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3302 * Updates user's group folder subscriptsion (Sugar only)
3303 * @param ieID The group folder to add to the tree view
3305 retrieveGroupFolderSubscriptions : function() {
3307 var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3308 var activeGroupFolders = "";
3309 var activeGroupIds = [];
3310 for(i=0;i<a_rs.length;i++)
3312 var t_record = a_rs[i];
3313 var is_active = t_record.getData('is_active');
3314 var isGroupFolder = t_record.getData('has_groupfolder');
3315 var ieID = t_record.getData('id');
3319 activeGroupIds.push(ieID);
3323 return activeGroupIds;
3328 SE.folders.checkEmail2 = function() {
3329 AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3331 //// END FOLDERS OBJECT
3332 ///////////////////////////////////////////////////////////////////////////////
3335 ///////////////////////////////////////////////////////////////////////////////
3338 * Keypress Event capture and processing
3341 overall : function(e) {
3342 switch(e.charCode) {
3344 if(e.ctrlKey || e.altKey) {
3345 var focusRegion = SE.innerLayout.regions.center;
3346 if(focusRegion.activePanel.closable == true) {
3347 focusRegion.remove(focusRegion.activePanel);
3355 ///////////////////////////////////////////////////////////////////////////////
3358 ///////////////////////////////////////////////////////////////////////////////
3361 * ListView object methods and attributes
3367 * Fills the ListView pane with detected messages.
3369 populateListFrame : function(node, ieId, forceRefresh) {
3370 SE.innerLayout.selectTab(0);
3371 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3373 Dom.get('_blank').innerHTML = "";
3374 SE.grid.params['emailUIAction'] = 'getMessageList';
3375 SE.grid.params['mbox'] = node.data.mbox;
3376 SE.grid.params['ieId'] = ieId;
3377 forcePreview = true; // loads the preview pane with first item in grid
3378 SE.listView.refreshGrid();
3382 * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3384 populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3385 SE.innerLayout.selectTab(0);
3386 Dom.get('_blank').innerHTML = "";
3387 SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3388 SE.grid.params['ieId'] = node.data.id;
3389 SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3390 SE.listView.refreshGrid();
3394 * Sets sort order as user preference
3397 saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3399 ieName = ieNamePassed;
3400 focusFolder = focusFolderPassed;
3402 SE.util.clearHiddenFieldValues('emailUIForm');
3403 var previousSort = document.getElementById('sortBy').value;
3405 document.getElementById('sortBy').value = sortBy;
3406 document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3407 document.getElementById('focusFolder').value = focusFolder;
3408 document.getElementById('ieId').value = ieId;
3410 if(sortBy == previousSort) {
3411 document.getElementById('reverse').value = '1';
3414 var formObject = document.getElementById('emailUIForm');
3415 YAHOO.util.Connect.setForm(formObject);
3417 AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3422 * Enables click/arrow select of grid items which then populate the preview pane.
3424 selectFirstRow : function() {
3425 SE.grid.selModel.selectFirstRow();
3428 selectLastRow : function() {
3429 SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3432 setEmailListStyles : function() {
3433 SE.listView.boldUnreadRows();
3435 var ds = SE.grid.getStore();
3436 if (SE.grid.getSelections().length == 0) {
3437 document.getElementById('_blank').innerHTML = '';
3441 if(typeof(ds.baseParams.mbox) != 'undefined') {
3442 acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3443 var cm = SE.grid.getColumnModel();
3444 if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3445 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3447 } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3448 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3452 var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3453 SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3456 // 4/20/2007 added to hide overlay after search
3458 if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3459 var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3460 var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3461 if (node) node.data.unseen = unread;
3463 SE.accounts.renderTree();
3466 // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3467 if(forcePreview && ds.totalCount > 0) {
3468 SE.detailView.getEmailPreview();
3469 forcePreview = false;
3474 * Removes a row if found via its UID
3476 removeRowByUid : function(uid) {
3477 uid = new String(uid);
3478 uids = uid.split(',');
3479 var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3481 for(j=0; j<uids.length; j++) {
3482 var theUid = uids[j];
3483 for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3484 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3485 SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3491 displaySelectedEmails : function(rows) {
3492 var dm = SE.grid.getDataModel();
3495 for(i=0; i<rows.length; i++) {
3496 var rowIndex = rows[i].rowIndex;
3497 var metadata = dm.data[rowIndex];
3502 uids += metadata[5];
3504 // unbold unseen email
3505 this.unboldRow(rowIndex);
3508 SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3512 * exception handler for data load failures
3514 loadException : function(dataModel, ex, response) {
3519 * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3520 * @param string sourceIeId Email's source I-E id
3521 * @param string sourceFolder Email's current folder
3522 * @param destinationIeId Destination I-E id
3523 * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3525 * @param array emailUids Array of email's UIDs
3527 moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3528 if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3529 overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3531 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3532 // remove rows from visibility
3533 for(row in selectedRows) {
3534 //SE.grid.getStore().remove(row);
3537 var baseUrl = '&sourceIeId=' + sourceIeId +
3538 '&sourceFolder=' + sourceFolder +
3539 '&destinationIeId=' + destinationIeId +
3540 '&destinationFolder=' + destinationFolder;
3543 for(i=0; i<emailUids.length; i++) {
3545 uids += app_strings.LBL_EMAIL_DELIMITER;
3547 uids += emailUids[i];
3549 if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3550 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3552 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3558 * Unbolds text in the grid view to denote read status
3560 markRead : function(index, record) {
3561 // unbold unseen email
3562 var row = SE.grid.getRecord(record);
3563 row.getData().seen = 1;
3564 SE.grid.getTrEl(record).style.fontWeight = "normal";
3568 * grid row output, bolding unread emails
3570 boldUnreadRows : function() {
3571 // bold unread emails
3572 var trEl = SE.grid.getFirstTrEl();
3573 while(trEl != null) {
3574 if(SE.grid.getRecord(trEl).getData().seen == "0")
3575 trEl.style.fontWeight = "bold";
3577 trEl.style.fontWeight = "";
3578 trEl = SE.grid.getNextTrEl(trEl);
3583 * Show preview for an email if 1 and only 1 is selected
3584 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3586 handleRowSelect : function(e) {
3587 if(e.selectedRows.length == 1) {
3588 SE.detailView.getEmailPreview();
3592 handleDrop : function(e, dd, targetId, e2) {
3594 case 'htmleditordiv':
3595 var rows = SE.grid.getSelectedRows();
3596 if(rows.length > 0) {
3597 SE.listView.displaySelectedEmails(rows);
3602 var targetElId = new String(targetId);
3603 var targetIndex = targetElId.replace('ygtvlabelel',"");
3604 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3605 var dm = SE.grid.getDataModel();
3606 var emailUids = new Array();
3607 var destinationIeId = targetNode.data.ieId;
3608 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3611 var rows = SE.grid.getSelectedRows();
3612 // iterate through dragged rows
3613 for(i=0; i<rows.length; i++) {
3614 //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3615 var rowIndex = rows[i].rowIndex;
3616 var dataModelRow = dm.data[rowIndex];
3617 var sourceIeId = dataModelRow[7];
3618 var sourceFolder = dataModelRow[6];
3619 emailUids[i] = dataModelRow[5];
3622 // event wrapped call - need FQ
3623 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3624 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3630 * Hack-around to get double-click and single clicks to work on the grid
3631 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3633 handleClick : function(o) {
3634 SUGAR.email2.grid.clearTextSelection();
3636 var el = SUGAR.email2.grid.getSelectedRows();
3638 //Load an email preview only if a single record is selected. For multiple selections do nothing.
3639 if ( el.length == 1)
3642 SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3643 SUGAR.email2.listView.currentRowIndex = rowId;
3644 clearTimeout(SUGAR.email2.detailView.previewTimer);
3645 SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3650 * Custom handler for double-click/enter
3651 * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3653 getEmail : function(e) {
3654 var rows = SE.grid.getSelectedRows();
3655 var row = SE.grid.getRecord(rows[0]).getData();
3657 clearTimeout(SE.detailView.previewTimer);
3658 document.getElementById("_blank").innerHTML = "";
3660 if(row.type != "draft") {
3661 SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3663 // circumventing yui-ext tab generation, let callback handler build new view
3664 SE.util.clearHiddenFieldValues('emailUIForm');
3665 //function(uid, mbox, ieId, setRead, destination) {
3666 document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3667 document.getElementById('uid').value = row.uid; // uid;
3668 document.getElementById('mbox').value = row.mbox; // mbox;
3669 document.getElementById('ieId').value = row.ieId; // ieId;
3671 YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3672 AjaxObject.target = '_blank';
3673 AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3678 * Retrieves a row if found via its UID
3682 getRowIndexByUid : function(uid) {
3683 uid = new String(uid);
3684 uids = uid.split(',');
3686 for(j=0; j<uids.length; j++) {
3687 var theUid = uids[j];
3689 for(i=0; i<SE.grid.getStore().data.length; i++) {
3690 if(SE.grid.getStore().data[i].id == theUid) {
3698 * Returns the UID's of the seleted rows
3701 getUidsFromSelection : function() {
3702 var rows = SE.grid.getSelectedRows();
3704 /* iterate through available rows JIC a row is deleted - use first available */
3705 for(var i=0; i<rows.length; i++) {
3706 uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3711 refreshGrid : function() {
3712 SE.grid.getDataSource().sendRequest(
3713 SUGAR.util.paramsToUrl(SE.grid.params),
3714 SE.grid.onDataReturnInitializeTable,
3720 //// END SE.listView
3721 ///////////////////////////////////////////////////////////////////////////////
3723 ///////////////////////////////////////////////////////////////////////////////
3727 * sends search criteria
3728 * @param reference element search field
3730 search : function(el) {
3731 var searchCriteria = new String(el.value);
3733 if(searchCriteria == '') {
3734 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3738 var safeCriteria = escape(searchCriteria);
3740 var accountListSearch = document.getElementById('accountListSearch');
3741 //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3743 SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3744 SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3745 SE.grid.getStore().baseParams['subject'] = safeCriteria;
3746 SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3747 SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3752 * sends advanced search criteria
3754 searchAdvanced : function() {
3755 var formObject = document.getElementById('advancedSearchForm');
3758 //Set assigned user id to blank if name is not present.
3759 if (formObject.elements['assigned_user_name'].value == "")
3760 formObject.elements['assigned_user_id'].value = "";
3762 for(i=0; i<formObject.elements.length; i++) {
3763 if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3766 if(formObject.elements[i].type == 'text') {
3767 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3769 if(formObject.elements[i].type == 'hidden') {
3770 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3772 if(formObject.elements[i].type == 'select-one') {
3773 var el = formObject.elements[i];
3774 var v = el.options[el.selectedIndex].value;
3777 SE.grid.params[el.name] = v;
3780 //Clear previous search results if necessary
3781 if(typeof( SE.grid.params[el.name]) != 'undefined')
3782 delete SE.grid.params[el.name]
3789 if(! this.validateSearchFormInput() )
3792 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3793 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3794 var accountListSearch = document.getElementById('accountListSearch');
3795 SE.listView.refreshGrid();
3797 alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3802 * Validates the search form inputs to ensure all parameters are valid
3805 validateSearchFormInput: function()
3807 addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3808 addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3809 var dateCheck = check_form('advancedSearchForm');
3811 //If the parent type is selected ensure the user selected a parent_id.
3812 if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3818 * Toggles the advanced options, either hidding or showing the selection.
3820 toggleAdvancedOptions: function()
3822 var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3824 for(var i=0;i<el.length;i++)
3826 if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3827 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3829 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3833 * clears adv search form fields
3835 searchClearAdvanced : function() {
3836 var form = document.getElementById('advancedSearchForm');
3838 for(i=0; i<form.elements.length; i++) {
3839 if(form.elements[i].type != 'button') {
3840 form.elements[i].value = '';
3846 //////////////////////////////////////////////////////////////////////////////
3849 //////////////////////////////////////////////////////////////////////////////
3852 /******************************************************************************
3853 * USER SIGNATURES calls stolen from Users module
3854 *****************************************************************************/
3855 createSignature : function(record, the_user_id) {
3856 var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3858 URL += "&record="+record;
3860 if(the_user_id != "") {
3861 URL += "&the_user_id="+the_user_id;
3863 var windowName = 'email_signature';
3864 var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3866 var win = window.open(URL, windowName, windowFeatures);
3867 if(win && win.focus) {
3868 // put the focus on the popup if the browser supports the focus() method
3873 deleteSignature : function() {
3874 if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3875 overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3876 var singature_id = document.getElementById('signature_id').value;
3877 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3881 saveOptionsGeneral : function(displayMessage) {
3882 var formObject = document.getElementById('formEmailSettingsGeneral');
3883 if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3884 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3887 YAHOO.util.Connect.setForm(formObject);
3888 SE.composeLayout.emailTemplates = null;
3890 AjaxObject.target = 'frameFlex';
3891 AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3894 alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3896 SE.settings.settingsDialog.hide();
3900 * Shows settings container screen
3902 showSettings : function() {
3903 if(!SE.settings.settingsDialog) {
3904 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3910 constraintoviewport: true
3912 dlg.showEvent.subscribe( function (){
3913 var el = this.element;
3914 var viewH = YAHOO.util.Dom.getViewportHeight();
3915 if (this.header && el && viewH - 50 < el.clientHeight) {
3916 var body = this.header.nextElementSibling;
3917 body.style.overflow = "auto";
3918 body.style.height = (viewH - 50) + "px";
3921 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3922 dlg.setBody('<div id="settingsTabDiv"/>');
3923 dlg.beforeRenderEvent.subscribe(function() {
3924 var dd = new YAHOO.util.DDProxy(dlg.element);
3925 dd.setHandleElId(dlg.header);
3926 dd.on('endDragEvent', function() {
3932 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3933 var tabContent = Dom.get("tab_general");
3934 tp.addTab(new YAHOO.widget.Tab({
3935 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3937 content : tabContent.innerHTML,
3938 id : "generalSettings",
3941 tabContent.parentNode.removeChild(tabContent);
3942 tabContent = Dom.get("tab_accounts");
3943 var accountTab = new YAHOO.widget.Tab({
3944 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3946 content : tabContent.innerHTML,
3947 id : "accountSettings"
3949 tp.addTab(accountTab);
3950 tabContent.parentNode.removeChild(tabContent);
3952 tp.appendTo(dlg.body);
3955 SE.settings.settingsDialog.show();
3956 SE.folders.lazyLoadSettings();
3957 SE.accounts.lazyLoad();
3961 lazyLoadRules : function() {
3962 if(false/*!SE.settings.rules*/) {
3963 AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3968 //// END SE.settings
3969 ///////////////////////////////////////////////////////////////////////////////
3972 /******************************************************************************
3974 *****************************************************************************/
3975 function removeHiddenNodes(nodes, grid) {
3977 for(var i = nodes.length - 1; i > -1; i--) {
3978 el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3979 if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3985 function strpad(val) {
3986 return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3989 function refreshTodos() {
3990 SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3991 AjaxObject.target = 'todo';
3992 AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3995 /******************************************************************************
3996 * MUST STAY IN GLOBAL NAMESPACE
3997 *****************************************************************************/
3998 function refresh_signature_list(signature_id, signature_name) {
3999 var field=document.getElementById('signature_id');
4001 for (var i=0; i < field.options.length; i++) {
4002 if (field.options[i].value == signature_id) {
4003 if (field.options[i].selected==false) {
4004 field.options[i].selected=true;
4009 //add item to selection list.
4011 var newElement=document.createElement('option');
4012 newElement.text=signature_name;
4013 newElement.value=signature_id;
4014 field.options.add(newElement);
4015 newElement.selected=true;
4018 //enable the edit button.
4019 var field1=document.getElementById('edit_sig');
4020 field1.style.visibility="inherit";
4021 var deleteButt = document.getElementById('delete_sig');
4022 deleteButt.style.visibility="inherit";
4025 function setDefaultSigId(id) {
4026 var checkbox = document.getElementById("signature_default");
4027 var default_sig = document.getElementById("signatureDefault");
4029 if(checkbox.checked) {
4030 default_sig.value = id;
4032 default_sig.value = "";
4036 function setSigEditButtonVisibility() {
4037 var field = document.getElementById('signature_id');
4038 var editButt = document.getElementById('edit_sig');
4039 var deleteButt = document.getElementById('delete_sig');
4040 if(field.value != '') {
4041 editButt.style.visibility = "inherit";
4042 deleteButt.style.visibility = "inherit";
4044 editButt.style.visibility = "hidden";
4045 deleteButt.style.visibility = "hidden";
4047 }// End of File modules/Emails/javascript/EmailUI.js
4049 /*********************************************************************************
4050 * SugarCRM Community Edition is a customer relationship management program developed by
4051 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4053 * This program is free software; you can redistribute it and/or modify it under
4054 * the terms of the GNU Affero General Public License version 3 as published by the
4055 * Free Software Foundation with the addition of the following permission added
4056 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4057 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4058 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4060 * This program is distributed in the hope that it will be useful, but WITHOUT
4061 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4062 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
4065 * You should have received a copy of the GNU Affero General Public License along with
4066 * this program; if not, see http://www.gnu.org/licenses or write to the Free
4067 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4070 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4071 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4073 * The interactive user interfaces in modified source and object code versions
4074 * of this program must display Appropriate Legal Notices, as required under
4075 * Section 5 of the GNU Affero General Public License version 3.
4077 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4078 * these Appropriate Legal Notices must retain the display of the "Powered by
4079 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4080 * technical reasons, the Appropriate Legal Notices must display the words
4081 * "Powered by SugarCRM".
4082 ********************************************************************************/
4085 var sw = YAHOO.SUGAR,
4086 Event = YAHOO.util.Event,
4087 Connect = YAHOO.util.Connect,
4088 Dom = YAHOO.util.Dom
4091 ///////////////////////////////////////////////////////////////////////////////
4094 _contactCache : new Array(), // cache of contacts
4095 _dd : new Array(), // filtered list, same format as _contactCache
4096 _ddLists : new Array(), // list of Lists
4097 _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4098 _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4099 clickBubble : true, // hack to get around onclick event bubbling
4101 relatedBeanType : '',
4104 itemSpacing : 'white-space:nowrap; padding:2px;',
4110 * YUI bug fix 2527707. Causes nested datatable's in <tables> to cause 404 errors whens earching.
4112 initFixForDatatableSort: function () {
4113 //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4114 YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4115 var oColumn = this._oColumnSet.getColumn(column);
4118 // Validate TD element
4119 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4121 oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4123 // Validate TH element
4125 elCell = this.getThEl(column);
4128 var allColumns = this._oColumnSet.flat;
4129 for(var i=0, len=allColumns.length; i<len; i++) {
4130 if(allColumns[i].getThEl().id === elCell.id) {
4131 oColumn = allColumns[i];
4142 cancelEdit : function() {
4143 if(this.editContactDialog)
4144 this.editContactDialog.hide();
4145 if(this.editMailingListDialog)
4146 this.editMailingListDialog.hide();
4150 * Clears filter form
4152 clear : function() {
4153 var t = document.getElementById('contactsFilter');
4159 * handle context-menu Compose-to call
4160 * @param string type 'contacts' or 'lists'
4162 composeTo : function(type, waited) {
4163 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4164 if (activePanel.substring(0, 10) != "composeTab") {
4165 SE.composeLayout.c0_composeNewEmail();
4166 setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4167 SE.contextMenus.contactsContextMenu.hide();
4170 var idx = activePanel.substring(10);
4173 // determine if we have a selection to work with
4174 if(type == 'contacts') {
4175 var ids = SE.contactView.getSelectedRows();
4176 for (var i in ids) {
4177 rows[i] = SE.contactView.getRecord(ids[i]);
4179 removeHiddenNodes(rows, SE.contactView);
4183 if(rows.length > 0) {
4184 SE.composeLayout.handleDrop(
4185 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4186 null, rows, 'addressTO' + idx );
4188 alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4192 editContact : function() {
4193 SE.contextMenus.contactsContextMenu.hide();
4194 var element = SE.contactView.getSelectedNodes()[0];
4196 if (element.className.indexOf('address-contact') > -1) {
4197 elementId = element.id;
4198 } else if (element.className.indexOf('address-exp-contact') > -1) {
4199 elementId = element.id.substring(2);
4205 * Filters contact entries based on user input
4207 filter : function(inputEl) {
4208 var ret = new Object();
4209 var re = new RegExp(inputEl.value, "gi");
4211 for(var i in this._contactCache) {
4212 if(this._contactCache[i].name.match(re)) {
4213 ret[i] = this._contactCache[i];
4217 this.buildContactList(ret);
4220 fullForm : function(id, module) {
4221 document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4225 * returns a formatted email address from the addressBook cache
4227 getFormattedAddress : function(id) {
4228 var o = this._contactCache[id];
4229 var primaryEmail = '';
4231 for(var i=0; i<o.email.length; i++) {
4232 var currentEmail = o.email[i].email_address;
4234 if(o.email[i].primary_address == 1) {
4235 primaryEmail = o.email[i].email_address;
4239 var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4240 var name = new String(o.name);
4241 var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/'/gi,'\'');
4242 var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
4248 * Sets up async call to query for matching contacts, users, etc.
4250 searchContacts : function() {
4251 var fn = document.getElementById('input_searchField').value;
4252 var pe = document.getElementById('input_searchPerson').value;
4254 var rb = document.getElementById('hasRelatedBean').checked;
4257 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4258 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4259 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4260 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4262 this.addressBookDataModel.params['related_bean_id'] = '';
4265 this.addressBookDataModel.params['search_field'] = fn;
4266 this.addressBookDataModel.params['person'] = pe;
4267 this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4268 this.grid._oDataSource = this.addressBookDataModel;
4269 this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
4273 * Clear Search Crieteria For Addressbook
4275 clearAddressBookSearch : function() {
4276 document.getElementById('input_searchField').value = "";
4277 document.getElementById('input_searchPerson').selectedIndex = 0;
4281 * Opens modal select window to add contacts to addressbook
4283 selectContactsDialogue : function(destId) {
4284 if(!this.contactsDialogue) {
4285 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4289 constraintoviewport: true,
4291 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4292 {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4294 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4296 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4297 dlg.setBody(body.innerHTML);
4298 dlg.renderEvent.subscribe(function() {
4299 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4300 if (iev && !SUGAR.isIE) {
4301 this.body.style.width = "950px";
4306 dlg.beforeRenderEvent.subscribe(function() {
4307 var dd = new YAHOO.util.DDProxy(dlg.element);
4308 dd.setHandleElId(dlg.header);
4309 dd.on('endDragEvent', function() {
4315 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4317 var tabContent = SUGAR.util.getAndRemove("searchForm");
4318 tp.addTab(new YAHOO.widget.Tab({
4319 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4321 content : tabContent.innerHTML,
4322 id : "addressSearchTab",
4326 var addListenerFields = ['input_searchPerson','input_searchField' ]
4327 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4328 if (e.keyCode == 13) {
4329 YAHOO.util.Event.stopEvent(e);
4330 SUGAR.email2.addressBook.searchContacts();
4334 this.contactsDialogue.render();
4337 //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4338 if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4342 var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4343 var idx = activePanel.substring(10);
4345 SE.addressBook.idx = idx;
4348 if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4349 document.getElementById('relatedBeanColumn').style.display = '';
4350 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4351 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4352 relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4353 document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4354 SE.addressBook.relatedBeanType = relatedBeanType;
4356 document.getElementById('relatedBeanColumn').style.display = 'none';
4357 document.getElementById('hasRelatedBean').checked = false;
4360 if (!SE.addressBook.grid)
4362 if (hasRelatedBeanId) {
4363 document.getElementById('hasRelatedBean').checked = true;
4365 AddressSearchGridInit();
4366 SE.addressBook.relatedBeanId = relatedBeanId;
4370 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4372 SE.addressBook.relatedBeanId = relatedBeanId;
4373 document.getElementById('hasRelatedBean').checked = true;
4375 if (document.getElementById('hasRelatedBean').checked == true)
4377 SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4378 SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4380 SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4381 SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4383 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4384 SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4385 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4388 //Remove any lingering rows in the result set table if the module was closed.
4389 SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4391 SE.addressBook.populateResulstTableEmailAddresses();
4393 this.contactsDialogue.show();
4396 * Clear all email addresses from result table.
4399 clearAllEmailAddressFieldsFromResultTable: function () {
4400 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4401 //Unhighlight any rows currently selected if the emails were cleared.
4402 SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4403 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4406 * Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4407 * results table. This function is called when the address book is displayed.
4409 populateResulstTableEmailAddresses: function () {
4411 var idx = SE.addressBook.idx;
4412 var emailFields = ['to','cc','bcc'];
4414 for(var k=0;k<emailFields.length;k++)
4416 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4417 var allEmails = document.getElementById(elKey).value;
4421 var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4423 for (var i=0; i<formatedEmails.length; i++)
4425 var t_name = formatedEmails[i].name;
4426 var t_emailAddr = formatedEmails[i].email_address;
4427 var displayEmail = t_name + ' <' + t_emailAddr + '>';
4429 t_name = displayEmail = t_emailAddr;
4431 var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4432 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4433 'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4439 * Checks all entries in the result table against a particular email address, returning true
4440 * if the email address is found, false otherwise.
4442 doesEmailAdddressExistInResultTable: function(emailAddress)
4444 if(trim(emailAddress) == '')
4447 var emailAddressFound = false;
4448 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4449 for (var i=0; i < contacts.length; i++)
4451 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4452 //If we are adding to cc or bcc fields, make them visible.
4453 if(data.email_address == emailAddress)
4455 emailAddressFound = true;
4460 return emailAddressFound;
4463 * Takes all email addresses that the users wishes to add from the address book and populates the To
4464 * fields on the compose tab.
4466 populateEmailAddressFieldsFromResultTable: function()
4468 //Clear the fields first, all email addresses are stored in the address book
4469 var idx = SE.addressBook.idx;
4470 var emailFields = ['to','cc','bcc'];
4471 for(var k=0;k<emailFields.length;k++)
4473 var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4474 document.getElementById(elKey).value = "";
4477 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4478 for (var i=0; i < contacts.length; i++)
4480 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4482 var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4483 //If we are adding to cc or bcc fields, make them visible.
4484 if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4485 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4486 //Construct the target id
4487 var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4489 var target = document.getElementById(target_id);
4490 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4493 //Delete all rows from the result set table
4494 SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4497 SE.addressBook.contactsDialogue.hide()
4500 * Insert contacts into the result table.
4502 insertContactToResultTable : function(event,address_type) {
4504 var contactsDialogue = SE.addressBook.contactsDialogue;
4505 var contacts = SE.addressBook.grid.getSelectedRows();
4507 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4508 for (var i = 0; i < rows.length; i++)
4510 if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4512 var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4513 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4514 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4515 rows[i].setData("selected",true);
4518 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4519 for (var i = 0; i < checkBoxes.length; i++) {
4520 checkBoxes[i].checked = false;
4526 insertContactRowToResultTable : function(rowId, addressType) {
4527 var data = SE.addressBook.grid.getRecord(rowId).getData();
4528 if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4530 var name = data.name.replace(/'/gi,'\'').replace(/"/gi,'"');
4531 var ea = name + ' <' + data.email.replace(/'/gi,'\'') + '>';
4532 if(addressType == null)
4533 addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4534 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':name,'email_address': data.email,'display_email_address': ea,'bean_id': data.bean_id,'idx' : SE.addressBook.idx});
4537 * Remove a row from the gridsResult table.
4539 removeRowFromGridResults : function(rowId,emailAddress)
4541 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4542 for (var i=0; i < contacts.length; i++)
4544 var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4545 var data = rec.getData();
4546 if(data.email_address == emailAddress)
4548 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4553 SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4556 * Translates between the addressType To|Cc|Bcc labels/keys.
4558 translateAddresType: function(addressType,fromKey)
4560 var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4561 var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4562 var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4563 var mappingObject = {};
4566 mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4569 mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4570 mappingObject[displayCc] = 'cc';
4571 mappingObject[displayBcc] = 'bcc';
4574 return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4580 toggleSearchRowIcon : function(rowId,show)
4584 var idToShow = rowId + '_add_img';
4585 var idToHide = rowId + '_rm_img';
4589 var idToShow = rowId + '_rm_img';
4590 var idToHide = rowId + '_add_img';
4594 Dom.addClass(idToHide, "yui-hidden");
4595 Dom.removeClass(idToShow, "yui-hidden");
4598 * Determine if an entry has already been added to the grid results table to prevent duplicates.
4600 doesGridResultsEntryExist: function(emailAddrs)
4603 var contactExists = false;
4604 var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4605 for (var i=0; i < contacts.length; i++)
4607 var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4608 if(data.email_address == emailAddrs)
4610 contactExists = true;
4614 return contactExists;
4618 * adds an email address to a string, but first checks if it exists
4619 * @param string concat The string we are appending email addresses to
4620 * @param string addr Email address to add
4623 smartAddEmailAddressToComposeField : function(concat, addr) {
4624 var re = new RegExp(addr);
4626 if(!concat.match(re)) {
4628 concat += "; " + addr;
4637 //// END ADDRESS BOOK
4638 ///////////////////////////////////////////////////////////////////////////////
4642 ///////////////////////////////////////////////////////////////////////////////
4645 * Auto-complete object
4649 delimChar : [";", ","],
4653 prehighlightClassName : "yui-ac-prehighlight",
4656 instances : new Array(),
4659 * Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
4660 * @param object Contact from AddressBook
4663 getPrimaryAddress : function(contact) {
4664 var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4666 for(var eIndex in contact.email) {
4667 address = contact.email[eIndex].email_address;
4668 if(contact.email[eIndex].primary_address == 1) {
4669 return contact.email[eIndex].email_address;
4677 * initializes autocomplete widgets for a given compose view
4680 init : function(idx) {
4681 var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4682 "queryMatchContains" : false,
4683 "queryMatchSubset" : true
4686 this.instances[idx] = {
4693 // instantiate the autoComplete widgets
4694 this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4695 this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4696 this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4698 // enable hiding of interfering textareas
4699 this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4700 this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4701 this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4703 // enable reshowing of hidden textareas
4704 this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4705 this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4706 this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4708 // enable refreshes of contact lists
4709 this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4710 this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4711 this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4714 refreshDataSource : function(sType, aArgs) {
4715 var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4717 var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4719 if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4720 idx = textBoxId.substr(9);
4722 idx = textBoxId.substr(10);
4725 SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4726 SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4727 SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4731 * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4733 returnDataSource : function(contacts) {
4734 var ret = new Array();
4735 for(var id in contacts) {
4736 if (contacts[id].name) {
4737 var primary = this.getPrimaryAddress(contacts[id]);
4739 ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4740 //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4742 for(var emailIndex in contacts[id].email) {
4743 ret[ret.length] = contacts[id].email[emailIndex].email_address;
4752 * Hides address textareas to prevent autocomplete dropdown from being obscured
4754 toggleTextareaHide : function(sType, aArgs) {
4755 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4759 if(textBoxId.indexOf("addressTO") > -1) {
4761 } else if(textBoxId.indexOf("addressCC") > -1) {
4764 idx = textBoxId.substr(9);
4766 // follow through if not BCC
4768 var cc = document.getElementById("addressCC" + idx);
4769 var bcc = document.getElementById("addressBCC" + idx);
4773 cc.style.visibility = 'hidden';
4775 bcc.style.visibility = 'hidden';
4782 * Redisplays the textareas after an address is commited
4784 toggleTextareaShow : function(sType, aArgs) {
4785 var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4789 if(textBoxId.indexOf("addressTO") > -1) {
4791 } else if(textBoxId.indexOf("addressCC") > -1) {
4794 idx = textBoxId.substr(9);
4796 // follow through if not BCC
4798 document.getElementById("addressCC" + idx).style.visibility = 'visible';
4799 document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4804 //// END AUTOCOMPLETE
4805 ///////////////////////////////////////////////////////////////////////////////
4807 ///////////////////////////////////////////////////////////////////////////////
4810 * expands the options sidebar
4812 SE.composeLayout = {
4813 currentInstanceId : 0,
4816 outboundAccountErrors : null,
4817 loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4819 showAddressDetails : function(e) {
4820 var linkElement = document.getElementById("More"+e.id);
4821 var spanElement = document.getElementById("Detail"+e.id);
4822 var emailAddressList = e.value;
4823 if(e.value.length > 96)
4825 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4826 var displayArray = [];
4827 for (var i=0; i<resultArray.length; i++)
4829 var t_name = resultArray[i].name;
4830 var t_emailAddr = resultArray[i].email_address;
4832 displayArray.push('<br/><' + t_emailAddr + '>');
4834 displayArray.push(t_name + '<br/><' + t_emailAddr + '>');
4837 var result = displayArray.join('<br/>');
4839 linkElement.style.display = "inline";
4840 linkElement.style.height="10px";
4841 linkElement.style.overflow="visible";
4842 spanElement.innerHTML = result;
4845 linkElement.style.display = "none";
4850 * Given a string of email address, return an array containing the name portion (if available)
4851 * and email portion.
4853 _getEmailArrayFromString : function (emailAddressList){
4856 while ((results = reg.exec(emailAddressList)) != null)
4858 orignial = results[0];
4859 parsedResult = results[0].replace(';', ':::::');
4860 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4864 while ((results = reg.exec(emailAddressList)) != null)
4866 orignial = results[0];
4867 parsedResult = results[0].replace(',', ':::::');
4868 emailAddressList = emailAddressList.replace (orignial, parsedResult);
4870 //Administrator <johndoe@som.com> ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4871 var emailArr = emailAddressList.split(":::::");
4872 var resultsArray = [];
4874 for (var i=0; i<emailArr.length; i++)
4876 var rposition = emailArr[i].indexOf('<');
4877 var lposition = emailArr[i].indexOf('>');
4879 if(trim(emailArr[i]) != '')
4881 if(rposition != -1 && lposition != -1)
4883 var t_name = emailArr[i].substr(0, rposition-1);
4884 var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4885 resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4889 resultsArray.push({'name':'', 'email_address': emailArr[i]});
4893 return resultsArray;
4895 ///////////////////////////////////////////////////////////////////////////
4898 * Prepare bucket DIV and yui-ext tab panels
4900 _0_yui : function() {
4901 var idx = this.currentInstanceId;
4903 var composeTab = new YAHOO.SUGAR.ClosableTab({
4904 label: mod_strings.LNK_NEW_SEND_EMAIL,
4906 content : "<div id='htmleditordiv" + idx + "'/>",
4907 id : "composeTab" + idx,
4908 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4911 SE.innerLayout.addTab(composeTab);
4913 // get template engine with template
4914 if (!SE.composeLayout.composeTemplate) {
4915 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4918 // create Tab inner layout
4919 var composePanel = this.getComposeLayout();
4920 composePanel.getUnitByPosition("right").collapse();
4921 composePanel.autoSize();
4925 * Generate the quick compose layout
4926 * @method getQuickComposeLayout
4927 * @param {Pannel} parentPanel Parent pannel
4928 * @param {Object} o Options
4931 getQuickComposeLayout : function (parentPanel,o) {
4932 var idx = SE.composeLayout.currentInstanceId;
4934 //Before rendering the parent pannel we need to initalize the grid layout
4935 parentPanel.beforeRenderEvent.subscribe(function() {
4937 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4938 SE.composeLayout._createComposeLayout(idx);
4939 SE.composeLayout[idx].set('height', 350);
4940 SE.composeLayout[idx].render();
4944 //Wait until the Compose Layout has rendered, then add the
4945 //options tab and perform the tiny initialization.
4946 parentPanel.renderEvent.subscribe(function() {
4948 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4949 SE.composeLayout._initComposeOptionTabs(idx);
4950 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4951 //Initialize tinyMCE
4952 if (!SUGAR.util.isTouchScreen())
4953 SE.composeLayout._1_tiny(false);
4954 //Init templates and address book
4955 SE.composeLayout._2_final();
4957 SE.composeLayout.quickCreateComposePackage(o);
4962 //Check if we have the div override for the shortcut bar
4963 if(typeof o.menu_id != 'undefined') {
4964 parentPanel.render(o.menu_id);
4966 parentPanel.render(document.body);
4969 return SE.composeLayout[idx];
4972 * Fill in all fields into the quick compose layout.
4973 * @method quickCreateComposePackage
4974 * @param {Object} o Options
4977 quickCreateComposePackage: function(o)
4979 //If we have a compose package fill in defaults.
4980 if (typeof(o.composePackage) != 'undefined')
4982 composePackage = o.composePackage; //Set the compose data object
4983 //Hijack this method called by composePackage as it's not need for quick creates.
4984 SE.composeLayout.c0_composeNewEmail = function(){};
4985 SE.composeLayout.composePackage(); //Fill in defaults.
4988 getComposeLayout : function() {
4989 var idx = SE.composeLayout.currentInstanceId;
4991 this._createComposeLayout(idx);
4992 SE.composeLayout[idx].render();
4993 this._initComposeOptionTabs(idx);
4995 return SE.composeLayout[idx];
4999 * Create the layout manager for the compose window.
5001 _createComposeLayout : function(idx)
5003 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
5004 parent: SE.complexLayout,
5014 SE.composeLayout.composeTemplate.exec({
5015 'app_strings':app_strings,
5016 'mod_strings':mod_strings,
5018 'linkbeans_options' : linkBeans,
5019 'idx' : SE.composeLayout.currentInstanceId
5030 body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5033 header: app_strings.LBL_EMAIL_OPTIONS
5039 * Create compose tab which will populate the 'right' container in the compose window.
5041 _initComposeOptionTabs : function(idx)
5043 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5044 var tab = new YAHOO.widget.Tab({
5045 label: app_strings.LBL_EMAIL_ATTACHMENT,
5047 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5048 id : "divAttachments" + idx,
5052 tab.layout = SE.composeLayout[idx];
5054 tab.on("activeChange", function(o){
5056 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5062 tab = new YAHOO.widget.Tab({
5063 label: app_strings.LBL_EMAIL_OPTIONS,
5065 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5066 id : "divOptions" + idx,
5070 tab.layout = SE.composeLayout[idx];
5071 tab.on("activeChange", function(o){
5073 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5078 SE.composeLayout[idx].autoSize = function() {
5079 var pEl = this.get("element").parentNode.parentNode.parentNode;
5080 this.set("height", pEl.clientHeight-30);
5084 SE.composeLayout[idx].rightTabs = cTabs;
5086 isParentTypeValid : function(idx) {
5087 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5088 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5089 if (trim(parentTypeValue) == ""){
5090 alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5096 isParentTypeAndNameValid : function(idx) {
5097 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5098 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5099 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5100 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5101 (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5102 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5108 callopenpopupForEmail2 : function(idx,options) {
5110 var formName = 'emailCompose' + idx;
5112 if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5113 formName = options.form_name;
5115 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5116 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5117 if (!SE.composeLayout.isParentTypeValid(idx)) {
5120 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5122 call_back_function:"SE.composeLayout.popupAddEmail",
5124 field_to_name_array:{
5125 id:'data_parent_id' + idx,
5126 name:'data_parent_name' + idx,
5131 popupAddEmail : function(o)
5133 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5134 var data = o.name_to_value_array;
5135 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5136 && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5138 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5139 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5146 _1_tiny : function(isReplyForward) {
5147 var idx = SE.composeLayout.currentInstanceId;
5148 var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5149 SE.tinyInstances[elId] = { };
5150 SE.tinyInstances[elId].ready = false;
5151 var t = tinyMCE.getInstanceById(elId);
5153 if(typeof(t) == 'undefined') {
5154 tinyMCE.execCommand('mceAddControl', false, elId);
5155 YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5156 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
5161 resizeEditorSetSignature : function(idx,setSignature)
5163 var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5165 if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
5166 setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+isReplyForward+"');",500);
5170 SE.composeLayout.resizeEditor(idx);
5172 setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
5177 resizeEditor : function(idx)
5179 var cof = Dom.get('composeOverFrame' + idx);
5180 var head = Dom.get('composeHeaderTable' + idx);
5181 var targetHeight = cof.clientHeight - head.clientHeight;
5182 var instance = SE.util.getTiny('htmleditor' + idx);
5185 var parentEl = Dom.get(instance.editorId + '_parent');
5186 var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5187 var contentEl = instance.contentAreaContainer;
5188 var iFrame = contentEl.firstChild;
5189 var tinMceToolbarOffset = 18;
5190 iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
5193 setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
5198 * Initializes d&d, auto-complete, email templates
5200 _2_final : function() {
5201 var idx = SE.composeLayout.currentInstanceId;
5203 if(this.emailTemplates) {
5204 this.setComposeOptions(idx);
5206 //populate email template cache
5207 AjaxObject.target = '';
5208 AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5211 // handle drop targets for addressBook
5212 var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5213 var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5214 var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5215 to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5217 // auto-complete setup
5218 SE.autoComplete.init(idx);
5221 document.getElementById("addressTO" + idx).focus();
5225 * hide tinyMCE tool bar if send email as plaintext is checked
5227 renderTinyMCEToolBar : function (idx, hide) {
5229 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5231 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5235 c1_composeEmail : function(isReplyForward, retry) {
5239 if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5240 setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5242 this._1_tiny(isReplyForward);
5245 if(isReplyForward) {
5246 this.replyForwardEmailStage2();
5252 * takes draft info and prepopulates
5254 c0_composeDraft : function() {
5255 this.getNewInstanceId();
5257 document.getElementById('_blank').innerHTML = '';
5258 var idx = SE.composeLayout.currentInstanceId;
5259 SE.composeLayout.draftObject = new Object();
5260 SE.composeLayout.draftObject.id = idx;
5261 SE.composeLayout.draftObject.isDraft = true;
5262 SE.composeLayout.currentInstanceId = idx;
5263 SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5264 SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5265 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5267 SE.composeLayout._0_yui();
5268 SE.composeLayout._1_tiny(true);
5271 SE.composeLayout._2_final();
5273 /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5274 setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5278 * Strip & Prep editor hidden fields
5280 c0_composeNewEmail : function() {
5281 this.getNewInstanceId();
5282 this.c1_composeEmail(false);
5286 * Sends async request to get the compose view.
5287 * Requests come from "reply" or "forwards"
5289 c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5290 SE.composeLayout.replyForwardObj = new Object();
5291 SE.composeLayout.replyForwardObj.ieId = ieId;
5292 SE.composeLayout.replyForwardObj.uid = uid;
5293 SE.composeLayout.replyForwardObj.mbox = mbox;
5294 SE.composeLayout.replyForwardObj.type = type;
5296 if(mbox == 'sugar::Emails') {
5297 SE.composeLayout.replyForwardObj.sugarEmail = true;
5300 SE.composeLayout.getNewInstanceId();
5301 SE.composeLayout.c1_composeEmail(true);
5303 //// END COMPOSE FLOW
5304 ///////////////////////////////////////////////////////////////////////////
5307 * Called when a contact, email, or mailinglist is dropped
5308 * into one of the compose fields.
5310 handleDrop : function (source, event, data, target) {
5313 target = event.getTarget();
5315 data.nodes = [data.nodes];
5319 target = document.getElementById(target);
5323 if (target.id.indexOf('address') > -1) {
5324 // dropped onto email to/cc/bcc field
5325 for(var i in nodes) {
5326 var node = nodes[i].getData();
5328 if (node[1].indexOf('contact') > -1) {
5329 email = SE.addressBook.getFormattedAddress(node[0]);
5330 } else if (node[1].indexOf('address-email') > -1){
5331 email = node[3].replace(/ /gi, '');
5332 email = email.replace('<', '<').replace('>', '>');
5333 var tr = source.getTrEl(nodes[i]);
5334 while (tr && !Dom.hasClass(tr, "address-contact")) {
5335 tr = source.getPreviousTrEl(tr);
5337 var CID = source.getRecord(tr).getData()[0];
5338 var o = SE.addressBook._contactCache[CID];
5339 var name = new String(o.name);
5340 var finalName = name.replace(/(<([^>]+)>)/ig, "");
5341 email = finalName + email;
5343 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5349 /*/////////////////////////////////////////////////////////////////////////////
5350 /// EMAIL TEMPLATE CODE
5352 applyEmailTemplate : function (idx, id) {
5355 var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5356 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5357 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5360 var to_addr = document.getElementById('addressTO'+idx);
5361 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
5363 box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5364 box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5367 // id is selected index of email template drop-down
5368 if(id == '' || id == "0") {
5369 YAHOO.SUGAR.MessageBox.show({
5374 if(btn=='no'){return;};
5375 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5382 YAHOO.SUGAR.MessageBox.show({
5387 if(btn=='no'){return;};
5388 SUGAR.email2.composeLayout.processResult(idx, id);},
5394 processNoneResult : function(idx, id) {
5395 var tiny = SE.util.getTiny('htmleditor' + idx);
5396 var tinyHTML = tiny.getContent();
5397 var openTag = '<div><span><span>';
5398 var htmllow = tinyHTML.toLowerCase();
5399 var start = htmllow.indexOf(openTag);
5401 tinyHTML = tinyHTML.substr(start);
5402 tiny.setContent(tinyHTML);
5404 tiny.setContent('');
5408 processResult : function(idx , id){
5409 call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5411 // get attachments if any
5412 AjaxObject.target = '';
5413 AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5416 appendEmailTemplateJSON : function() {
5417 var idx = SE.composeLayout.currentInstanceId; // post increment
5419 // query based on template, contact_id0,related_to
5420 //jchi 09/10/2008 refix #7743
5421 if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5422 document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5425 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,'"');
5427 // cn: bug 14361 - text-only templates don't fill compose screen
5429 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/>");
5432 var tiny = SE.util.getTiny('htmleditor' + idx);
5433 var tinyHTML = tiny.getContent();
5434 var openTag = '<div><span><span>';
5435 var closeTag = '</span></span></div>';
5436 var htmllow = tinyHTML.toLowerCase();
5437 var start = htmllow.indexOf(openTag);
5439 var htmlPart2 = tinyHTML.substr(start);
5440 tinyHTML = text + htmlPart2;
5441 tiny.setContent(tinyHTML);
5443 tiny.setContent(text);
5448 * Writes out the signature in the email editor
5450 setSignature : function(idx) {
5453 var hide = document.getElementById('setEditor' + idx).checked;
5454 SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5455 //wait for signatures to load before trying to set them
5456 if (!SE.composeLayout.signatures) {
5457 setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5462 var sel = document.getElementById('signatures' + idx);
5464 var sel = document.getElementById('signature_id');
5465 idx = SE.tinyInstances.currentHtmleditor;
5468 //Ensure that the tinyMCE html has been rendered.
5469 if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5470 setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5477 signature = sel.options[sel.selectedIndex].value;
5482 var openTag = '<div><span><span>';
5483 var closeTag = '</span></span></div>';
5484 var t = tinyMCE.getInstanceById('htmleditor' + idx);
5486 if(typeof(t) != 'undefined')
5488 t.contentDocument = t.contentWindow.document;
5489 var html = t.getContent();
5496 var htmllow = html.toLowerCase();
5497 var start = htmllow.indexOf(openTag);
5498 var end = htmllow.indexOf(closeTag) + closeTag.length;
5500 // selected "none" - remove signature from email
5501 if(signature == '') {
5503 var htmlPart1 = html.substr(0, start);
5504 var htmlPart2 = html.substr(end, html.length);
5506 html = htmlPart1 + htmlPart2;
5509 SE.signatures.lastAttemptedLoad = '';
5513 if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5514 SE.signatures.lastAttemptedLoad = '';
5516 SE.signatures.lastAttemptedLoad = signature;
5518 if(typeof(SE.signatures[signature]) == 'undefined') {
5520 SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5521 SE.signatures.targetInstance = (idx) ? idx : "";
5522 AjaxObject.target = '';
5523 AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5525 var newSignature = this.prepareSignature(SE.signatures[signature]);
5527 // clear out old signature
5528 if(SE.signatures.lastAttemptedLoad && start > -1) {
5529 var htmlPart1 = html.substr(0, start);
5530 var htmlPart2 = html.substr(end, html.length);
5532 html = htmlPart1 + htmlPart2;
5536 start = html.indexOf('<div><hr></div>');
5537 if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5538 var htmlPart1 = html.substr(0, start);
5539 var htmlPart2 = html.substr(start, html.length);
5540 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5541 } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5542 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5544 var newHtml = html + openTag + newSignature + closeTag;
5546 //tinyMCE.setContent(newHtml);
5547 t.setContent(newHtml);
5551 prepareSignature : function(str) {
5552 var signature = new String(str);
5554 signature = signature.replace(/</gi, '<');
5555 signature = signature.replace(/>/gi, '>');
5561 showAttachmentPanel : function(idx) {
5562 var east = SE.composeLayout[idx].getUnitByPosition("right");
5563 var tabs = SE.composeLayout[idx].rightTabs;
5565 tabs.set("activeTab", tabs.getTab(0));
5569 * expands sidebar and displays options panel
5571 showOptionsPanel : function(idx) {
5572 var east = SE.composeLayout[idx].getUnitByPosition("right");
5573 var tabs = SE.composeLayout[idx].rightTabs;
5575 tabs.set("activeTab", tabs.getTab(1));
5579 * Selects the Contacts tab
5581 showContactsPanel : function() {
5582 SE.complexLayout.regions.west.showPanel("contactsTab");
5586 * Generates fields for Select Document
5588 addDocumentField : function(idx) {
5589 var basket = document.getElementById('addedDocuments' + idx);
5591 var index = (basket.childNodes.length / 7) - 1;
5598 var test = document.getElementById('documentId' + idx + index);
5600 while(test != null) {
5602 test = document.getElementById('documentId' + idx + index);
5605 var documentCup = document.createElement("div");
5606 documentCup.id = 'documentCup' + idx + index;
5607 documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5608 // document id field
5609 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5610 // document name field
5611 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5613 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5614 "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5615 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5617 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5618 "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5619 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5622 basket.appendChild(documentCup);
5623 //basket.innerHTML += out;
5628 * Makes async call to save a draft of the email
5629 * @param int Instance index
5631 saveDraft : function(tinyInstance) {
5632 this.sendEmail(tinyInstance, true);
5635 selectDocument : function(target) {
5636 URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5637 windowName = 'selectDocument';
5638 windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5640 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5642 // put the focus on the popup if the browser supports the focus() method
5648 * Modal popup for file attachment dialogue
5650 addFileField : function() {
5651 if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5652 SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5656 constraintoviewport: true,
5658 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5659 fn:function(){SE.addFileDialog.hide();}
5662 SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5663 SE.addFileDialog.render();
5664 // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5666 Dom.removeClass("addFileDialog", "yui-hidden");
5668 SE.addFileDialog.show();
5672 * Async upload of file to temp dir
5674 uploadAttachment : function() {
5675 if(document.getElementById('email_attachment').value != "") {
5676 var formObject = document.getElementById('uploadAttachment');
5677 YAHOO.util.Connect.setForm(formObject, true, true);
5678 AjaxObject.target = '';
5679 AjaxObject.startRequest(callbackUploadAttachment, null);
5681 alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5686 * Adds a SugarDocument to an outbound email. Action occurs in a popup window displaying a ListView from the Documents module
5687 * @param string target in focus compose layout
5689 setDocument : function(idx, target, documentId, documentName, docRevId) {
5690 // fields are named/id'd [fieldName][instanceId][index]
5691 var addedDocs = document.getElementById("addedDocuments" + idx);
5692 var docId = document.getElementById('documentId' + idx + target);
5693 var docName = document.getElementById('documentName' + idx + target);
5694 var docRevisionId = document.getElementById('document' + idx + target);
5695 docId.value = documentId;
5696 docName.value = documentName;
5697 docRevisionId.value = docRevId;
5701 * Removes the bucket div containing the document input fields
5703 deleteDocumentField : function(documentCup) {
5704 var f0 = document.getElementById(documentCup);
5705 f0.parentNode.removeChild(f0);
5709 * Removes a Template Attachment field
5713 deleteTemplateAttachmentField : function(idx, index) {
5714 // create not-in-array values for removal filtering
5715 var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5721 r += document.getElementById('templateAttachmentId' + idx + index).value;
5722 document.getElementById("templateAttachmentsRemove" + idx).value = r;
5724 var target = 'templateAttachmentCup' + idx + index;
5725 d = document.getElementById(target);
5726 d.parentNode.removeChild(d);
5730 * Async removal of uploaded temp file
5731 * @param string index Should be a concatenation of idx and index
5734 deleteUploadAttachment : function(index, file) {
5735 var d = document.getElementById('email_attachment_bucket' + index);
5736 d.parentNode.removeChild(d);
5738 // make async call to delete cached file
5739 AjaxObject.target = '';
5740 AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5744 * Attaches files coming from Email Templates
5746 addTemplateAttachmentField : function(idx) {
5748 document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5750 var basket = document.getElementById('addedTemplateAttachments' + idx);
5753 var index = basket.childNodes.length;
5760 var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5762 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5763 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5764 idx + "\",\"" + index + "\");'/>" +
5766 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5767 // templateAttachment field
5768 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5770 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5772 "<span id='templateAttachmentName" + idx + index + "'" + "> </span>" +
5773 "<br id='br" + index + "></br>" +
5774 "<br id='brdoc" + index + "></br>" +
5776 basket.innerHTML = basket.innerHTML + out;
5782 * Sends one email via async call
5783 * @param int idx Editor instance ID
5784 * @param bool isDraft
5786 sendEmail : function(idx, isDraft) {
5788 //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5789 var obAccountID = document.getElementById('addressFrom' + idx).value;
5791 if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5793 overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5798 var form = document.getElementById('emailCompose' + idx);
5799 var composeOptionsFormName = "composeOptionsForm" + idx;
5800 var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5801 var html = t.getContent();
5802 var subj = document.getElementById('emailSubject' + idx).value;
5803 var to = trim(document.getElementById('addressTO' + idx).value);
5804 var cc = trim(document.getElementById('addressCC' + idx).value);
5805 var bcc = trim(document.getElementById('addressBCC' + idx).value);
5806 var email_id = document.getElementById('email_id' + idx).value;
5807 var composeType = document.getElementById('composeType').value;
5808 var parent_type = document.getElementById("parent_type").value;
5809 var parent_id = document.getElementById("parent_id").value;
5811 var el_uid = document.getElementById("uid");
5812 var uid = (el_uid == null) ? '' : el_uid.value;
5814 var el_ieId = document.getElementById("ieId");
5815 var ieId = (el_ieId == null) ? '' : el_ieId.value;
5817 var el_mbox = document.getElementById("mbox");
5818 var mbox = (el_mbox == null) ? '' : el_mbox.value;
5820 if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5821 alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5825 if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5828 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5829 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5830 parent_id = parentIdValue;
5831 parent_type = parentTypeValue;
5833 var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5834 // baseline viability check
5836 if(to == "" && cc == '' && bcc == '' && !isDraft) {
5837 alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5839 } else if(subj == '' && !isDraft) {
5840 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5843 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5845 } else if(html == '' && !isDraft) {
5846 if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5851 SE.util.clearHiddenFieldValues('emailCompose' + idx);
5852 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5853 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5854 overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5855 html = html.replace(/</ig, "sugarLessThan");
5856 html = html.replace(/>/ig, "sugarGreaterThan");
5858 form.sendDescription.value = html;
5859 form.sendSubject.value = subj;
5860 form.sendTo.value = to;
5861 form.sendCc.value = cc;
5862 form.sendBcc.value = bcc;
5863 form.email_id.value = email_id;
5864 form.composeType.value = composeType;
5865 form.composeLayoutId.value = 'composeLayout' + idx;
5866 form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5867 form.saveToSugar.value = 1;
5868 form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5869 form.parent_type.value = parent_type;
5870 form.parent_id.value = parent_id;
5871 form.uid.value = uid;
5872 form.ieId.value = ieId;
5873 form.mbox.value = mbox;
5875 // email attachments
5876 var addedFiles = document.getElementById('addedFiles' + idx);
5878 for(i=0; i<addedFiles.childNodes.length; i++) {
5879 var bucket = addedFiles.childNodes[i];
5881 for(j=0; j<bucket.childNodes.length; j++) {
5882 var node = bucket.childNodes[j];
5883 var nName = new String(node.name);
5885 if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5886 if(form.attachments.value != '') {
5887 form.attachments.value += "::";
5889 form.attachments.value += node.value;
5896 var addedDocs = document.getElementById('addedDocuments' + idx);
5898 for(i=0; i<addedDocs.childNodes.length; i++) {
5899 var cNode = addedDocs.childNodes[i];
5900 for(j=0; j<cNode.childNodes.length; j++) {
5901 var node = cNode.childNodes[j];
5902 var nName = new String(node.name);
5903 if(node.type == 'hidden' && nName.match(/documentId/)) {
5904 if(form.documents.value != '') {
5905 form.documents.value += "::";
5907 form.documents.value += node.value;
5913 // template attachments
5914 var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5915 if(addedTemplateAttachments) {
5916 for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5917 var cNode = addedTemplateAttachments.childNodes[i];
5918 for(j=0; j<cNode.childNodes.length; j++) {
5919 var node = cNode.childNodes[j];
5920 var nName = new String(node.name);
5921 if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5922 if(form.templateAttachments.value != "") {
5923 form.templateAttachments.value += "::";
5925 form.templateAttachments.value += node.value;
5931 // remove attachments
5932 form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5934 YAHOO.util.Connect.setForm(form);
5936 AjaxObject.target = 'frameFlex';
5938 // sending a draft email
5939 if(!isDraft && in_draft) {
5941 SE.listView.removeRowByUid(email_id);
5944 var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5945 var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5947 AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5951 * Handles clicking the email address link from a given view
5953 composePackage : function() {
5954 if(composePackage != null) {
5955 SE.composeLayout.c0_composeNewEmail();
5958 if(composePackage.to_email_addrs) {
5959 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5961 if (composePackage.subject != null && composePackage.subject.length > 0) {
5962 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5965 //If no parent fields are set in the composePackage, ensure they are cleared.
5966 var parentFields = ['parent_type','parent_name','parent_id'];
5967 for(var i=0;i<parentFields.length;i++)
5969 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5970 composePackage[parentFields[i]] = "";
5973 document.getElementById("parent_type").value = composePackage.parent_type;
5974 document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5975 document.getElementById("parent_id").value = composePackage.parent_id;
5976 document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5977 document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5979 if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5980 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5982 if (composePackage.body != null && composePackage.body.length > 0) {
5983 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5984 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5985 setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5987 if (composePackage.attachments != null) {
5988 SE.composeLayout.loadAttachments(composePackage.attachments);
5991 if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5992 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5993 SE.util.emptySelectOptions(addressFrom);
5994 var fromAccountOpts = composePackage.fromAccounts.data;
5995 for(i=0; i<fromAccountOpts.length; i++) {
5996 var key = fromAccountOpts[i].value;
5997 var display = fromAccountOpts[i].text;
5998 var opt = new Option(display, key);
5999 if (fromAccountOpts[i].selected) {
6000 opt.selected = true;
6002 addressFrom.options.add(opt);
6009 setContentOnThisTiny : function() {
6010 var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6011 var tinyHTML = tiny.getContent();
6012 composePackage.body = decodeURI(encodeURI(composePackage.body));
6013 // cn: bug 14361 - text-only templates don't fill compose screen
6014 if(composePackage.body == '') {
6015 composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
6017 //Flag determines if we should clear the tiny contents or just append
6018 if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
6019 SE.composeLayout.tinyHTML = '';
6021 SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
6023 tiny.setContent(SE.composeLayout.tinyHTML);
6024 //Indicate that the contents has been loaded successfully.
6025 SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
6028 * Confirms closure of a compose screen if "x" is clicked
6030 confirmClose : function(panel) {
6031 if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6032 SE.composeLayout.closeCompose(panel.id);
6040 * forces close of a compose screen
6042 forceCloseCompose : function(id) {
6043 SE.composeLayout.closeCompose(id);
6045 // handle flow back to originating view
6046 if(composePackage) {
6047 // check if it's a module we need to return to
6048 if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6049 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6050 var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6051 window.location = url;
6058 * closes the editor that just sent email
6059 * @param string id ID of composeLayout tab
6061 closeCompose : function(id) {
6062 // destroy tinyMCE instance
6063 var idx = id.substr(13, id.length);
6064 var instanceId = "htmleditor" + idx;
6065 tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6067 // nullify DOM and namespace values.
6069 SE.composeLayout[idx] = null;
6070 SE.tinyInstances[instanceId] = null;
6071 var tabsArray = SE.innerLayout.get("tabs");
6072 for (i = 0 ; i < tabsArray.length ; i++) {
6073 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6074 tabsArray[i].close();
6078 //SE.innerLayout.getTab(idx).close();
6082 * Enable the quick search for the compose relate field or search tab
6084 enableQuickSearchRelate: function(idx,overides){
6086 if(typeof overides != 'undefined')
6088 var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6089 var newModule = document.getElementById(newModuleID).value;
6090 var formName = overides['formName'];
6091 var fieldName = overides['fieldName'];
6092 var fieldId = overides['fieldId'];
6093 var fullName = formName + "_" + fieldName;
6094 var postBlurFunction = null;
6098 var newModule = document.getElementById('data_parent_type'+idx).value;
6099 var formName = 'emailCompose'+idx;
6100 var fieldName = 'data_parent_name'+idx;
6101 var fieldId = 'data_parent_id'+idx;
6102 var fullName = formName + "_" + fieldName;
6103 var postBlurFunction = "SE.composeLayout.qsAddAddress";
6106 if(typeof sqs_objects == 'undefined')
6107 window['sqs_objects'] = new Array;
6109 window['sqs_objects'][fullName] = {
6112 modules:[newModule],
6114 field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6115 conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6116 post_onblur_function: postBlurFunction,
6117 order:"name","limit":"30","no_match_text":"No Match"};
6120 if(typeof QSProcessedFieldsArray != 'undefined')
6121 QSProcessedFieldsArray[fullName] = false;
6122 if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6123 QSFieldsArray[fullName].destroy();
6124 delete QSFieldsArray[fullName];
6126 if (Dom.get(fullName + "_results")) {
6127 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6133 qsAddAddress : function(o) {
6134 if (o.name != "" && o.email1 != "")
6136 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6137 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6141 * Returns a new instance ID, 0-index
6143 getNewInstanceId : function() {
6144 this.currentInstanceId = this.currentInstanceId + 1;
6145 return this.currentInstanceId;
6149 * 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.
6151 loadAttachments : function(result) {
6152 var idx = SE.composeLayout.currentInstanceId;
6154 if(typeof(result) == 'object') {
6155 //jchi #20680. Clean the former template attachments;
6156 var basket = document.getElementById('addedTemplateAttachments' + idx);
6157 if(basket.innerHTML != ''){
6158 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6160 basket.innerHTML = '';
6165 if(typeof result[i] == 'object') {
6166 var index = SE.composeLayout.addTemplateAttachmentField(idx);
6167 var bean = result[i];
6168 document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6169 document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6176 * fills drop-down values for email templates and signatures
6178 setComposeOptions : function(idx) {
6179 // send from accounts
6180 var addressFrom = document.getElementById('addressFrom' + idx);
6182 if (addressFrom.options.length <= 0) {
6183 SE.util.emptySelectOptions(addressFrom);
6184 var fromAccountOpts = SE.composeLayout.fromAccounts;
6185 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6186 var key = fromAccountOpts[id].value;
6187 var display = fromAccountOpts[id].text;
6188 var is_default = false;
6189 if(key == SUGAR.default_inbound_accnt_id)
6191 var opt = new Option(display, key);
6192 addressFrom.options.add(opt);
6193 addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6198 var et = document.getElementById('email_template' + idx);
6199 SE.util.emptySelectOptions(et);
6201 for(var key in this.emailTemplates) { // iterate through assoc array
6202 var display = this.emailTemplates[key];
6203 var opt = new Option(display, key);
6204 et.options.add(opt);
6208 var sigs = document.getElementById('signatures' + idx);
6209 SE.util.emptySelectOptions(sigs);
6211 for(var key in this.signatures) { // iterate through assoc array
6212 var display = this.signatures[key];
6213 var opt = new Option(display, key);
6215 if(key == SE.userPrefs.signatures.signature_default) {
6216 opt.selected = true;
6219 sigs.options.add(opt);
6222 // html/plain email?
6223 var htmlEmail = document.getElementById('setEditor' + idx);
6224 if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6225 htmlEmail.checked = true;
6227 htmlEmail.checked = false;
6230 SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6234 * After compose screen is rendered, async call to get email body from Sugar
6236 replyForwardEmailStage2 : function() {
6237 SE.util.clearHiddenFieldValues('emailUIForm');
6238 overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6240 var ieId = SE.composeLayout.replyForwardObj.ieId;
6241 var uid = SE.composeLayout.replyForwardObj.uid;
6242 var mbox = SE.composeLayout.replyForwardObj.mbox;
6243 var type = SE.composeLayout.replyForwardObj.type;
6244 var idx = SE.composeLayout.currentInstanceId;
6246 var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6248 document.getElementById('emailSubject' + idx).value = type;
6249 document.getElementById('emailUIAction').value = 'composeEmail';
6250 document.getElementById('composeType').value = type;
6251 document.getElementById('ieId').value = ieId;
6252 document.getElementById('uid').value = uid;
6253 document.getElementById('mbox').value = mbox;
6254 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6255 var formObject = document.getElementById('emailUIForm');
6256 YAHOO.util.Connect.setForm(formObject);
6258 var sendType = type;
6259 AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6263 * Show the hidden cc or bcc fields
6265 showHiddenAddress: function(addrType,idx){
6267 Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6268 Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6269 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6270 this[addrType+'Hidden'+idx] = false;
6272 //After bcc or cc is added, move options below last addr field
6273 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6275 //If both cc and bcc hidden, remove the empty row containing text.
6276 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6277 && ( this['ccHidden'+idx] == false && this['bccHidden'+idx] == false) )
6278 Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6280 // SE.composeLayout.resizeEditor(idx);
6283 * Hide the cc and bcc fields if they were shown.
6285 hideHiddenAddresses: function(idx){
6287 var addrTypes = ['cc','bcc'];
6288 for(var i = 0;i<addrTypes.length;i++)
6290 Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6291 Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6292 this[addrTypes[i] + 'Hidden'+idx] = true
6295 Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6296 Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6297 Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6301 //// END SE.composeLayout
6302 ///////////////////////////////////////////////////////////////////////////////
6303 ///////////////////////////////////////////////////////////////////////////////
6307 * Cleans serialized UID lists of duplicates
6311 cleanUids : function(str) {
6312 var seen = new Object();
6314 var arr = new String(str).split(",");
6316 for(var i=0; i<arr.length; i++) {
6321 clean += (clean != "") ? "," : "";
6323 seen[arr[i]] = true;
6330 * Clears hidden field values
6331 * @param string id ID of form element to clear
6333 clearHiddenFieldValues : function(id) {
6334 var form = document.getElementById(id);
6336 for(i=0; i<form.elements.length; i++) {
6337 if(form.elements[i].type == 'hidden') {
6338 var e = form.elements[i];
6339 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6347 * Reduces a SELECT drop-down to 0 items to prepare for new ones
6349 emptySelectOptions : function(el) {
6351 for(i=el.childNodes.length - 1; i >= 0; i--) {
6352 if(el.childNodes[i]) {
6353 el.removeChild(el.childNodes[i]);
6360 * Returns the MBOX path in the manner php_imap expects:
6361 * ie: INBOX.DEBUG.test
6362 * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6364 generateMboxPath : function(str) {
6365 var ex = str.split("::");
6367 /* we have a serialized MBOX path */
6371 for(var i=0; i<ex.length; i++) {
6372 if(ex[i] == 'INBOX') {
6384 /* we have a Sugar folder GUID - do nothing */
6392 * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6393 * @param HTMLElement el
6394 * @return string GUID of found element or empty on failure
6396 getGuidFromElement : function(el) {
6402 for(var i=0; i<iterations; i++) {
6404 if(el.id.match(SE.reGUID)) {
6416 * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6419 getPanelId : function() {
6420 return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6424 * wrapper to handle weirdness with IE
6425 * @param string instanceId
6426 * @return tinyMCE Controller object
6428 getTiny : function(instanceId) {
6429 if(instanceId == '') {
6433 var t = tinyMCE.getInstanceById(instanceId);
6437 YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6443 * Simple check for MSIE browser
6447 var nav = new String(navigator.appVersion);
6448 if(nav.match(/MSIE/)) {
6455 * Recursively removes an element from the DOM
6456 * @param HTMLElement
6458 removeElementRecursive : function(el) {
6459 this.emptySelectOptions(el);
6466 sleep : function(secs) {
6467 setTimeout("void(0);", secs);
6471 * Converts a <select> element to an Ext.form.combobox
6473 convertSelect : function(select) {
6474 alert('in convertSelect');
6475 if (typeof(select) == "string") {
6476 select = document.getElementById(select);
6480 findChildNode : function (parent, property, value) {
6481 for (i in parent.children) {
6482 var child = parent.children[i];
6483 if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6485 var searchChild = SE.util.findChildNode(child, property, value);
6492 cascadeNodes : function (parent, fn, scope, args) {
6493 for (i in parent.children) {
6494 var child = parent.children[i];
6495 var s = scope ? scope : child;
6496 var a = args ? args : child;
6498 SE.util.cascadeNodes(child, fn, scope, args);
6505 ///////////////////////////////////////////////////////////////////////////////
6508 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6510 /*********************************************************************************
6511 * SugarCRM Community Edition is a customer relationship management program developed by
6512 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6514 * This program is free software; you can redistribute it and/or modify it under
6515 * the terms of the GNU Affero General Public License version 3 as published by the
6516 * Free Software Foundation with the addition of the following permission added
6517 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6518 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6519 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6521 * This program is distributed in the hope that it will be useful, but WITHOUT
6522 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6523 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
6526 * You should have received a copy of the GNU Affero General Public License along with
6527 * this program; if not, see http://www.gnu.org/licenses or write to the Free
6528 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6531 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6532 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6534 * The interactive user interfaces in modified source and object code versions
6535 * of this program must display Appropriate Legal Notices, as required under
6536 * Section 5 of the GNU Affero General Public License version 3.
6538 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6539 * these Appropriate Legal Notices must retain the display of the "Powered by
6540 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6541 * technical reasons, the Appropriate Legal Notices must display the words
6542 * "Powered by SugarCRM".
6543 ********************************************************************************/
6546 if (typeof console == "undefined")
6547 console = { log: function(o) {alert(o)} };
6551 currentRequestObject : null,
6552 //timeout : 30000, // 30 second timeout default
6553 timeout : 9999999999, // 30 second timeout default
6555 trail : new Array(),
6559 _reset : function() {
6560 this.timeout = 30000;
6561 this.forceAbort = false;
6564 folderRenameCleanup : function() {
6565 SUGAR.email2.folders.setSugarFolders();
6568 fullSyncCleanup : function(o) {
6569 this.folders.checkMailCleanup(o);
6570 SUGAR.email2.settings.settingsDialog.hide();
6575 composeCache : function(o) {
6576 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6577 // get email templates and user signatures
6578 var ret = YAHOO.lang.JSON.parse(o.responseText);
6580 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6581 SUGAR.email2.composeLayout.signatures = ret.signatures;
6582 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6584 SUGAR.email2.composeLayout.setComposeOptions(idx);
6586 //Set the error array so we can notify the user when they try to hit send if any errors
6587 //are present. We will also notify them now (after hitting compose button).
6588 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6591 //if error element is returning an array, then check the length to make sure we have error messages
6592 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6593 //add error messages for display
6594 for(i in ret.errorArray)
6595 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6596 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6597 //if error element is returning an object, and the object value is not empty or null, then display error message
6598 for(i in ret.errorArray)
6599 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6602 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6604 var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6606 overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6612 handleDeleteSignature : function(o) {
6614 var ret = YAHOO.lang.JSON.parse(o.responseText);
6615 SUGAR.email2.composeLayout.signatures = ret.signatures;
6616 var field = document.getElementById('signature_id');
6617 SUGAR.email2.util.emptySelectOptions(field);
6619 for(var i in ret.signatures) { // iterate through assoc array
6620 var opt = new Option(ret.signatures[i], i);
6621 field.options.add(opt);
6623 setSigEditButtonVisibility();
6628 handleDeleteReturn : function(o) {
6629 // force refresh ListView
6631 if(document.getElementById('focusEmailMbox')) {
6632 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6635 // need to display success message before calling next async call?
6636 document.getElementById(this.target).innerHTML = o.responseText;
6641 handleFailure : function(o) {
6643 overlay('Exception occurred...', o.statusText, 'alert');
6644 if(document.getElementById('saveButton')) {
6645 document.getElementById('saveButton').disabled = false;
6649 handleReplyForward : function(o) {
6650 var a = YAHOO.lang.JSON.parse(o.responseText);
6652 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6654 document.getElementById('email_id' + idx).value = a.uid;
6655 document.getElementById('emailSubject' + idx).value = a.name;
6656 document.getElementById('addressTO' + idx).value = a.from;
6657 document.getElementById('uid' + idx).value = a.uid;
6659 document.getElementById('addressCC' + idx).value = a.cc;
6660 SE.composeLayout.showHiddenAddress('cc', idx);
6664 document.getElementById('type' + idx).value = a.type;
6667 // apply attachment values
6668 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6670 setTimeout("callbackReplyForward.finish(globalA);", 500);
6673 handleReplyForwardForDraft : function(o) {
6674 var a = YAHOO.lang.JSON.parse(o.responseText);
6676 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6678 document.getElementById('email_id' + idx).value = a.uid;
6679 document.getElementById('emailSubject' + idx).value = a.name;
6680 document.getElementById('addressTO' + idx).value = a.to;
6683 document.getElementById('addressCC' + idx).value = a.cc;
6684 SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6688 document.getElementById('addressBCC' + idx).value = a.bcc;
6689 SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6694 document.getElementById('type' + idx).value = a.type;
6698 // apply attachment values
6699 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6701 setTimeout("callbackReplyForward.finish(globalA);", 500);
6706 handleSuccess : function(o) {
6707 document.getElementById(this.target).innerHTML = o.responseText;
6713 ieDeleteSuccess : function(o) {
6716 SUGAR.email2.accounts.refreshInboundAccountTable();
6717 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6718 SUGAR.email2.accounts.rebuildFolderList();
6723 ieSaveSuccess : function(o) {
6724 document.getElementById('saveButton').disabled = false;
6725 var a = YAHOO.lang.JSON.parse(o.responseText);
6728 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6729 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6731 resp = YAHOO.lang.JSON.parse(o.responseText);
6732 SUGAR.email2.accounts.refreshInboundAccountTable();
6733 SUGAR.email2.accounts.refreshOuboundAccountTable();
6734 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6735 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6739 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6746 loadAttachments : function(o) {
6747 var result = YAHOO.lang.JSON.parse(o.responseText);
6749 SUGAR.email2.composeLayout.loadAttachments(result);
6754 loadSignature : function(o) {
6755 var ret = YAHOO.lang.JSON.parse(o.responseText);
6756 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6757 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6761 * Follow up to mark email read|unread|flagged
6763 markEmailCleanup : function(o) {
6764 var ret = YAHOO.lang.JSON.parse(o.responseText);
6765 if (!ret['status']) {
6767 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6769 SUGAR.email2.contextMenus.markEmailCleanup();
6775 rebuildShowFolders : function(o) {
6776 var t = YAHOO.lang.JSON.parse(o.responseText);
6777 var show = document.getElementById('ieAccountListShow');
6779 SUGAR.email2.util.emptySelectOptions(show);
6781 for(i=0; i<t.length; i++) { // iterate through assoc array
6782 var opt = new Option(t[i].text, t[i].value, t[i].selected);
6783 opt.selected = t[i].selected;
6784 show.options.add(opt);
6787 SUGAR.email2.accounts.renderTree();
6791 saveListViewSortOrderPart2 : function() {
6792 // create the JSON string the func expects
6793 focusFolderPath = '[ "Home", "' + ieName + '"';
6795 var f = new String(focusFolder);
6796 var fEx = f.split('.');
6798 for(i=0; i<fEx.length; i++) {
6799 focusFolderPath += ', "' + fEx[i] +'"'
6802 focusFolderPath += ']';
6804 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6805 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6811 sendEmailCleanUp : function(o) {
6816 ret = YAHOO.lang.JSON.parse(o.responseText);
6817 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6818 //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6820 if (o.responseText) {
6821 overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6823 // Else we have an error here.
6826 if (typeof(SE.grid) != 'undefined')
6827 SE.listView.refreshGrid();
6828 //Disabled while address book is disabled
6830 //If this call back was initiated by quick compose from a Detail View page, refresh the
6831 //history subpanel. If it was initiated by quickcreate from shortcut bar, then
6832 //close the shortcut bar menu
6833 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6834 if(action_sugar_grp1 == 'DetailView') {
6835 showSubPanel('history',null,true);
6836 } else if(action_sugar_grp1 == 'quickcreate') {
6837 closeEmailOverlay();
6843 ieSendSuccess : function(o) {
6845 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6850 settingsFolderRefresh : function(o) {
6851 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6852 var ret = YAHOO.lang.JSON.parse(o.responseText);
6853 var user = document.getElementById('userFolders');
6855 SUGAR.email2.util.emptySelectOptions(user);
6857 for(i=0; i<ret.userFolders.length; i++) {
6858 var display = ret.userFolders[i].name;
6859 var value = ret.userFolders[i].id;
6860 var selected = (ret.userFolders[i].selected != "") ? true : false;
6861 var opt = new Option(display, value, selected);
6862 opt.selected = selected;
6863 user.options.add(opt);
6869 startRequest : function(callback, args, forceAbort) {
6870 if(this.currentRequestObject != null) {
6871 if(this.forceAbort == true) {
6872 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6875 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6879 requestInProgress : function() {
6880 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6885 updateFolderSubscriptions : function() {
6886 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6887 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6893 updateFrameFolder : function() {
6894 SUGAR.email2.folders.checkEmailAccounts();
6899 updateUserPrefs : function(o) {
6900 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
6901 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6906 uploadAttachmentSuccessful : function(o) {
6908 document.getElementById('email_attachment').value = '';
6910 var ret = YAHOO.lang.JSON.parse(o.responseText);
6911 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6912 var overall = document.getElementById('addedFiles' + idx);
6913 var index = overall.childNodes.length;
6915 "<div id='email_attachment_bucket" + idx + index + "'>" +
6917 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6918 "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6919 idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6921 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6922 "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6924 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6926 ((ret.nameForDisplay != null) ? ret.nameForDisplay + " " : ret.name + " ") +
6929 overall.innerHTML += out;
6930 if(SUGAR.email2.util.isIe()) {
6931 document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6935 SUGAR.email2.addFileDialog.hide();
6936 // focus attachments
6937 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6942 ///////////////////////////////////////////////////////////////////////////
6943 //// PER MODULE CALLBACK OBJECTS
6944 AjaxObject.accounts = {
6945 saveOutboundCleanup : function(o) {
6946 SUGAR.email2.accounts.refreshOuboundAccountTable();
6947 SUGAR.email2.accounts.outboundDialog.hide();
6948 var id = o.responseText;
6949 SUGAR.email2.accounts.newAddedOutboundId = id;
6951 saveDefaultOutboundCleanup: function(o){
6954 callbackEditOutbound : {
6955 success : function(o)
6957 var ret = YAHOO.lang.JSON.parse(o.responseText);
6959 SUGAR.email2.accounts.showAddSmtp();
6962 document.getElementById("mail_id").value = ret.id;
6963 document.getElementById("type").value = ret.type;
6964 document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6965 document.getElementById("mail_name").value = ret.name;
6966 document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6967 document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6968 document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6969 document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6970 document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6971 SUGAR.email2.accounts.smtp_authenticate_field_display();
6972 document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6974 if(ret.type == 'system-override') {
6975 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6976 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6979 SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6980 SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6982 SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6985 failure : AjaxObject.handleFailure,
6986 timeout : AjaxObject.timeout,
6989 callbackDeleteOutbound : {
6990 success : function(o) {
6991 var ret = YAHOO.lang.JSON.parse(o.responseText);
6994 if(confirm(ret.error_message))
6996 overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6997 AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
7005 SUGAR.email2.accounts.refreshOuboundAccountTable();
7009 failure : AjaxObject.handleFailure,
7010 timeout : AjaxObject.timeout,
7014 callbackCheckMailProgress : {
7015 success : function(o) {
7016 if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
7017 SUGAR.email2.accounts.totalMsgCount = -1;
7020 //Check for server timeout / errors
7021 var ret = YAHOO.lang.JSON.parse(o.responseText);
7024 if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
7026 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7027 SUGAR.email2.accounts.totalMsgCount = -1;
7028 //SUGAR.email2.folders.rebuildFolders();
7032 var currIeId = ret['ieid'];
7035 var serverCount = ret.count;
7037 if (ret['status'] == 'done') {
7038 for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7039 if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7043 } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7044 //Go to next account
7045 currIeId = SUGAR.email2.accounts.ieIds[i+1];
7047 SUGAR.email2.accounts.totalMsgCount = -1;
7052 else if (ret.mbox && ret.totalcount && ret.count) {
7053 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7054 if (ret.count >= ret.totalcount) {
7057 } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7058 SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7061 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7062 SUGAR.email2.accounts.totalMsgCount = -1;
7067 SUGAR.email2.accounts.totalMsgCount = -1;
7069 SUGAR.email2.folders.rebuildFolders();
7070 SE.listView.refreshGrid();
7071 } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7072 YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7073 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7074 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=0&synch=" + ret.synch);
7076 YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7077 app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7078 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7079 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "¤tCount=" + serverCount +
7080 '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7083 failure : AjaxObject.handleFailure,
7084 timeout : AjaxObject.timeout,
7089 ///////////////////////////////////////////////////////////////////////////////
7091 AjaxObject.composeLayout = {
7093 * Populates the record id
7095 saveDraftCleanup : function(o) {
7100 ret = YAHOO.lang.JSON.parse(o.responseText);
7101 SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7103 if (o.responseText) {
7104 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7110 AjaxObject.composeLayout.callback = {
7112 success : AjaxObject.composeLayout.saveDraftCleanup,
7113 failure : AjaxObject.handleFailure,
7114 timeout : AjaxObject.timeout,
7119 AjaxObject.detailView = {
7121 * Pops-up a printable view of an email
7123 displayPrintable : function(o) {
7124 var ret = YAHOO.lang.JSON.parse(o.responseText);
7125 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7126 // 2 below must be in global context
7128 meta['panelId'] = SUGAR.email2.util.getPanelId();
7129 email = ret.meta.email;
7130 if (typeof(email.cc) == 'undefined') {
7134 var out = displayTemplate.exec({
7135 'app_strings' : app_strings,
7139 'email' : meta.email
7142 // open popup window
7143 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7144 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7146 popup.document.write(out);
7147 popup.document.close();
7151 * Takes formatted response and creates a modal pop-over containing a title and content
7153 displayView : function(o) {
7154 var SED = SUGAR.email2.detailView;
7155 var ret = YAHOO.lang.JSON.parse(o.responseText);
7157 if(!SED.viewDialog) {
7158 SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7162 constraintoviewport: true,
7165 SED.viewDialog.renderEvent.subscribe(function() {
7166 var content = this.body.firstChild;
7167 var viewH = YAHOO.util.Dom.getViewportHeight();
7169 this.body.style.overflow = "auto";
7170 this.body.style.width = "800px";
7171 this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7175 SED.viewDialog.setHeader(ret.title);
7176 SED.viewDialog.setBody(ret.html);
7177 SED.viewDialog.render();
7178 SED.viewDialog.show();
7182 * Generates a modal popup to populate with the contents of bean's full EditView
7184 showQuickCreateForm : function(o) {
7185 var SED = SUGAR.email2.detailView;
7186 var ret = YAHOO.lang.JSON.parse(o.responseText);
7188 if(!SED.quickCreateDialog) {
7189 SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7193 constraintoviewport: true,
7197 SED.quickCreateDialog.renderEvent.subscribe(function() {
7198 var viewH = YAHOO.util.Dom.getViewportHeight();
7200 for (var i in this.body.childNodes) {
7201 if (this.body.childNodes[i].clientHeight) {
7202 contH += this.body.childNodes[i].clientHeight;
7203 } else if (this.body.childNodes[i].offsetHeight) {
7204 contH += this.body.childNodes[i].offsetHeight;
7207 this.body.style.width = "800px";
7208 this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7209 this.body.style.overflow = "auto";
7210 }, SED.quickCreateDialog);
7212 SED.quickCreateDialog.hideEvent.subscribe(function(){
7213 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7214 /*for(var qsField in qsFields){
7215 if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7216 Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7219 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7222 ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7224 SED.quickCreateDialog.setBody(ret.html ? ret.html : " ");
7225 SED.quickCreateDialog.render();
7226 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7228 SED.quickCreateDialog.ieId = ret.ieId;
7229 SED.quickCreateDialog.uid = ret.uid;
7230 SED.quickCreateDialog.mbox = ret.mbox;
7231 SED.quickCreateDialog.qcmodule = ret.module;
7233 SED.quickCreateDialog.show();
7235 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7237 editForm.module.value = 'Emails';
7238 var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7239 var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7240 var instId = ret.module + count;
7241 SED.quickCreateEmailsToAdd = ret.emailAddress;
7242 SED.quickCreateEmailCallback = function(instId, tableId) {
7243 var eaw = SUGAR.EmailAddressWidget.instances[instId];
7244 if (typeof(eaw) == "undefined")
7245 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7246 + instId + "','" + tableId + "');", 100);
7247 eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7249 window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7250 + instId + "','" + tableId + "');", 100);
7254 saveQuickCreateForm : function(o) {
7256 SUGAR.email2.detailView.quickCreateDialog.hide();
7257 validate['EditView'] = [ ];
7260 saveQuickCreateFormAndReply : function(o) {
7262 var ret = YAHOO.lang.JSON.parse(o.responseText);
7263 SUGAR.email2.detailView.quickCreateDialog.hide();
7264 var qcd = SUGAR.email2.detailView.quickCreateDialog;
7265 var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7267 var emailID = ret.id;
7268 SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7270 SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7272 //Cean the validate cache to prevent errors on the next call
7273 validate['EditView'] = [ ];
7276 saveQuickCreateFormAndAddToAddressBook : function(o) {
7278 SUGAR.email2.detailView.quickCreateDialog.hide();
7279 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7280 validate['EditView'] = [ ];
7283 handleAssignmentDialogAssignAction : function() {
7286 var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7288 var dist = 'direct';
7292 var found_teams = false;
7293 var warning_message = mod_strings.LBL_WARN_NO_USERS;
7294 if(!found_teams && assign_user_id == '' )
7296 alert(warning_message);
7300 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7302 for(i=0; i<emailUids.length; i++) {
7304 uids += app_strings.LBL_EMAIL_DELIMITER;
7306 uids += emailUids[i];
7309 var row = SUGAR.email2.grid.getSelectedRows()[0];
7310 var data = SUGAR.email2.grid.getRecord(row).getData();
7311 var ieid = data.ieId;
7312 var mbox = data.mbox;
7313 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7314 SUGAR.email2.contextMenus.assignToDialogue.hide();
7315 overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7319 handleAssignmentDialogDeleteAction : function() {
7320 // TO pass list of UIDS/emailIds
7321 var uids = SUGAR.email2.listView.getUidsFromSelection();
7322 var row = SUGAR.email2.grid.getSelections()[0];
7323 var ieid = row.data.ieId;
7324 var mbox = row.data.mbox;
7325 AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7326 SUGAR.email2.contextMenus.assignmentDialog.hide();
7327 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7333 showEmailDetailView : function(o) {
7335 var SED = SUGAR.email2.detailView;
7336 var ret = YAHOO.lang.JSON.parse(o.responseText);
7338 if(!SED.quickCreateDialog) {
7339 SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7343 constraintoviewport: true,
7345 autofillheight: "body",
7348 SED.quickCreateDialog.renderEvent.subscribe(function() {
7349 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7351 for (var i in this.body.childNodes) {
7352 if (this.body.childNodes[i].offsetHeight)
7353 contH += this.body.childNodes[i].offsetHeight;
7355 this.body.style.overflow = "auto";
7356 this.body.style.width = "800px";
7357 this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7359 }, SED.quickCreateDialog);
7361 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7362 SED.quickCreateDialog.setBody(ret.html);
7363 SED.quickCreateDialog.render();
7364 SUGAR.util.evalScript(ret.html);
7365 SED.quickCreateDialog.show();
7368 showAssignmentDialogWithData : function(o) {
7369 var SEC = SUGAR.email2.contextMenus;
7371 var ret = YAHOO.lang.JSON.parse(o.responseText);
7372 if (!SEC.assignmentDialog) {
7373 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7376 constraintoviewport: true,
7379 SEC.assignmentDialog.setBody("");
7380 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7381 SEC.assignmentDialog.renderEvent.subscribe(function() {
7382 var iev = YAHOO.util.Dom.get("Distribute");
7384 this.body.style.width = "700px";
7386 }, SEC.assignmentDialog);
7387 SEC.assignmentDialog.render();
7389 SEC.assignmentDialog.setBody(ret);
7390 SEC.assignmentDialog.render();
7392 SEC.assignmentDialog.show();
7393 SUGAR.util.evalScript(ret);
7396 showImportForm : function(o) {
7397 var SED = SUGAR.email2.detailView;
7398 var ret = YAHOO.lang.JSON.parse(o.responseText);
7400 document.getElementById('quickCreateContent').innerHTML = "";
7406 if(!SED.importDialog) {
7407 SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7411 constraintoviewport: true,
7413 text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7414 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7418 SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7419 SED.importDialog.setBody("");
7420 SED.importDialog.hideEvent.subscribe(function(){
7421 for(var i in QSFieldsArray) {
7422 if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7423 QSFieldsArray[i].destroy();
7424 delete QSFieldsArray[i];
7426 if (QSProcessedFieldsArray[i]) {
7427 QSProcessedFieldsArray[i] = false;
7431 SED.importDialog.renderEvent.subscribe(function() {
7432 var iev = YAHOO.util.Dom.get("ImportEditView");
7434 //this.body.style.height = (iev.clientHeight + 10) + "px";
7435 this.body.style.width = "600px";
7437 }, SED.importDialog);
7438 SED.importDialog.render();
7440 SED.importDialog.setBody(ret.html);
7441 SED.importDialog.ret = ret;
7442 SUGAR.util.evalScript(ret.html);
7443 SED.importDialog.render();
7445 SED.importDialog.show();
7446 SED.importDialog.focusFirstButton();
7448 getImportAction : function(ret) {
7449 if (!check_form('ImportEditView')) return false;
7450 if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7451 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7455 var editView = document.getElementById('ImportEditView');
7456 if (editView.assigned_user_id != null) {
7457 get = get + "&user_id=" + editView.assigned_user_id.value
7458 //var user_id = editView.assigned_user_id.value;
7460 var parent_id = editView.parent_id.value;
7461 var parent_type = editView.parent_type.value;
7462 var row = SUGAR.email2.grid.getSelectedRows()[0];
7463 row = SUGAR.email2.grid.getRecord(row);
7464 var data = row.getData();
7465 var ieId = data.ieId;
7466 var mbox = data.mbox;
7467 var serverDelete = editView.serverDelete.checked;
7468 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7470 for(i=0; i<emailUids.length; i++) {
7472 uids += app_strings.LBL_EMAIL_DELIMITER;
7474 uids += emailUids[i];
7477 var action = 'importEmail&uid=';
7479 action = 'moveEmails';
7480 action = action + '&sourceFolder=' + ret['srcFolder'];
7481 action = action + '&sourceIeId=' + ret['srcIeId'];
7482 action = action + '&destinationFolder=' + ret['dstFolder'];
7483 action = action + '&destinationIeId=' + ret['dstIeId'];
7484 action = action + '&emailUids=';
7486 if (action.search(/importEmail/) != -1) {
7487 overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7489 overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7492 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7493 get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7494 SUGAR.email2.detailView.importDialog.hide();
7495 document.getElementById('importDialogContent').innerHTML = "";
7498 showRelateForm : function(o) {
7499 var SED = SUGAR.email2.detailView;
7500 var ret = YAHOO.lang.JSON.parse(o.responseText);
7501 document.getElementById('quickCreateContent').innerHTML = "";
7506 dialog_loaded = true;
7508 if(!SED.relateDialog) {
7509 SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7514 constraintoviewport: true,
7516 text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7517 if (!check_form('RelateEditView')) return false;
7519 var editView = document.getElementById('RelateEditView');
7520 var parent_id = editView.parent_id.value;
7521 var parent_type = editView.parent_type.value;
7522 var row = SUGAR.email2.grid.getSelectedRows()[0];
7523 row = SUGAR.email2.grid.getRecord(row);
7524 var ieId = row.getData().ieId;
7525 var mbox = row.getData().mbox;
7526 var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7528 for(i=0; i<emailUids.length; i++) {
7530 uids += app_strings.LBL_EMAIL_DELIMITER;
7532 uids += emailUids[i];
7534 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7535 AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7536 + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7537 SED.relateDialog.hide();
7538 document.getElementById('relateDialogContent').innerHTML = "";
7543 SED.relateDialog.hideEvent.subscribe(function(){
7544 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7545 QSFieldsArray['ImportEditView_parent_name'].destroy();
7546 delete QSFieldsArray['ImportEditView_parent_name'];
7548 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7549 QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7553 SED.relateDialog.renderEvent.subscribe(function() {
7554 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7556 for (var i in this.body.childNodes) {
7557 if (this.body.childNodes[i].clientHeight)
7558 contH += this.body.childNodes[i].clientHeight;
7560 }, SED.relateDialog);
7561 SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7564 SED.relateDialog.setBody(ret.html);
7565 SED.relateDialog.render();
7566 SUGAR.util.evalScript(ret.html);
7567 SED.relateDialog.show();
7571 * DetailView callbacks
7573 AjaxObject.detailView.callback = {
7575 success : function(o) {
7577 var ret = YAHOO.lang.JSON.parse(o.responseText);
7578 SUGAR.email2.detailView.consumeMetaDetail(ret);
7580 argument: [targetDiv],
7581 failure : AjaxObject.handleFailure,
7586 success : function(o) {
7588 var ret = YAHOO.lang.JSON.parse(o.responseText);
7589 SUGAR.email2.detailView.consumeMetaPreview(ret);
7591 failure : AjaxObject.handleFailure,
7596 success : AjaxObject.detailView.displayPrintable,
7597 failure : AjaxObject.handleFailure,
7598 timeout : AjaxObject.timeout,
7602 success : AjaxObject.detailView.displayView,
7603 failure : AjaxObject.handleFailure,
7604 timeout : AjaxObject.timeout,
7613 AjaxObject.folders = {
7615 * check-mail post actions
7617 checkMailCleanup : function(o) {
7619 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7621 // refresh focus ListView
7622 SE.listView.refreshGrid();
7623 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7628 rebuildFolders : function(o) {
7631 var data = YAHOO.lang.JSON.parse(o.responseText);
7633 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7634 SUGAR.email2.folders.setSugarFolders();
7637 AjaxObject.folders.callback = {
7639 success : AjaxObject.folders.checkMailCleanup,
7640 failure : AjaxObject.handleFailure,
7641 timeout : 600000, // 5 mins
7646 AjaxObject.rules = {
7647 loadRulesForSettings : function(o) {
7648 document.getElementById("rulesListCell").innerHTML = o.responseText;
7649 // assume we have the class we need
7650 SUGAR.routing.getStrings();
7651 SUGAR.routing.getDependentDropdowns();
7654 //// END PER MODULE CALLBACK OBJECTS
7655 ///////////////////////////////////////////////////////////////////////////
7659 success : AjaxObject.handleSuccess,
7660 failure : AjaxObject.handleFailure,
7661 timeout : AjaxObject.timeout,
7664 var callbackAccount = {
7665 success : AjaxObject.ieSaveSuccess,
7666 failure : AjaxObject.handleFailure,
7667 timeout : AjaxObject.timeout,
7670 var callbackAccountDelete = {
7671 success : AjaxObject.ieDeleteSuccess,
7672 failure : AjaxObject.handleFailure,
7673 timeout : AjaxObject.timeout,
7676 var callbackOutboundTest = {
7677 success : AjaxObject.ieSendSuccess,
7678 failure : AjaxObject.handleFailure,
7679 timeout : AjaxObject.timeout,
7685 var callbackTeamInfoForSettings = {
7686 success : function (o) {
7687 var data = YAHOO.lang.JSON.parse(o.responseText);
7688 document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7690 failure : AjaxObject.handleFailure,
7691 timeout : AjaxObject.timeout,
7696 var callbackStatusForImport = {
7697 success : function (o) {
7699 if (o.responseText != "") {
7700 var statusString = "";
7701 var data = YAHOO.lang.JSON.parse(o.responseText);
7702 for(i=0; i<data.length; i++) {
7703 statusString = statusString + data[i] + '<br/>';
7705 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7707 SE.listView.refreshGrid();
7710 failure : AjaxObject.handleFailure,
7711 timeout : AjaxObject.timeout,
7715 var callbackComposeCache = {
7716 success : AjaxObject.composeCache,
7717 failure : AjaxObject.handleFailure,
7718 timeout : AjaxObject.timeout,
7721 var callbackDelete = {
7722 success : AjaxObject.handleDeleteReturn,
7723 failure : AjaxObject.handleFailure,
7724 timeout : AjaxObject.timeout,
7727 var callbackEmailDetailMultiple = {
7728 success : function(o) {
7730 var retMulti = YAHOO.lang.JSON.parse(o.responseText);
7731 var ret = new Object();
7733 for(var i=0; i<retMulti.length; i++) {
7736 SUGAR.email2._setDetailCache(ret);
7737 SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7740 failure : AjaxObject.handleFailure,
7744 var callbackListViewSortOrderChange = {
7745 success : AjaxObject.saveListViewSortOrderPart2,
7746 failure : AjaxObject.handleFailure,
7747 timeout : AjaxObject.timeout,
7749 argument : [ieId, ieName, focusFolder]
7751 var callbackEmptyTrash = {
7752 success : function(o) {
7754 AjaxObject.folderRenameCleanup;
7756 failure : AjaxObject.handleFailure,
7757 timeout : AjaxObject.timeout,
7760 var callbackClearCacheFiles = {
7761 success : function(o) {
7764 failure : AjaxObject.handleFailure,
7765 timeout : AjaxObject.timeout,
7768 var callbackFolderRename = {
7769 success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7770 failure : AjaxObject.handleFailure,
7771 timeout : AjaxObject.timeout,
7774 var callbackFolderDelete = {
7775 success : function(o) {
7776 var ret = YAHOO.lang.JSON.parse(o.responseText);
7778 if (ret.folder_id) {
7779 var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7781 SUGAR.email2.tree.removeNode(node, true);
7782 } else if (ret.ieId && ret.mbox) {
7783 var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7785 SUGAR.email2.tree.removeNode(node, true);
7788 //SUGAR.email2.folders.loadSettingFolder();
7791 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7794 failure : AjaxObject.handleFailure,
7795 timeout : AjaxObject.timeout,
7798 var callbackFolderSave = {
7799 success : function(o) {
7800 var ret = YAHOO.lang.JSON.parse(o.responseText);
7802 switch(ret.action) {
7803 case 'newFolderSave':
7804 SUGAR.email2.folders.rebuildFolders();
7808 failure : AjaxObject.handleFailure,
7809 timeout : AjaxObject.timeout,
7812 var callbackFolderSubscriptions = {
7813 success : AjaxObject.updateFolderSubscriptions,
7814 failure : AjaxObject.handleFailure,
7815 timeout : AjaxObject.timeout,
7818 var callbackFolderUpdate = {
7819 success : AjaxObject.updateFrameFolder,
7820 failure : AjaxObject.handleFailure,
7821 timeout : AjaxObject.timeout,
7824 var callbackFolders = {
7825 success : AjaxObject.folders.rebuildFolders,
7826 //success : void(true),
7827 failure : AjaxObject.handleFailure,
7828 timeout : AjaxObject.timeout,
7831 var callbackFullSync = {
7832 success : AjaxObject.fullSyncCleanup,
7833 failure : AjaxObject.handleFailure,
7834 timeout : 9999999999999,
7837 var callbackGeneric = {
7838 success : function() {
7841 failure : AjaxObject.handleFailure,
7842 timeout : AjaxObject.timeout,
7845 var callbackIeAccountRetrieve = {
7846 success : function(o) {
7847 // return JSON encoding
7849 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7850 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7852 failure : AjaxObject.handleFailure,
7853 timeout : AjaxObject.timeout,
7856 var callbackImportOneEmail = {
7857 success : AjaxObject.detailView.showImportForm,
7858 failure : AjaxObject.handleFailure,
7859 timeout : AjaxObject.timeout,
7862 var callbackRelateEmail = {
7863 success : AjaxObject.detailView.showRelateForm,
7864 failure : AjaxObject.handleFailure,
7865 timeout : AjaxObject.timeout,
7868 var callbackEmailDetailView = {
7869 success : AjaxObject.detailView.showEmailDetailView,
7870 failure : AjaxObject.handleFailure,
7871 timeout : AjaxObject.timeout,
7874 var callbackAssignmentDialog = {
7875 success : AjaxObject.detailView.showAssignmentDialogWithData,
7876 failure : AjaxObject.handleFailure,
7877 timeout : AjaxObject.timeout,
7880 var callbackAssignmentAction = {
7881 success : function(o) {
7882 SE.listView.refreshGrid();
7884 if(o.responseText != '') {
7885 overlay('Assignment action result', o.responseText, 'alert');
7888 failure : AjaxObject.handleFailure,
7889 timeout : AjaxObject.timeout,
7892 var callbackMoveEmails = {
7893 success : function(o) {
7894 SE.listView.refreshGrid();
7896 if(o.responseText != '') {
7897 overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7900 failure : AjaxObject.handleFailure,
7901 timeout : AjaxObject.timeout,
7904 var callbackLoadAttachments = {
7905 success : AjaxObject.loadAttachments,
7906 failure : AjaxObject.handleFailure,
7907 timeout : AjaxObject.timeout,
7910 var callbackLoadRules = {
7911 success : AjaxObject.rules.loadRulesForSettings,
7912 failure : AjaxObject.handleFailure,
7913 timeout : AjaxObject.timeout,
7916 var callbackLoadSignature = {
7917 success : AjaxObject.loadSignature,
7918 failure : AjaxObject.handleFailure,
7919 timeout : AjaxObject.timeout,
7922 var callbackDeleteSignature = {
7923 success : AjaxObject.handleDeleteSignature,
7924 failure : AjaxObject.handleFailure,
7925 timeout : AjaxObject.timeout,
7928 /*var callbackMoveEmails = {
7929 success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7930 failure : AjaxObject.handleFailure,
7931 timeout : AjaxObject.timeout,
7934 var callbackOutboundSave = {
7935 success : AjaxObject.accounts.saveOutboundCleanup,
7936 failure : AjaxObject.handleFailure,
7937 timeout : AjaxObject.timeout,
7940 var callbackDefaultOutboundSave = {
7941 success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7942 failure : AjaxObject.handleFailure,
7943 timeout : AjaxObject.timeout,
7946 var callbackQuickCreate = {
7947 success : AjaxObject.detailView.showQuickCreateForm,
7948 failure : AjaxObject.handleFailure,
7949 timeout : AjaxObject.timeout,
7952 var callbackQuickCreateSave = {
7953 success : AjaxObject.detailView.saveQuickCreateForm,
7954 failure : AjaxObject.handleFailure,
7955 timeout : AjaxObject.timeout,
7958 var callbackQuickCreateSaveAndAddToAddressBook = {
7959 success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7960 failure : AjaxObject.handleFailure,
7961 timeout : AjaxObject.timeout,
7964 var callbackQuickCreateSaveAndReply = {
7965 success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7966 failure : AjaxObject.handleFailure,
7967 timeout : AjaxObject.timeout,
7970 var callbackQuickCreateSaveAndReplyCase = {
7971 success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7972 failure : AjaxObject.handleFailure,
7973 timeout : AjaxObject.timeout,
7976 var callbackRebuildShowAccountList = {
7977 success : AjaxObject.rebuildShowFolders,
7978 failure : AjaxObject.handleFailure,
7979 timeout : AjaxObject.timeout,
7983 var callbackRefreshSugarFolders = {
7984 success : function(o) {
7985 var t = YAHOO.lang.JSON.parse(o.responseText);
7986 SUGAR.email2.folders.setSugarFoldersEnd(t);
7988 failure : AjaxObject.handleFailure,
7989 timeout : AjaxObject.timeout,
7992 var callbackReplyForward = {
7993 success : AjaxObject.handleReplyForward,
7994 finish : function(a, retryCount) {
7995 if (typeof(retryCount) == 'undefined') {
8000 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8001 var t = tinyMCE.getInstanceById('htmleditor' + idx);
8003 var html = t.getContent();
8005 html = " <div><hr></div>" + a.description;
8007 t.setContent(html);//
8009 if (a.type != 'draft') {
8010 // Next step, attach signature
8011 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
8015 if (retryCount < 5) {
8016 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
8020 var tabArray = SUGAR.email2.innerLayout.get("tabs");
8021 if (tabArray != null && tabArray.length > 0) {
8022 for (i = 0 ; i < tabArray.length ; i++) {
8023 var tabObject = tabArray[i];
8024 if (tabObject.get("id") == ("composeTab" + idx)) {
8025 var tabLabel = a.name;
8026 if (tabLabel != null && tabLabel.length > 25) {
8027 tabLabel = tabLabel.substring(0, 25) + "...";
8029 tabObject.get("labelEl").firstChild.data = tabLabel;
8035 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8036 if (a.parent_name != null && a.parent_name != "") {
8037 document.getElementById('data_parent_name' + idx).value = a.parent_name;
8039 if (a.parent_type != null && a.parent_type != "") {
8040 document.getElementById('data_parent_type' + idx).value = a.parent_type;
8042 if (a.parent_id != null && a.parent_id != "") {
8043 document.getElementById('data_parent_id' + idx).value = a.parent_id;
8045 if (a.fromAccounts.status) {
8046 var addressFrom = document.getElementById('addressFrom' + idx);
8047 SUGAR.email2.util.emptySelectOptions(addressFrom);
8048 var fromAccountOpts = a.fromAccounts.data;
8049 for(i=0; i<fromAccountOpts.length; i++) {
8050 var key = fromAccountOpts[i].value;
8051 var display = fromAccountOpts[i].text;
8052 var opt = new Option(display, key);
8053 if (fromAccountOpts[i].selected) {
8054 opt.selected = true;
8056 addressFrom.options.add(opt);
8062 failure : AjaxObject.handleFailure,
8063 timeout : AjaxObject.timeout,
8065 argument : [sendType]
8067 var callbackSendEmail = {
8068 success : AjaxObject.sendEmailCleanUp,
8069 failure : AjaxObject.handleFailure,
8070 timeout : AjaxObject.timeout,
8073 var callbackSettings = {
8074 success : AjaxObject.updateUserPrefs,
8075 failure : AjaxObject.handleFailure,
8076 timeout : AjaxObject.timeout,
8079 var callbackSettingsFolderRefresh = {
8080 success : AjaxObject.settingsFolderRefresh,
8081 failure : AjaxObject.handleFailure,
8082 timeout : AjaxObject.timeout,
8085 var callbackLoadSettingFolder = {
8086 success : function(o) {
8087 AjaxObject.settingsFolderRefresh(o);
8088 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8090 failure : AjaxObject.handleFailure,
8091 timeout : AjaxObject.timeout,
8095 var callbackUploadAttachment = {
8096 success : AjaxObject.uploadAttachmentSuccessful,
8097 upload : AjaxObject.uploadAttachmentSuccessful,
8098 failure : AjaxObject.handleFailure,
8099 timeout : AjaxObject.timeout,
8102 var callbackUserPrefs = {
8103 success : function(o) {
8104 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
8106 failure : AjaxObject.handleFailure,
8107 timeout : AjaxObject.timeout,
8111 var callbackContextmenus = {
8113 success : AjaxObject.markEmailCleanup,
8114 failure : AjaxObject.handleFailure,
8115 timeout : AjaxObject.timeout,
8120 var callbackCheckEmail2 = {
8121 success : function(o) {
8122 var ret = YAHOO.lang.JSON.parse(o.responseText);
8123 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8127 failure : AjaxObject.handleFailure,
8128 timeout : AjaxObject.timeout,
8130 }// End of File modules/Emails/javascript/ajax.js
8132 /*********************************************************************************
8133 * SugarCRM Community Edition is a customer relationship management program developed by
8134 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8136 * This program is free software; you can redistribute it and/or modify it under
8137 * the terms of the GNU Affero General Public License version 3 as published by the
8138 * Free Software Foundation with the addition of the following permission added
8139 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8140 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8141 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8143 * This program is distributed in the hope that it will be useful, but WITHOUT
8144 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8145 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8148 * You should have received a copy of the GNU Affero General Public License along with
8149 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8150 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8153 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8154 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8156 * The interactive user interfaces in modified source and object code versions
8157 * of this program must display Appropriate Legal Notices, as required under
8158 * Section 5 of the GNU Affero General Public License version 3.
8160 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8161 * these Appropriate Legal Notices must retain the display of the "Powered by
8162 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8163 * technical reasons, the Appropriate Legal Notices must display the words
8164 * "Powered by SugarCRM".
8165 ********************************************************************************/
8167 function gridInit() {
8168 if(SUGAR.email2.grid) {
8169 SUGAR.email2.grid.destroy();
8175 var Ck = YAHOO.util.Cookie;
8176 var widths = [ 10, 10, 150, 250, 175, 125 ];
8178 if (Ck.get("EmailGridWidths")) {
8179 for (var i=0; i < widths.length; i++) {
8180 widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8183 for (var i=0; i < widths.length; i++) {
8184 Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8188 // changes "F" to an icon
8189 function flaggedIcon(cell, record, column, value) {
8191 cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8194 // changes "A" to replied icon
8195 function repliedIcon(cell, record, column, value) {
8197 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8200 function attachIcon(cell, record, column, value) {
8202 cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8209 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>",
8214 formatter: attachIcon,
8218 label: "<span style='color: #f00; font-weight:bold;'>!</span>",
8223 formatter: flaggedIcon,
8227 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>",
8232 formatter: repliedIcon,
8236 label: app_strings.LBL_EMAIL_FROM,
8243 label: app_strings.LBL_EMAIL_SUBJECT,
8250 label: mod_strings.LBL_LIST_DATE,
8257 label: app_strings.LBL_EMAIL_TO,
8293 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8294 responseType: YAHOO.util.DataSource.TYPE_JSON,
8296 resultsList: 'Email',
8297 fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8298 metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8304 action : "EmailUIAjax",
8305 emailUIAction : "getMessageList",
8308 forceRefresh : "false"
8310 if(lazyLoadFolder != null) {
8311 params['mbox'] = lazyLoadFolder.folder;
8312 params['ieId'] = lazyLoadFolder.ieId;
8313 //Check if the folder is a Sugar Folder
8314 var test = new String(lazyLoadFolder.folder);
8315 if(test.match(/SUGAR\./)) {
8316 params['emailUIAction'] = 'getMessageListSugarFolders';
8317 params['mbox'] = test.substr(6);
8320 //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8323 var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8324 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8326 paginator: new YAHOO.widget.Paginator({
8327 rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),
8328 containers : ["dt-pag-nav"],
8329 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8330 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8331 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8332 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8333 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8335 initialRequest:SUGAR.util.paramsToUrl(params),
8342 //Override Paging request construction
8343 grid.set("generateRequest", function(oState, oSelf) {
8344 oState = oState || {pagination:null, sortedBy:null};
8345 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8346 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8347 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8348 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8349 // Build the request
8351 SUGAR.util.paramsToUrl(oSelf.params) +
8354 "&start=" + startIndex +
8355 ((results !== null) ? "&limit=" + results : "");
8360 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8361 oPayload = oPayload || { };
8363 oPayload.totalRecords = oResponse.meta.total;
8364 oPayload.unreadRecords = oResponse.meta.unread;
8366 var tabObject = SE.innerLayout.get("tabs")[0];
8368 if (this.params.mbox != null) {
8369 mboxTitle = this.params.mbox;
8371 var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8372 tabObject.get("labelEl").firstChild.data = tabtext;
8375 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8377 node.data.unseen = oResponse.meta.unread;
8378 SE.accounts.renderTree();
8384 var resize = grid.resizeGrid = function () {
8385 SUGAR.email2.grid.set("width", SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8386 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8388 grid.convertDDRows = function() {
8389 var rowEl = this.getFirstTrEl();
8390 while (rowEl != null) {
8391 new this.DDRow(this, this.getRecord(rowEl), rowEl);
8392 rowEl = this.getNextTrEl(rowEl);
8397 grid.on("columnResizeEvent", function(o) {
8398 //Find the index of the column
8399 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8400 for (var i=0; i < colSet.length; i++) {
8401 if (o.column == colSet[i]) {
8402 //Store it in the cookie
8403 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8406 //this.resizeGrid();
8409 grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8410 grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);
8411 grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);
8413 SUGAR.email2.listViewLayout.on("render", resize);
8416 //Setup the default load parameters
8417 SUGAR.email2.grid.params = params;
8419 grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8420 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8421 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8428 function initRowDD() {
8429 var sg = SUGAR.email2.grid,
8430 Dom = YAHOO.util.Dom;
8431 sg.DDRow = function(oDataTable, oRecord, elTr) {
8432 if(oDataTable && oRecord && elTr) {
8433 this.ddtable = oDataTable;
8434 this.table = oDataTable.getTableEl();
8437 this.newIndex = null;
8439 this.initFrame(); // Needed for DDProxy
8440 this.invalidHandleTypes = {};
8444 YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8445 _resizeProxy: function() {
8446 this.constructor.superclass._resizeProxy.apply(this, arguments);
8447 var dragEl = this.getDragEl(),
8449 var xy = Dom.getXY(el);
8451 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8452 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8453 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8454 Dom.setStyle(dragEl, 'display', "");
8457 startDrag: function(x, y) {
8458 //Check if we should be dragging a set of rows rather than just the one.
8459 var selectedRows = this.ddtable.getSelectedRows();
8460 var iSelected = false;
8461 for (var i in selectedRows) {
8462 if (this.rowEl.id == selectedRows[i]) {
8469 for (var i in selectedRows) {
8470 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8473 this.rows = [this.row];
8474 this.ddtable.unselectAllRows();
8475 this.ddtable.selectRow(this.row);
8478 //Initialize the dragable proxy
8479 var dragEl = this.getDragEl();
8480 var clickEl = this.getEl();
8481 Dom.setStyle(clickEl, "opacity", "0.25");
8482 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>";
8483 Dom.addClass(dragEl, "yui-dt-liner");
8484 Dom.setStyle(dragEl, "opacity", "0.5");
8485 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8486 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
8487 Dom.setStyle(dragEl, "border", "2px solid gray");
8490 clickValidator: function(e) {
8491 if (this.row.getData()[0] == " ")
8493 var target = YAHOO.util.Event.getTarget(e);
8494 return ( this.isValidHandleChild(target) &&
8495 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8498 * This funciton checks that the target of the drag is a table row in this
8499 * DDGroup and simply moves the sourceEL to that location as a preview.
8501 onDragOver: function(ev, id) {
8502 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8503 if (node && node != this.targetNode) {
8504 this.targetNode = node;
8505 SUGAR.email2.folders.unhighliteAll();
8510 onDragOut: function(e, id) {
8511 if (this.targetNode) {
8512 SUGAR.email2.folders.unhighliteAll();
8513 this.targetNode = false;
8516 endDrag: function() {
8517 Dom.setStyle(this.getEl(), "opacity", "");
8518 Dom.setStyle(this.getDragEl(), "display", "none");
8519 if (this.targetNode) {
8520 SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8522 SUGAR.email2.folders.unhighliteAll();
8528 function AddressSearchGridInit() {
8529 function moduleIcon(elCell, oRecord, oColumn, oData) {
8530 elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8532 function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8533 elCell.innerHTML = '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8535 var checkHeader = '<input type="checkbox" ';
8536 if (SUGAR.email2.util.isIe()) {
8537 checkHeader += 'style="top:-5px" ';
8539 checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8544 formatter: selectionCheckBox,
8548 label: mod_strings.LBL_LIST_TYPE,
8550 formatter: moduleIcon,
8554 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME,
8560 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8566 var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8567 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8569 resultsList: 'Person',
8570 fields: ['name', 'email', 'bean_id', 'bean_module'],
8571 metaFields: {total: 'TotalCount'}
8573 //enable sorting on the server accross all data
8576 dataModel.params = {
8579 action : "EmailUIAjax",
8580 emailUIAction:"getAddressSearchResults"
8582 var rb = document.getElementById('hasRelatedBean').checked;
8584 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8585 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8586 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8587 dataModel.params['related_bean_id'] = relatedBeanId;
8588 dataModel.params['related_bean_type'] = relatedBeanType;
8589 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8591 SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8593 var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8594 MSG_EMPTY: " ", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8596 paginator: new YAHOO.widget.Paginator({
8598 containers : ["dt-pag-nav-addressbook"],
8599 template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8600 firstPageLinkLabel: "<button class='button'><div class='paginator-start'/></button>",
8601 previousPageLinkLabel: "<button class='button'><div class='paginator-previous'/></button>",
8602 nextPageLinkLabel: "<button class='button'><div class='paginator-next'/></button>",
8603 lastPageLinkLabel: "<button class='button'><div class='paginator-end'/></button>"
8605 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8609 //Override Paging request construction
8610 grid.set("generateRequest", function(oState, oSelf) {
8611 oState = oState || {pagination:null, sortedBy:null};
8612 var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8613 var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8614 var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8615 var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8616 // Build the request
8618 SUGAR.util.paramsToUrl(oSelf.getDataSource().params) +
8619 "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8620 ((results !== null) ? "&limit=" + results : "");
8624 grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
8625 oPayload = oPayload || { };
8626 oPayload.totalRecords = oResponse.meta.total;
8630 grid.clickToggleSelect= function(args) {
8631 var isIE = (args.event.target == null);
8632 var targetElement = isIE ? args.event.srcElement : args.event.target;
8633 if(targetElement.type == null || targetElement.type != 'checkbox') {
8634 SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8638 grid.reSelectRowsOnRender = function (){
8639 var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8640 for (var i = 0; i < rows.length; i++)
8642 var emailAddress = rows[i].getData("email");
8643 var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8646 rows[i].setData("selected", true);
8647 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8651 rows[i].setData("selected", false);
8652 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8656 grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow);
8657 grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow);
8658 grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8659 grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8662 dataModel.subscribe("requestEvent", grid.disable, grid, true);
8663 dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8665 grid.toggleSelectCheckbox = function(id,checked){
8666 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8667 row.setData("checked",checked);
8669 grid.toggleSelect = function(id, checked) {
8670 var row = SUGAR.email2.addressBook.grid.getRecord(id);
8671 checked = row.getData("selected");
8674 SUGAR.email2.addressBook.grid.selectRow(row);
8675 SE.addressBook.insertContactRowToResultTable(id,null)
8678 SUGAR.email2.addressBook.grid.unselectRow(row);
8679 SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8681 row.setData("selected", !checked);
8684 grid.toggleSelectAll = function(checked) {
8685 rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8686 for (var i = 0; i < rows.length; i++) {
8687 if (typeof(rows[i]) != "undefined")
8688 rows[i].setData("checked", checked);
8690 var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8691 for (var i = 0; i < checkBoxes.length; i++) {
8692 checkBoxes[i].checked = checked;
8696 //Initialize the grid result table.
8697 AddressSearchResultsGridInit();
8703 * Initalize the results table for the address book selection.
8706 function AddressSearchResultsGridInit()
8709 /* Full name sort funciton to compare by last name if available */
8710 var fullNameSort = function(a, b, desc) {
8711 // Deal with empty values
8712 if(!YAHOO.lang.isValue(a))
8713 return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8714 else if(!YAHOO.lang.isValue(b))
8717 var aNames = a.getData("name").split(' ');
8718 var bNames = b.getData("name").split(' ');
8720 var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8721 var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8723 return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8727 var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8728 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8729 app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')];
8731 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})},
8732 {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8734 var myDataSource = new YAHOO.util.DataSource([]);
8735 myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
8736 myDataSource.responseSchema = {
8737 fields: ["name","type","email_address","display_email_address","bean_id","idx"]
8740 var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8741 width: "350px",height: "250px", MSG_EMPTY: " "});
8743 var highlightEditableCell = function(oArgs) {
8744 var elCell = oArgs.target;
8745 if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8746 this.highlightCell(elCell);
8750 gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8751 gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8752 gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8753 gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow);
8754 gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow);
8756 //Setup the context menus
8757 var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
8758 var task = p_aArgs[1];
8761 var elRow = this.contextEventTarget;
8762 elRow = p_myDataTable.getTrEl(elRow);
8769 var oRecord = p_myDataTable.getRecord(elRow);
8770 p_myDataTable.deleteRow(elRow);
8771 SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
8776 var contextMenu = new YAHOO.widget.ContextMenu("contextmenu",
8777 {trigger:gridResults.getTbodyEl()});
8778 contextMenu.addItem(app_strings.LBL_EMAIL_DELETE);
8779 contextMenu.render("addrSearchResultGrid");
8780 contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults);
8782 // End of File modules/Emails/javascript/grid.js
8784 /*********************************************************************************
8785 * SugarCRM Community Edition is a customer relationship management program developed by
8786 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8788 * This program is free software; you can redistribute it and/or modify it under
8789 * the terms of the GNU Affero General Public License version 3 as published by the
8790 * Free Software Foundation with the addition of the following permission added
8791 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8792 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8793 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8795 * This program is distributed in the hope that it will be useful, but WITHOUT
8796 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8797 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
8800 * You should have received a copy of the GNU Affero General Public License along with
8801 * this program; if not, see http://www.gnu.org/licenses or write to the Free
8802 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8805 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8806 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8808 * The interactive user interfaces in modified source and object code versions
8809 * of this program must display Appropriate Legal Notices, as required under
8810 * Section 5 of the GNU Affero General Public License version 3.
8812 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8813 * these Appropriate Legal Notices must retain the display of the "Powered by
8814 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8815 * technical reasons, the Appropriate Legal Notices must display the words
8816 * "Powered by SugarCRM".
8817 ********************************************************************************/
8820 /******************************************************************************
8821 * Initialize Email 2.0 Application
8824 //Override Sugar Languge so quick creates work properly
8827 function email2init() {
8830 // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
8831 // "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
8832 if (!SUGAR.util.isTouchScreen()) {
8834 convert_urls : false,
8835 theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
8836 width: tinyConfig.width,
8837 theme: tinyConfig.theme,
8838 theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
8839 theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
8840 theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
8841 theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
8842 plugins : tinyConfig.plugins,
8843 elements : tinyConfig.elements,
8844 language : tinyConfig.language,
8845 extended_valid_elements : tinyConfig.extended_valid_elements,
8846 mode: tinyConfig.mode,
8847 strict_loading_mode : true,
8848 force_br_newlines : true,
8849 forced_root_block : '',
8850 directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
8854 // initialze message overlay
8855 SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
8865 if (SUGAR.themes.tempHideLeftCol)
8866 SUGAR.themes.tempHideLeftCol();
8868 // add key listener for kb shortcust - disable backspace nav in mozilla/ie
8869 // YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
8871 // set defaults for YAHOO.util.DragDropManager
8872 YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
8874 SUGAR.email2.nextYear = new Date();
8875 SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
8878 // initialize and display UI framework (complexLayout.js)
8879 complexLayoutInit();
8881 // initialize and display grid (grid.js)
8884 // initialize treeview for folders
8886 SUGAR.email2.folders.rebuildFolders(true);
8889 //Setup the Message Box overlay
8890 /*Ext.MessageBox.maxWidth = 350;
8891 Ext.MessageBox.minProgressWidth = 350;
8893 ///////////////////////////////////////////////////////////////////////////
8896 SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
8898 var SEC = SUGAR.email2.contextMenus;
8901 var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
8902 trigger: SUGAR.email2.grid.get("element"),
8905 emailMenu.subscribe("beforeShow", function() {
8906 var oTarget = this.contextEventTarget;
8907 if (typeof(oTarget) == "undefined")
8909 var grid = SUGAR.email2.grid;
8910 var selectedRows = grid.getSelectedRows();
8911 var multipleSelected = (selectedRows.length > 1) ? true: false;
8912 if (!multipleSelected)
8914 grid.unselectAllRows();
8915 grid.selectRow(oTarget);
8916 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8918 else if(multipleSelected)
8920 SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8924 //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
8925 //us to access individual elements easier by name rather than by index
8926 emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2, 'reply' : 3,'replyAll' : 4,'forward' : 5,
8927 'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
8928 emailMenu.addItems([
8930 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
8931 id: 'showDetailView',
8932 onclick: { fn: SEC.showDetailView }
8935 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
8936 onclick: { fn: SEC.openMultiple }
8939 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
8940 onclick: { fn: SEC.archiveToSugar }
8943 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
8945 onclick: { fn: SEC.replyForwardEmailContext }
8948 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
8950 onclick: { fn: SEC.replyForwardEmailContext }
8953 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
8955 onclick: { fn: SEC.replyForwardEmailContext }
8958 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
8960 onclick: { fn: SEC.markDeleted }
8963 text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
8965 onclick: { fn: SEC.viewPrintable }
8969 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
8971 id: "markEmailMenu",
8974 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
8975 onclick: { fn: SEC.markUnread }
8978 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
8979 onclick: { fn: SEC.markRead }
8982 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
8983 onclick: { fn: SEC.markFlagged }
8986 text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
8987 onclick: { fn: SEC.markUnflagged }
8993 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
8995 onclick: { fn: SEC.assignEmailsTo }
8998 text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9000 onclick: { fn: SEC.relateTo }
9003 SEC.emailListContextMenu.render();
9005 //Handle the Tree folder menu trigger ourselves
9006 YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9010 SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9014 SEC.frameFoldersContextMenu.addItems([
9015 { text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9016 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9017 onclick: { fn: function() {
9018 var node = SUGAR.email2.clickedFolderNode;
9019 if (node.data.ieId) {
9020 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9023 { text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9024 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9025 onclick: { fn: function() {
9026 var node = SUGAR.email2.clickedFolderNode;
9027 if (node.data.ieId) {
9028 SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9032 text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9033 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9034 onclick: { fn: SUGAR.email2.folders.folderAdd }
9037 text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9038 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9039 onclick: { fn: SUGAR.email2.folders.folderDelete }
9042 text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9043 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9044 onclick: { fn: SUGAR.email2.folders.folderRename }
9047 text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9048 //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9049 onclick: { fn: SUGAR.email2.folders.emptyTrash }
9052 text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9053 onclick: { fn: function() {
9054 var node = SUGAR.email2.clickedFolderNode;
9055 if (node.data.ieId) {
9056 SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9060 SEC.frameFoldersContextMenu.render();
9062 SEC.initContactsMenu = function() {
9064 SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9065 trigger: "contacts",
9068 SEC.contactsContextMenu.addItems([
9070 text: app_strings.LBL_EMAIL_MENU_REMOVE,
9071 onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9074 text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9075 onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9078 SEC.contactsContextMenu.subscribe("beforeShow", function() {
9079 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9080 if (oTarget && !grid.isSelected(oTarget)) {
9081 grid.unselectAllRows();
9082 grid.selectRow(oTarget);
9085 SEC.contactsContextMenu.render();
9089 // set auto-check timer
9090 SUGAR.email2.folders.startCheckTimer();
9091 // check if we're coming from an email-link click
9092 setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9094 YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9096 //Init fix for YUI 2.7.0 datatable sort.
9097 SUGAR.email2.addressBook.initFixForDatatableSort();
9100 function createTreePanel(treeData, params) {
9101 var tree = new YAHOO.widget.TreeView(params.id);
9102 var root = tree.getRoot();
9104 //if (treeData.nodes && treeData[0].id == "Home")
9105 // treeData = treeData[0];
9109 function addChildNodes(parentNode, parentData) {
9110 var Ck = YAHOO.util.Cookie;
9111 var nextyear = SUGAR.email2.nextYear;
9112 var nodes = parentData.nodes || parentData.children;
9114 if (typeof(nodes[i]) == 'object') {
9115 if (nodes[i].data) {
9116 // See comment about href below.
9117 // nodes[i].data.href = '#';
9118 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode);
9119 node.action = nodes[i].data.action;
9121 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9122 addChildNodes(parentNode, nodes[i]);
9125 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9126 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9128 nodes[i].className = nodes[i].cls;
9130 // Previously, span was added in the label so it was rendering in the tree.
9131 // Default behavior is to wrap in span if no href property, and since this href
9132 // doesn't do anything, remove it so that it will be wrapped in spans.
9133 // nodes[i].href = "#";
9134 if (nodes[i].text) nodes[i].label = nodes[i].text;
9135 //Override YUI child node creation
9136 if (nodes[i].children) {
9137 nodes[i].nodes = nodes[i].children;
9138 nodes[i].children = [ ];
9140 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9143 if (typeof(nodes[i].nodes) == 'object') {
9144 addChildNodes(node, nodes[i]);
9151 * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9153 function email2treeinit(tree, treedata, treediv, params) {
9154 //ensure the tree data is not corrupt
9158 if (SUGAR.email2.tree) {
9159 SUGAR.email2.tree.destroy();
9160 SUGAR.email2.tree = null;
9163 var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9167 tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9168 tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9169 tree.subscribe("expandComplete", function(node){
9170 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9171 for (var i in node.children) {
9172 SE.accounts.setupDDTarget(node.children[i]);
9175 tree.setCollapseAnim("TVSlideOut");
9176 tree.setExpandAnim("TVSlideIn");
9177 var root = tree.root;
9178 while (root.hasChildren()) {
9179 var node = root.children[0];
9181 tree.removeNode(root.children[0], false);
9183 addChildNodes(root, treedata);
9185 SUGAR.email2.accounts.renderTree();
9188 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9189 SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9193 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {
9194 startDrag: function(x, y) {
9195 var Dom = YAHOO.util.Dom;
9196 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9199 var dragEl = this.getDragEl();
9200 var clickEl = this.getEl();
9201 Dom.setStyle(clickEl, "color", "#AAA");
9202 Dom.setStyle(clickEl, "opacity", "0.25");
9203 dragEl.innerHTML = clickEl.innerHTML;
9205 Dom.addClass(dragEl, "ygtvcell");
9206 Dom.addClass(dragEl, "ygtvcontent");
9207 Dom.addClass(dragEl, "folderDragProxy");
9208 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9209 Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9210 Dom.setStyle(dragEl, "backgroundColor", "#FFF");
9211 Dom.setStyle(dragEl, "opacity", "0.5");
9212 Dom.setStyle(dragEl, "border", "1px solid #AAA");
9215 onDragOver: function(ev, id) {
9216 var Dom = YAHOO.util.Dom;
9217 if (id != this.dragId)
9219 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9220 if(node.data.cls != "sugarFolder") {
9221 SUGAR.email2.folders.unhighliteAll();
9225 this.targetNode = node;
9226 SUGAR.email2.folders.unhighliteAll();
9231 onDragOut: function(e, id) {
9232 if (this.targetNode) {
9233 SUGAR.email2.folders.unhighliteAll();
9234 this.targetNode = false;
9235 this.dragId = false;
9239 endDrag: function() {
9240 YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9241 if (this.targetNode) {
9242 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9245 });// End of File modules/Emails/javascript/init.js
9247 /*********************************************************************************
9248 * SugarCRM Community Edition is a customer relationship management program developed by
9249 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9251 * This program is free software; you can redistribute it and/or modify it under
9252 * the terms of the GNU Affero General Public License version 3 as published by the
9253 * Free Software Foundation with the addition of the following permission added
9254 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9255 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9256 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9258 * This program is distributed in the hope that it will be useful, but WITHOUT
9259 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9260 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9263 * You should have received a copy of the GNU Affero General Public License along with
9264 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9265 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9268 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9269 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9271 * The interactive user interfaces in modified source and object code versions
9272 * of this program must display Appropriate Legal Notices, as required under
9273 * Section 5 of the GNU Affero General Public License version 3.
9275 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9276 * these Appropriate Legal Notices must retain the display of the "Powered by
9277 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9278 * technical reasons, the Appropriate Legal Notices must display the words
9279 * "Powered by SugarCRM".
9280 ********************************************************************************/
9285 function complexLayoutInit() {
9286 var se = SUGAR.email2;
9287 var Dom = YAHOO.util.Dom;
9289 getInnerLayout : function(rows) {
9290 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
9291 parent: se.complexLayout,
9297 scroll:false, // grid should autoScroll itself
9299 body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
9307 body: "<div id='listBottom' />"
9315 body: "<div id='listRight' />",
9316 titlebar: false //,header: "right"
9319 se.complexLayout.on("render", function(){
9320 var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
9321 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9322 SUGAR.email2.listViewLayout.set("height", height);
9323 SUGAR.email2.listViewLayout.render();
9325 se.listViewLayout.render();
9327 se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
9328 var rp = se.listViewLayout.resizePreview = function() {
9329 var pre = Dom.get("displayEmailFramePreview");
9331 var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
9332 pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
9335 se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
9336 se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
9337 se.e2Layout.setPreviewPanel(rows);
9338 se.previewLayout = se.listViewLayout;
9339 return se.listViewLayout;
9342 getInnerLayout2Rows : function() {
9343 return this.getInnerLayout(true);
9345 getInnerLayout2Columns : function() {
9346 return this.getInnerLayout(false);
9350 // initialize state manager, we will use cookies
9351 // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
9352 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
9353 se.complexLayout = new YAHOO.widget.Layout("container", {
9356 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
9357 width: Dom.getViewportWidth() - 40,
9361 body: "<div id='emailtabs'></div>"
9366 body: "<div id='lefttabs'></div>",
9376 header: Dom.get('footerLinks').innerHTML,
9383 se.complexLayout.render();
9384 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
9385 tp.addTab(new YAHOO.widget.Tab({
9388 content : "<div id='listViewDiv'/>",
9392 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
9393 tp.appendTo(centerEl);
9395 tp.get("element").style.borderRight = "1px solid #666"
9397 var listV = this.getInnerLayout2Rows();
9398 listV.set("height", tp.get("element").clientHeight - 25);
9401 se.leftTabs = new YAHOO.widget.TabView("lefttabs");
9402 var folderTab = new YAHOO.widget.Tab({
9403 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
9405 content : "<div id='emailtree'/>",
9409 folderTab.on("activeChange", function(o){
9411 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
9414 se.leftTabs.addTab(folderTab);
9416 var tabContent = SUGAR.util.getAndRemove("searchTab");
9417 var searchTab = new YAHOO.widget.Tab({
9418 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
9420 content : tabContent.innerHTML,
9423 searchTab.on("activeChange", function(o){
9426 se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
9427 //Setup the calendars if needed
9428 Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
9429 Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
9431 //Initalize sqs object for assigned user name
9432 se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');
9434 //Attach event handler for when the relate module option is selected for the correct sqs object
9435 var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
9436 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
9437 YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){
9438 SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
9440 //If enter key is pressed, perform search
9441 var addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
9442 for(var i=0; i < addKeyPressFields.length;i++)
9444 YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
9445 if (e.keyCode == 13) {
9446 YAHOO.util.Event.stopEvent(e);
9447 SUGAR.email2.search.searchAdvanced();
9451 //Initiate quick search for the search tab. Do this only when the tab is selected rather than onDomLoad for perf. gains.
9453 //Clear parent values if selecting another parent type.
9454 YAHOO.util.Event.addListener('data_parent_type_search','change',
9456 document.getElementById('data_parent_id_search').value ='';
9457 document.getElementById('data_parent_name_search').value ='';
9462 se.leftTabs.addTab(searchTab);
9464 var resizeTabBody = function() {
9465 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
9466 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9469 se.complexLayout.on("render", resizeTabBody);
9470 se.leftTabs.on("activeTabChange", resizeTabBody);
9471 //hack to allow left pane scroll bar to fully show
9472 var lefttabsDiv = document.getElementById('lefttabs');
9473 var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
9474 var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
9475 lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
9478 initSQSObject: function(formName,fieldName)
9480 var fullFieldName = formName + '_' + fieldName; //SQS Convention
9481 var resultName = fullFieldName + '_' + 'results';
9483 if (QSFieldsArray[fullFieldName] != null)
9485 QSFieldsArray[fullFieldName].destroy();
9486 delete QSFieldsArray[fullFieldName];
9488 if (QSProcessedFieldsArray[fullFieldName])
9489 QSProcessedFieldsArray[fullFieldName] = false;
9491 if( Dom.get(resultName) )
9493 var obj = document.getElementById(resultName);
9494 obj.parentNode.removeChild(obj);
9497 setPreviewPanel: function(rows) {
9499 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9500 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9501 Dom.get("listRight").innerHTML = "";
9502 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9504 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9505 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9506 Dom.get("listBottom").innerHTML = "";
9507 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9514 var myBufferedListenerObject = new Object();
9515 myBufferedListenerObject.refit = function() {
9516 if(SUGAR.email2.grid) {
9517 SUGAR.email2.grid.autoSize();
9520 // End of File modules/Emails/javascript/complexLayout.js
9522 /*********************************************************************************
9523 * SugarCRM Community Edition is a customer relationship management program developed by
9524 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9526 * This program is free software; you can redistribute it and/or modify it under
9527 * the terms of the GNU Affero General Public License version 3 as published by the
9528 * Free Software Foundation with the addition of the following permission added
9529 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9530 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9531 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9533 * This program is distributed in the hope that it will be useful, but WITHOUT
9534 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9535 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9538 * You should have received a copy of the GNU Affero General Public License along with
9539 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9540 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9543 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9544 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9546 * The interactive user interfaces in modified source and object code versions
9547 * of this program must display Appropriate Legal Notices, as required under
9548 * Section 5 of the GNU Affero General Public License version 3.
9550 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9551 * these Appropriate Legal Notices must retain the display of the "Powered by
9552 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9553 * technical reasons, the Appropriate Legal Notices must display the words
9554 * "Powered by SugarCRM".
9555 ********************************************************************************/
9557 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9558 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9559 ' <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9560 ' <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9561 ' <input type="hidden" id="uid{idx}" name="uid" value="">' +
9562 ' <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9563 ' <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9564 ' <input type="hidden" id="type{idx}" name="type" value="">' +
9565 ' <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9566 ' <input type="hidden" id="composeType" name="composeType">' +
9567 ' <input type="hidden" id="fromAccount" name="fromAccount">' +
9568 ' <input type="hidden" id="sendSubject" name="sendSubject">' +
9569 ' <input type="hidden" id="sendDescription" name="sendDescription">' +
9570 ' <input type="hidden" id="sendTo" name="sendTo">' +
9571 ' <input type="hidden" id="sendBcc" name="sendBcc">' +
9572 ' <input type="hidden" id="sendCc" name="sendCc">' +
9573 ' <input type="hidden" id="setEditor" name="setEditor">' +
9574 ' <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9575 ' <input type="hidden" id="parent_id" name="parent_id">' +
9576 ' <input type="hidden" id="parent_type" name="parent_type">' +
9577 ' <input type="hidden" id="attachments" name="attachments">' +
9578 ' <input type="hidden" id="documents" name="documents">' +
9579 ' <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9580 ' <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9581 ' <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9582 ' <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9584 ' <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9585 ' <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>' +
9586 ' <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>' +
9587 ' <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>' +
9588 ' <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>' +
9589 '</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>' +
9590 ' </td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9591 '<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>' +
9592 ' </td></tr></tbody></table></th>' +
9596 ' <div style="margin:5px;">' +
9597 ' <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9599 ' <td class="emailUILabel" NOWRAP >' +
9600 ' {app_strings.LBL_EMAIL_FROM}:' +
9602 ' <td class="emailUIField" NOWRAP>' +
9604 ' <select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9609 ' <td class="emailUILabel" NOWRAP>' +
9610 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' +
9611 ' {app_strings.LBL_EMAIL_TO}:' +
9614 ' <td class="emailUIField" NOWRAP>' +
9615 ' <div class="ac_autocomplete">' +
9616 ' <input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9617 ' <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}"> </span></a> </span>' +
9618 ' <div class="ac_container" id="addressToAC{idx}"></div>' +
9622 ' <tr id="add_addr_options_tr{idx}">' +
9623 ' <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>'+
9625 ' <tr class="yui-hidden" id="cc_tr{idx}">' +
9626 ' <td class="emailUILabel" NOWRAP>' +
9627 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' +
9628 ' {app_strings.LBL_EMAIL_CC}:' +
9631 ' <td class="emailUIField" NOWRAP>' +
9632 ' <div class="ac_autocomplete">' +
9633 ' <input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9634 ' <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#" style="display: none;">+<span id="DetailaddressCC{idx}"> </span></a> </span>' +
9635 ' <div class="ac_container" id="addressCcAC{idx}"></div>' +
9639 ' <tr class="yui-hidden" id="bcc_tr{idx}">' +
9640 ' <td class="emailUILabel" NOWRAP>' +
9641 ' <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' +
9642 ' {app_strings.LBL_EMAIL_BCC}:' +
9645 ' <td class="emailUIField" NOWRAP>' +
9646 ' <div class="ac_autocomplete">' +
9647 ' <input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9648 ' <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}"> </span></a> </span>' +
9649 ' <div class="ac_container" id="addressBccAC{idx}"></div>' +
9654 ' <td class="emailUILabel" NOWRAP width="1%">' +
9655 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9657 ' <td class="emailUIField" NOWRAP width="99%">' +
9658 ' <div class="ac_autocomplete">' +
9659 ' <input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9668 ' <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9669 ' <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9670 ' <div style="padding:5px;">' +
9671 ' <table cellpadding="2" cellspacing="0" border="0">' +
9674 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9681 ' <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9682 ' <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9694 ' <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9701 ' <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9702 ' <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>' +
9714 ' <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9721 ' <div id="addedTemplateAttachments{idx}"></div>' +
9728 ' <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9729 ' <div style="padding:5px;">' +
9730 ' <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' +
9731 ' <table border="0" width="100%">' +
9733 ' <td NOWRAP style="padding:2px;">' +
9734 ' <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9738 ' <td NOWRAP style="padding:2px;">' +
9739 ' <select name="email_template{idx}" id="email_template{idx}" onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9744 ' <table border="0" width="100%">' +
9746 ' <td NOWRAP style="padding:2px;">' +
9747 ' <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9751 ' <td NOWRAP style="padding:2px;">' +
9752 ' <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9756 ' <table border="0" width="100%">' +
9758 ' <td NOWRAP style="padding:2px;">' +
9759 ' <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/> ' +
9760 ' <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9768 // End of File modules/Emails/javascript/composeEmailTemplate.js
9770 /*********************************************************************************
9771 * SugarCRM Community Edition is a customer relationship management program developed by
9772 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9774 * This program is free software; you can redistribute it and/or modify it under
9775 * the terms of the GNU Affero General Public License version 3 as published by the
9776 * Free Software Foundation with the addition of the following permission added
9777 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9778 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9779 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9781 * This program is distributed in the hope that it will be useful, but WITHOUT
9782 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9783 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9786 * You should have received a copy of the GNU Affero General Public License along with
9787 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9788 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9791 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9792 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9794 * The interactive user interfaces in modified source and object code versions
9795 * of this program must display Appropriate Legal Notices, as required under
9796 * Section 5 of the GNU Affero General Public License version 3.
9798 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9799 * these Appropriate Legal Notices must retain the display of the "Powered by
9800 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9801 * technical reasons, the Appropriate Legal Notices must display the words
9802 * "Powered by SugarCRM".
9803 ********************************************************************************/
9805 SUGAR.email2.templates['displayOneEmail'] =
9806 '<div class="emailDetailTable" style="height:100%">' +
9807 '<div id="viewMenuDiv{idx}"></div>' +
9808 '<div width="100%" class="displayEmailValue">' +
9809 ' <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>' +
9810 ' <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>' +
9811 ' <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>' +
9812 ' <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>' +
9813 ' <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>' +
9814 ' <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>' +
9815 ' <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>' +
9816 ' <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>' +
9817 ' <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>' +
9819 ' <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9821 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9822 ' {app_strings.LBL_EMAIL_FROM}:' +
9824 ' <td width="99%" class="displayEmailValue">' +
9825 ' {email.from_addr}' +
9829 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9830 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9832 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9833 ' <b>{email.name}</b>' +
9837 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9838 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9840 ' <td class="displayEmailValue">' +
9841 ' {email.date_start} {email.time_start}' +
9845 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9846 ' {app_strings.LBL_EMAIL_TO}:' +
9848 ' <td class="displayEmailValue">' +
9849 ' {email.toaddrs}' +
9852 ' <tr>{meta.cc}</tr>' +
9853 ' <tr>{email.attachments}</tr>' +
9855 ' <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>' +
9856 //' {email.description}' +
9858 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9860 /*********************************************************************************
9861 * SugarCRM Community Edition is a customer relationship management program developed by
9862 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9864 * This program is free software; you can redistribute it and/or modify it under
9865 * the terms of the GNU Affero General Public License version 3 as published by the
9866 * Free Software Foundation with the addition of the following permission added
9867 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9868 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9869 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9871 * This program is distributed in the hope that it will be useful, but WITHOUT
9872 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9873 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9876 * You should have received a copy of the GNU Affero General Public License along with
9877 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9878 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9881 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9882 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9884 * The interactive user interfaces in modified source and object code versions
9885 * of this program must display Appropriate Legal Notices, as required under
9886 * Section 5 of the GNU Affero General Public License version 3.
9888 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9889 * these Appropriate Legal Notices must retain the display of the "Powered by
9890 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9891 * technical reasons, the Appropriate Legal Notices must display the words
9892 * "Powered by SugarCRM".
9893 ********************************************************************************/
9895 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9896 '<body onload="javascript:window.print();">' +
9900 ' font-family: helvetica, impact, sans-serif;' +
9901 ' font-size : 12pt;' +
9908 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9911 ' <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9913 ' <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9914 ' {app_strings.LBL_EMAIL_FROM}:' +
9916 ' <td width="99%" class="displayEmailValue">' +
9917 ' {email.from_name} <{email.from_addr}>' +
9921 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9922 ' {app_strings.LBL_EMAIL_SUBJECT}:' +
9924 ' <td NOWRAP valign="top" class="displayEmailValue">' +
9925 ' <b>{email.name}</b>' +
9929 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9930 ' {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9932 ' <td class="displayEmailValue">' +
9933 ' {email.date_start} {email.time_start}' +
9937 ' <td NOWRAP valign="top" class="displayEmailLabel">' +
9938 ' {app_strings.LBL_EMAIL_TO}:' +
9940 ' <td class="displayEmailValue">' +
9941 ' {email.toaddrs}' +
9945 ' {email.attachments}' +
9951 ' <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9953 ' <td style="border-top: 1px solid #333;">' +
9954 ' <div style="padding:5px;">' +
9955 '{email.description}' +
9965 // End of File modules/Emails/javascript/viewPrintable.js
9967 /*********************************************************************************
9968 * SugarCRM Community Edition is a customer relationship management program developed by
9969 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9971 * This program is free software; you can redistribute it and/or modify it under
9972 * the terms of the GNU Affero General Public License version 3 as published by the
9973 * Free Software Foundation with the addition of the following permission added
9974 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9975 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9976 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9978 * This program is distributed in the hope that it will be useful, but WITHOUT
9979 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9980 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
9983 * You should have received a copy of the GNU Affero General Public License along with
9984 * this program; if not, see http://www.gnu.org/licenses or write to the Free
9985 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9988 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9989 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9991 * The interactive user interfaces in modified source and object code versions
9992 * of this program must display Appropriate Legal Notices, as required under
9993 * Section 5 of the GNU Affero General Public License version 3.
9995 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9996 * these Appropriate Legal Notices must retain the display of the "Powered by
9997 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9998 * technical reasons, the Appropriate Legal Notices must display the words
9999 * "Powered by SugarCRM".
10000 ********************************************************************************/
10001 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
10002 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;}
10003 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');}
10004 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;}}
10005 if(QSProcessedFieldsArray[qs_index_id]){continue;}
10006 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
10007 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}
10008 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="";}}
10009 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
10010 {search.clearFields=function(){};search.setFields=function(data,filter)
10011 {var label_str='';var label_data_str='';var current_label_data_str='';var label_data_hash=new Array();for(var i in this.fields){for(var key in this.qs_obj.field_list){if(this.fields[i]==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&document.getElementById(this.qs_obj.populate_list[key]+'_label')&&this.qs_obj.populate_list[key].match(filter)){var displayValue=data[i].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');var data_label=document.getElementById(this.qs_obj.populate_list[key]+'_label').innerHTML.replace(/\n/gi,'');label_and_data=data_label+' '+displayValue;if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&!label_data_hash[data_label])
10012 {label_str+=data_label+' \n';label_data_str+=label_and_data+'\n';label_data_hash[data_label]=true;current_label_data_str+=data_label+' '+document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value+'\n';}}}}
10013 if(label_str!=current_label_data_str&¤t_label_data_str!=label_data_str){module_key=(typeof document.forms[form_id].elements['module']!='undefined')?document.forms[form_id].elements['module'].value:'app_strings';warning_label=SUGAR.language.translate(module_key,'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM')+'\n\n'+label_data_str;if(!confirm(warning_label))
10014 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
10015 {if(this.inputElement.id=='shipping_account_name')
10016 {filter=Dom.get('shipping_checkbox').checked?/(account_id|office_phone)/:filter;}else if(this.inputElement.id=='billing_account_name'){filter=Dom.get('shipping_checkbox').checked?filter:/(account_id|office_phone|billing)/;}}else if(Dom.get('alt_checkbox')){filter=Dom.get('alt_checkbox').checked?filter:/^(?!alt)/;}
10017 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
10018 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
10019 search.itemSelectEvent.subscribe(function(e,args){var data=args[2];var fields=this.fields;this.setFields(data,/\S/);if(typeof(this.qs_obj['post_onblur_function'])!='undefined'){collection_extended=new Array();for(var i in fields){for(var key in this.qs_obj.field_list){if(fields[i]==this.qs_obj.field_list[key]){collection_extended[this.qs_obj.field_list[key]]=data[i];}}}
10020 eval(this.qs_obj['post_onblur_function']+'(collection_extended, this.qs_obj.id)');}});search.textboxFocusEvent.subscribe(function(){this.oldValue=this.getInputEl().value;});search.selectionEnforceEvent.subscribe(function(e,args){if(this.oldValue!=args[1]){this.clearFields();}else{this.getInputEl().value=this.oldValue;}});search.dataReturnEvent.subscribe(function(e,args){if(this.getInputEl().value.length==0&&args[2].length>0){var data=[];for(var key in this.qs_obj.field_list){data[data.length]=args[2][0][this.qs_obj.field_list[key]];}
10021 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});search.typeAheadEvent.subscribe(function(e,args){this.getInputEl().value=this.getInputEl().value.replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
10022 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
10023 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}
10024 // End of File include/javascript/quicksearch.js