/* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
/**
* @class a YAHOO.util.DDProxy implementation. During the drag over event, the
* dragged element is inserted before the dragged-over element.
*
* @extends YAHOO.util.DDProxy
* @constructor
* @param {String} id the id of the linked element
* @param {String} sGroup the group of related DragDrop objects
*/
function ygDDList(id, sGroup) {
if (id) {
this.init(id, sGroup);
this.initFrame();
//this.logger = new ygLogger("ygDDList");
}
var s = this.getDragEl().style;
s.borderColor = "transparent";
s.backgroundColor = "#f6f5e5";
s.opacity = 0.76;
s.filter = "alpha(opacity=76)";
}
ygDDList.prototype = new YAHOO.util.DDProxy();
ygDDList.prototype.borderDiv = null;
ygDDList.prototype.originalDisplayProperties = Array();
ygDDList.prototype.startDrag = function(x, y) {
//this.logger.debug(this.id + " startDrag");
var dragEl = this.getDragEl();
var clickEl = this.getEl();
dragEl.innerHTML = clickEl.innerHTML;
dragElObjects = dragEl.getElementsByTagName('object');
dragEl.className = clickEl.className;
dragEl.style.color = clickEl.style.color;
dragEl.style.border = "1px solid #aaa";
// save the style of the object
clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
this.borderDiv = document.createElement('div'); // create a div to display border
this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
this.borderDiv.style.border = '2px dashed #cccccc';
for(i in clickEl.childNodes) { // hide contents of the target elements contents
if(typeof clickEl.childNodes[i].style != 'undefined') {
this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
clickEl.childNodes[i].style.display = 'none';
}
}
clickEl.appendChild(this.borderDiv);
};
ygDDList.prototype.endDrag = function(e) {
// disable moving the linked element
var clickEl = this.getEl();
clickEl.removeChild(this.borderDiv); // remove border div
for(i in clickEl.childNodes) { // show target elements contents
if(typeof clickEl.childNodes[i].style != 'undefined') {
clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
}
}
if(this.clickHeight)
clickEl.style.height = this.clickHeight;
else
clickEl.style.height = '';
if(this.clickBorder)
clickEl.style.border = this.clickBorder;
else
clickEl.style.border = '';
dragEl = this.getDragEl();
dragEl.innerHTML = '';
this.afterEndDrag(e);
};
ygDDList.prototype.afterEndDrag = function(e) {
}
ygDDList.prototype.onDrag = function(e, id) {
};
ygDDList.prototype.onDragOver = function(e, id) {
// this.logger.debug(this.id.toString() + " onDragOver " + id);
var el;
if ("string" == typeof id) {
el = YAHOO.util.DDM.getElement(id);
} else {
el = YAHOO.util.DDM.getBestMatch(id).getEl();
}
dragEl = this.getDragEl();
elRegion = YAHOO.util.Dom.getRegion(el);
// this.logger.debug('id: ' + el.id);
// this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
// this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
// this.logger.debug('mid: ' + mid);
// this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " < " + mid);
// this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
var el2 = this.getEl();
var p = el.parentNode;
p.insertBefore(el2, el);
}
if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
var el2 = this.getEl();
var p = el.parentNode;
p.insertBefore(el2, el.nextSibling);
}
};
ygDDList.prototype.onDragEnter = function(e, id) {
// this.logger.debug(this.id.toString() + " onDragEnter " + id);
// this.getDragEl().style.border = "1px solid #449629";
};
ygDDList.prototype.onDragOut = function(e, id) {
// I need to know when we are over nothing
// this.getDragEl().style.border = "1px solid #964428";
}
/////////////////////////////////////////////////////////////////////////////
function ygDDListBoundary(id, sGroup) {
if (id) {
this.init(id, sGroup);
//this.logger = new ygLogger("ygDDListBoundary");
this.isBoundary = true;
}
}
ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
// End of File include/javascript/yui/ygDDList.js
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
(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'))
document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'
'+' '+' '+' '+' '+' '+' '+' ',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
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())){if(/save|full|cancel|change/.test(elm.value.toLowerCase())){savePressed=true;}}}
if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
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);if(this.verifyElementValue==null||typeof(this.verifyElementValue)=='undefined'){return false;}
this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
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)
return;this.addInProgress=true;if(!address)
address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag=document.createElement("input");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);}
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'];}
var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i0){var emailcontainer=Dom.getAncestorByTagName(insertInto,'span');YAHOO.util.Event.addListener(newContent,"change",function(ev,el){SUGAR.util.callOnChangeListers(el);},emailcontainer);}
this.EmailAddressValidation(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},EmailAddressValidation:function(ev,fn,r,stR){YAHOO.util.Event.onContentReady(fn,function(){addToValidate(ev,fn,'email',r,stR);});},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;x0){DCMenu.save(theForm.id);}else if(this.emailView.indexOf('QuickCreate')>=0){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value+'_subpanel_save_button');}}}};emailAddressWidgetLoaded=true;})();
// End of File include/SugarEmailAddress/SugarEmailAddress.js
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
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)
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_","_")]);}
var checked=false;for(var k=0;k='A'&&b<='Z')||(b>='a'&&b<='z')?Rot13.map[b]:b);}
return s;},init:function(){if(Rot13.map!=null)
return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i0){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='';}
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='';}
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='';}}
return words;}
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)
{if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
if(typeof(ie_id)=='undefined'||ie_id=='')
ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id.value:'';URL='index.php?'
+'module='+module_name
+'&to_pdf=1'
+'&action='+action
+'&target='+pageTarget
+'&target1='+pageTarget
+'&server_url='+mail_server
+'&email_user='+words[0]
+'&protocol='+protocol
+'&port='+port
+'&email_password='+words[1]
+'&mailbox='+words[2]
+'&ssl='+ssl
+'&ie_id='+ie_id
+'&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)
SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
this.body.style.width=w}}
var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
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();}
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'));}
if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
if(errors.length>0){out=SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_DESC');for(i=0;i ';
}
};
this.showBoolean = function(el, oRecord, oColumn, oData)
{
var is_group = oRecord.getData("is_group");
var bChecked = oData;
bChecked = (bChecked) ? " checked" : "";
if(!is_group)
{
el.innerHTML = " ";
}
};
YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
var typeHoverHelp = ' ';
this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
{key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
{key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
{key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
{key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
{key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
this.ieDataSource = new YAHOO.util.DataSource(query);
this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
this.ieDataSource.responseSchema = {
resultsList: "account_list",
fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
};
this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
var elCheckbox = oArgs.target;
var oColumn = this.getColumn(elCheckbox);
if(oColumn.key == 'is_active')
{
var oRecord = this.getRecord(elCheckbox);
oRecord.setData("is_active",elCheckbox.checked);
var t_id = oRecord.getData('id');
var isGroupFolder = oRecord.getData('has_groupfolder');
if(isGroupFolder)
SUGAR.email2.folders.updateSubscriptions();
else
SUGAR.email2.folders.setFolderSelection();
}
});
var lastDefaultSelectedId = "";
this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
var elRadio = oArgs.target;
var oColumn = this.getColumn(elRadio);
if(oColumn.key == 'is_default')
{
var oRecord = this.getRecord(elRadio);
var t_id = oRecord.getData('id');
var t_isGroup = oRecord.getData('is_group');
if(t_id != lastDefaultSelectedId && !t_isGroup)
{
SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
lastDefaultSelectedId = t_id;
AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
}
else if(t_isGroup)
YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
}
});
this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
}
},
_setupOutboundAccountTable: function()
{
if(!this.outboundAccountsSettingsTable)
{
this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
var clckEvent = oColumn.key;
var imgSrc = "";
var isEditable = oRecord.getData("is_editable");
var type = oRecord.getData("type");
if(isEditable)
{
if(oColumn.key == 'edit')
{
clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
}
else if(oColumn.key == 'delete' && type == 'user')
{
clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
imgSrc = 'index.php?entryPoint=getImage&themeName=Sugar&imageName='+oColumn.key+'_inline.gif';
}
if(imgSrc != '')
elLiner.innerHTML = ' ';
}
};
//Custom formatter to display any error messages.
this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
SUGAR.email2.composeLayout.outboundAccountErrors = {};
var id = oRecord.getData('id');
var message = oRecord.getData("errors");
if(message != '')
{
elLiner.innerHTML = '' + message + ' ';
//Add the id and message for all outbound accounts.
SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
}
else
{
if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
}
};
YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
{key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
{key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
{key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
this.obDataSource = new YAHOO.util.DataSource(query);
this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
this.obDataSource.responseSchema = {
resultsList: "outbound_account_list",
fields: ['id','name','is_editable','mail_smtpserver','type','errors']
};
this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
}
},
/**
* Displays a modal diaglogue to edit outbound account settings
*/
showEditInboundAccountDialogue : function(clear) {
if(!this.inboundAccountEditDialog) {
var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
modal:true,
visible:true,
fixedcenter:true,
constraintoviewport: true,
width : "600px",
shadow : true
});
EAD.showEvent.subscribe(function() {
var el = this.element;
var viewH = YAHOO.util.Dom.getViewportHeight();
if (this.header && el && viewH - 50 < el.clientHeight) {
var body = this.header.nextElementSibling;
body.style.overflow = "hidden";
body.style.height = "100%";
}
}, EAD);
EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
Dom.removeClass("editAccountDialogue", "yui-hidden");
} // end lazy load
if(clear == undefined || clear == true)
{
SE.accounts.clearInboundAccountEditScreen();
//Set default protocol to IMAP when creating new records
document.forms['ieAccount'].elements['protocol'].value = "imap";
SE.accounts.setPortDefault();
}
//Check if we should display username/password fields for outbound account if errors were detected.
this.checkOutBoundSelection();
this.inboundAccountEditDialog.render();
this.inboundAccountEditDialog.show();
SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
},
/**
* Set all fields on the outbound edit form to either enabled/disabled
* except for the username/password.
*
*/
toggleOutboundAccountDisabledFields: function(disable)
{
var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
for(var i=0;iAccounts
*/
fillIeAccount:function(jsonstr) {
var o = YAHOO.lang.JSON.parse(jsonstr);
document.getElementById('ie_id').value = o.id;
document.getElementById('ie_name').value = o.name;
if (o.stored_options != null) {
document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
if (o.stored_options.trashFolder != null) {
document.getElementById('trashFolder').value = o.stored_options.trashFolder;
}
if (o.stored_options.sentFolder != null) {
document.getElementById('sentFolder').value = o.stored_options.sentFolder;
}
}
document.getElementById('server_url').value = o.server_url;
document.getElementById('email_user').value = o.email_user;
document.getElementById('port').value = o.port;
document.getElementById('group_id').value = o.group_id;
document.getElementById('mailbox').value = o.mailbox;
var i = 0;
// handle SSL
if(typeof(o.service[2]) != 'undefined') {
document.getElementById('ssl').checked = true;
}
// handle protocol
if(document.getElementById('protocol').value != o.protocol) {
var prot = document.getElementById('protocol');
for(i=0; i ";
}
if(trim(smtpServer) == '') {
isError = true;
errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + " ";
}
if(trim(smtpPort) == '') {
isError = true;
errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + " ";
}
if(mailsmtpauthreq.checked) {
if(trim(document.getElementById('mail_smtpuser').value) == '') {
isError = true;
errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + " ";
}
}
}
if(isError) {
SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
return false;
} else {
return true;
}
},
testOutboundSettings: function() {
var errorMessage = '';
var isError = false;
var fromAddress = document.getElementById("outboundtest_from_address").value;
if (trim(fromAddress) == "") {
errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + " ";
SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
return false;
}
else if (!isValidEmail(fromAddress)) {
errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + " ";
SUGAR.showMessageBox(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
return false;
}
//Hide the dialogue and show an in progress indicator.
SE.accounts.testOutboundDialog.hide();
SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
//If the outbound mail type is a system override we need to re-enable the post fields otherwise
//nothing is sent in the request.
var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
if(outboundType == 'system-override')
SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
var data = "&emailUIAction=testOutbound&outboundtest_from_address=" + fromAddress;
AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
},
testOutboundSettingsDialog: function() {
//Ensure that all settings are correct before proceeding to send test email.
if(!SE.accounts.checkOutboundSettings())
return;
// lazy load dialogue
if(!SE.accounts.testOutboundDialog) {
SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
modal:true,
visible:true,
fixedcenter:true,
constraintoviewport: true,
width : 600,
shadow : true
});
SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
Dom.removeClass("testOutboundDialog", "yui-hidden");
} // end lazy load
SE.accounts.testOutboundDialog.render();
SE.accounts.testOutboundDialog.show();
},
/**
* Saves Outbound email settings
*/
saveOutboundSettings : function() {
if(SE.accounts.checkOutboundSettings()) {
//Enable the form fields for the post.
SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
} else {
return false;
}
},
saveIeAccount : function() {
//Before saving check if there are any error messages associated with the outbound account.
var outboundID = document.getElementById('outbound_email').value;
if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
'validateSMTPCreds':true}) )
{
document.getElementById('saveButton').disabled = true;
SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
var formObject = document.getElementById('ieAccount');
YAHOO.util.Connect.setForm(formObject);
AjaxObject._reset();
AjaxObject.target = 'frameFlex';
AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
}
},
testSettings : function() {
form = document.getElementById('ieAccount');
if(SE.accounts.checkIeCreds()) {
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);
}
},
getFoldersListForInboundAccountForEmail2 : function() {
form = document.getElementById('ieAccount');
if(SE.accounts.checkIeCreds()) {
var mailBoxValue = form.mailbox.value;
if (form.searchField.value.length > 0) {
mailBoxValue = "";
} // if
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 );
} // if
},
checkIeCreds : function(validateRules) {
if(typeof(validateRules) == 'undefined')
validateRules = {};
var errors = new Array();
var out = new String();
var ie_name = Dom.get('ie_name').value;
var fromAddress = Dom.get('ie_from_addr').value;
var server_url = Dom.get('server_url').value;
var email_user = Dom.get('email_user').value;
var email_password = Dom.get('email_password').value;
var protocol = Dom.get('protocol').value;
var port = Dom.get('port').value;
var oe = Dom.get('outbound_email');
// Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
// other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
// return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
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;
var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
var outboundPass = Dom.get('inbound_mail_smtppass').value;
//If the username and password were provided then ignore the error messge
var outboundCredentialsFound = false;
if(outboundUserName != "" && outboundPass != "")
outboundCredentialsFound = true;
var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
&& validateSMTPCreds)
{
if(trim(outboundUserName) == "") {
errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
}
if(trim(outboundPass) == "") {
errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
}
}
if(trim(ie_name) == "") {
errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
}
if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
{
if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
}
}
if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
|| trim(oe_value) == "SYSTEM_ADD") ) {
errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
}
if(trim(server_url) == "") {
errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
}
if(trim(email_user) == "") {
errors.push(app_strings.LBL_EMAIL_ERROR_USER);
}
if(protocol == "") {
errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
}
if (protocol == 'imap') {
var mailbox = document.getElementById('mailbox').value;
if (trim(mailbox) == "") {
errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
} // if
if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
var trashFolder = document.getElementById('trashFolder').value;
if (trim(trashFolder) == "") {
errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
} // if
} // if
}
if(port == "") {
errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
}
if(errors.length > 0) {
out = app_strings.LBL_EMAIL_ERROR_DESC;
for(i=0; i 0) {
node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
// Add bold style to label, kinda hacky
node.labelStyle += " ygtvlabelbold";
}
else {
node.setUpLabel(node.data.origText);
}
} else {
node.setUpLabel(node.data.origText);
}
SE.accounts.setupDDTarget(node);
},
setupDDTarget : function(node) {
if (node.ddTarget) {
node.ddTarget.removeFromGroup();
delete node.ddTarget;
}
var id = node.getElId();
var num = id.substring(4);
if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
}
else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
}
},
/**
* Async call to rebuild the folder list. After a folder delete or account delete
*/
rebuildFolderList : function() {
SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
},
/**
* Returns the number of remote accounts the user has active.
*/
getAccountCount : function() {
var tree = SE.tree;
var count = 0;
for(i=0; i 1) {
alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
return;
}
var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
var folder = SE.grid.getRecord(rows[0]).getData().mbox;
/* iterate through available rows JIC a row is deleted - use first available */
var uid = SE.grid.getRecord(rows[0]).getData().uid;
SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
},
/**
*
*/
showEmailDetailViewInPopup : function(ieId,uid, folder) {
SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
},
/**
* Opens multiple messages from ListView context click
*/
openMultiple : function() {
SE.contextMenus.emailListContextMenu.hide();
var rows = SE.grid.getSelectedRows();
var uids = SE.listView.getUidsFromSelection();
if(uids.length > 0) {
var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
}
},
/**
* Replies/forwards email
*/
replyForwardEmailContext : function() {
SE.contextMenus.emailListContextMenu.hide();
var indexes = SE.grid.getSelectedRows();
//var dm = SE.grid.getDataModel();
var type = this.id;
for(var i=0; i 25) {
tabLabel = tabLabel.substring(0, 25) + "...";
} // if
targetDiv.set("label", tabLabel);
targetDiv.set("content", out);
var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
if (SUGAR.email2.util.isIe()) {
displayEmailFrameDiv.style.height = "390px";
} else {
displayEmailFrameDiv.style.height = "410px";
}
var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
displayFrame.contentWindow.document.write(email.description);
displayFrame.contentWindow.document.close();
// hide archive links
if(ret.meta.is_sugarEmail) {
document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
} else {
if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
} // else
},
consumeMetaPreview : function(ret) {
// cache contents browser-side
SE._setDetailCache(ret);
var currrow = SE.grid.getLastSelectedRecord();
currrow = SE.grid.getRecord(currrow);
if (!currrow) {
document.getElementById('_blank').innerHTML = '';
return;
}
// handling if the Email drafts
if(ret.type == 'draft'){
if (currrow.getData().uid == ret.uid) {
SE.composeLayout.c0_composeDraft();
}
return;
}
if (currrow.getData().uid != ret.meta.uid) {
return;
}
// remove loading sprite
document.getElementById('_blank').innerHTML = '';
var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
meta = ret.meta;
meta['panelId'] = SE.util.getPanelId();
email = ret.meta.email;
document.getElementById('_blank').innerHTML = displayTemplate.exec({
'app_strings' : app_strings,
'theme' : theme,
'idx' : 'Preview',
'meta' : meta,
'email' :meta.email,
'linkBeans' : linkBeans
});
// document.getElementById('_blank').innerHTML = meta.email;
/* displayTemplate.append('_blank', {
'app_strings' : app_strings,
'theme' : theme,
'idx' : 'Preview',
'meta' : meta,
'email' :meta.email,
'linkBeans' : linkBeans
});*/
var displayFrame = document.getElementById('displayEmailFramePreview');
displayFrame.contentWindow.document.write(email.description);
displayFrame.contentWindow.document.close();
SE.listViewLayout.resizePreview();
// hide archive links
if(ret.meta.is_sugarEmail) {
document.getElementById("archiveEmailPreview").innerHTML = " ";
document.getElementById("btnEmailViewPreview").style.display = "none";
document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
} else {
//hide view relationship link
document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
}
},
/**
* wraps emailDelete() for single messages, comes from preview or tab
*/
emailDeleteSingle : function(ieId, uid, mbox) {
if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
// find active panel and close if the user double clicked the email to view.
var activeTabId = SE.util.getPanelId();
if(activeTabId != 'Preview')
SE.innerLayout.get("activeTab").close();
document.getElementById('_blank').innerHTML = "";
var ser = [ ];
ser.push(uid);
uid = YAHOO.lang.JSON.stringify(ser);
this.emailDelete(ieId, uid, mbox);
}
},
/**
* Sends async call to delete a given message
* @param
*/
emailDelete : function(ieId, uid, mbox) {
SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
uid + "&ieId=" + ieId + "&folder=" + mbox);
},
/**
* retrieves one email to display in the preview pane.
*/
getEmailPreview : function() {
var row = SUGAR.email2.listView.currentRow;
var data = row.getData();
if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
var setRead = (data['seen'] == 0) ? true : false;
SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
}
},
/**
* Imports one email into Sugar
*/
importEmail : function(ieId, uid, mbox) {
SE.util.clearHiddenFieldValues('emailUIForm');
SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
AjaxObject.target = '';
AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
},
/**
* Populates the frameFlex div with the contents of an email
*/
populateDetailView : function(uid, mbox, ieId, setRead, destination) {
SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
var mboxStr = new String(mbox);
var compKey = mbox + uid;
if(setRead == true) {
SE.listView.boldUnreadRows()
SE.folders.decrementUnreadCount(ieId, mbox, 1);
}
if(destination == SE.innerLayout) {
/*
* loading email into a tab, peer with ListView
* targetDiv must remain in the global namespace as it is used by AjaxObject
*/
//Check if we already have a tab of the email open
var tabs = SE.innerLayout.get("tabs");
for (var t in tabs) {
if (tabs[t].id && tabs[t].id == uid) {
SE.innerLayout.set("activeTab", tabs[t]);
return;
}
}
targetDiv = new YAHOO.SUGAR.ClosableTab({
label: loadingSprite,
scroll : true,
content : "",
active : true
}, SE.innerLayout);
targetDiv.id = uid;
SE.innerLayout.addTab(targetDiv);
// use cache if available
if(SE.cache[compKey]) {
SE.detailView.consumeMetaDetail(SE.cache[compKey]);
} else {
// open email as peer-tab to listView
SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
// AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
}
} else {
// loading email into preview pane
document.getElementById('_blank').innerHTML = loadingSprite;
// use cache if available
if(SE.cache[compKey]) {
SE.detailView.consumeMetaPreview(SE.cache[compKey]);
} else {
AjaxObject.forceAbort = true;
// open in preview window
SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
// AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
}
}
},
requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
{
if(mboxStr.substring(0,7) == 'sugar::') {
// display an email from Sugar
document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
} else {
// display an email from an email server
document.getElementById('emailUIAction').value = 'getSingleMessage';
}
document.getElementById('mbox').value = mbox;
document.getElementById('ieId').value = ieId;
document.getElementById('uid').value = uid;
YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
AjaxObject.forceAbort = true;
AjaxObject.target = '_blank';
AjaxObject.startRequest(callback, null);
},
/**
* Retrieves multiple emails for DetailView
*/
populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
SE.util.clearHiddenFieldValues('emailUIForm');
var mboxStr = new String(mbox);
uids = SE.util.cleanUids(uids);
if(mboxStr.substring(0,7) == 'sugar::') {
// display an email from Sugar
document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
document.getElementById('uid').value = uids;
} else {
// display an email from an email server
document.getElementById('emailUIAction').value = 'getMultipleMessages';
document.getElementById('mbox').value = mbox;
document.getElementById('ieId').value = ieId;
document.getElementById('uid').value = uids;
}
var formObject = document.getElementById('emailUIForm');
YAHOO.util.Connect.setForm(formObject);
AjaxObject.target = 'frameFlex';
AjaxObject.startRequest(callbackEmailDetailMultiple, null);
if(setRead == true) {
var c = uids.split(",");
SE.folders.decrementUnreadCount(ieId, mbox, c.length);
}
},
/**
* Makes async call to get QuickCreate form
* Renders a modal edit view for a given module
*/
quickCreate : function(module, ieId, uid, mailbox) {
var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
get += "&sugarEmail=true";
}
AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
},
/**
* Makes async call to save a quick create
* @param bool
*/
saveQuickCreate : function(action) {
var qcd = SE.detailView.quickCreateDialog;
if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
var theCallback = callbackQuickCreateSave;
var accountType = '&sugarEmail=true';
if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
accountType = '&ieId=' + qcd.ieId;
}
if (action == 'reply') {
theCallback = callbackQuickCreateSaveAndReply;
} else if (action == true) {
theCallback = callbackQuickCreateSaveAndAddToAddressBook;
}
formObject.action.value = 'EmailUIAjax';
YAHOO.util.Connect.setForm(formObject);
SUGAR.showMessageBox('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
accountType + '&mbox=' + qcd.mbox);
}
},
/**
* Code to show/hide long list of email address in DetailView
*/
showCroppedEmailList : function(el) {
el.style.display = 'none';
el.previousSibling.style.display = 'inline'
},
showFullEmailList : function(el) {
el.style.display = 'none';
el.nextSibling.style.display = 'inline';
},
/**
* Shows the QuickCreate overlay
* @param string ieId
* @param string uid
* @param string mailbox
*/
showQuickCreate : function(ieId, uid, mailbox) {
var panelId = SE.util.getPanelId();
var context = document.getElementById("quickCreateSpan" + panelId);
if (!SE.detailView.cqMenus)
SE.detailView.cqMenus = {};
if (SE.detailView.cqMenus[context])
SE.detailView.cqMenus[context].destroy();
var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
lazyload:true,
context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
});
for (var i=0; i < this.qcmodules.length; i++) {
var module = this.qcmodules[i];
menu.addItem({
text: app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
modulename: module,
value: module,
onclick: { fn: function() {
SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
}
}
});
}
menu.render(document.body);
menu.show();
},
/**
* Displays the "View" submenu in the detailView
* @param string ieId
* @param string uid
* @param string mailbox
*/
showViewMenu : function(ieId, uid, mailbox) {
var panelId = SE.util.getPanelId();
var context = "btnEmailView" + panelId;
if (!SE.detailView.viewMenus)
SE.detailView.viewMenus = {};
if (SE.detailView.viewMenus[context])
SE.detailView.viewMenus[context].destroy();
var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
lazyload:true,
context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
clicktohide: true
});
menu.addItems(
(ieId == 'null' || ieId == null) ?
//No ieId - Sugar Email
[{
text: app_strings.LBL_EMAIL_VIEW_RAW,
onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
}]
:
//IeID exists, on a remote server
[{
text: app_strings.LBL_EMAIL_VIEW_HEADERS,
onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
},{
text: app_strings.LBL_EMAIL_VIEW_RAW,
onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
}]
);
menu.render(document.body);
menu.show();
/*
//#23108 jchi@07/17/2008
menu.render('quickCreateSpan'+ panelId);*/
//this.viewMenu = menu;
//this.viewMenu.show(context);
},
/**
* Makes async call to get an email's headers
*/
viewHeaders : function(ieId, uid, mailbox) {
var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
},
/**
* Makes async call to get a printable version
*/
viewPrintable : function(ieId, uid, mailbox) {
if(mailbox == 'sugar::Emails') {
// display an email from Sugar
var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
} else {
// display an email from an email server
var emailUIAction = '&emailUIAction=getSingleMessage';
}
var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
},
/**
* Makes async call to get an email's raw source
*/
viewRaw : function(ieId, uid, mailbox) {
var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
},
/**
* Display all email addresses in detailview.
*/
displayAllAddrs : function(el) {
el.style.display = 'none';
Dom.getNextSibling(el).style.display = 'inline';
}
};
//// END SE.detailView
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//// SE.folders
SE.folders = {
contextMenuFocus : new Object(),
/**
* Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
* SugarFolder ID - folder strings
*/
_createFolderId : function(node) {
var ret = '';
if(!node.data.id)
return ret;
if(node.data.ieId) {
/* we have a local Sugar folder */
if(node.data.ieId == 'folder') {
ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
} else if(node.data.ieId.match(SE.reGUID)) {
ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
}
} else {
ret = node.data.id;
}
return ret;
},
addChildNode : function(parentNode, childNode) {
var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
if(childNode.nodes) {
if(childNode.nodes.length > 0) {
for(j=0; j " + app_strings.LBL_EMAIL_CHECKING_DESC + " ");
}
AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
} else {
// wait 5 secs before trying again.
SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
}
},
/**
* Starts check of all email Accounts using a loading bar for large POP accounts
*/
startEmailAccountCheck : function() {
// don't do two checks at the same time
if(!AjaxObject.requestInProgress()) {
SUGAR.showMessageBox(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
SE.accounts.ieIds = SE.folders.getIeIds();
if (SE.accounts.ieIds.length > 0) {
AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
'&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "¤tCount=0");
} else {
SUGAR.hideMessageBox();
}
} else {
// wait 5 secs before trying again.
SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
}
},
/**
* Checks a single Account check based on passed ieId
*/
startEmailCheckOneAccount : function(ieId, synch) {
if (synch) {
synch = true;
} else {
synch = false;
}
var mbox = "";
var node = SE.clickedFolderNode;
if (node && !synch) {
mbox = node.data.mbox;
} // if
SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
SE.accounts.ieIds = [ieId];
AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
'&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "¤tCount=0&synch=" + synch);
},
/**
* Empties trash for subscribed accounts
*/
emptyTrash : function() {
SE.contextMenus.frameFoldersContextMenu.hide();
SUGAR.showMessageBox(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
},
/**
* Clears Cache files of the inboundemail account
*/
clearCacheFiles : function(ieId) {
SE.contextMenus.frameFoldersContextMenu.hide();
SUGAR.showMessageBox(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
},
/**
* Returns an array of all the active accounts in the folder view
*/
getIeIds : function() {
var ieIds = [];
var root = SE.tree.getRoot();
for(i=0; i < root.children.length; i++) {
if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
(root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
ieIds.push(root.children[i].children[0].data.ieId);
}
}
return ieIds;
},
/**
* loads folder lists in Settings->Folders
*/
lazyLoadSettings : function() {
AjaxObject.timeout = 300000; // 5 min timeout for long checks
AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
},
/**
* After the add new folder is done via folders tab on seetings, this function should get called
* It will refresh the folder list after inserting an entry on the UI to update the new folder list
*/
loadSettingFolder : function() {
AjaxObject.timeout = 300000; // 5 min timeout for long checks
AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
},
/**
* Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
*/
removeSugarFolders : function() {
var tree = SE.tree;
var root = tree.getRoot();
var folder = SE.util.findChildNode(root, "ieId", "folder");
while(folder) {
tree.removeNode(folder);
folder = SE.util.findChildNode(root, "ieId", "folder");
}
if (!root.childrenRendered) {
root.childrenRendered = true;
}
},
rebuildFolders : function(silent) {
if (!silent) SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
},
/**
* Updates TreeView with Sugar Folders
*/
setSugarFolders : function(delay) {
this.removeSugarFolders();
//AjaxObject.forceAbort = true;
AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
},
/**
* Takes async data object and creates the sugar folders in TreeView
*/
setSugarFoldersEnd : function(o) {
var root = SE.tree.getRoot();
addChildNodes(root, {nodes: o});
SE.accounts.renderTree();
//If nothing is loaded in the grid, load "My Inbox"
if (SE.grid.params.ieId == "undefined") {
SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
}
},
startCheckTimer : function() {
if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
if(typeof(SE.folders.checkTimer) != 'undefined') {
clearTimeout(SE.folders.checkTimer);
}
SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
if (!SE.userPrefs.emailSettings.firstAutoCheck)
{
SE.userPrefs.emailSettings.firstAutoCheck = true;
SE.folders.checkEmailAccountsSilent(false);
}
}
},
/**
* makes an async call to save user preference and refresh folder view
* @param object SELECT list object
*/
setFolderSelection : function() {
SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
var a_active_accnts = "";
for(i=0;i 0) {
var check = unseen - count;
var finalCount = (check >= 0) ? check : 0;
node.data.unseen = finalCount;
}
SE.accounts.renderTree();
}
},
/**
* gets the TreeView node with a given ID/ieId
* @param string id ID to look for
* @return object Node
*/
getNodeFromId : function(id) {
SE.folders.focusNode = null;
SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
SE.folders.focusNode = this;
return false;
}
}, null, [id]);
return SE.folders.focusNode;
},
/**
* Uses ieId and mailbox to try to find a node in the tree
*/
getNodeFromIeIdAndMailbox : function(id, mbox) {
SE.folders.focusNode = null;
if (mbox == "sugar::Emails") {
mbox = id;
id = "folder";
} // if
SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
if (varsarray instanceof Array) {
if (this.data.ieId && this.data.ieId == varsarray[0]
&& this.data.mbox == varsarray[1]) {
SE.folders.focusNode = this;
return false;
} }
else {
if (this.data.ieId && this.data.ieId == varsarray) {
SE.folders.focusNode = this;
return false;
}
}
}, null, [id, mbox]);
return SE.folders.focusNode;
},
unhighliteAll : function() {
SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
},
/**
* Displays a short form
*/
folderAdd : function() {
SE.contextMenus.frameFoldersContextMenu.hide();
var node = SE.clickedFolderNode;
if(node != null && node.data) {
SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
app_strings.LBL_EMAIL_SETTINGS_NAME,
'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
} else {
alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
}
},
folderAddRegisterEnter : function() {
this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
{keys: YAHOO.util.KeyListener.KEY.ENTER},
this.buttons[1].handler);
this.enterKeyListener.enable();
},
folderRemoveRegisterEnter : function() {
this.enterKeyListener.disable();
},
folderAddXmlCall : function(name) {
if (trim(name) == "") {
alert(mod_strings.LBL_ENTER_FOLDER_NAME);
return false;
}
name = escape(name);
var post = '';
var type = 'sugar';
var parentNode = SE.clickedFolderNode;
this.contextMenuFocus = parentNode;
if(parentNode.data.ieId) {
if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
type = 'imap';
}
}
if(type == 'imap') {
// make an IMAP folder
post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
} else if(type == 'sugar') {
// make a Sugar folder
if(SE.folders.isUniqueFolderName(name)) {
post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
} else {
alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
SE.folders.folderAdd();
return;
}
} else {
alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
}
// hide add-folder diaglogue
SE.e2overlay.hide();
},
/**
* Removes either an IMAP folder or a Sugar Folder
*/
folderDelete : function() {
SE.contextMenus.frameFoldersContextMenu.hide();
if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
var post = '';
var parentNode = SE.clickedFolderNode;
if(parentNode != null && parentNode.data) {
if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
return;
}
AjaxObject.target = 'frameFlex';
if(parentNode.data.ieId != 'folder') {
// delete an IMAP folder
post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
} else {
// delete a sugar folder
post = "&folderType=sugar&folder_id=" + parentNode.data.id;
}
SUGAR.showMessageBox("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
} else {
alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
}
}
},
/**
* Rename folder form
*/
//EXT111
folderRename : function() {
SE.contextMenus.frameFoldersContextMenu.hide();
var node = SE.clickedFolderNode;
if(node != null) {
if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
return;
}
SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
app_strings.LBL_EMAIL_SETTINGS_NAME,
'prompt',
{fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
} else {
alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
}
},
/**
* fills an Object with key-value pairs of available folders
*/
getAvailableFoldersObject : function() {
var ret = new Object();
var tree = SE.tree.root;
if(tree.children) {
for(var i=0; i 0) {
/* handle visual separtors differentiating b/t mailserver and local */
if(node.data.ieId && node.data.ieId == 'folder') {
spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
}
if(!ret.spacer0) {
ret['spacer0'] = spacer;
} else if(ret.spacer0 != spacer) {
ret['spacer1'] = spacer
}
var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
var depthMarker = currentPath;
var retIndex = SE.folders._createFolderId(node);
ret[retIndex] = depthMarker + theLabel;
}
if(node.children != null) {
if(theLabel) {
currentPath += theLabel + "/";
}
for(var i=0; i " + app_strings.LBL_EMAIL_COFFEE_BREAK);
AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
}
},
/**
* Updates user's folder subscriptsion (Sugar only)
* @param object SELECT DOM object in focus
* @param string type of Folder selection
*/
updateSubscriptions : function() {
SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
var active = "";
select = document.getElementById('userFolders');
for(i=0; i 0){
var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
if (node) node.data.unseen = unread;
}
SE.accounts.renderTree();
// bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
if(forcePreview && ds.totalCount > 0) {
SE.detailView.getEmailPreview();
forcePreview = false;
}
},
/**
* Removes a row if found via its UID
*/
removeRowByUid : function(uid) {
uid = new String(uid);
uids = uid.split(',');
var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
for(j=0; j 0) {
SE.listView.displaySelectedEmails(rows);
}
break;
default:
var targetElId = new String(targetId);
var targetIndex = targetElId.replace('ygtvlabelel',"");
var targetNode = SE.tree.getNodeByIndex(targetIndex);
var dm = SE.grid.getDataModel();
var emailUids = new Array();
var destinationIeId = targetNode.data.ieId;
var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
var rows = SE.grid.getSelectedRows();
// iterate through dragged rows
for(i=0; i ');
dlg.beforeRenderEvent.subscribe(function() {
var dd = new YAHOO.util.DDProxy(dlg.element);
dd.setHandleElId(dlg.header);
dd.on('endDragEvent', function() {
dlg.show();
});
}, dlg, true);
dlg.render();
var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
var tabContent = Dom.get("tab_general");
tp.addTab(new YAHOO.widget.Tab({
label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
scroll : true,
content : tabContent.innerHTML,
id : "generalSettings",
active : true
}));
tabContent.parentNode.removeChild(tabContent);
tabContent = Dom.get("tab_accounts");
var accountTab = new YAHOO.widget.Tab({
label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
scroll : true,
content : tabContent.innerHTML,
id : "accountSettings"
});
tp.addTab(accountTab);
tabContent.parentNode.removeChild(tabContent);
tp.appendTo(dlg.body);
}
SE.settings.settingsDialog.show();
SE.folders.lazyLoadSettings();
SE.accounts.lazyLoad();
},
lazyLoadRules : function() {
if(false/*!SE.settings.rules*/) {
AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
}
}
};
//// END SE.settings
///////////////////////////////////////////////////////////////////////////////
})();
/******************************************************************************
* UTILITIES
*****************************************************************************/
function removeHiddenNodes(nodes, grid) {
var el;
for(var i = nodes.length - 1; i > -1; i--) {
el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
nodes.splice(i,1);
}
}
}
function strpad(val) {
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
};
function refreshTodos() {
SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
AjaxObject.target = 'todo';
AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
};
/******************************************************************************
* MUST STAY IN GLOBAL NAMESPACE
*****************************************************************************/
function refresh_signature_list(signature_id, signature_name) {
var field=document.getElementById('signature_id');
var bfound=0;
for (var i=0; i < field.options.length; i++) {
if (field.options[i].value == signature_id) {
if (field.options[i].selected==false) {
field.options[i].selected=true;
}
bfound=1;
}
}
//add item to selection list.
if (bfound == 0) {
var newElement=document.createElement('option');
newElement.text=signature_name;
newElement.value=signature_id;
field.options.add(newElement);
newElement.selected=true;
}
//enable the edit button.
var field1=document.getElementById('edit_sig');
field1.style.visibility="inherit";
var deleteButt = document.getElementById('delete_sig');
deleteButt.style.visibility="inherit";
};
function setDefaultSigId(id) {
var checkbox = document.getElementById("signature_default");
var default_sig = document.getElementById("signatureDefault");
if(checkbox.checked) {
default_sig.value = id;
} else {
default_sig.value = "";
}
};
function setSigEditButtonVisibility() {
var field = document.getElementById('signature_id');
var editButt = document.getElementById('edit_sig');
var deleteButt = document.getElementById('delete_sig');
if(field.value != '') {
editButt.style.visibility = "inherit";
deleteButt.style.visibility = "inherit";
} else {
editButt.style.visibility = "hidden";
deleteButt.style.visibility = "hidden";
}
}// End of File modules/Emails/javascript/EmailUI.js
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
(function() {
var sw = YAHOO.SUGAR,
Event = YAHOO.util.Event,
Connect = YAHOO.util.Connect,
Dom = YAHOO.util.Dom
SE = SUGAR.email2;
///////////////////////////////////////////////////////////////////////////////
//// ADDRESS BOOK
SE.addressBook = {
_contactCache : new Array(), // cache of contacts
_dd : new Array(), // filtered list, same format as _contactCache
_ddLists : new Array(), // list of Lists
_dd_mlUsed : new Array(), // contacts in mailing list edit view column1
_dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
clickBubble : true, // hack to get around onclick event bubbling
relatedBeanId : '',
relatedBeanType : '',
idx : 0,
itemSpacing : 'white-space:nowrap; padding:2px;',
reGUID : SE.reGUID,
/**
* YUI bug fix 2527707. Causes nested datatable's in to cause 404 errors whens earching.
*/
initFixForDatatableSort: function () {
//Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
YAHOO.widget.DataTable.prototype.getColumn = function(column) {
var oColumn = this._oColumnSet.getColumn(column);
if(!oColumn) {
// Validate TD element
var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
if(elCell) {
oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
}
// Validate TH element
else {
elCell = this.getThEl(column);
if(elCell) {
// Find by TH el ID
var allColumns = this._oColumnSet.flat;
for(var i=0, len=allColumns.length; i 0) {
SE.composeLayout.handleDrop(
(type == 'contacts') ? SE.contactView : SE.emailListsView,
null, rows, 'addressTO' + idx );
} else {
alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
}
},
editContact : function() {
SE.contextMenus.contactsContextMenu.hide();
var element = SE.contactView.getSelectedNodes()[0];
var elementId = "";
if (element.className.indexOf('address-contact') > -1) {
elementId = element.id;
} else if (element.className.indexOf('address-exp-contact') > -1) {
elementId = element.id.substring(2);
}
},
/**
* Filters contact entries based on user input
*/
filter : function(inputEl) {
var ret = new Object();
var re = new RegExp(inputEl.value, "gi");
for(var i in this._contactCache) {
if(this._contactCache[i].name.match(re)) {
ret[i] = this._contactCache[i];
}
}
this.buildContactList(ret);
},
fullForm : function(id, module) {
document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
},
/**
* returns a formatted email address from the addressBook cache
*/
getFormattedAddress : function(id) {
var o = this._contactCache[id];
var primaryEmail = '';
for(var i=0; i]+)>)/ig, "").replace(/'/gi,'\'');
var ret = finalName + " <" + finalEmail.replace(/'/gi,'\'') + ">";
return ret;
},
/**
* Sets up async call to query for matching contacts, users, etc.
*/
searchContacts : function() {
var fn = document.getElementById('input_searchField').value;
var pe = document.getElementById('input_searchPerson').value;
var rb = document.getElementById('hasRelatedBean').checked;
if (rb) {
var idx = this.idx;
var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
} else {
this.addressBookDataModel.params['related_bean_id'] = '';
}
this.addressBookDataModel.params['search_field'] = fn;
this.addressBookDataModel.params['person'] = pe;
this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
this.grid._oDataSource = this.addressBookDataModel;
this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params), this.grid.onDataReturnInitializeTable, this.grid);
},
/**
* Clear Search Crieteria For Addressbook
*/
clearAddressBookSearch : function() {
document.getElementById('input_searchField').value = "";
document.getElementById('input_searchPerson').selectedIndex = 0;
},
/**
* Opens modal select window to add contacts to addressbook
*/
selectContactsDialogue : function(destId) {
if(!this.contactsDialogue) {
var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
modal:true,
visible:false,
draggable: false,
constraintoviewport: true,
width : 980,
buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
});
dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
dlg.setBody(body.innerHTML);
dlg.renderEvent.subscribe(function() {
var iev = YAHOO.util.Dom.get("contactsDialogueBody");
if (iev && !SUGAR.isIE) {
this.body.style.width = "950px";
}
}, dlg);
dlg.beforeRenderEvent.subscribe(function() {
var dd = new YAHOO.util.DDProxy(dlg.element);
dd.setHandleElId(dlg.header);
dd.on('endDragEvent', function() {
dlg.show();
});
}, dlg, true);
dlg.render();
var tp = new YAHOO.widget.TabView("contactsSearchTabs");
var tabContent = SUGAR.util.getAndRemove("searchForm");
tp.addTab(new YAHOO.widget.Tab({
label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
scroll : true,
content : tabContent.innerHTML,
id : "addressSearchTab",
active : true
}));
var addListenerFields = ['input_searchPerson','input_searchField' ]
YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
if (e.keyCode == 13) {
YAHOO.util.Event.stopEvent(e);
SUGAR.email2.addressBook.searchContacts();
}
});
this.contactsDialogue.render();
dlg.center();
}
//Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
if (typeof(SUGAR.email2.innerLayout) == 'undefined')
var idx = 0;
else
{
var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
var idx = activePanel.substring(10);
}
SE.addressBook.idx = idx;
var relatedBeanId;
if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
document.getElementById('relatedBeanColumn').style.display = '';
var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
relatedBeanId = document.getElementById('data_parent_id' + idx).value;
document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' ' + relatedBeanName + ' ';
SE.addressBook.relatedBeanType = relatedBeanType;
} else {
document.getElementById('relatedBeanColumn').style.display = 'none';
document.getElementById('hasRelatedBean').checked = false;
}
if (!SE.addressBook.grid)
{
if (hasRelatedBeanId) {
document.getElementById('hasRelatedBean').checked = true;
}
AddressSearchGridInit();
SE.addressBook.relatedBeanId = relatedBeanId;
}
else
{
if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
{
SE.addressBook.relatedBeanId = relatedBeanId;
document.getElementById('hasRelatedBean').checked = true;
}
if (document.getElementById('hasRelatedBean').checked == true)
{
SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
} else {
SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
}
SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params), SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
}
//Remove any lingering rows in the result set table if the module was closed.
SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
//Repopulate
SE.addressBook.populateResulstTableEmailAddresses();
this.contactsDialogue.show();
},
/**
* Clear all email addresses from result table.
*
*/
clearAllEmailAddressFieldsFromResultTable: function () {
SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
//Unhighlight any rows currently selected if the emails were cleared.
SUGAR.email2.addressBook.grid.toggleSelectAll(false);
SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
},
/**
* Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
* results table. This function is called when the address book is displayed.
*/
populateResulstTableEmailAddresses: function () {
var idx = SE.addressBook.idx;
var emailFields = ['to','cc','bcc'];
for(var k=0;k';
if(t_name == '')
t_name = displayEmail = t_emailAddr;
var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
}
}
},
/**
* Checks all entries in the result table against a particular email address, returning true
* if the email address is found, false otherwise.
*/
doesEmailAdddressExistInResultTable: function(emailAddress)
{
if(trim(emailAddress) == '')
return false;
var emailAddressFound = false;
var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
for (var i=0; i < contacts.length; i++)
{
var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
//If we are adding to cc or bcc fields, make them visible.
if(data.email_address == emailAddress)
{
emailAddressFound = true;
break;
}
}
return emailAddressFound;
},
/**
* Takes all email addresses that the users wishes to add from the address book and populates the To
* fields on the compose tab.
*/
populateEmailAddressFieldsFromResultTable: function()
{
//Clear the fields first, all email addresses are stored in the address book
var idx = SE.addressBook.idx;
var emailFields = ['to','cc','bcc'];
for(var k=0;k';
if(addressType == null)
addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
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});
},
/**
* Remove a row from the gridsResult table.
*/
removeRowFromGridResults : function(rowId,emailAddress)
{
var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
for (var i=0; i < contacts.length; i++)
{
var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
var data = rec.getData();
if(data.email_address == emailAddress)
{
SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
break;
}
}
SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
},
/**
* Translates between the addressType To|Cc|Bcc labels/keys.
*/
translateAddresType: function(addressType,fromKey)
{
var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
var mappingObject = {};
if(fromKey)
mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
else
{
mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
mappingObject[displayCc] = 'cc';
mappingObject[displayBcc] = 'bcc';
}
return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
},
/**
*
*/
toggleSearchRowIcon : function(rowId,show)
{
if(show)
{
var idToShow = rowId + '_add_img';
var idToHide = rowId + '_rm_img';
}
else
{
var idToShow = rowId + '_rm_img';
var idToHide = rowId + '_add_img';
}
Dom.addClass(idToHide, "yui-hidden");
Dom.removeClass(idToShow, "yui-hidden");
},
/**
* Determine if an entry has already been added to the grid results table to prevent duplicates.
*/
doesGridResultsEntryExist: function(emailAddrs)
{
var contactExists = false;
var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
for (var i=0; i < contacts.length; i++)
{
var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
if(data.email_address == emailAddrs)
{
contactExists = true;
break;
}
}
return contactExists;
},
/**
* adds an email address to a string, but first checks if it exists
* @param string concat The string we are appending email addresses to
* @param string addr Email address to add
* @return string
*/
smartAddEmailAddressToComposeField : function(concat, addr) {
var re = new RegExp(addr);
if(!concat.match(re)) {
if(concat != "") {
concat += "; " + addr;
} else {
concat = addr;
}
}
return concat;
}
};
//// END ADDRESS BOOK
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//// AUTOCOMPLETE
/**
* Auto-complete object
*/
SE.autoComplete = {
config : {
delimChar : [";", ","],
useShadow : false,
useIFrame : false,
typeAhead : true,
prehighlightClassName : "yui-ac-prehighlight",
queryDelay : 0
},
instances : new Array(),
/**
* Parses an addressBook entry looking for primary address. If not found, it will return the last found address.
* @param object Contact from AddressBook
* @return string
*/
getPrimaryAddress : function(contact) {
var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
for(var eIndex in contact.email) {
address = contact.email[eIndex].email_address;
if(contact.email[eIndex].primary_address == 1) {
return contact.email[eIndex].email_address;
}
}
return address;
},
/**
* initializes autocomplete widgets for a given compose view
* @param int idx
*/
init : function(idx) {
var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
"queryMatchContains" : false,
"queryMatchSubset" : true
});
this.instances[idx] = {
to : null,
cc : null,
bcc : null
};
// instantiate the autoComplete widgets
this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
// enable hiding of interfering textareas
this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
// enable reshowing of hidden textareas
this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
// enable refreshes of contact lists
this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
},
refreshDataSource : function(sType, aArgs) {
var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
var idx;
var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
idx = textBoxId.substr(9);
} else {
idx = textBoxId.substr(10);
}
SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
},
/**
* Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
*/
returnDataSource : function(contacts) {
var ret = new Array();
for(var id in contacts) {
if (contacts[id].name) {
var primary = this.getPrimaryAddress(contacts[id]);
ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
//ret[ret.length] = contacts[id].name + " <" + primary + ">";
for(var emailIndex in contacts[id].email) {
ret[ret.length] = contacts[id].email[emailIndex].email_address;
}
}
}
return ret;
},
/**
* Hides address textareas to prevent autocomplete dropdown from being obscured
*/
toggleTextareaHide : function(sType, aArgs) {
var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
var type = "";
var idx = -1;
if(textBoxId.indexOf("addressTO") > -1) {
type = "to";
} else if(textBoxId.indexOf("addressCC") > -1) {
type = "cc";
}
idx = textBoxId.substr(9);
// follow through if not BCC
if(type != "") {
var cc = document.getElementById("addressCC" + idx);
var bcc = document.getElementById("addressBCC" + idx);
switch(type) {
case "to":
cc.style.visibility = 'hidden';
case "cc":
bcc.style.visibility = 'hidden';
break;
}
}
},
/**
* Redisplays the textareas after an address is commited
*/
toggleTextareaShow : function(sType, aArgs) {
var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
var type = "";
var idx = -1;
if(textBoxId.indexOf("addressTO") > -1) {
type = "to";
} else if(textBoxId.indexOf("addressCC") > -1) {
type = "cc";
}
idx = textBoxId.substr(9);
// follow through if not BCC
if(type != "") {
document.getElementById("addressCC" + idx).style.visibility = 'visible';
document.getElementById("addressBCC" + idx).style.visibility = 'visible';
}
}
};
//// END AUTOCOMPLETE
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//// COMPOSE & SEND
/**
* expands the options sidebar
*/
SE.composeLayout = {
currentInstanceId : 0,
ccHidden : true,
bccHidden : true,
outboundAccountErrors : null,
loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
showAddressDetails : function(e) {
var linkElement = document.getElementById("More"+e.id);
var spanElement = document.getElementById("Detail"+e.id);
var emailAddressList = e.value;
if(e.value.length > 96)
{
var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
var displayArray = [];
for (var i=0; i <' + t_emailAddr + '>');
else
displayArray.push(t_name + ' <' + t_emailAddr + '>');
}
var result = displayArray.join(' ');
// Display
linkElement.style.display = "inline";
linkElement.style.height="10px";
linkElement.style.overflow="visible";
spanElement.innerHTML = result;
}
else
linkElement.style.display = "none";
},
/**
* Given a string of email address, return an array containing the name portion (if available)
* and email portion.
*/
_getEmailArrayFromString : function (emailAddressList){
var reg = /@.*?;/g;
while ((results = reg.exec(emailAddressList)) != null)
{
orignial = results[0];
parsedResult = results[0].replace(';', ':::::');
emailAddressList = emailAddressList.replace (orignial, parsedResult);
}
reg = /@.*?,/g;
while ((results = reg.exec(emailAddressList)) != null)
{
orignial = results[0];
parsedResult = results[0].replace(',', ':::::');
emailAddressList = emailAddressList.replace (orignial, parsedResult);
}
//Administrator ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
var emailArr = emailAddressList.split(":::::");
var resultsArray = [];
var newArr = [];
for (var i=0; i');
if(trim(emailArr[i]) != '')
{
if(rposition != -1 && lposition != -1)
{
var t_name = emailArr[i].substr(0, rposition-1);
var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
}
else
{
resultsArray.push({'name':'', 'email_address': emailArr[i]});
}
}
}
return resultsArray;
},
///////////////////////////////////////////////////////////////////////////
//// COMPOSE FLOW
/**
* Prepare bucket DIV and yui-ext tab panels
*/
_0_yui : function() {
var idx = this.currentInstanceId;
var composeTab = new YAHOO.SUGAR.ClosableTab({
label: mod_strings.LNK_NEW_SEND_EMAIL,
scroll : true,
content : "
",
id : "composeTab" + idx,
closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
active : true
}, SE.innerLayout);
SE.innerLayout.addTab(composeTab);
// get template engine with template
if (!SE.composeLayout.composeTemplate) {
SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
}
// create Tab inner layout
var composePanel = this.getComposeLayout();
composePanel.getUnitByPosition("right").collapse();
composePanel.autoSize();
},
/**
* Generate the quick compose layout
* @method getQuickComposeLayout
* @param {Pannel} parentPanel Parent pannel
* @param {Object} o Options
* @return {} none
**/
getQuickComposeLayout : function (parentPanel,o) {
var idx = SE.composeLayout.currentInstanceId;
//Before rendering the parent pannel we need to initalize the grid layout
parentPanel.beforeRenderEvent.subscribe(function() {
YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
SE.composeLayout._createComposeLayout(idx);
SE.composeLayout[idx].set('height', 350);
SE.composeLayout[idx].render();
});
});
//Wait until the Compose Layout has rendered, then add the
//options tab and perform the tiny initialization.
parentPanel.renderEvent.subscribe(function() {
YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
SE.composeLayout._initComposeOptionTabs(idx);
SE.composeLayout[idx].getUnitByPosition("right").collapse();
//Initialize tinyMCE
SE.composeLayout._1_tiny(false);
//Init templates and address book
SE.composeLayout._2_final();
SE.composeLayout.quickCreateComposePackage(o);
});
});
//Check if we have the div override for the shortcut bar
if(typeof o.menu_id != 'undefined') {
parentPanel.render(o.menu_id);
} else {
parentPanel.render(document.body);
}
return SE.composeLayout[idx];
},
/**
* Fill in all fields into the quick compose layout.
* @method quickCreateComposePackage
* @param {Object} o Options
* @return {} none
**/
quickCreateComposePackage: function(o)
{
//If we have a compose package fill in defaults.
if (typeof(o.composePackage) != 'undefined')
{
composePackage = o.composePackage; //Set the compose data object
//Hijack this method called by composePackage as it's not need for quick creates.
SE.composeLayout.c0_composeNewEmail = function(){};
SE.composeLayout.composePackage(); //Fill in defaults.
}
},
getComposeLayout : function() {
var idx = SE.composeLayout.currentInstanceId;
this._createComposeLayout(idx);
SE.composeLayout[idx].render();
this._initComposeOptionTabs(idx);
return SE.composeLayout[idx];
},
/**
* Create the layout manager for the compose window.
*/
_createComposeLayout : function(idx)
{
SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
parent: SE.complexLayout,
border:true,
hideOnLayout: true,
height: 400,
units: [{
position: "center",
animate: false,
scroll: false,
split:true,
body:
SE.composeLayout.composeTemplate.exec({
'app_strings':app_strings,
'mod_strings':mod_strings,
'linkbeans_options' : linkBeans,
'idx' : SE.composeLayout.currentInstanceId
})
},{
position: "right",
scroll:true,
collapse: true,
collapsed: true,
resize: true,
border:true,
animate: false,
width:'230',
body: "
",
titlebar: true,
split: true,
header: app_strings.LBL_EMAIL_OPTIONS
}]
});
},
/**
* Create compose tab which will populate the 'right' container in the compose window.
*/
_initComposeOptionTabs : function(idx)
{
var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
var tab = new YAHOO.widget.Tab({
label: app_strings.LBL_EMAIL_ATTACHMENT,
scroll : true,
content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
id : "divAttachments" + idx,
active : true
});
tab.layout = SE.composeLayout[idx];
tab.on("activeChange", function(o){
if (o.newValue) {
this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
}
});
cTabs.addTab(tab);
tab = new YAHOO.widget.Tab({
label: app_strings.LBL_EMAIL_OPTIONS,
scroll : true,
content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
id : "divOptions" + idx,
active : false
});
tab.layout = SE.composeLayout[idx];
tab.on("activeChange", function(o){
if (o.newValue) {
this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
}
});
cTabs.addTab(tab);
SE.composeLayout[idx].autoSize = function() {
var pEl = this.get("element").parentNode.parentNode.parentNode;
this.set("height", pEl.clientHeight-30);
this.render();
}
SE.composeLayout[idx].rightTabs = cTabs;
},
isParentTypeValid : function(idx) {
var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
var parentNameValue = document.getElementById('data_parent_name' + idx).value;
if (trim(parentTypeValue) == ""){
alert(mod_strings.LBL_ERROR_SELECT_MODULE);
return false;
} // if
return true;
},
isParentTypeAndNameValid : function(idx) {
var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
var parentNameValue = document.getElementById('data_parent_name' + idx).value;
var parentIdValue = document.getElementById('data_parent_id' + idx).value;
if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
(trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
return false;
} // if
return true;
},
callopenpopupForEmail2 : function(idx,options) {
var formName = 'emailCompose' + idx;
if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
formName = options.form_name;
var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
var parentNameValue = document.getElementById('data_parent_name' + idx).value;
if (!SE.composeLayout.isParentTypeValid(idx)) {
return;
} // if
open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
{
call_back_function:"SE.composeLayout.popupAddEmail",
form_name:formName,
field_to_name_array:{
id:'data_parent_id' + idx,
name:'data_parent_name' + idx,
email1:'email1'}
});
},
popupAddEmail : function(o)
{
var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
var data = o.name_to_value_array;
if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
&& typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
{
var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
}
set_return(o);
},
/**
* Prepare TinyMCE
*/
_1_tiny : function(isReplyForward) {
var idx = SE.composeLayout.currentInstanceId;
var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
SE.tinyInstances[elId] = { };
SE.tinyInstances[elId].ready = false;
if (!SUGAR.util.isTouchScreen()) {
var t = tinyMCE.getInstanceById(elId);
}
if(typeof(t) == 'undefined') {
if (!SUGAR.util.isTouchScreen()) {
tinyMCE.execCommand('mceAddControl', false, elId);
}
YAHOO.util.Event.onAvailable(elId + "_parent", function() {
SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
}, this);
}
},
resizeEditorSetSignature : function(idx,setSignature)
{
var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+setSignature+"');",500);
return;
}
SE.composeLayout.resizeEditor(idx);
if(setSignature) {
setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
}
},
resizeEditor : function(idx)
{
var cof = Dom.get('composeOverFrame' + idx);
var head = Dom.get('composeHeaderTable' + idx);
var targetHeight = cof.clientHeight - head.clientHeight;
var instance = SE.util.getTiny('htmleditor' + idx);
try {
var parentEl = Dom.get(instance.editorId + '_parent');
var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
var contentEl = instance.contentAreaContainer;
var iFrame = contentEl.firstChild;
var tinMceToolbarOffset = 18;
iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset) + "px";
} catch(e) {
setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
}
},
/**
* Initializes d&d, auto-complete, email templates
*/
_2_final : function() {
var idx = SE.composeLayout.currentInstanceId;
if(this.emailTemplates) {
this.setComposeOptions(idx);
} else {
//populate email template cache
AjaxObject.target = '';
AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
}
// handle drop targets for addressBook
var to = new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
var cc = new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
// auto-complete setup
SE.autoComplete.init(idx);
// set focus on to:
document.getElementById("addressTO" + idx).focus();
},
/**
* hide tinyMCE tool bar if send email as plaintext is checked
*/
renderTinyMCEToolBar : function (idx, hide) {
if (hide) {
document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
} else {
document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
}
},
c1_composeEmail : function(isReplyForward, retry) {
if (!retry) {
this._0_yui();
}
if (!SUGAR.util.isTouchScreen() && (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined')){
setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
} else {
this._1_tiny(isReplyForward);
this._2_final();
if(isReplyForward) {
this.replyForwardEmailStage2();
}
}
},
/**
* takes draft info and prepopulates
*/
c0_composeDraft : function() {
this.getNewInstanceId();
inCompose = true;
document.getElementById('_blank').innerHTML = '';
var idx = SE.composeLayout.currentInstanceId;
SE.composeLayout.draftObject = new Object();
SE.composeLayout.draftObject.id = idx;
SE.composeLayout.draftObject.isDraft = true;
SE.composeLayout.currentInstanceId = idx;
SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
SE.composeLayout._0_yui();
SE.composeLayout._1_tiny(true);
// final touches
SE.composeLayout._2_final();
/* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
},
/**
* Strip & Prep editor hidden fields
*/
c0_composeNewEmail : function() {
this.getNewInstanceId();
this.c1_composeEmail(false);
},
/**
* Sends async request to get the compose view.
* Requests come from "reply" or "forwards"
*/
c0_replyForwardEmail : function(ieId, uid, mbox, type) {
SE.composeLayout.replyForwardObj = new Object();
SE.composeLayout.replyForwardObj.ieId = ieId;
SE.composeLayout.replyForwardObj.uid = uid;
SE.composeLayout.replyForwardObj.mbox = mbox;
SE.composeLayout.replyForwardObj.type = type;
if(mbox == 'sugar::Emails') {
SE.composeLayout.replyForwardObj.sugarEmail = true;
}
SE.composeLayout.getNewInstanceId();
SE.composeLayout.c1_composeEmail(true);
},
//// END COMPOSE FLOW
///////////////////////////////////////////////////////////////////////////
/**
* Called when a contact, email, or mailinglist is dropped
* into one of the compose fields.
*/
handleDrop : function (source, event, data, target) {
var nodes;
if (!target) {
target = event.getTarget();
if (data.single) {
data.nodes = [data.nodes];
}
nodes = data.nodes;
} else {
target = document.getElementById(target);
nodes = data;
}
if (target.id.indexOf('address') > -1) {
// dropped onto email to/cc/bcc field
for(var i in nodes) {
var node = nodes[i].getData();
var email = "";
if (node[1].indexOf('contact') > -1) {
email = SE.addressBook.getFormattedAddress(node[0]);
} else if (node[1].indexOf('address-email') > -1){
email = node[3].replace(/ /gi, '');
email = email.replace('<', '<').replace('>', '>');
var tr = source.getTrEl(nodes[i]);
while (tr && !Dom.hasClass(tr, "address-contact")) {
tr = source.getPreviousTrEl(tr);
}
var CID = source.getRecord(tr).getData()[0];
var o = SE.addressBook._contactCache[CID];
var name = new String(o.name);
var finalName = name.replace(/(<([^>]+)>)/ig, "");
email = finalName + email;
}
target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
}
}
},
/*/////////////////////////////////////////////////////////////////////////////
/// EMAIL TEMPLATE CODE
*/
applyEmailTemplate : function (idx, id) {
//bug #20680
var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
//bug #6224
var to_addr = document.getElementById('addressTO'+idx);
if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
{
box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + ' ' + box_msg;
}
// id is selected index of email template drop-down
if(id == '' || id == "0") {
YAHOO.SUGAR.MessageBox.show({
title:box_title,
msg: box_none_msg,
type: 'confirm',
fn: function(btn){
if(btn=='no'){return;};
SUGAR.email2.composeLayout.processNoneResult(idx, id);},
modal:true,
scope:this
});
return;
}
YAHOO.SUGAR.MessageBox.show({
title:box_title,
msg: box_msg,
type: 'confirm',
fn: function(btn){
if(btn=='no'){return;};
SUGAR.email2.composeLayout.processResult(idx, id);},
modal:true,
scope:this
});
},
processNoneResult : function(idx, id) {
var tiny = SE.util.getTiny('htmleditor' + idx);
var tinyHTML = tiny.getContent();
var openTag = '';
var htmllow = tinyHTML.toLowerCase();
var start = htmllow.indexOf(openTag);
if (start > -1) {
tinyHTML = tinyHTML.substr(start);
tiny.setContent(tinyHTML);
} else {
tiny.setContent('');
}
},
processResult : function(idx , id){
var post_data = {"module":"EmailTemplates","record":id};
var global_rpcClient = new SugarRPCClient();
result = global_rpcClient.call_method('retrieve', post_data, true);
if(!result['record']) return;
json_objects['email_template_object'] = result['record'];
this.appendEmailTemplateJSON();
// get attachments if any
AjaxObject.target = '';
AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
},
appendEmailTemplateJSON : function() {
var idx = SE.composeLayout.currentInstanceId; // post increment
// query based on template, contact_id0,related_to
//jchi 09/10/2008 refix #7743
if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
}
var text = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body_html'])).replace(/ /ig, '\n').replace(/ /gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
// cn: bug 14361 - text-only templates don't fill compose screen
if(text == '') {
text = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body'])).replace(/ /ig, '\n').replace(/ /gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"').replace(/\r\n/gi," ");
}
var tiny = SE.util.getTiny('htmleditor' + idx);
var tinyHTML = tiny.getContent();
var openTag = '';
var closeTag = '
';
var htmllow = tinyHTML.toLowerCase();
var start = htmllow.indexOf(openTag);
if (start > -1) {
var htmlPart2 = tinyHTML.substr(start);
tinyHTML = text + htmlPart2;
tiny.setContent(tinyHTML);
} else {
tiny.setContent(text);
}
},
/**
* Writes out the signature in the email editor
*/
setSignature : function(idx) {
if (!tinyMCE)
return false;
var hide = document.getElementById('setEditor' + idx).checked;
SE.composeLayout.renderTinyMCEToolBar(idx,hide);
//wait for signatures to load before trying to set them
if (!SE.composeLayout.signatures) {
setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
return;
}
if(idx) {
var sel = document.getElementById('signatures' + idx);
} else {
var sel = document.getElementById('signature_id');
idx = SE.tinyInstances.currentHtmleditor;
}
//Ensure that the tinyMCE html has been rendered.
if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
return;
}
var signature = '';
try {
signature = sel.options[sel.selectedIndex].value;
} catch(e) {
}
var openTag = ' ';
var closeTag = '
';
var t = tinyMCE.getInstanceById('htmleditor' + idx);
//IE 6 Hack
if(typeof(t) != 'undefined')
{
t.contentDocument = t.contentWindow.document;
var html = t.getContent();
}
else
{
var html = '';
}
var htmllow = html.toLowerCase();
var start = htmllow.indexOf(openTag);
var end = htmllow.indexOf(closeTag) + closeTag.length;
// selected "none" - remove signature from email
if(signature == '') {
if (start > -1) {
var htmlPart1 = html.substr(0, start);
var htmlPart2 = html.substr(end, html.length);
html = htmlPart1 + htmlPart2;
t.setContent(html);
}
SE.signatures.lastAttemptedLoad = '';
return false;
}
if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
SE.signatures.lastAttemptedLoad = '';
SE.signatures.lastAttemptedLoad = signature;
if(typeof(SE.signatures[signature]) == 'undefined') {
//lazy load
SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
SE.signatures.targetInstance = (idx) ? idx : "";
AjaxObject.target = '';
AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
} else {
var newSignature = this.prepareSignature(SE.signatures[signature]);
// clear out old signature
if(SE.signatures.lastAttemptedLoad && start > -1) {
var htmlPart1 = html.substr(0, start);
var htmlPart2 = html.substr(end, html.length);
html = htmlPart1 + htmlPart2;
}
// [pre|ap]pend
start = html.indexOf('
');
if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
var htmlPart1 = html.substr(0, start);
var htmlPart2 = html.substr(start, html.length);
var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
} else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
var newHtml = ' ' + openTag + newSignature + closeTag + html;
} else {
var body = html.indexOf('