snappymail/rainloop/v/0.0.0/static/js/bro.js
2014-08-20 19:03:12 +04:00

6484 lines
152 KiB
JavaScript

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
var
kn = require('./Knoin/Knoin.js'),
RL = require('./Boots/RainLoopApp.js')
;
kn.bootstart(RL);
},{"./Boots/RainLoopApp.js":3,"./Knoin/Knoin.js":21}],2:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
var
_ = require('../External/underscore.js'),
ko = require('../External/ko.js'),
window = require('../External/window.js'),
$html = require('../External/$html.js'),
$window = require('../External/$window.js'),
$doc = require('../External/$doc.js'),
AppData = require('../External/AppData.js'),
Globals = require('../Common/Globals.js'),
Utils = require('../Common/Utils.js'),
KnoinAbstractBoot = require('../Knoin/KnoinAbstractBoot.js')
;
/**
* @constructor
* @extends KnoinAbstractBoot
*/
function AbstractApp()
{
KnoinAbstractBoot.call(this);
this.oSettings = null;
this.oPlugins = null;
this.oLocal = null;
this.oLink = null;
this.oSubs = {};
this.isLocalAutocomplete = true;
this.popupVisibilityNames = ko.observableArray([]);
this.popupVisibility = ko.computed(function () {
return 0 < this.popupVisibilityNames().length;
}, this);
this.iframe = $('<iframe style="display:none" src="javascript:;" />').appendTo('body');
$window.on('error', function (oEvent) {
if (oEvent && oEvent.originalEvent && oEvent.originalEvent.message &&
-1 === Utils.inArray(oEvent.originalEvent.message, [
'Script error.', 'Uncaught Error: Error calling method on NPObject.'
]))
{
// TODO cjs
RL.remote().jsError(
Utils.emptyFunction,
oEvent.originalEvent.message,
oEvent.originalEvent.filename,
oEvent.originalEvent.lineno,
window.location && window.location.toString ? window.location.toString() : '',
$html.attr('class'),
Utils.microtime() - Globals.now
);
}
});
$doc.on('keydown', function (oEvent) {
if (oEvent && oEvent.ctrlKey)
{
$html.addClass('rl-ctrl-key-pressed');
}
}).on('keyup', function (oEvent) {
if (oEvent && !oEvent.ctrlKey)
{
$html.removeClass('rl-ctrl-key-pressed');
}
});
}
_.extend(AbstractApp.prototype, KnoinAbstractBoot.prototype);
AbstractApp.prototype.oSettings = null;
AbstractApp.prototype.oPlugins = null;
AbstractApp.prototype.oLocal = null;
AbstractApp.prototype.oLink = null;
AbstractApp.prototype.oSubs = {};
/**
* @param {string} sLink
* @return {boolean}
*/
AbstractApp.prototype.download = function (sLink)
{
var
oE = null,
oLink = null,
sUserAgent = window.navigator.userAgent.toLowerCase()
;
if (sUserAgent && (sUserAgent.indexOf('chrome') > -1 || sUserAgent.indexOf('chrome') > -1))
{
oLink = window.document.createElement('a');
oLink['href'] = sLink;
if (window.document['createEvent'])
{
oE = window.document['createEvent']('MouseEvents');
if (oE && oE['initEvent'] && oLink['dispatchEvent'])
{
oE['initEvent']('click', true, true);
oLink['dispatchEvent'](oE);
return true;
}
}
}
if (Globals.bMobileDevice)
{
window.open(sLink, '_self');
window.focus();
}
else
{
this.iframe.attr('src', sLink);
// window.document.location.href = sLink;
}
return true;
};
/**
* @return {LinkBuilder}
*/
AbstractApp.prototype.link = function ()
{
if (null === this.oLink)
{
this.oLink = new LinkBuilder(); // TODO cjs
}
return this.oLink;
};
/**
* @return {LocalStorage}
*/
AbstractApp.prototype.local = function ()
{
if (null === this.oLocal)
{
this.oLocal = new LocalStorage(); // TODO cjs
}
return this.oLocal;
};
/**
* @param {string} sName
* @return {?}
*/
AbstractApp.prototype.settingsGet = function (sName)
{
if (null === this.oSettings)
{
this.oSettings = Utils.isNormal(AppData) ? AppData : {};
}
return Utils.isUnd(this.oSettings[sName]) ? null : this.oSettings[sName];
};
/**
* @param {string} sName
* @param {?} mValue
*/
AbstractApp.prototype.settingsSet = function (sName, mValue)
{
if (null === this.oSettings)
{
this.oSettings = Utils.isNormal(AppData) ? AppData : {};
}
this.oSettings[sName] = mValue;
};
AbstractApp.prototype.setTitle = function (sTitle)
{
sTitle = ((Utils.isNormal(sTitle) && 0 < sTitle.length) ? sTitle + ' - ' : '') +
RL.settingsGet('Title') || ''; // TODO cjs
window.document.title = '_';
window.document.title = sTitle;
};
/**
* @param {boolean=} bLogout = false
* @param {boolean=} bClose = false
*/
AbstractApp.prototype.loginAndLogoutReload = function (bLogout, bClose)
{
var
sCustomLogoutLink = Utils.pString(RL.settingsGet('CustomLogoutLink')),
bInIframe = !!RL.settingsGet('InIframe')
;
// TODO cjs
bLogout = Utils.isUnd(bLogout) ? false : !!bLogout;
bClose = Utils.isUnd(bClose) ? false : !!bClose;
if (bLogout && bClose && window.close)
{
window.close();
}
if (bLogout && '' !== sCustomLogoutLink && window.location.href !== sCustomLogoutLink)
{
_.delay(function () {
if (bInIframe && window.parent)
{
window.parent.location.href = sCustomLogoutLink;
}
else
{
window.location.href = sCustomLogoutLink;
}
}, 100);
}
else
{
kn.routeOff();
kn.setHash(RL.link().root(), true);
kn.routeOff();
_.delay(function () {
if (bInIframe && window.parent)
{
window.parent.location.reload();
}
else
{
window.location.reload();
}
}, 100);
}
};
AbstractApp.prototype.historyBack = function ()
{
window.history.back();
};
/**
* @param {string} sQuery
* @param {Function} fCallback
*/
AbstractApp.prototype.getAutocomplete = function (sQuery, fCallback)
{
fCallback([], sQuery);
};
/**
* @param {string} sName
* @param {Function} fFunc
* @param {Object=} oContext
* @return {AbstractApp}
*/
AbstractApp.prototype.sub = function (sName, fFunc, oContext)
{
if (Utils.isUnd(this.oSubs[sName]))
{
this.oSubs[sName] = [];
}
this.oSubs[sName].push([fFunc, oContext]);
return this;
};
/**
* @param {string} sName
* @param {Array=} aArgs
* @return {AbstractApp}
*/
AbstractApp.prototype.pub = function (sName, aArgs)
{
Plugins.runHook('rl-pub', [sName, aArgs]);
if (!Utils.isUnd(this.oSubs[sName]))
{
_.each(this.oSubs[sName], function (aItem) {
if (aItem[0])
{
aItem[0].apply(aItem[1] || null, aArgs || []);
}
});
}
return this;
};
/**
* @param {string} sName
* @return {boolean}
*/
AbstractApp.prototype.capa = function (sName)
{
var mCapa = this.settingsGet('Capa');
return Utils.isArray(mCapa) && Utils.isNormal(sName) && -1 < Utils.inArray(sName, mCapa);
};
AbstractApp.prototype.bootstart = function ()
{
var ssm = require('../External/ssm.js');
Utils.initOnStartOrLangChange(function () {
Utils.initNotificationLanguage();
}, null);
_.delay(function () {
Utils.windowResize();
}, 1000);
ssm.addState({
'id': 'mobile',
'maxWidth': 767,
'onEnter': function() {
$html.addClass('ssm-state-mobile');
RL.pub('ssm.mobile-enter');
},
'onLeave': function() {
$html.removeClass('ssm-state-mobile');
RL.pub('ssm.mobile-leave');
}
});
ssm.addState({
'id': 'tablet',
'minWidth': 768,
'maxWidth': 999,
'onEnter': function() {
$html.addClass('ssm-state-tablet');
},
'onLeave': function() {
$html.removeClass('ssm-state-tablet');
}
});
ssm.addState({
'id': 'desktop',
'minWidth': 1000,
'maxWidth': 1400,
'onEnter': function() {
$html.addClass('ssm-state-desktop');
},
'onLeave': function() {
$html.removeClass('ssm-state-desktop');
}
});
ssm.addState({
'id': 'desktop-large',
'minWidth': 1400,
'onEnter': function() {
$html.addClass('ssm-state-desktop-large');
},
'onLeave': function() {
$html.removeClass('ssm-state-desktop-large');
}
});
RL.sub('ssm.mobile-enter', function () { // TODO cjs
RL.data().leftPanelDisabled(true);
});
RL.sub('ssm.mobile-leave', function () { // TODO cjs
RL.data().leftPanelDisabled(false);
});
RL.data().leftPanelDisabled.subscribe(function (bValue) { // TODO cjs
$html.toggleClass('rl-left-panel-disabled', bValue);
});
ssm.ready();
};
module.exports = AbstractApp;
}(module));
},{"../Common/Globals.js":6,"../Common/Utils.js":8,"../External/$doc.js":9,"../External/$html.js":10,"../External/$window.js":11,"../External/AppData.js":12,"../External/ko.js":17,"../External/ssm.js":18,"../External/underscore.js":19,"../External/window.js":20,"../Knoin/KnoinAbstractBoot.js":22}],3:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
var
window = require('../External/window.js'),
$ = require('../External/jquery.js'),
_ = require('../External/underscore.js'),
Enums = require('../Common/Enums.js'),
Globals = require('../Common/Globals.js'),
Consts = require('../Common/Consts.js'),
Plugins = require('../Common/Plugins.js'),
Utils = require('../Common/Utils.js'),
kn = require('../Knoin/Knoin.js'),
AbstractApp = require('./AbstractApp.js')
;
/**
* @constructor
* @extends AbstractApp
*/
function RainLoopApp()
{
AbstractApp.call(this);
this.oData = null;
this.oRemote = null;
this.oCache = null;
this.oMoveCache = {};
this.quotaDebounce = _.debounce(this.quota, 1000 * 30);
this.moveOrDeleteResponseHelper = _.bind(this.moveOrDeleteResponseHelper, this);
this.messagesMoveTrigger = _.debounce(this.messagesMoveTrigger, 500);
window.setInterval(function () {
RL.pub('interval.30s');
}, 30000);
window.setInterval(function () {
RL.pub('interval.1m');
}, 60000);
window.setInterval(function () {
RL.pub('interval.2m');
}, 60000 * 2);
window.setInterval(function () {
RL.pub('interval.3m');
}, 60000 * 3);
window.setInterval(function () {
RL.pub('interval.5m');
}, 60000 * 5);
window.setInterval(function () {
RL.pub('interval.10m');
}, 60000 * 10);
window.setTimeout(function () {
window.setInterval(function () {
RL.pub('interval.10m-after5m');
}, 60000 * 10);
}, 60000 * 5);
$.wakeUp(function () {
RL.remote().jsVersion(function (sResult, oData) {
if (Enums.StorageResultType.Success === sResult && oData && !oData.Result)
{
if (window.parent && !!RL.settingsGet('InIframe'))
{
window.parent.location.reload();
}
else
{
window.location.reload();
}
}
}, RL.settingsGet('Version'));
}, {}, 60 * 60 * 1000);
}
_.extend(RainLoopApp.prototype, AbstractApp.prototype);
RainLoopApp.prototype.oData = null;
RainLoopApp.prototype.oRemote = null;
RainLoopApp.prototype.oCache = null;
/**
* @return {WebMailDataStorage}
*/
RainLoopApp.prototype.data = function ()
{
if (null === this.oData)
{
this.oData = new WebMailDataStorage();
}
return this.oData;
};
/**
* @return {WebMailAjaxRemoteStorage}
*/
RainLoopApp.prototype.remote = function ()
{
if (null === this.oRemote)
{
this.oRemote = new WebMailAjaxRemoteStorage();
}
return this.oRemote;
};
/**
* @return {WebMailCacheStorage}
*/
RainLoopApp.prototype.cache = function ()
{
if (null === this.oCache)
{
this.oCache = new WebMailCacheStorage();
}
return this.oCache;
};
RainLoopApp.prototype.reloadFlagsCurrentMessageListAndMessageFromCache = function ()
{
var oCache = RL.cache();
_.each(RL.data().messageList(), function (oMessage) {
oCache.initMessageFlagsFromCache(oMessage);
});
oCache.initMessageFlagsFromCache(RL.data().message());
};
/**
* @param {boolean=} bDropPagePosition = false
* @param {boolean=} bDropCurrenFolderCache = false
*/
RainLoopApp.prototype.reloadMessageList = function (bDropPagePosition, bDropCurrenFolderCache)
{
var
oRLData = RL.data(),
iOffset = (oRLData.messageListPage() - 1) * oRLData.messagesPerPage()
;
if (Utils.isUnd(bDropCurrenFolderCache) ? false : !!bDropCurrenFolderCache)
{
RL.cache().setFolderHash(oRLData.currentFolderFullNameRaw(), '');
}
if (Utils.isUnd(bDropPagePosition) ? false : !!bDropPagePosition)
{
oRLData.messageListPage(1);
iOffset = 0;
}
oRLData.messageListLoading(true);
RL.remote().messageList(function (sResult, oData, bCached) {
if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{
oRLData.messageListError('');
oRLData.messageListLoading(false);
oRLData.setMessageList(oData, bCached);
}
else if (Enums.StorageResultType.Unload === sResult)
{
oRLData.messageListError('');
oRLData.messageListLoading(false);
}
else if (Enums.StorageResultType.Abort !== sResult)
{
oRLData.messageList([]);
oRLData.messageListLoading(false);
oRLData.messageListError(oData && oData.ErrorCode ?
Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST')
);
}
}, oRLData.currentFolderFullNameRaw(), iOffset, oRLData.messagesPerPage(), oRLData.messageListSearch());
};
RainLoopApp.prototype.recacheInboxMessageList = function ()
{
RL.remote().messageList(Utils.emptyFunction, 'INBOX', 0, RL.data().messagesPerPage(), '', true);
};
RainLoopApp.prototype.reloadMessageListHelper = function (bEmptyList)
{
RL.reloadMessageList(bEmptyList);
};
/**
* @param {Function} fResultFunc
* @returns {boolean}
*/
RainLoopApp.prototype.contactsSync = function (fResultFunc)
{
var oContacts = RL.data().contacts;
if (oContacts.importing() || oContacts.syncing() || !RL.data().enableContactsSync() || !RL.data().allowContactsSync())
{
return false;
}
oContacts.syncing(true);
RL.remote().contactsSync(function (sResult, oData) {
oContacts.syncing(false);
if (fResultFunc)
{
fResultFunc(sResult, oData);
}
});
return true;
};
RainLoopApp.prototype.messagesMoveTrigger = function ()
{
var
self = this,
sSpamFolder = RL.data().spamFolder()
;
_.each(this.oMoveCache, function (oItem) {
var
bSpam = sSpamFolder === oItem['To'],
bHam = !bSpam && sSpamFolder === oItem['From'] && 'INBOX' === oItem['To']
;
RL.remote().messagesMove(self.moveOrDeleteResponseHelper, oItem['From'], oItem['To'], oItem['Uid'],
bSpam ? 'SPAM' : (bHam ? 'HAM' : ''));
});
this.oMoveCache = {};
};
RainLoopApp.prototype.messagesMoveHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForMove)
{
var sH = '$$' + sFromFolderFullNameRaw + '$$' + sToFolderFullNameRaw + '$$';
if (!this.oMoveCache[sH])
{
this.oMoveCache[sH] = {
'From': sFromFolderFullNameRaw,
'To': sToFolderFullNameRaw,
'Uid': []
};
}
this.oMoveCache[sH]['Uid'] = _.union(this.oMoveCache[sH]['Uid'], aUidForMove);
this.messagesMoveTrigger();
};
RainLoopApp.prototype.messagesCopyHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForCopy)
{
RL.remote().messagesCopy(
this.moveOrDeleteResponseHelper,
sFromFolderFullNameRaw,
sToFolderFullNameRaw,
aUidForCopy
);
};
RainLoopApp.prototype.messagesDeleteHelper = function (sFromFolderFullNameRaw, aUidForRemove)
{
RL.remote().messagesDelete(
this.moveOrDeleteResponseHelper,
sFromFolderFullNameRaw,
aUidForRemove
);
};
RainLoopApp.prototype.moveOrDeleteResponseHelper = function (sResult, oData)
{
if (Enums.StorageResultType.Success === sResult && RL.data().currentFolder())
{
if (oData && Utils.isArray(oData.Result) && 2 === oData.Result.length)
{
RL.cache().setFolderHash(oData.Result[0], oData.Result[1]);
}
else
{
RL.cache().setFolderHash(RL.data().currentFolderFullNameRaw(), '');
if (oData && -1 < Utils.inArray(oData.ErrorCode,
[Enums.Notification.CantMoveMessage, Enums.Notification.CantCopyMessage]))
{
window.alert(Utils.getNotification(oData.ErrorCode));
}
}
RL.reloadMessageListHelper(0 === RL.data().messageList().length);
RL.quotaDebounce();
}
};
/**
* @param {string} sFromFolderFullNameRaw
* @param {Array} aUidForRemove
*/
RainLoopApp.prototype.deleteMessagesFromFolderWithoutCheck = function (sFromFolderFullNameRaw, aUidForRemove)
{
this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
RL.data().removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
};
/**
* @param {number} iDeleteType
* @param {string} sFromFolderFullNameRaw
* @param {Array} aUidForRemove
* @param {boolean=} bUseFolder = true
*/
RainLoopApp.prototype.deleteMessagesFromFolder = function (iDeleteType, sFromFolderFullNameRaw, aUidForRemove, bUseFolder)
{
var
self = this,
oData = RL.data(),
oCache = RL.cache(),
oMoveFolder = null,
nSetSystemFoldersNotification = null
;
switch (iDeleteType)
{
case Enums.FolderType.Spam:
oMoveFolder = oCache.getFolderFromCacheList(oData.spamFolder());
nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Spam;
break;
case Enums.FolderType.NotSpam:
oMoveFolder = oCache.getFolderFromCacheList('INBOX');
break;
case Enums.FolderType.Trash:
oMoveFolder = oCache.getFolderFromCacheList(oData.trashFolder());
nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Trash;
break;
case Enums.FolderType.Archive:
oMoveFolder = oCache.getFolderFromCacheList(oData.archiveFolder());
nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Archive;
break;
}
bUseFolder = Utils.isUnd(bUseFolder) ? true : !!bUseFolder;
if (bUseFolder)
{
if ((Enums.FolderType.Spam === iDeleteType && Consts.Values.UnuseOptionValue === oData.spamFolder()) ||
(Enums.FolderType.Trash === iDeleteType && Consts.Values.UnuseOptionValue === oData.trashFolder()) ||
(Enums.FolderType.Archive === iDeleteType && Consts.Values.UnuseOptionValue === oData.archiveFolder()))
{
bUseFolder = false;
}
}
if (!oMoveFolder && bUseFolder)
{
kn.showScreenPopup(PopupsFolderSystemViewModel, [nSetSystemFoldersNotification]);
}
else if (!bUseFolder || (Enums.FolderType.Trash === iDeleteType &&
(sFromFolderFullNameRaw === oData.spamFolder() || sFromFolderFullNameRaw === oData.trashFolder())))
{
kn.showScreenPopup(PopupsAskViewModel, [Utils.i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), function () {
self.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
oData.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
}]);
}
else if (oMoveFolder)
{
this.messagesMoveHelper(sFromFolderFullNameRaw, oMoveFolder.fullNameRaw, aUidForRemove);
oData.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove, oMoveFolder.fullNameRaw);
}
};
/**
* @param {string} sFromFolderFullNameRaw
* @param {Array} aUidForMove
* @param {string} sToFolderFullNameRaw
* @param {boolean=} bCopy = false
*/
RainLoopApp.prototype.moveMessagesToFolder = function (sFromFolderFullNameRaw, aUidForMove, sToFolderFullNameRaw, bCopy)
{
if (sFromFolderFullNameRaw !== sToFolderFullNameRaw && Utils.isArray(aUidForMove) && 0 < aUidForMove.length)
{
var
oFromFolder = RL.cache().getFolderFromCacheList(sFromFolderFullNameRaw),
oToFolder = RL.cache().getFolderFromCacheList(sToFolderFullNameRaw)
;
if (oFromFolder && oToFolder)
{
if (Utils.isUnd(bCopy) ? false : !!bCopy)
{
this.messagesCopyHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove);
}
else
{
this.messagesMoveHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove);
}
RL.data().removeMessagesFromList(oFromFolder.fullNameRaw, aUidForMove, oToFolder.fullNameRaw, bCopy);
return true;
}
}
return false;
};
/**
* @param {Function=} fCallback
*/
RainLoopApp.prototype.folders = function (fCallback)
{
this.data().foldersLoading(true);
this.remote().folders(_.bind(function (sResult, oData) {
RL.data().foldersLoading(false);
if (Enums.StorageResultType.Success === sResult)
{
this.data().setFolders(oData);
if (fCallback)
{
fCallback(true);
}
}
else
{
if (fCallback)
{
fCallback(false);
}
}
}, this));
};
RainLoopApp.prototype.reloadOpenPgpKeys = function ()
{
if (RL.data().capaOpenPGP())
{
var
aKeys = [],
oEmail = new EmailModel(),
oOpenpgpKeyring = RL.data().openpgpKeyring,
oOpenpgpKeys = oOpenpgpKeyring ? oOpenpgpKeyring.getAllKeys() : []
;
_.each(oOpenpgpKeys, function (oItem, iIndex) {
if (oItem && oItem.primaryKey)
{
var
oPrimaryUser = oItem.getPrimaryUser(),
sUser = (oPrimaryUser && oPrimaryUser.user) ? oPrimaryUser.user.userId.userid
: (oItem.users && oItem.users[0] ? oItem.users[0].userId.userid : '')
;
oEmail.clear();
oEmail.mailsoParse(sUser);
if (oEmail.validate())
{
aKeys.push(new OpenPgpKeyModel(
iIndex,
oItem.primaryKey.getFingerprint(),
oItem.primaryKey.getKeyId().toHex().toLowerCase(),
sUser,
oEmail.email,
oItem.isPrivate(),
oItem.armor())
);
}
}
});
RL.data().openpgpkeys(aKeys);
}
};
RainLoopApp.prototype.accountsAndIdentities = function ()
{
var oRainLoopData = RL.data();
oRainLoopData.accountsLoading(true);
oRainLoopData.identitiesLoading(true);
RL.remote().accountsAndIdentities(function (sResult, oData) {
oRainLoopData.accountsLoading(false);
oRainLoopData.identitiesLoading(false);
if (Enums.StorageResultType.Success === sResult && oData.Result)
{
var
sParentEmail = RL.settingsGet('ParentEmail'),
sAccountEmail = oRainLoopData.accountEmail()
;
sParentEmail = '' === sParentEmail ? sAccountEmail : sParentEmail;
if (Utils.isArray(oData.Result['Accounts']))
{
oRainLoopData.accounts(_.map(oData.Result['Accounts'], function (sValue) {
return new AccountModel(sValue, sValue !== sParentEmail);
}));
}
if (Utils.isArray(oData.Result['Identities']))
{
oRainLoopData.identities(_.map(oData.Result['Identities'], function (oIdentityData) {
var
sId = Utils.pString(oIdentityData['Id']),
sEmail = Utils.pString(oIdentityData['Email']),
oIdentity = new IdentityModel(sId, sEmail, sId !== sAccountEmail)
;
oIdentity.name(Utils.pString(oIdentityData['Name']));
oIdentity.replyTo(Utils.pString(oIdentityData['ReplyTo']));
oIdentity.bcc(Utils.pString(oIdentityData['Bcc']));
return oIdentity;
}));
}
}
});
};
RainLoopApp.prototype.quota = function ()
{
this.remote().quota(function (sResult, oData) {
if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
Utils.isArray(oData.Result) && 1 < oData.Result.length &&
Utils.isPosNumeric(oData.Result[0], true) && Utils.isPosNumeric(oData.Result[1], true))
{
RL.data().userQuota(Utils.pInt(oData.Result[1]) * 1024);
RL.data().userUsageSize(Utils.pInt(oData.Result[0]) * 1024);
}
});
};
/**
* @param {string} sFolder
* @param {Array=} aList = []
*/
RainLoopApp.prototype.folderInformation = function (sFolder, aList)
{
if ('' !== Utils.trim(sFolder))
{
this.remote().folderInformation(function (sResult, oData) {
if (Enums.StorageResultType.Success === sResult)
{
if (oData && oData.Result && oData.Result.Hash && oData.Result.Folder)
{
var
iUtc = moment().unix(),
sHash = RL.cache().getFolderHash(oData.Result.Folder),
oFolder = RL.cache().getFolderFromCacheList(oData.Result.Folder),
bCheck = false,
sUid = '',
aList = [],
bUnreadCountChange = false,
oFlags = null
;
if (oFolder)
{
oFolder.interval = iUtc;
if (oData.Result.Hash)
{
RL.cache().setFolderHash(oData.Result.Folder, oData.Result.Hash);
}
if (Utils.isNormal(oData.Result.MessageCount))
{
oFolder.messageCountAll(oData.Result.MessageCount);
}
if (Utils.isNormal(oData.Result.MessageUnseenCount))
{
if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount))
{
bUnreadCountChange = true;
}
oFolder.messageCountUnread(oData.Result.MessageUnseenCount);
}
if (bUnreadCountChange)
{
RL.cache().clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
}
if (oData.Result.Flags)
{
for (sUid in oData.Result.Flags)
{
if (oData.Result.Flags.hasOwnProperty(sUid))
{
bCheck = true;
oFlags = oData.Result.Flags[sUid];
RL.cache().storeMessageFlagsToCacheByFolderAndUid(oFolder.fullNameRaw, sUid.toString(), [
!oFlags['IsSeen'], !!oFlags['IsFlagged'], !!oFlags['IsAnswered'], !!oFlags['IsForwarded'], !!oFlags['IsReadReceipt']
]);
}
}
if (bCheck)
{
RL.reloadFlagsCurrentMessageListAndMessageFromCache();
}
}
RL.data().initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages);
if (oData.Result.Hash !== sHash || '' === sHash)
{
if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
{
RL.reloadMessageList();
}
else if ('INBOX' === oFolder.fullNameRaw)
{
RL.recacheInboxMessageList();
}
}
else if (bUnreadCountChange)
{
if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
{
aList = RL.data().messageList();
if (Utils.isNonEmptyArray(aList))
{
RL.folderInformation(oFolder.fullNameRaw, aList);
}
}
}
}
}
}
}, sFolder, aList);
}
};
/**
* @param {boolean=} bBoot = false
*/
RainLoopApp.prototype.folderInformationMultiply = function (bBoot)
{
bBoot = Utils.isUnd(bBoot) ? false : !!bBoot;
var
iUtc = moment().unix(),
aFolders = RL.data().getNextFolderNames(bBoot)
;
if (Utils.isNonEmptyArray(aFolders))
{
this.remote().folderInformationMultiply(function (sResult, oData) {
if (Enums.StorageResultType.Success === sResult)
{
if (oData && oData.Result && oData.Result.List && Utils.isNonEmptyArray(oData.Result.List))
{
_.each(oData.Result.List, function (oItem) {
var
aList = [],
sHash = RL.cache().getFolderHash(oItem.Folder),
oFolder = RL.cache().getFolderFromCacheList(oItem.Folder),
bUnreadCountChange = false
;
if (oFolder)
{
oFolder.interval = iUtc;
if (oItem.Hash)
{
RL.cache().setFolderHash(oItem.Folder, oItem.Hash);
}
if (Utils.isNormal(oItem.MessageCount))
{
oFolder.messageCountAll(oItem.MessageCount);
}
if (Utils.isNormal(oItem.MessageUnseenCount))
{
if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oItem.MessageUnseenCount))
{
bUnreadCountChange = true;
}
oFolder.messageCountUnread(oItem.MessageUnseenCount);
}
if (bUnreadCountChange)
{
RL.cache().clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
}
if (oItem.Hash !== sHash || '' === sHash)
{
if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
{
RL.reloadMessageList();
}
}
else if (bUnreadCountChange)
{
if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
{
aList = RL.data().messageList();
if (Utils.isNonEmptyArray(aList))
{
RL.folderInformation(oFolder.fullNameRaw, aList);
}
}
}
}
});
if (bBoot)
{
RL.folderInformationMultiply(true);
}
}
}
}, aFolders);
}
};
RainLoopApp.prototype.setMessageSeen = function (oMessage)
{
if (oMessage.unseen())
{
oMessage.unseen(false);
var oFolder = RL.cache().getFolderFromCacheList(oMessage.folderFullNameRaw);
if (oFolder)
{
oFolder.messageCountUnread(0 <= oFolder.messageCountUnread() - 1 ?
oFolder.messageCountUnread() - 1 : 0);
}
RL.cache().storeMessageFlagsToCache(oMessage);
RL.reloadFlagsCurrentMessageListAndMessageFromCache();
}
RL.remote().messageSetSeen(Utils.emptyFunction, oMessage.folderFullNameRaw, [oMessage.uid], true);
};
RainLoopApp.prototype.googleConnect = function ()
{
window.open(RL.link().socialGoogle(), 'Google', 'left=200,top=100,width=650,height=600,menubar=no,status=no,resizable=yes,scrollbars=yes');
};
RainLoopApp.prototype.twitterConnect = function ()
{
window.open(RL.link().socialTwitter(), 'Twitter', 'left=200,top=100,width=650,height=350,menubar=no,status=no,resizable=yes,scrollbars=yes');
};
RainLoopApp.prototype.facebookConnect = function ()
{
window.open(RL.link().socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
};
/**
* @param {boolean=} bFireAllActions
*/
RainLoopApp.prototype.socialUsers = function (bFireAllActions)
{
var oRainLoopData = RL.data();
if (bFireAllActions)
{
oRainLoopData.googleActions(true);
oRainLoopData.facebookActions(true);
oRainLoopData.twitterActions(true);
}
RL.remote().socialUsers(function (sResult, oData) {
if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{
oRainLoopData.googleUserName(oData.Result['Google'] || '');
oRainLoopData.facebookUserName(oData.Result['Facebook'] || '');
oRainLoopData.twitterUserName(oData.Result['Twitter'] || '');
}
else
{
oRainLoopData.googleUserName('');
oRainLoopData.facebookUserName('');
oRainLoopData.twitterUserName('');
}
oRainLoopData.googleLoggined('' !== oRainLoopData.googleUserName());
oRainLoopData.facebookLoggined('' !== oRainLoopData.facebookUserName());
oRainLoopData.twitterLoggined('' !== oRainLoopData.twitterUserName());
oRainLoopData.googleActions(false);
oRainLoopData.facebookActions(false);
oRainLoopData.twitterActions(false);
});
};
RainLoopApp.prototype.googleDisconnect = function ()
{
RL.data().googleActions(true);
RL.remote().googleDisconnect(function () {
RL.socialUsers();
});
};
RainLoopApp.prototype.facebookDisconnect = function ()
{
RL.data().facebookActions(true);
RL.remote().facebookDisconnect(function () {
RL.socialUsers();
});
};
RainLoopApp.prototype.twitterDisconnect = function ()
{
RL.data().twitterActions(true);
RL.remote().twitterDisconnect(function () {
RL.socialUsers();
});
};
/**
* @param {Array} aSystem
* @param {Array} aList
* @param {Array=} aDisabled
* @param {Array=} aHeaderLines
* @param {?number=} iUnDeep
* @param {Function=} fDisableCallback
* @param {Function=} fVisibleCallback
* @param {Function=} fRenameCallback
* @param {boolean=} bSystem
* @param {boolean=} bBuildUnvisible
* @return {Array}
*/
RainLoopApp.prototype.folderListOptionsBuilder = function (aSystem, aList, aDisabled, aHeaderLines, iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible)
{
var
iIndex = 0,
iLen = 0,
/**
* @type {?FolderModel}
*/
oItem = null,
bSep = false,
sDeepPrefix = '\u00A0\u00A0\u00A0',
aResult = []
;
bSystem = !Utils.isNormal(bSystem) ? 0 < aSystem.length : bSystem;
bBuildUnvisible = Utils.isUnd(bBuildUnvisible) ? false : !!bBuildUnvisible;
iUnDeep = !Utils.isNormal(iUnDeep) ? 0 : iUnDeep;
fDisableCallback = Utils.isNormal(fDisableCallback) ? fDisableCallback : null;
fVisibleCallback = Utils.isNormal(fVisibleCallback) ? fVisibleCallback : null;
fRenameCallback = Utils.isNormal(fRenameCallback) ? fRenameCallback : null;
if (!Utils.isArray(aDisabled))
{
aDisabled = [];
}
if (!Utils.isArray(aHeaderLines))
{
aHeaderLines = [];
}
for (iIndex = 0, iLen = aHeaderLines.length; iIndex < iLen; iIndex++)
{
aResult.push({
'id': aHeaderLines[iIndex][0],
'name': aHeaderLines[iIndex][1],
'system': false,
'seporator': false,
'disabled': false
});
}
bSep = true;
for (iIndex = 0, iLen = aSystem.length; iIndex < iLen; iIndex++)
{
oItem = aSystem[iIndex];
if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true)
{
if (bSep && 0 < aResult.length)
{
aResult.push({
'id': '---',
'name': '---',
'system': false,
'seporator': true,
'disabled': true
});
}
bSep = false;
aResult.push({
'id': oItem.fullNameRaw,
'name': fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name(),
'system': true,
'seporator': false,
'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) ||
(fDisableCallback ? fDisableCallback.call(null, oItem) : false)
});
}
}
bSep = true;
for (iIndex = 0, iLen = aList.length; iIndex < iLen; iIndex++)
{
oItem = aList[iIndex];
if (oItem.subScribed() || !oItem.existen)
{
if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true)
{
if (Enums.FolderType.User === oItem.type() || !bSystem || 0 < oItem.subFolders().length)
{
if (bSep && 0 < aResult.length)
{
aResult.push({
'id': '---',
'name': '---',
'system': false,
'seporator': true,
'disabled': true
});
}
bSep = false;
aResult.push({
'id': oItem.fullNameRaw,
'name': (new window.Array(oItem.deep + 1 - iUnDeep)).join(sDeepPrefix) +
(fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name()),
'system': false,
'seporator': false,
'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) ||
(fDisableCallback ? fDisableCallback.call(null, oItem) : false)
});
}
}
}
if (oItem.subScribed() && 0 < oItem.subFolders().length)
{
aResult = aResult.concat(RL.folderListOptionsBuilder([], oItem.subFolders(), aDisabled, [],
iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible));
}
}
return aResult;
};
/**
* @param {string} sQuery
* @param {Function} fCallback
*/
RainLoopApp.prototype.getAutocomplete = function (sQuery, fCallback)
{
var
aData = []
;
RL.remote().suggestions(function (sResult, oData) {
if (Enums.StorageResultType.Success === sResult && oData && Utils.isArray(oData.Result))
{
aData = _.map(oData.Result, function (aItem) {
return aItem && aItem[0] ? new EmailModel(aItem[0], aItem[1]) : null;
});
fCallback(_.compact(aData));
}
else if (Enums.StorageResultType.Abort !== sResult)
{
fCallback([]);
}
}, sQuery);
};
/**
* @param {string} sQuery
* @param {Function} fCallback
*/
RainLoopApp.prototype.getContactTagsAutocomplete = function (sQuery, fCallback)
{
fCallback(_.filter(RL.data().contactTags(), function (oContactTag) {
return oContactTag && oContactTag.filterHelper(sQuery);
}));
};
/**
* @param {string} sMailToUrl
* @returns {boolean}
*/
RainLoopApp.prototype.mailToHelper = function (sMailToUrl)
{
if (sMailToUrl && 'mailto:' === sMailToUrl.toString().substr(0, 7).toLowerCase())
{
sMailToUrl = sMailToUrl.toString().substr(7);
var
oParams = {},
oEmailModel = null,
sEmail = sMailToUrl.replace(/\?.+$/, ''),
sQueryString = sMailToUrl.replace(/^[^\?]*\?/, '')
;
oEmailModel = new EmailModel();
oEmailModel.parse(window.decodeURIComponent(sEmail));
if (oEmailModel && oEmailModel.email)
{
oParams = Utils.simpleQueryParser(sQueryString);
kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Empty, null, [oEmailModel],
Utils.isUnd(oParams.subject) ? null : Utils.pString(oParams.subject),
Utils.isUnd(oParams.body) ? null : Utils.plainToHtml(Utils.pString(oParams.body))
]);
}
return true;
}
return false;
};
RainLoopApp.prototype.bootstart = function ()
{
RL.pub('rl.bootstart');
AbstractApp.prototype.bootstart.call(this);
RL.data().populateDataOnStart();
var
sCustomLoginLink = '',
sJsHash = RL.settingsGet('JsHash'),
iContactsSyncInterval = Utils.pInt(RL.settingsGet('ContactsSyncInterval')),
bGoogle = RL.settingsGet('AllowGoogleSocial'),
bFacebook = RL.settingsGet('AllowFacebookSocial'),
bTwitter = RL.settingsGet('AllowTwitterSocial')
;
if (!RL.settingsGet('ChangePasswordIsAllowed'))
{
Utils.removeSettingsViewModel(SettingsChangePasswordScreen);
}
if (!RL.settingsGet('ContactsIsAllowed'))
{
Utils.removeSettingsViewModel(SettingsContacts);
}
if (!RL.capa(Enums.Capa.AdditionalAccounts))
{
Utils.removeSettingsViewModel(SettingsAccounts);
}
if (RL.capa(Enums.Capa.AdditionalIdentities))
{
Utils.removeSettingsViewModel(SettingsIdentity);
}
else
{
Utils.removeSettingsViewModel(SettingsIdentities);
}
if (!RL.capa(Enums.Capa.OpenPGP))
{
Utils.removeSettingsViewModel(SettingsOpenPGP);
}
if (!RL.capa(Enums.Capa.TwoFactor))
{
Utils.removeSettingsViewModel(SettingsSecurity);
}
if (!RL.capa(Enums.Capa.Themes))
{
Utils.removeSettingsViewModel(SettingsThemes);
}
if (!RL.capa(Enums.Capa.Filters))
{
Utils.removeSettingsViewModel(SettingsFilters);
}
if (!bGoogle && !bFacebook && !bTwitter)
{
Utils.removeSettingsViewModel(SettingsSocialScreen);
}
Utils.initOnStartOrLangChange(function () {
$.extend(true, $.magnificPopup.defaults, {
'tClose': Utils.i18n('MAGNIFIC_POPUP/CLOSE'),
'tLoading': Utils.i18n('MAGNIFIC_POPUP/LOADING'),
'gallery': {
'tPrev': Utils.i18n('MAGNIFIC_POPUP/GALLERY_PREV'),
'tNext': Utils.i18n('MAGNIFIC_POPUP/GALLERY_NEXT'),
'tCounter': Utils.i18n('MAGNIFIC_POPUP/GALLERY_COUNTER')
},
'image': {
'tError': Utils.i18n('MAGNIFIC_POPUP/IMAGE_ERROR')
},
'ajax': {
'tError': Utils.i18n('MAGNIFIC_POPUP/AJAX_ERROR')
}
});
}, this);
if (window.SimplePace)
{
window.SimplePace.set(70);
window.SimplePace.sleep();
}
if (!!RL.settingsGet('Auth'))
{
this.setTitle(Utils.i18n('TITLES/LOADING'));
this.folders(_.bind(function (bValue) {
kn.hideLoading();
if (bValue)
{
if (window.$LAB && window.crypto && window.crypto.getRandomValues && RL.capa(Enums.Capa.OpenPGP))
{
window.$LAB.script(window.openpgp ? '' : RL.link().openPgpJs()).wait(function () {
if (window.openpgp)
{
RL.data().openpgpKeyring = new window.openpgp.Keyring();
RL.data().capaOpenPGP(true);
RL.pub('openpgp.init');
RL.reloadOpenPgpKeys();
}
});
}
else
{
RL.data().capaOpenPGP(false);
}
kn.startScreens([MailBoxScreen, SettingsScreen]);
if (bGoogle || bFacebook || bTwitter)
{
RL.socialUsers(true);
}
RL.sub('interval.2m', function () {
RL.folderInformation('INBOX');
});
RL.sub('interval.2m', function () {
var sF = RL.data().currentFolderFullNameRaw();
if ('INBOX' !== sF)
{
RL.folderInformation(sF);
}
});
RL.sub('interval.3m', function () {
RL.folderInformationMultiply();
});
RL.sub('interval.5m', function () {
RL.quota();
});
RL.sub('interval.10m', function () {
RL.folders();
});
iContactsSyncInterval = 5 <= iContactsSyncInterval ? iContactsSyncInterval : 20;
iContactsSyncInterval = 320 >= iContactsSyncInterval ? iContactsSyncInterval : 320;
window.setInterval(function () {
RL.contactsSync();
}, iContactsSyncInterval * 60000 + 5000);
_.delay(function () {
RL.contactsSync();
}, 5000);
_.delay(function () {
RL.folderInformationMultiply(true);
}, 500);
Plugins.runHook('rl-start-user-screens');
RL.pub('rl.bootstart-user-screens');
if (!!RL.settingsGet('AccountSignMe') && window.navigator.registerProtocolHandler)
{
_.delay(function () {
try {
window.navigator.registerProtocolHandler('mailto',
window.location.protocol + '//' + window.location.host + window.location.pathname + '?mailto&to=%s',
'' + (RL.settingsGet('Title') || 'RainLoop'));
} catch(e) {}
if (RL.settingsGet('MailToEmail'))
{
RL.mailToHelper(RL.settingsGet('MailToEmail'));
}
}, 500);
}
}
else
{
kn.startScreens([LoginScreen]);
Plugins.runHook('rl-start-login-screens');
RL.pub('rl.bootstart-login-screens');
}
if (window.SimplePace)
{
window.SimplePace.set(100);
}
if (!Globals.bMobileDevice)
{
_.defer(function () {
Utils.initLayoutResizer('#rl-left', '#rl-right', Enums.ClientSideKeyName.FolderListSize);
});
}
}, this));
}
else
{
sCustomLoginLink = Utils.pString(RL.settingsGet('CustomLoginLink'));
if (!sCustomLoginLink)
{
kn.hideLoading();
kn.startScreens([LoginScreen]);
Plugins.runHook('rl-start-login-screens');
RL.pub('rl.bootstart-login-screens');
if (window.SimplePace)
{
window.SimplePace.set(100);
}
}
else
{
kn.routeOff();
kn.setHash(RL.link().root(), true);
kn.routeOff();
_.defer(function () {
window.location.href = sCustomLoginLink;
});
}
}
if (bGoogle)
{
window['rl_' + sJsHash + '_google_service'] = function () {
RL.data().googleActions(true);
RL.socialUsers();
};
}
if (bFacebook)
{
window['rl_' + sJsHash + '_facebook_service'] = function () {
RL.data().facebookActions(true);
RL.socialUsers();
};
}
if (bTwitter)
{
window['rl_' + sJsHash + '_twitter_service'] = function () {
RL.data().twitterActions(true);
RL.socialUsers();
};
}
RL.sub('interval.1m', function () {
Globals.momentTrigger(!Globals.momentTrigger());
});
Plugins.runHook('rl-start-screens');
RL.pub('rl.bootstart-end');
};
module.exports = new RainLoopApp();
}(module));
},{"../Common/Consts.js":4,"../Common/Enums.js":5,"../Common/Globals.js":6,"../Common/Plugins.js":7,"../Common/Utils.js":8,"../External/jquery.js":16,"../External/underscore.js":19,"../External/window.js":20,"../Knoin/Knoin.js":21,"./AbstractApp.js":2}],4:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
var Consts = {};
Consts.Values = {};
Consts.DataImages = {};
Consts.Defaults = {};
/**
* @const
* @type {number}
*/
Consts.Defaults.MessagesPerPage = 20;
/**
* @const
* @type {number}
*/
Consts.Defaults.ContactsPerPage = 50;
/**
* @const
* @type {Array}
*/
Consts.Defaults.MessagesPerPageArray = [10, 20, 30, 50, 100/*, 150, 200, 300*/];
/**
* @const
* @type {number}
*/
Consts.Defaults.DefaultAjaxTimeout = 30000;
/**
* @const
* @type {number}
*/
Consts.Defaults.SearchAjaxTimeout = 300000;
/**
* @const
* @type {number}
*/
Consts.Defaults.SendMessageAjaxTimeout = 300000;
/**
* @const
* @type {number}
*/
Consts.Defaults.SaveMessageAjaxTimeout = 200000;
/**
* @const
* @type {number}
*/
Consts.Defaults.ContactsSyncAjaxTimeout = 200000;
/**
* @const
* @type {string}
*/
Consts.Values.UnuseOptionValue = '__UNUSE__';
/**
* @const
* @type {string}
*/
Consts.Values.ClientSideCookieIndexName = 'rlcsc';
/**
* @const
* @type {number}
*/
Consts.Values.ImapDefaulPort = 143;
/**
* @const
* @type {number}
*/
Consts.Values.ImapDefaulSecurePort = 993;
/**
* @const
* @type {number}
*/
Consts.Values.SmtpDefaulPort = 25;
/**
* @const
* @type {number}
*/
Consts.Values.SmtpDefaulSecurePort = 465;
/**
* @const
* @type {number}
*/
Consts.Values.MessageBodyCacheLimit = 15;
/**
* @const
* @type {number}
*/
Consts.Values.AjaxErrorLimit = 7;
/**
* @const
* @type {number}
*/
Consts.Values.TokenErrorLimit = 10;
/**
* @const
* @type {string}
*/
Consts.DataImages.UserDotPic = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2P8DwQACgAD/il4QJ8AAAAASUVORK5CYII=';
/**
* @const
* @type {string}
*/
Consts.DataImages.TranspPic = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=';
module.exports = Consts;
}(module));
},{}],5:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
var Enums = {};
/**
* @enum {string}
*/
Enums.StorageResultType = {
'Success': 'success',
'Abort': 'abort',
'Error': 'error',
'Unload': 'unload'
};
/**
* @enum {number}
*/
Enums.State = {
'Empty': 10,
'Login': 20,
'Auth': 30
};
/**
* @enum {number}
*/
Enums.StateType = {
'Webmail': 0,
'Admin': 1
};
/**
* @enum {string}
*/
Enums.Capa = {
'Prem': 'PREM',
'TwoFactor': 'TWO_FACTOR',
'OpenPGP': 'OPEN_PGP',
'Prefetch': 'PREFETCH',
'Gravatar': 'GRAVATAR',
'Themes': 'THEMES',
'Filters': 'FILTERS',
'AdditionalAccounts': 'ADDITIONAL_ACCOUNTS',
'AdditionalIdentities': 'ADDITIONAL_IDENTITIES'
};
/**
* @enum {string}
*/
Enums.KeyState = {
'All': 'all',
'None': 'none',
'ContactList': 'contact-list',
'MessageList': 'message-list',
'FolderList': 'folder-list',
'MessageView': 'message-view',
'Compose': 'compose',
'Settings': 'settings',
'Menu': 'menu',
'PopupComposeOpenPGP': 'compose-open-pgp',
'PopupKeyboardShortcutsHelp': 'popup-keyboard-shortcuts-help',
'PopupAsk': 'popup-ask'
};
/**
* @enum {number}
*/
Enums.FolderType = {
'Inbox': 10,
'SentItems': 11,
'Draft': 12,
'Trash': 13,
'Spam': 14,
'Archive': 15,
'NotSpam': 80,
'User': 99
};
/**
* @enum {string}
*/
Enums.LoginSignMeTypeAsString = {
'DefaultOff': 'defaultoff',
'DefaultOn': 'defaulton',
'Unused': 'unused'
};
/**
* @enum {number}
*/
Enums.LoginSignMeType = {
'DefaultOff': 0,
'DefaultOn': 1,
'Unused': 2
};
/**
* @enum {string}
*/
Enums.ComposeType = {
'Empty': 'empty',
'Reply': 'reply',
'ReplyAll': 'replyall',
'Forward': 'forward',
'ForwardAsAttachment': 'forward-as-attachment',
'Draft': 'draft',
'EditAsNew': 'editasnew'
};
/**
* @enum {number}
*/
Enums.UploadErrorCode = {
'Normal': 0,
'FileIsTooBig': 1,
'FilePartiallyUploaded': 2,
'FileNoUploaded': 3,
'MissingTempFolder': 4,
'FileOnSaveingError': 5,
'FileType': 98,
'Unknown': 99
};
/**
* @enum {number}
*/
Enums.SetSystemFoldersNotification = {
'None': 0,
'Sent': 1,
'Draft': 2,
'Spam': 3,
'Trash': 4,
'Archive': 5
};
/**
* @enum {number}
*/
Enums.ClientSideKeyName = {
'FoldersLashHash': 0,
'MessagesInboxLastHash': 1,
'MailBoxListSize': 2,
'ExpandedFolders': 3,
'FolderListSize': 4
};
/**
* @enum {number}
*/
Enums.EventKeyCode = {
'Backspace': 8,
'Tab': 9,
'Enter': 13,
'Esc': 27,
'PageUp': 33,
'PageDown': 34,
'Left': 37,
'Right': 39,
'Up': 38,
'Down': 40,
'End': 35,
'Home': 36,
'Space': 32,
'Insert': 45,
'Delete': 46,
'A': 65,
'S': 83
};
/**
* @enum {number}
*/
Enums.MessageSetAction = {
'SetSeen': 0,
'UnsetSeen': 1,
'SetFlag': 2,
'UnsetFlag': 3
};
/**
* @enum {number}
*/
Enums.MessageSelectAction = {
'All': 0,
'None': 1,
'Invert': 2,
'Unseen': 3,
'Seen': 4,
'Flagged': 5,
'Unflagged': 6
};
/**
* @enum {number}
*/
Enums.DesktopNotifications = {
'Allowed': 0,
'NotAllowed': 1,
'Denied': 2,
'NotSupported': 9
};
/**
* @enum {number}
*/
Enums.MessagePriority = {
'Low': 5,
'Normal': 3,
'High': 1
};
/**
* @enum {string}
*/
Enums.EditorDefaultType = {
'Html': 'Html',
'Plain': 'Plain'
};
/**
* @enum {string}
*/
Enums.CustomThemeType = {
'Light': 'Light',
'Dark': 'Dark'
};
/**
* @enum {number}
*/
Enums.ServerSecure = {
'None': 0,
'SSL': 1,
'TLS': 2
};
/**
* @enum {number}
*/
Enums.SearchDateType = {
'All': -1,
'Days3': 3,
'Days7': 7,
'Month': 30
};
/**
* @enum {number}
*/
Enums.EmailType = {
'Defailt': 0,
'Facebook': 1,
'Google': 2
};
/**
* @enum {number}
*/
Enums.SaveSettingsStep = {
'Animate': -2,
'Idle': -1,
'TrueResult': 1,
'FalseResult': 0
};
/**
* @enum {string}
*/
Enums.InterfaceAnimation = {
'None': 'None',
'Normal': 'Normal',
'Full': 'Full'
};
/**
* @enum {number}
*/
Enums.Layout = {
'NoPreview': 0,
'SidePreview': 1,
'BottomPreview': 2
};
/**
* @enum {string}
*/
Enums.FilterConditionField = {
'From': 'From',
'To': 'To',
'Recipient': 'Recipient',
'Subject': 'Subject'
};
/**
* @enum {string}
*/
Enums.FilterConditionType = {
'Contains': 'Contains',
'NotContains': 'NotContains',
'EqualTo': 'EqualTo',
'NotEqualTo': 'NotEqualTo'
};
/**
* @enum {string}
*/
Enums.FiltersAction = {
'None': 'None',
'Move': 'Move',
'Discard': 'Discard',
'Forward': 'Forward',
};
/**
* @enum {string}
*/
Enums.FilterRulesType = {
'And': 'And',
'Or': 'Or'
};
/**
* @enum {number}
*/
Enums.SignedVerifyStatus = {
'UnknownPublicKeys': -4,
'UnknownPrivateKey': -3,
'Unverified': -2,
'Error': -1,
'None': 0,
'Success': 1
};
/**
* @enum {number}
*/
Enums.ContactPropertyType = {
'Unknown': 0,
'FullName': 10,
'FirstName': 15,
'LastName': 16,
'MiddleName': 16,
'Nick': 18,
'NamePrefix': 20,
'NameSuffix': 21,
'Email': 30,
'Phone': 31,
'Web': 32,
'Birthday': 40,
'Facebook': 90,
'Skype': 91,
'GitHub': 92,
'Note': 110,
'Custom': 250
};
/**
* @enum {number}
*/
Enums.Notification = {
'InvalidToken': 101,
'AuthError': 102,
'AccessError': 103,
'ConnectionError': 104,
'CaptchaError': 105,
'SocialFacebookLoginAccessDisable': 106,
'SocialTwitterLoginAccessDisable': 107,
'SocialGoogleLoginAccessDisable': 108,
'DomainNotAllowed': 109,
'AccountNotAllowed': 110,
'AccountTwoFactorAuthRequired': 120,
'AccountTwoFactorAuthError': 121,
'CouldNotSaveNewPassword': 130,
'CurrentPasswordIncorrect': 131,
'NewPasswordShort': 132,
'NewPasswordWeak': 133,
'NewPasswordForbidden': 134,
'ContactsSyncError': 140,
'CantGetMessageList': 201,
'CantGetMessage': 202,
'CantDeleteMessage': 203,
'CantMoveMessage': 204,
'CantCopyMessage': 205,
'CantSaveMessage': 301,
'CantSendMessage': 302,
'InvalidRecipients': 303,
'CantCreateFolder': 400,
'CantRenameFolder': 401,
'CantDeleteFolder': 402,
'CantSubscribeFolder': 403,
'CantUnsubscribeFolder': 404,
'CantDeleteNonEmptyFolder': 405,
'CantSaveSettings': 501,
'CantSavePluginSettings': 502,
'DomainAlreadyExists': 601,
'CantInstallPackage': 701,
'CantDeletePackage': 702,
'InvalidPluginPackage': 703,
'UnsupportedPluginPackage': 704,
'LicensingServerIsUnavailable': 710,
'LicensingExpired': 711,
'LicensingBanned': 712,
'DemoSendMessageError': 750,
'AccountAlreadyExists': 801,
'MailServerError': 901,
'ClientViewError': 902,
'InvalidInputArgument': 903,
'UnknownNotification': 999,
'UnknownError': 999
};
module.exports = Enums;
}(module));
},{}],6:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
var
Globals = {},
window = require('../External/window.js'),
ko = require('../External/ko.js'),
$html = require('../External/$html.js')
;
/**
* @type {?}
*/
Globals.now = (new window.Date()).getTime();
/**
* @type {?}
*/
Globals.momentTrigger = ko.observable(true);
/**
* @type {?}
*/
Globals.dropdownVisibility = ko.observable(false).extend({'rateLimit': 0});
/**
* @type {?}
*/
Globals.tooltipTrigger = ko.observable(false).extend({'rateLimit': 0});
/**
* @type {?}
*/
Globals.langChangeTrigger = ko.observable(true);
/**
* @type {number}
*/
Globals.iAjaxErrorCount = 0;
/**
* @type {number}
*/
Globals.iTokenErrorCount = 0;
/**
* @type {number}
*/
Globals.iMessageBodyCacheCount = 0;
/**
* @type {boolean}
*/
Globals.bUnload = false;
/**
* @type {string}
*/
Globals.sUserAgent = (window.navigator.userAgent || '').toLowerCase();
/**
* @type {boolean}
*/
Globals.bIsiOSDevice = -1 < Globals.sUserAgent.indexOf('iphone') || -1 < Globals.sUserAgent.indexOf('ipod') || -1 < Globals.sUserAgent.indexOf('ipad');
/**
* @type {boolean}
*/
Globals.bIsAndroidDevice = -1 < Globals.sUserAgent.indexOf('android');
/**
* @type {boolean}
*/
Globals.bMobileDevice = Globals.bIsiOSDevice || Globals.bIsAndroidDevice;
/**
* @type {boolean}
*/
Globals.bDisableNanoScroll = Globals.bMobileDevice;
/**
* @type {boolean}
*/
Globals.bAllowPdfPreview = !Globals.bMobileDevice;
/**
* @type {boolean}
*/
Globals.bAnimationSupported = !Globals.bMobileDevice && $html.hasClass('csstransitions');
/**
* @type {boolean}
*/
Globals.bXMLHttpRequestSupported = !!window.XMLHttpRequest;
/**
* @type {string}
*/
Globals.sAnimationType = '';
/**
* @type {Object}
*/
Globals.oHtmlEditorDefaultConfig = {
'title': false,
'stylesSet': false,
'customConfig': '',
'contentsCss': '',
'toolbarGroups': [
{name: 'spec'},
{name: 'styles'},
{name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
{name: 'colors'},
{name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align']},
{name: 'links'},
{name: 'insert'},
{name: 'others'}
// {name: 'document', groups: ['mode', 'document', 'doctools']}
],
'removePlugins': 'contextmenu', //blockquote
'removeButtons': 'Format,Undo,Redo,Cut,Copy,Paste,Anchor,Strike,Subscript,Superscript,Image,SelectAll',
'removeDialogTabs': 'link:advanced;link:target;image:advanced;images:advanced',
'extraPlugins': 'plain',
'allowedContent': true,
'autoParagraph': false,
'font_defaultLabel': 'Arial',
'fontSize_defaultLabel': '13',
'fontSize_sizes': '10/10px;12/12px;13/13px;14/14px;16/16px;18/18px;20/20px;24/24px;28/28px;36/36px;48/48px'
};
/**
* @type {Object}
*/
Globals.oHtmlEditorLangsMap = {
'de': 'de',
'es': 'es',
'fr': 'fr',
'hu': 'hu',
'is': 'is',
'it': 'it',
'ko': 'ko',
'ko-kr': 'ko',
'lv': 'lv',
'nl': 'nl',
'no': 'no',
'pl': 'pl',
'pt': 'pt',
'pt-pt': 'pt',
'pt-br': 'pt-br',
'ru': 'ru',
'ro': 'ro',
'zh': 'zh',
'zh-cn': 'zh-cn'
};
if (Globals.bAllowPdfPreview && window.navigator && window.navigator.mimeTypes)
{
Globals.bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, function (oType) {
return oType && 'application/pdf' === oType.type;
});
}
Globals.oI18N = {},
Globals.oNotificationI18N = {},
Globals.aBootstrapDropdowns = [],
Globals.aViewModels = {
'settings': [],
'settings-removed': [],
'settings-disabled': []
};
module.exports = Globals;
}(module));
},{"../External/$html.js":10,"../External/ko.js":17,"../External/window.js":20}],7:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
var
Plugins = {},
Utils = require('./Utils.js')
;
/**
* @type {Object}
*/
Plugins.oViewModelsHooks = {};
/**
* @type {Object}
*/
Plugins.oSimpleHooks = {};
/**
* @param {string} sName
* @param {Function} ViewModel
*/
Plugins.regViewModelHook = function (sName, ViewModel)
{
if (ViewModel)
{
ViewModel.__hookName = sName;
}
};
/**
* @param {string} sName
* @param {Function} fCallback
*/
Plugins.addHook = function (sName, fCallback)
{
if (Utils.isFunc(fCallback))
{
if (!Utils.isArray(Plugins.oSimpleHooks[sName]))
{
Plugins.oSimpleHooks[sName] = [];
}
Plugins.oSimpleHooks[sName].push(fCallback);
}
};
/**
* @param {string} sName
* @param {Array=} aArguments
*/
Plugins.runHook = function (sName, aArguments)
{
if (Utils.isArray(Plugins.oSimpleHooks[sName]))
{
aArguments = aArguments || [];
_.each(Plugins.oSimpleHooks[sName], function (fCallback) {
fCallback.apply(null, aArguments);
});
}
};
/**
* @param {string} sName
* @return {?}
*/
Plugins.mainSettingsGet = function (sName)
{
return RL ? RL.settingsGet(sName) : null; // TODO cjs
};
/**
* @param {Function} fCallback
* @param {string} sAction
* @param {Object=} oParameters
* @param {?number=} iTimeout
* @param {string=} sGetAdd = ''
* @param {Array=} aAbortActions = []
*/
Plugins.remoteRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
{
if (RL) // TODO cjs
{
RL.remote().defaultRequest(fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions); // TODO cjs
}
};
/**
* @param {string} sPluginSection
* @param {string} sName
* @return {?}
*/
Plugins.settingsGet = function (sPluginSection, sName)
{
var oPlugin = Plugins.mainSettingsGet('Plugins');
oPlugin = oPlugin && Utils.isUnd(oPlugin[sPluginSection]) ? null : oPlugin[sPluginSection];
return oPlugin ? (Utils.isUnd(oPlugin[sName]) ? null : oPlugin[sName]) : null;
};
module.exports = Plugins;
}(module));
},{"./Utils.js":8}],8:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
var
Utils = {},
$ = require('../External/jquery.js'),
_ = require('../External/underscore.js'),
ko = require('../External/ko.js'),
window = require('../External/window.js'),
$window = require('../External/$window.js'),
$doc = require('../External/$doc.js'),
NotificationClass = require('../External/NotificationClass.js'),
Enums = require('./Enums.js'),
Globals = require('./Globals.js')
;
Utils.trim = $.trim;
Utils.inArray = $.inArray;
Utils.isArray = _.isArray;
Utils.isFunc = _.isFunction;
Utils.isUnd = _.isUndefined;
Utils.isNull = _.isNull;
Utils.emptyFunction = function () {};
/**
* @param {*} oValue
* @return {boolean}
*/
Utils.isNormal = function (oValue)
{
return !Utils.isUnd(oValue) && !Utils.isNull(oValue);
};
Utils.windowResize = _.debounce(function (iTimeout) {
if (Utils.isUnd(iTimeout))
{
$window.resize();
}
else
{
window.setTimeout(function () {
$window.resize();
}, iTimeout);
}
}, 50);
/**
* @param {(string|number)} mValue
* @param {boolean=} bIncludeZero
* @return {boolean}
*/
Utils.isPosNumeric = function (mValue, bIncludeZero)
{
return Utils.isNormal(mValue) ?
((Utils.isUnd(bIncludeZero) ? true : !!bIncludeZero) ?
(/^[0-9]*$/).test(mValue.toString()) :
(/^[1-9]+[0-9]*$/).test(mValue.toString())) :
false;
};
/**
* @param {*} iValue
* @param {number=} iDefault = 0
* @return {number}
*/
Utils.pInt = function (iValue, iDefault)
{
var iResult = Utils.isNormal(iValue) && '' !== iValue ? window.parseInt(iValue, 10) : (iDefault || 0);
return window.isNaN(iResult) ? (iDefault || 0) : iResult;
};
/**
* @param {*} mValue
* @return {string}
*/
Utils.pString = function (mValue)
{
return Utils.isNormal(mValue) ? '' + mValue : '';
};
/**
* @param {*} aValue
* @return {boolean}
*/
Utils.isNonEmptyArray = function (aValue)
{
return Utils.isArray(aValue) && 0 < aValue.length;
};
/**
* @param {string} sQueryString
* @return {Object}
*/
Utils.simpleQueryParser = function (sQueryString)
{
var
oParams = {},
aQueries = [],
aTemp = [],
iIndex = 0,
iLen = 0
;
aQueries = sQueryString.split('&');
for (iIndex = 0, iLen = aQueries.length; iIndex < iLen; iIndex++)
{
aTemp = aQueries[iIndex].split('=');
oParams[window.decodeURIComponent(aTemp[0])] = window.decodeURIComponent(aTemp[1]);
}
return oParams;
};
/**
* @param {string} aValue
* @param {string} sKey
* @param {string} sLongKey
* @return {string|boolean}
*/
Utils.rsaEncode = function (sValue, sHash, sKey, sLongKey)
{
if (window.crypto && window.crypto.getRandomValues && window.RSAKey && sHash && sKey && sLongKey)
{
var oRsa = new window.RSAKey();
oRsa.setPublic(sLongKey, sKey);
sValue = oRsa.encrypt(Utils.fakeMd5() + ':' + sValue + ':' + Utils.fakeMd5());
if (false !== sValue)
{
return 'rsa:' + sHash + ':' + sValue;
}
}
return false;
};
Utils.rsaEncode.supported = !!(window.crypto && window.crypto.getRandomValues && window.RSAKey);
/**
* @param {string} sPath
* @param {*=} oObject
* @param {Object=} oObjectToExportTo
*/
Utils.exportPath = function (sPath, oObject, oObjectToExportTo)
{
var
part = null,
parts = sPath.split('.'),
cur = oObjectToExportTo || window
;
for (; parts.length && (part = parts.shift());)
{
if (!parts.length && !Utils.isUnd(oObject))
{
cur[part] = oObject;
}
else if (cur[part])
{
cur = cur[part];
}
else
{
cur = cur[part] = {};
}
}
};
/**
* @param {Object} oObject
* @param {string} sName
* @param {*} mValue
*/
Utils.pImport = function (oObject, sName, mValue)
{
oObject[sName] = mValue;
};
/**
* @param {Object} oObject
* @param {string} sName
* @param {*} mDefault
* @return {*}
*/
Utils.pExport = function (oObject, sName, mDefault)
{
return Utils.isUnd(oObject[sName]) ? mDefault : oObject[sName];
};
/**
* @param {string} sText
* @return {string}
*/
Utils.encodeHtml = function (sText)
{
return Utils.isNormal(sText) ? sText.toString()
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&#039;') : '';
};
/**
* @param {string} sText
* @param {number=} iLen
* @return {string}
*/
Utils.splitPlainText = function (sText, iLen)
{
var
sPrefix = '',
sSubText = '',
sResult = sText,
iSpacePos = 0,
iNewLinePos = 0
;
iLen = Utils.isUnd(iLen) ? 100 : iLen;
while (sResult.length > iLen)
{
sSubText = sResult.substring(0, iLen);
iSpacePos = sSubText.lastIndexOf(' ');
iNewLinePos = sSubText.lastIndexOf('\n');
if (-1 !== iNewLinePos)
{
iSpacePos = iNewLinePos;
}
if (-1 === iSpacePos)
{
iSpacePos = iLen;
}
sPrefix += sSubText.substring(0, iSpacePos) + '\n';
sResult = sResult.substring(iSpacePos + 1);
}
return sPrefix + sResult;
};
Utils.timeOutAction = (function () {
var
oTimeOuts = {}
;
return function (sAction, fFunction, iTimeOut)
{
if (Utils.isUnd(oTimeOuts[sAction]))
{
oTimeOuts[sAction] = 0;
}
window.clearTimeout(oTimeOuts[sAction]);
oTimeOuts[sAction] = window.setTimeout(fFunction, iTimeOut);
};
}());
Utils.timeOutActionSecond = (function () {
var
oTimeOuts = {}
;
return function (sAction, fFunction, iTimeOut)
{
if (!oTimeOuts[sAction])
{
oTimeOuts[sAction] = window.setTimeout(function () {
fFunction();
oTimeOuts[sAction] = 0;
}, iTimeOut);
}
};
}());
Utils.audio = (function () {
var
oAudio = false
;
return function (sMp3File, sOggFile) {
if (false === oAudio)
{
if (Globals.bIsiOSDevice)
{
oAudio = null;
}
else
{
var
bCanPlayMp3 = false,
bCanPlayOgg = false,
oAudioLocal = window.Audio ? new window.Audio() : null
;
if (oAudioLocal && oAudioLocal.canPlayType && oAudioLocal.play)
{
bCanPlayMp3 = '' !== oAudioLocal.canPlayType('audio/mpeg; codecs="mp3"');
if (!bCanPlayMp3)
{
bCanPlayOgg = '' !== oAudioLocal.canPlayType('audio/ogg; codecs="vorbis"');
}
if (bCanPlayMp3 || bCanPlayOgg)
{
oAudio = oAudioLocal;
oAudio.preload = 'none';
oAudio.loop = false;
oAudio.autoplay = false;
oAudio.muted = false;
oAudio.src = bCanPlayMp3 ? sMp3File : sOggFile;
}
else
{
oAudio = null;
}
}
else
{
oAudio = null;
}
}
}
return oAudio;
};
}());
/**
* @param {(Object|null|undefined)} oObject
* @param {string} sProp
* @return {boolean}
*/
Utils.hos = function (oObject, sProp)
{
return oObject && window.Object && window.Object.hasOwnProperty ? window.Object.hasOwnProperty.call(oObject, sProp) : false;
};
/**
* @param {string} sKey
* @param {Object=} oValueList
* @param {string=} sDefaulValue
* @return {string}
*/
Utils.i18n = function (sKey, oValueList, sDefaulValue)
{
var
sValueName = '',
sResult = Utils.isUnd(Globals.oI18N[sKey]) ? (Utils.isUnd(sDefaulValue) ? sKey : sDefaulValue) : Globals.oI18N[sKey]
;
if (!Utils.isUnd(oValueList) && !Utils.isNull(oValueList))
{
for (sValueName in oValueList)
{
if (Utils.hos(oValueList, sValueName))
{
sResult = sResult.replace('%' + sValueName + '%', oValueList[sValueName]);
}
}
}
return sResult;
};
/**
* @param {Object} oElement
*/
Utils.i18nToNode = function (oElement)
{
_.defer(function () {
$('.i18n', oElement).each(function () {
var
jqThis = $(this),
sKey = ''
;
sKey = jqThis.data('i18n-text');
if (sKey)
{
jqThis.text(Utils.i18n(sKey));
}
else
{
sKey = jqThis.data('i18n-html');
if (sKey)
{
jqThis.html(Utils.i18n(sKey));
}
sKey = jqThis.data('i18n-placeholder');
if (sKey)
{
jqThis.attr('placeholder', Utils.i18n(sKey));
}
sKey = jqThis.data('i18n-title');
if (sKey)
{
jqThis.attr('title', Utils.i18n(sKey));
}
}
});
});
};
Utils.i18nReload = function ()
{
if (window['rainloopI18N'])
{
Globals.oI18N = window['rainloopI18N'] || {};
Utils.i18nToNode($doc);
Globals.langChangeTrigger(!Globals.langChangeTrigger());
}
window['rainloopI18N'] = null;
};
/**
* @param {Function} fCallback
* @param {Object} oScope
* @param {Function=} fLangCallback
*/
Utils.initOnStartOrLangChange = function (fCallback, oScope, fLangCallback)
{
if (fCallback)
{
fCallback.call(oScope);
}
if (fLangCallback)
{
Globals.langChangeTrigger.subscribe(function () {
if (fCallback)
{
fCallback.call(oScope);
}
fLangCallback.call(oScope);
});
}
else if (fCallback)
{
Globals.langChangeTrigger.subscribe(fCallback, oScope);
}
};
/**
* @return {boolean}
*/
Utils.inFocus = function ()
{
if (document.activeElement)
{
if (Utils.isUnd(document.activeElement.__inFocusCache))
{
document.activeElement.__inFocusCache = $(document.activeElement).is('input,textarea,iframe,.cke_editable');
}
return !!document.activeElement.__inFocusCache;
}
return false;
};
Utils.removeInFocus = function ()
{
if (document && document.activeElement && document.activeElement.blur)
{
var oA = $(document.activeElement);
if (oA.is('input,textarea'))
{
document.activeElement.blur();
}
}
};
Utils.removeSelection = function ()
{
if (window && window.getSelection)
{
var oSel = window.getSelection();
if (oSel && oSel.removeAllRanges)
{
oSel.removeAllRanges();
}
}
else if (document && document.selection && document.selection.empty)
{
document.selection.empty();
}
};
/**
* @param {string} sPrefix
* @param {string} sSubject
* @return {string}
*/
Utils.replySubjectAdd = function (sPrefix, sSubject)
{
sPrefix = Utils.trim(sPrefix.toUpperCase());
sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
var
iIndex = 0,
sResult = '',
bDrop = false,
sTrimmedPart = '',
aSubject = [],
aParts = [],
bRe = 'RE' === sPrefix,
bFwd = 'FWD' === sPrefix,
bPrefixIsRe = !bFwd
;
if ('' !== sSubject)
{
bDrop = false;
aParts = sSubject.split(':');
for (iIndex = 0; iIndex < aParts.length; iIndex++)
{
sTrimmedPart = Utils.trim(aParts[iIndex]);
if (!bDrop &&
(/^(RE|FWD)$/i.test(sTrimmedPart) || /^(RE|FWD)[\[\(][\d]+[\]\)]$/i.test(sTrimmedPart))
)
{
if (!bRe)
{
bRe = !!(/^RE/i.test(sTrimmedPart));
}
if (!bFwd)
{
bFwd = !!(/^FWD/i.test(sTrimmedPart));
}
}
else
{
aSubject.push(aParts[iIndex]);
bDrop = true;
}
}
if (0 < aSubject.length)
{
sResult = Utils.trim(aSubject.join(':'));
}
}
if (bPrefixIsRe)
{
bRe = false;
}
else
{
bFwd = false;
}
return Utils.trim(
(bPrefixIsRe ? 'Re: ' : 'Fwd: ') +
(bRe ? 'Re: ' : '') +
(bFwd ? 'Fwd: ' : '') +
sResult
);
};
/**
* @param {string} sSubject
* @return {string}
*/
Utils.fixLongSubject = function (sSubject)
{
var
iLimit = 30,
mReg = /^Re([\[\(]([\d]+)[\]\)]|):[\s]{0,3}Re([\[\(]([\d]+)[\]\)]|):/ig,
oMatch = null
;
sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
do
{
iLimit--;
oMatch = mReg.exec(sSubject);
if (!oMatch || Utils.isUnd(oMatch[0]))
{
oMatch = null;
}
if (oMatch)
{
sSubject = sSubject.replace(mReg, 'Re:');
}
}
while (oMatch || 0 < iLimit);
return sSubject.replace(/[\s]+/, ' ');
};
/**
* @deprecated
* @param {string} sPrefix
* @param {string} sSubject
* @param {boolean=} bFixLongSubject = true
* @return {string}
*/
Utils._replySubjectAdd_ = function (sPrefix, sSubject, bFixLongSubject)
{
var
oMatch = null,
sResult = Utils.trim(sSubject)
;
if (null !== (oMatch = (new window.RegExp('^' + sPrefix + '[\\s]?\\:(.*)$', 'gi')).exec(sSubject)) && !Utils.isUnd(oMatch[1]))
{
sResult = sPrefix + '[2]: ' + oMatch[1];
}
else if (null !== (oMatch = (new window.RegExp('^(' + sPrefix + '[\\s]?[\\[\\(]?)([\\d]+)([\\]\\)]?[\\s]?\\:.*)$', 'gi')).exec(sSubject)) &&
!Utils.isUnd(oMatch[1]) && !Utils.isUnd(oMatch[2]) && !Utils.isUnd(oMatch[3]))
{
sResult = oMatch[1] + (Utils.pInt(oMatch[2]) + 1) + oMatch[3];
}
else
{
sResult = sPrefix + ': ' + sSubject;
}
sResult = sResult.replace(/[\s]+/g, ' ');
sResult = (Utils.isUnd(bFixLongSubject) ? true : bFixLongSubject) ? Utils.fixLongSubject(sResult) : sResult;
// sResult = sResult.replace(/^(Re|Fwd)[\s]?\[[\d]+\]:/ig, '$1:');
return sResult;
};
/**
* @deprecated
* @param {string} sSubject
* @return {string}
*/
Utils._fixLongSubject_ = function (sSubject)
{
var
iCounter = 0,
oMatch = null
;
sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
do
{
oMatch = /^Re(\[([\d]+)\]|):[\s]{0,3}Re(\[([\d]+)\]|):/ig.exec(sSubject);
if (!oMatch || Utils.isUnd(oMatch[0]))
{
oMatch = null;
}
if (oMatch)
{
iCounter = 0;
iCounter += Utils.isUnd(oMatch[2]) ? 1 : 0 + Utils.pInt(oMatch[2]);
iCounter += Utils.isUnd(oMatch[4]) ? 1 : 0 + Utils.pInt(oMatch[4]);
sSubject = sSubject.replace(/^Re(\[[\d]+\]|):[\s]{0,3}Re(\[[\d]+\]|):/gi, 'Re' + (0 < iCounter ? '[' + iCounter + ']' : '') + ':');
}
}
while (oMatch);
sSubject = sSubject.replace(/[\s]+/, ' ');
return sSubject;
};
/**
* @param {number} iNum
* @param {number} iDec
* @return {number}
*/
Utils.roundNumber = function (iNum, iDec)
{
return Math.round(iNum * Math.pow(10, iDec)) / Math.pow(10, iDec);
};
/**
* @param {(number|string)} iSizeInBytes
* @return {string}
*/
Utils.friendlySize = function (iSizeInBytes)
{
iSizeInBytes = Utils.pInt(iSizeInBytes);
if (iSizeInBytes >= 1073741824)
{
return Utils.roundNumber(iSizeInBytes / 1073741824, 1) + 'GB';
}
else if (iSizeInBytes >= 1048576)
{
return Utils.roundNumber(iSizeInBytes / 1048576, 1) + 'MB';
}
else if (iSizeInBytes >= 1024)
{
return Utils.roundNumber(iSizeInBytes / 1024, 0) + 'KB';
}
return iSizeInBytes + 'B';
};
/**
* @param {string} sDesc
*/
Utils.log = function (sDesc)
{
if (window.console && window.console.log)
{
window.console.log(sDesc);
}
};
/**
* @param {number} iCode
* @param {*=} mMessage = ''
* @return {string}
*/
Utils.getNotification = function (iCode, mMessage)
{
iCode = Utils.pInt(iCode);
if (Enums.Notification.ClientViewError === iCode && mMessage)
{
return mMessage;
}
return Utils.isUnd(Globals.oNotificationI18N[iCode]) ? '' : Globals.oNotificationI18N[iCode];
};
Utils.initNotificationLanguage = function ()
{
var oN = Globals.oNotificationI18N || {};
oN[Enums.Notification.InvalidToken] = Utils.i18n('NOTIFICATIONS/INVALID_TOKEN');
oN[Enums.Notification.AuthError] = Utils.i18n('NOTIFICATIONS/AUTH_ERROR');
oN[Enums.Notification.AccessError] = Utils.i18n('NOTIFICATIONS/ACCESS_ERROR');
oN[Enums.Notification.ConnectionError] = Utils.i18n('NOTIFICATIONS/CONNECTION_ERROR');
oN[Enums.Notification.CaptchaError] = Utils.i18n('NOTIFICATIONS/CAPTCHA_ERROR');
oN[Enums.Notification.SocialFacebookLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_FACEBOOK_LOGIN_ACCESS_DISABLE');
oN[Enums.Notification.SocialTwitterLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_TWITTER_LOGIN_ACCESS_DISABLE');
oN[Enums.Notification.SocialGoogleLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_GOOGLE_LOGIN_ACCESS_DISABLE');
oN[Enums.Notification.DomainNotAllowed] = Utils.i18n('NOTIFICATIONS/DOMAIN_NOT_ALLOWED');
oN[Enums.Notification.AccountNotAllowed] = Utils.i18n('NOTIFICATIONS/ACCOUNT_NOT_ALLOWED');
oN[Enums.Notification.AccountTwoFactorAuthRequired] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_REQUIRED');
oN[Enums.Notification.AccountTwoFactorAuthError] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_ERROR');
oN[Enums.Notification.CouldNotSaveNewPassword] = Utils.i18n('NOTIFICATIONS/COULD_NOT_SAVE_NEW_PASSWORD');
oN[Enums.Notification.CurrentPasswordIncorrect] = Utils.i18n('NOTIFICATIONS/CURRENT_PASSWORD_INCORRECT');
oN[Enums.Notification.NewPasswordShort] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_SHORT');
oN[Enums.Notification.NewPasswordWeak] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_WEAK');
oN[Enums.Notification.NewPasswordForbidden] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_FORBIDDENT');
oN[Enums.Notification.ContactsSyncError] = Utils.i18n('NOTIFICATIONS/CONTACTS_SYNC_ERROR');
oN[Enums.Notification.CantGetMessageList] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST');
oN[Enums.Notification.CantGetMessage] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE');
oN[Enums.Notification.CantDeleteMessage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_MESSAGE');
oN[Enums.Notification.CantMoveMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
oN[Enums.Notification.CantCopyMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
oN[Enums.Notification.CantSaveMessage] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_MESSAGE');
oN[Enums.Notification.CantSendMessage] = Utils.i18n('NOTIFICATIONS/CANT_SEND_MESSAGE');
oN[Enums.Notification.InvalidRecipients] = Utils.i18n('NOTIFICATIONS/INVALID_RECIPIENTS');
oN[Enums.Notification.CantCreateFolder] = Utils.i18n('NOTIFICATIONS/CANT_CREATE_FOLDER');
oN[Enums.Notification.CantRenameFolder] = Utils.i18n('NOTIFICATIONS/CANT_RENAME_FOLDER');
oN[Enums.Notification.CantDeleteFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_FOLDER');
oN[Enums.Notification.CantDeleteNonEmptyFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_NON_EMPTY_FOLDER');
oN[Enums.Notification.CantSubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_SUBSCRIBE_FOLDER');
oN[Enums.Notification.CantUnsubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_UNSUBSCRIBE_FOLDER');
oN[Enums.Notification.CantSaveSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_SETTINGS');
oN[Enums.Notification.CantSavePluginSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_PLUGIN_SETTINGS');
oN[Enums.Notification.DomainAlreadyExists] = Utils.i18n('NOTIFICATIONS/DOMAIN_ALREADY_EXISTS');
oN[Enums.Notification.CantInstallPackage] = Utils.i18n('NOTIFICATIONS/CANT_INSTALL_PACKAGE');
oN[Enums.Notification.CantDeletePackage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_PACKAGE');
oN[Enums.Notification.InvalidPluginPackage] = Utils.i18n('NOTIFICATIONS/INVALID_PLUGIN_PACKAGE');
oN[Enums.Notification.UnsupportedPluginPackage] = Utils.i18n('NOTIFICATIONS/UNSUPPORTED_PLUGIN_PACKAGE');
oN[Enums.Notification.LicensingServerIsUnavailable] = Utils.i18n('NOTIFICATIONS/LICENSING_SERVER_IS_UNAVAILABLE');
oN[Enums.Notification.LicensingExpired] = Utils.i18n('NOTIFICATIONS/LICENSING_EXPIRED');
oN[Enums.Notification.LicensingBanned] = Utils.i18n('NOTIFICATIONS/LICENSING_BANNED');
oN[Enums.Notification.DemoSendMessageError] = Utils.i18n('NOTIFICATIONS/DEMO_SEND_MESSAGE_ERROR');
oN[Enums.Notification.AccountAlreadyExists] = Utils.i18n('NOTIFICATIONS/ACCOUNT_ALREADY_EXISTS');
oN[Enums.Notification.MailServerError] = Utils.i18n('NOTIFICATIONS/MAIL_SERVER_ERROR');
oN[Enums.Notification.InvalidInputArgument] = Utils.i18n('NOTIFICATIONS/INVALID_INPUT_ARGUMENT');
oN[Enums.Notification.UnknownNotification] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
oN[Enums.Notification.UnknownError] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
};
/**
* @param {*} mCode
* @return {string}
*/
Utils.getUploadErrorDescByCode = function (mCode)
{
var sResult = '';
switch (Utils.pInt(mCode)) {
case Enums.UploadErrorCode.FileIsTooBig:
sResult = Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG');
break;
case Enums.UploadErrorCode.FilePartiallyUploaded:
sResult = Utils.i18n('UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED');
break;
case Enums.UploadErrorCode.FileNoUploaded:
sResult = Utils.i18n('UPLOAD/ERROR_NO_FILE_UPLOADED');
break;
case Enums.UploadErrorCode.MissingTempFolder:
sResult = Utils.i18n('UPLOAD/ERROR_MISSING_TEMP_FOLDER');
break;
case Enums.UploadErrorCode.FileOnSaveingError:
sResult = Utils.i18n('UPLOAD/ERROR_ON_SAVING_FILE');
break;
case Enums.UploadErrorCode.FileType:
sResult = Utils.i18n('UPLOAD/ERROR_FILE_TYPE');
break;
default:
sResult = Utils.i18n('UPLOAD/ERROR_UNKNOWN');
break;
}
return sResult;
};
/**
* @param {?} oObject
* @param {string} sMethodName
* @param {Array=} aParameters
* @param {number=} nDelay
*/
Utils.delegateRun = function (oObject, sMethodName, aParameters, nDelay)
{
if (oObject && oObject[sMethodName])
{
nDelay = Utils.pInt(nDelay);
if (0 >= nDelay)
{
oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
}
else
{
_.delay(function () {
oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
}, nDelay);
}
}
};
/**
* @param {?} oEvent
*/
Utils.killCtrlAandS = function (oEvent)
{
oEvent = oEvent || window.event;
if (oEvent && oEvent.ctrlKey && !oEvent.shiftKey && !oEvent.altKey)
{
var
oSender = oEvent.target || oEvent.srcElement,
iKey = oEvent.keyCode || oEvent.which
;
if (iKey === Enums.EventKeyCode.S)
{
oEvent.preventDefault();
return;
}
if (oSender && oSender.tagName && oSender.tagName.match(/INPUT|TEXTAREA/i))
{
return;
}
if (iKey === Enums.EventKeyCode.A)
{
if (window.getSelection)
{
window.getSelection().removeAllRanges();
}
else if (window.document.selection && window.document.selection.clear)
{
window.document.selection.clear();
}
oEvent.preventDefault();
}
}
};
/**
* @param {(Object|null|undefined)} oContext
* @param {Function} fExecute
* @param {(Function|boolean|null)=} fCanExecute
* @return {Function}
*/
Utils.createCommand = function (oContext, fExecute, fCanExecute)
{
var
fResult = fExecute ? function () {
if (fResult.canExecute && fResult.canExecute())
{
fExecute.apply(oContext, Array.prototype.slice.call(arguments));
}
return false;
} : function () {}
;
fResult.enabled = ko.observable(true);
fCanExecute = Utils.isUnd(fCanExecute) ? true : fCanExecute;
if (Utils.isFunc(fCanExecute))
{
fResult.canExecute = ko.computed(function () {
return fResult.enabled() && fCanExecute.call(oContext);
});
}
else
{
fResult.canExecute = ko.computed(function () {
return fResult.enabled() && !!fCanExecute;
});
}
return fResult;
};
/**
* @param {Object} oData
*/
Utils.initDataConstructorBySettings = function (oData)
{
oData.editorDefaultType = ko.observable(Enums.EditorDefaultType.Html);
oData.showImages = ko.observable(false);
oData.interfaceAnimation = ko.observable(Enums.InterfaceAnimation.Full);
oData.contactsAutosave = ko.observable(false);
Globals.sAnimationType = Enums.InterfaceAnimation.Full;
oData.capaThemes = ko.observable(false);
oData.allowLanguagesOnSettings = ko.observable(true);
oData.allowLanguagesOnLogin = ko.observable(true);
oData.useLocalProxyForExternalImages = ko.observable(false);
oData.desktopNotifications = ko.observable(false);
oData.useThreads = ko.observable(true);
oData.replySameFolder = ko.observable(true);
oData.useCheckboxesInList = ko.observable(true);
oData.layout = ko.observable(Enums.Layout.SidePreview);
oData.usePreviewPane = ko.computed(function () {
return Enums.Layout.NoPreview !== oData.layout();
});
oData.interfaceAnimation.subscribe(function (sValue) {
if (Globals.bMobileDevice || sValue === Enums.InterfaceAnimation.None)
{
$html.removeClass('rl-anim rl-anim-full').addClass('no-rl-anim');
Globals.sAnimationType = Enums.InterfaceAnimation.None;
}
else
{
switch (sValue)
{
case Enums.InterfaceAnimation.Full:
$html.removeClass('no-rl-anim').addClass('rl-anim rl-anim-full');
Globals.sAnimationType = sValue;
break;
case Enums.InterfaceAnimation.Normal:
$html.removeClass('no-rl-anim rl-anim-full').addClass('rl-anim');
Globals.sAnimationType = sValue;
break;
}
}
});
oData.interfaceAnimation.valueHasMutated();
oData.desktopNotificationsPermisions = ko.computed(function () {
oData.desktopNotifications();
var iResult = Enums.DesktopNotifications.NotSupported;
if (NotificationClass && NotificationClass.permission)
{
switch (NotificationClass.permission.toLowerCase())
{
case 'granted':
iResult = Enums.DesktopNotifications.Allowed;
break;
case 'denied':
iResult = Enums.DesktopNotifications.Denied;
break;
case 'default':
iResult = Enums.DesktopNotifications.NotAllowed;
break;
}
}
else if (window.webkitNotifications && window.webkitNotifications.checkPermission)
{
iResult = window.webkitNotifications.checkPermission();
}
return iResult;
});
oData.useDesktopNotifications = ko.computed({
'read': function () {
return oData.desktopNotifications() &&
Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions();
},
'write': function (bValue) {
if (bValue)
{
var iPermission = oData.desktopNotificationsPermisions();
if (Enums.DesktopNotifications.Allowed === iPermission)
{
oData.desktopNotifications(true);
}
else if (Enums.DesktopNotifications.NotAllowed === iPermission)
{
NotificationClass.requestPermission(function () {
oData.desktopNotifications.valueHasMutated();
if (Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions())
{
if (oData.desktopNotifications())
{
oData.desktopNotifications.valueHasMutated();
}
else
{
oData.desktopNotifications(true);
}
}
else
{
if (oData.desktopNotifications())
{
oData.desktopNotifications(false);
}
else
{
oData.desktopNotifications.valueHasMutated();
}
}
});
}
else
{
oData.desktopNotifications(false);
}
}
else
{
oData.desktopNotifications(false);
}
}
});
oData.language = ko.observable('');
oData.languages = ko.observableArray([]);
oData.mainLanguage = ko.computed({
'read': oData.language,
'write': function (sValue) {
if (sValue !== oData.language())
{
if (-1 < Utils.inArray(sValue, oData.languages()))
{
oData.language(sValue);
}
else if (0 < oData.languages().length)
{
oData.language(oData.languages()[0]);
}
}
else
{
oData.language.valueHasMutated();
}
}
});
oData.theme = ko.observable('');
oData.themes = ko.observableArray([]);
oData.mainTheme = ko.computed({
'read': oData.theme,
'write': function (sValue) {
if (sValue !== oData.theme())
{
var aThemes = oData.themes();
if (-1 < Utils.inArray(sValue, aThemes))
{
oData.theme(sValue);
}
else if (0 < aThemes.length)
{
oData.theme(aThemes[0]);
}
}
else
{
oData.theme.valueHasMutated();
}
}
});
oData.capaAdditionalAccounts = ko.observable(false);
oData.capaAdditionalIdentities = ko.observable(false);
oData.capaGravatar = ko.observable(false);
oData.determineUserLanguage = ko.observable(false);
oData.determineUserDomain = ko.observable(false);
oData.messagesPerPage = ko.observable(Consts.Defaults.MessagesPerPage);//.extend({'throttle': 200});
oData.mainMessagesPerPage = oData.messagesPerPage;
oData.mainMessagesPerPage = ko.computed({
'read': oData.messagesPerPage,
'write': function (iValue) {
if (-1 < Utils.inArray(Utils.pInt(iValue), Consts.Defaults.MessagesPerPageArray))
{
if (iValue !== oData.messagesPerPage())
{
oData.messagesPerPage(iValue);
}
}
else
{
oData.messagesPerPage.valueHasMutated();
}
}
});
oData.facebookSupported = ko.observable(false);
oData.facebookEnable = ko.observable(false);
oData.facebookAppID = ko.observable('');
oData.facebookAppSecret = ko.observable('');
oData.twitterEnable = ko.observable(false);
oData.twitterConsumerKey = ko.observable('');
oData.twitterConsumerSecret = ko.observable('');
oData.googleEnable = ko.observable(false);
oData.googleClientID = ko.observable('');
oData.googleClientSecret = ko.observable('');
oData.googleApiKey = ko.observable('');
oData.dropboxEnable = ko.observable(false);
oData.dropboxApiKey = ko.observable('');
oData.contactsIsAllowed = ko.observable(false);
};
/**
* @param {{moment:Function}} oObject
*/
Utils.createMomentDate = function (oObject)
{
if (Utils.isUnd(oObject.moment))
{
oObject.moment = ko.observable(moment());
}
return ko.computed(function () {
Globals.momentTrigger();
var oMoment = this.moment();
return 1970 === oMoment.year() ? '' : oMoment.fromNow();
}, oObject);
};
/**
* @param {{moment:Function, momentDate:Function}} oObject
*/
Utils.createMomentShortDate = function (oObject)
{
return ko.computed(function () {
var
sResult = '',
oMomentNow = moment(),
oMoment = this.moment(),
sMomentDate = this.momentDate()
;
if (1970 === oMoment.year())
{
sResult = '';
}
else if (4 >= oMomentNow.diff(oMoment, 'hours'))
{
sResult = sMomentDate;
}
else if (oMomentNow.format('L') === oMoment.format('L'))
{
sResult = Utils.i18n('MESSAGE_LIST/TODAY_AT', {
'TIME': oMoment.format('LT')
});
}
else if (oMomentNow.clone().subtract('days', 1).format('L') === oMoment.format('L'))
{
sResult = Utils.i18n('MESSAGE_LIST/YESTERDAY_AT', {
'TIME': oMoment.format('LT')
});
}
else if (oMomentNow.year() === oMoment.year())
{
sResult = oMoment.format('D MMM.');
}
else
{
sResult = oMoment.format('LL');
}
return sResult;
}, oObject);
};
/**
* @param {string} sFullNameHash
* @return {boolean}
*/
Utils.isFolderExpanded = function (sFullNameHash)
{
var aExpandedList = /** @type {Array|null} */ RL.local().get(Enums.ClientSideKeyName.ExpandedFolders);
return _.isArray(aExpandedList) && -1 !== _.indexOf(aExpandedList, sFullNameHash);
};
/**
* @param {string} sFullNameHash
* @param {boolean} bExpanded
*/
Utils.setExpandedFolder = function (sFullNameHash, bExpanded)
{
var aExpandedList = /** @type {Array|null} */ RL.local().get(Enums.ClientSideKeyName.ExpandedFolders);
if (!_.isArray(aExpandedList))
{
aExpandedList = [];
}
if (bExpanded)
{
aExpandedList.push(sFullNameHash);
aExpandedList = _.uniq(aExpandedList);
}
else
{
aExpandedList = _.without(aExpandedList, sFullNameHash);
}
RL.local().set(Enums.ClientSideKeyName.ExpandedFolders, aExpandedList);
};
Utils.initLayoutResizer = function (sLeft, sRight, sClientSideKeyName)
{
var
iDisabledWidth = 60,
iMinWidth = 155,
oLeft = $(sLeft),
oRight = $(sRight),
mLeftWidth = RL.local().get(sClientSideKeyName) || null,
fSetWidth = function (iWidth) {
if (iWidth)
{
oLeft.css({
'width': '' + iWidth + 'px'
});
oRight.css({
'left': '' + iWidth + 'px'
});
}
},
fDisable = function (bDisable) {
if (bDisable)
{
oLeft.resizable('disable');
fSetWidth(iDisabledWidth);
}
else
{
oLeft.resizable('enable');
var iWidth = Utils.pInt(RL.local().get(sClientSideKeyName)) || iMinWidth;
fSetWidth(iWidth > iMinWidth ? iWidth : iMinWidth);
}
},
fResizeFunction = function (oEvent, oObject) {
if (oObject && oObject.size && oObject.size.width)
{
RL.local().set(sClientSideKeyName, oObject.size.width);
oRight.css({
'left': '' + oObject.size.width + 'px'
});
}
}
;
if (null !== mLeftWidth)
{
fSetWidth(mLeftWidth > iMinWidth ? mLeftWidth : iMinWidth);
}
oLeft.resizable({
'helper': 'ui-resizable-helper',
'minWidth': iMinWidth,
'maxWidth': 350,
'handles': 'e',
'stop': fResizeFunction
});
RL.sub('left-panel.off', function () {
fDisable(true);
});
RL.sub('left-panel.on', function () {
fDisable(false);
});
};
/**
* @param {Object} oMessageTextBody
*/
Utils.initBlockquoteSwitcher = function (oMessageTextBody)
{
if (oMessageTextBody)
{
var $oList = $('blockquote:not(.rl-bq-switcher)', oMessageTextBody).filter(function () {
return 0 === $(this).parent().closest('blockquote', oMessageTextBody).length;
});
if ($oList && 0 < $oList.length)
{
$oList.each(function () {
var $self = $(this), iH = $self.height();
if (0 === iH || 100 < iH)
{
$self.addClass('rl-bq-switcher hidden-bq');
$('<span class="rlBlockquoteSwitcher"><i class="icon-ellipsis" /></span>')
.insertBefore($self)
.click(function () {
$self.toggleClass('hidden-bq');
Utils.windowResize();
})
.after('<br />')
.before('<br />')
;
}
});
}
}
};
/**
* @param {Object} oMessageTextBody
*/
Utils.removeBlockquoteSwitcher = function (oMessageTextBody)
{
if (oMessageTextBody)
{
$(oMessageTextBody).find('blockquote.rl-bq-switcher').each(function () {
$(this).removeClass('rl-bq-switcher hidden-bq');
});
$(oMessageTextBody).find('.rlBlockquoteSwitcher').each(function () {
$(this).remove();
});
}
};
/**
* @param {Object} oMessageTextBody
*/
Utils.toggleMessageBlockquote = function (oMessageTextBody)
{
if (oMessageTextBody)
{
oMessageTextBody.find('.rlBlockquoteSwitcher').click();
}
};
/**
* @param {string} sName
* @param {Function} ViewModelClass
* @param {Function=} AbstractViewModel = KnoinAbstractViewModel
*/
Utils.extendAsViewModel = function (sName, ViewModelClass, AbstractViewModel)
{
if (ViewModelClass)
{
if (!AbstractViewModel)
{
AbstractViewModel = KnoinAbstractViewModel;
}
ViewModelClass.__name = sName;
Plugins.regViewModelHook(sName, ViewModelClass);
_.extend(ViewModelClass.prototype, AbstractViewModel.prototype);
}
};
/**
* @param {Function} SettingsViewModelClass
* @param {string} sLabelName
* @param {string} sTemplate
* @param {string} sRoute
* @param {boolean=} bDefault
*/
Utils.addSettingsViewModel = function (SettingsViewModelClass, sTemplate, sLabelName, sRoute, bDefault)
{
SettingsViewModelClass.__rlSettingsData = {
'Label': sLabelName,
'Template': sTemplate,
'Route': sRoute,
'IsDefault': !!bDefault
};
Globals.aViewModels['settings'].push(SettingsViewModelClass);
};
/**
* @param {Function} SettingsViewModelClass
*/
Utils.removeSettingsViewModel = function (SettingsViewModelClass)
{
Globals.aViewModels['settings-removed'].push(SettingsViewModelClass);
};
/**
* @param {Function} SettingsViewModelClass
*/
Utils.disableSettingsViewModel = function (SettingsViewModelClass)
{
Globals.aViewModels['settings-disabled'].push(SettingsViewModelClass);
};
Utils.convertThemeName = function (sTheme)
{
if ('@custom' === sTheme.substr(-7))
{
sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
}
return Utils.trim(sTheme.replace(/[^a-zA-Z]+/g, ' ').replace(/([A-Z])/g, ' $1').replace(/[\s]+/g, ' '));
};
/**
* @param {string} sName
* @return {string}
*/
Utils.quoteName = function (sName)
{
return sName.replace(/["]/g, '\\"');
};
/**
* @return {number}
*/
Utils.microtime = function ()
{
return (new Date()).getTime();
};
/**
*
* @param {string} sLanguage
* @param {boolean=} bEng = false
* @return {string}
*/
Utils.convertLangName = function (sLanguage, bEng)
{
return Utils.i18n('LANGS_NAMES' + (true === bEng ? '_EN' : '') + '/LANG_' +
sLanguage.toUpperCase().replace(/[^a-zA-Z0-9]+/, '_'), null, sLanguage);
};
/**
* @param {number=} iLen
* @return {string}
*/
Utils.fakeMd5 = function(iLen)
{
var
sResult = '',
sLine = '0123456789abcdefghijklmnopqrstuvwxyz'
;
iLen = Utils.isUnd(iLen) ? 32 : Utils.pInt(iLen);
while (sResult.length < iLen)
{
sResult += sLine.substr(Math.round(Math.random() * sLine.length), 1);
}
return sResult;
};
/* jshint ignore:start */
/**
* @param {string} s
* @return {string}
*/
Utils.md5 = function(s){function L(k,d){return(k<<d)|(k>>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H<F){Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=(aa[Z]|(G.charCodeAt(H)<<d));H++}Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=aa[Z]|(128<<d);aa[I-2]=F<<3;aa[I-1]=F>>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F<k.length;F++){var x=k.charCodeAt(F);if(x<128){d+=String.fromCharCode(x)}else{if((x>127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P<C.length;P+=16){h=Y;E=X;v=W;g=V;Y=u(Y,X,W,V,C[P+0],S,3614090360);V=u(V,Y,X,W,C[P+1],Q,3905402710);W=u(W,V,Y,X,C[P+2],N,606105819);X=u(X,W,V,Y,C[P+3],M,3250441966);Y=u(Y,X,W,V,C[P+4],S,4118548399);V=u(V,Y,X,W,C[P+5],Q,1200080426);W=u(W,V,Y,X,C[P+6],N,2821735955);X=u(X,W,V,Y,C[P+7],M,4249261313);Y=u(Y,X,W,V,C[P+8],S,1770035416);V=u(V,Y,X,W,C[P+9],Q,2336552879);W=u(W,V,Y,X,C[P+10],N,4294925233);X=u(X,W,V,Y,C[P+11],M,2304563134);Y=u(Y,X,W,V,C[P+12],S,1804603682);V=u(V,Y,X,W,C[P+13],Q,4254626195);W=u(W,V,Y,X,C[P+14],N,2792965006);X=u(X,W,V,Y,C[P+15],M,1236535329);Y=f(Y,X,W,V,C[P+1],A,4129170786);V=f(V,Y,X,W,C[P+6],z,3225465664);W=f(W,V,Y,X,C[P+11],y,643717713);X=f(X,W,V,Y,C[P+0],w,3921069994);Y=f(Y,X,W,V,C[P+5],A,3593408605);V=f(V,Y,X,W,C[P+10],z,38016083);W=f(W,V,Y,X,C[P+15],y,3634488961);X=f(X,W,V,Y,C[P+4],w,3889429448);Y=f(Y,X,W,V,C[P+9],A,568446438);V=f(V,Y,X,W,C[P+14],z,3275163606);W=f(W,V,Y,X,C[P+3],y,4107603335);X=f(X,W,V,Y,C[P+8],w,1163531501);Y=f(Y,X,W,V,C[P+13],A,2850285829);V=f(V,Y,X,W,C[P+2],z,4243563512);W=f(W,V,Y,X,C[P+7],y,1735328473);X=f(X,W,V,Y,C[P+12],w,2368359562);Y=D(Y,X,W,V,C[P+5],o,4294588738);V=D(V,Y,X,W,C[P+8],m,2272392833);W=D(W,V,Y,X,C[P+11],l,1839030562);X=D(X,W,V,Y,C[P+14],j,4259657740);Y=D(Y,X,W,V,C[P+1],o,2763975236);V=D(V,Y,X,W,C[P+4],m,1272893353);W=D(W,V,Y,X,C[P+7],l,4139469664);X=D(X,W,V,Y,C[P+10],j,3200236656);Y=D(Y,X,W,V,C[P+13],o,681279174);V=D(V,Y,X,W,C[P+0],m,3936430074);W=D(W,V,Y,X,C[P+3],l,3572445317);X=D(X,W,V,Y,C[P+6],j,76029189);Y=D(Y,X,W,V,C[P+9],o,3654602809);V=D(V,Y,X,W,C[P+12],m,3873151461);W=D(W,V,Y,X,C[P+15],l,530742520);X=D(X,W,V,Y,C[P+2],j,3299628645);Y=t(Y,X,W,V,C[P+0],U,4096336452);V=t(V,Y,X,W,C[P+7],T,1126891415);W=t(W,V,Y,X,C[P+14],R,2878612391);X=t(X,W,V,Y,C[P+5],O,4237533241);Y=t(Y,X,W,V,C[P+12],U,1700485571);V=t(V,Y,X,W,C[P+3],T,2399980690);W=t(W,V,Y,X,C[P+10],R,4293915773);X=t(X,W,V,Y,C[P+1],O,2240044497);Y=t(Y,X,W,V,C[P+8],U,1873313359);V=t(V,Y,X,W,C[P+15],T,4264355552);W=t(W,V,Y,X,C[P+6],R,2734768916);X=t(X,W,V,Y,C[P+13],O,1309151649);Y=t(Y,X,W,V,C[P+4],U,4149444226);V=t(V,Y,X,W,C[P+11],T,3174756917);W=t(W,V,Y,X,C[P+2],R,718787259);X=t(X,W,V,Y,C[P+9],O,3951481745);Y=K(Y,h);X=K(X,E);W=K(W,v);V=K(V,g)}var i=B(Y)+B(X)+B(W)+B(V);return i.toLowerCase()};
/* jshint ignore:end */
Utils.convertPlainTextToHtml = function (sPlain)
{
return sPlain.toString()
.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;')
.replace(/\r/g, '').replace(/\n/g, '<br />');
};
Utils.draggeblePlace = function ()
{
return $('<div class="draggablePlace"><span class="text"></span>&nbsp;<i class="icon-copy icon-white visible-on-ctrl"></i><i class="icon-mail icon-white hidden-on-ctrl"></i></div>').appendTo('#rl-hidden');
};
Utils.defautOptionsAfterRender = function (oOption, oItem)
{
if (oItem && !Utils.isUnd(oItem.disabled) && oOption)
{
$(oOption)
.toggleClass('disabled', oItem.disabled)
.prop('disabled', oItem.disabled)
;
}
};
/**
* @param {Object} oViewModel
* @param {string} sTemplateID
* @param {string} sTitle
* @param {Function=} fCallback
*/
Utils.windowPopupKnockout = function (oViewModel, sTemplateID, sTitle, fCallback)
{
var
oScript = null,
oWin = window.open(''),
sFunc = '__OpenerApplyBindingsUid' + Utils.fakeMd5() + '__',
oTemplate = $('#' + sTemplateID)
;
window[sFunc] = function () {
if (oWin && oWin.document.body && oTemplate && oTemplate[0])
{
var oBody = $(oWin.document.body);
$('#rl-content', oBody).html(oTemplate.html());
$('html', oWin.document).addClass('external ' + $('html').attr('class'));
Utils.i18nToNode(oBody);
Knoin.prototype.applyExternal(oViewModel, $('#rl-content', oBody)[0]);
window[sFunc] = null;
fCallback(oWin);
}
};
oWin.document.open();
oWin.document.write('<html><head>' +
'<meta charset="utf-8" />' +
'<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />' +
'<meta name="viewport" content="user-scalable=no" />' +
'<meta name="apple-mobile-web-app-capable" content="yes" />' +
'<meta name="robots" content="noindex, nofollow, noodp" />' +
'<title>' + Utils.encodeHtml(sTitle) + '</title>' +
'</head><body><div id="rl-content"></div></body></html>');
oWin.document.close();
oScript = oWin.document.createElement('script');
oScript.type = 'text/javascript';
oScript.innerHTML = 'if(window&&window.opener&&window.opener[\'' + sFunc + '\']){window.opener[\'' + sFunc + '\']();window.opener[\'' + sFunc + '\']=null}';
oWin.document.getElementsByTagName('head')[0].appendChild(oScript);
};
Utils.settingsSaveHelperFunction = function (fCallback, koTrigger, oContext, iTimer)
{
oContext = oContext || null;
iTimer = Utils.isUnd(iTimer) ? 1000 : Utils.pInt(iTimer);
return function (sType, mData, bCached, sRequestAction, oRequestParameters) {
koTrigger.call(oContext, mData && mData['Result'] ? Enums.SaveSettingsStep.TrueResult : Enums.SaveSettingsStep.FalseResult);
if (fCallback)
{
fCallback.call(oContext, sType, mData, bCached, sRequestAction, oRequestParameters);
}
_.delay(function () {
koTrigger.call(oContext, Enums.SaveSettingsStep.Idle);
}, iTimer);
};
};
Utils.settingsSaveHelperSimpleFunction = function (koTrigger, oContext)
{
return Utils.settingsSaveHelperFunction(null, koTrigger, oContext, 1000);
};
Utils.$div = $('<div></div>');
/**
* @param {string} sHtml
* @return {string}
*/
Utils.htmlToPlain = function (sHtml)
{
var
iPos = 0,
iP1 = 0,
iP2 = 0,
iP3 = 0,
iLimit = 0,
sText = '',
splitPlainText = function (sText)
{
var
iLen = 100,
sPrefix = '',
sSubText = '',
sResult = sText,
iSpacePos = 0,
iNewLinePos = 0
;
while (sResult.length > iLen)
{
sSubText = sResult.substring(0, iLen);
iSpacePos = sSubText.lastIndexOf(' ');
iNewLinePos = sSubText.lastIndexOf('\n');
if (-1 !== iNewLinePos)
{
iSpacePos = iNewLinePos;
}
if (-1 === iSpacePos)
{
iSpacePos = iLen;
}
sPrefix += sSubText.substring(0, iSpacePos) + '\n';
sResult = sResult.substring(iSpacePos + 1);
}
return sPrefix + sResult;
},
convertBlockquote = function (sText) {
sText = splitPlainText($.trim(sText));
sText = '> ' + sText.replace(/\n/gm, '\n> ');
return sText.replace(/(^|\n)([> ]+)/gm, function () {
return (arguments && 2 < arguments.length) ? arguments[1] + $.trim(arguments[2].replace(/[\s]/, '')) + ' ' : '';
});
},
convertDivs = function () {
if (arguments && 1 < arguments.length)
{
var sText = $.trim(arguments[1]);
if (0 < sText.length)
{
sText = sText.replace(/<div[^>]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs);
sText = '\n' + $.trim(sText) + '\n';
}
return sText;
}
return '';
},
convertPre = function () {
return (arguments && 1 < arguments.length) ? arguments[1].toString().replace(/[\n]/gm, '<br />') : '';
},
fixAttibuteValue = function () {
return (arguments && 1 < arguments.length) ?
'' + arguments[1] + arguments[2].replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
},
convertLinks = function () {
return (arguments && 1 < arguments.length) ? $.trim(arguments[1]) : '';
}
;
sText = sHtml
.replace(/<pre[^>]*>([\s\S\r\n]*)<\/pre>/gmi, convertPre)
.replace(/[\s]+/gm, ' ')
.replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue)
.replace(/<br[^>]*>/gmi, '\n')
.replace(/<\/h[\d]>/gi, '\n')
.replace(/<\/p>/gi, '\n\n')
.replace(/<\/li>/gi, '\n')
.replace(/<\/td>/gi, '\n')
.replace(/<\/tr>/gi, '\n')
.replace(/<hr[^>]*>/gmi, '\n_______________________________\n\n')
.replace(/<div[^>]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs)
.replace(/<blockquote[^>]*>/gmi, '\n__bq__start__\n')
.replace(/<\/blockquote>/gmi, '\n__bq__end__\n')
.replace(/<a [^>]*>([\s\S\r\n]*?)<\/a>/gmi, convertLinks)
.replace(/<\/div>/gi, '\n')
.replace(/&nbsp;/gi, ' ')
.replace(/&quot;/gi, '"')
.replace(/<[^>]*>/gm, '')
;
sText = Utils.$div.html(sText).text();
sText = sText
.replace(/\n[ \t]+/gm, '\n')
.replace(/[\n]{3,}/gm, '\n\n')
.replace(/&gt;/gi, '>')
.replace(/&lt;/gi, '<')
.replace(/&amp;/gi, '&')
;
iPos = 0;
iLimit = 100;
while (0 < iLimit)
{
iLimit--;
iP1 = sText.indexOf('__bq__start__', iPos);
if (-1 < iP1)
{
iP2 = sText.indexOf('__bq__start__', iP1 + 5);
iP3 = sText.indexOf('__bq__end__', iP1 + 5);
if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3)
{
sText = sText.substring(0, iP1) +
convertBlockquote(sText.substring(iP1 + 13, iP3)) +
sText.substring(iP3 + 11);
iPos = 0;
}
else if (-1 < iP2 && iP2 < iP3)
{
iPos = iP2 - 1;
}
else
{
iPos = 0;
}
}
else
{
break;
}
}
sText = sText
.replace(/__bq__start__/gm, '')
.replace(/__bq__end__/gm, '')
;
return sText;
};
/**
* @param {string} sPlain
* @param {boolean} bLinkify = false
* @return {string}
*/
Utils.plainToHtml = function (sPlain, bLinkify)
{
sPlain = sPlain.toString().replace(/\r/g, '');
var
bIn = false,
bDo = true,
bStart = true,
aNextText = [],
sLine = '',
iIndex = 0,
aText = sPlain.split("\n")
;
do
{
bDo = false;
aNextText = [];
for (iIndex = 0; iIndex < aText.length; iIndex++)
{
sLine = aText[iIndex];
bStart = '>' === sLine.substr(0, 1);
if (bStart && !bIn)
{
bDo = true;
bIn = true;
aNextText.push('~~~blockquote~~~');
aNextText.push(sLine.substr(1));
}
else if (!bStart && bIn)
{
bIn = false;
aNextText.push('~~~/blockquote~~~');
aNextText.push(sLine);
}
else if (bStart && bIn)
{
aNextText.push(sLine.substr(1));
}
else
{
aNextText.push(sLine);
}
}
if (bIn)
{
bIn = false;
aNextText.push('~~~/blockquote~~~');
}
aText = aNextText;
}
while (bDo);
sPlain = aText.join("\n");
sPlain = sPlain
.replace(/&/g, '&amp;')
.replace(/>/g, '&gt;').replace(/</g, '&lt;')
.replace(/~~~blockquote~~~[\s]*/g, '<blockquote>')
.replace(/[\s]*~~~\/blockquote~~~/g, '</blockquote>')
.replace(/[\-_~]{10,}/g, '<hr />')
.replace(/\n/g, '<br />');
return bLinkify ? Utils.linkify(sPlain) : sPlain;
};
window.rainloop_Utils_htmlToPlain = Utils.htmlToPlain;
window.rainloop_Utils_plainToHtml = Utils.plainToHtml;
/**
* @param {string} sHtml
* @return {string}
*/
Utils.linkify = function (sHtml)
{
if ($.fn && $.fn.linkify)
{
sHtml = Utils.$div.html(sHtml.replace(/&amp;/ig, 'amp_amp_12345_amp_amp'))
.linkify()
.find('.linkified').removeClass('linkified').end()
.html()
.replace(/amp_amp_12345_amp_amp/g, '&amp;')
;
}
return sHtml;
};
Utils.resizeAndCrop = function (sUrl, iValue, fCallback)
{
var oTempImg = new window.Image();
oTempImg.onload = function() {
var
aDiff = [0, 0],
oCanvas = document.createElement('canvas'),
oCtx = oCanvas.getContext('2d')
;
oCanvas.width = iValue;
oCanvas.height = iValue;
if (this.width > this.height)
{
aDiff = [this.width - this.height, 0];
}
else
{
aDiff = [0, this.height - this.width];
}
oCtx.fillStyle = '#fff';
oCtx.fillRect(0, 0, iValue, iValue);
oCtx.drawImage(this, aDiff[0] / 2, aDiff[1] / 2, this.width - aDiff[0], this.height - aDiff[1], 0, 0, iValue, iValue);
fCallback(oCanvas.toDataURL('image/jpeg'));
};
oTempImg.src = sUrl;
};
Utils.computedPagenatorHelper = function (koCurrentPage, koPageCount)
{
return function() {
var
iPrev = 0,
iNext = 0,
iLimit = 2,
aResult = [],
iCurrentPage = koCurrentPage(),
iPageCount = koPageCount(),
/**
* @param {number} iIndex
* @param {boolean=} bPush
* @param {string=} sCustomName
*/
fAdd = function (iIndex, bPush, sCustomName) {
var oData = {
'current': iIndex === iCurrentPage,
'name': Utils.isUnd(sCustomName) ? iIndex.toString() : sCustomName.toString(),
'custom': Utils.isUnd(sCustomName) ? false : true,
'title': Utils.isUnd(sCustomName) ? '' : iIndex.toString(),
'value': iIndex.toString()
};
if (Utils.isUnd(bPush) ? true : !!bPush)
{
aResult.push(oData);
}
else
{
aResult.unshift(oData);
}
}
;
if (1 < iPageCount || (0 < iPageCount && iPageCount < iCurrentPage))
// if (0 < iPageCount && 0 < iCurrentPage)
{
if (iPageCount < iCurrentPage)
{
fAdd(iPageCount);
iPrev = iPageCount;
iNext = iPageCount;
}
else
{
if (3 >= iCurrentPage || iPageCount - 2 <= iCurrentPage)
{
iLimit += 2;
}
fAdd(iCurrentPage);
iPrev = iCurrentPage;
iNext = iCurrentPage;
}
while (0 < iLimit) {
iPrev -= 1;
iNext += 1;
if (0 < iPrev)
{
fAdd(iPrev, false);
iLimit--;
}
if (iPageCount >= iNext)
{
fAdd(iNext, true);
iLimit--;
}
else if (0 >= iPrev)
{
break;
}
}
if (3 === iPrev)
{
fAdd(2, false);
}
else if (3 < iPrev)
{
fAdd(Math.round((iPrev - 1) / 2), false, '...');
}
if (iPageCount - 2 === iNext)
{
fAdd(iPageCount - 1, true);
}
else if (iPageCount - 2 > iNext)
{
fAdd(Math.round((iPageCount + iNext) / 2), true, '...');
}
// first and last
if (1 < iPrev)
{
fAdd(1, false);
}
if (iPageCount > iNext)
{
fAdd(iPageCount, true);
}
}
return aResult;
};
};
Utils.selectElement = function (element)
{
/* jshint onevar: false */
if (window.getSelection)
{
var sel = window.getSelection();
sel.removeAllRanges();
var range = document.createRange();
range.selectNodeContents(element);
sel.addRange(range);
}
else if (document.selection)
{
var textRange = document.body.createTextRange();
textRange.moveToElementText(element);
textRange.select();
}
/* jshint onevar: true */
};
Utils.disableKeyFilter = function ()
{
if (window.key)
{
key.filter = function () {
return RL.data().useKeyboardShortcuts();
};
}
};
Utils.restoreKeyFilter = function ()
{
if (window.key)
{
key.filter = function (event) {
if (RL.data().useKeyboardShortcuts())
{
var
element = event.target || event.srcElement,
tagName = element ? element.tagName : ''
;
tagName = tagName.toUpperCase();
return !(tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA' ||
(element && tagName === 'DIV' && 'editorHtmlArea' === element.className && element.contentEditable)
);
}
return false;
};
}
};
Utils.detectDropdownVisibility = _.debounce(function () {
Globals.dropdownVisibility(!!_.find(Globals.aBootstrapDropdowns, function (oItem) {
return oItem.hasClass('open');
}));
}, 50);
Utils.triggerAutocompleteInputChange = function (bDelay) {
var fFunc = function () {
$('.checkAutocomplete').trigger('change');
};
if (bDelay)
{
_.delay(fFunc, 100);
}
else
{
fFunc();
}
};
module.exports = Utils;
}(module));
},{"../External/$doc.js":9,"../External/$window.js":11,"../External/NotificationClass.js":13,"../External/jquery.js":16,"../External/ko.js":17,"../External/underscore.js":19,"../External/window.js":20,"./Enums.js":5,"./Globals.js":6}],9:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
module.exports = require('./jquery.js')(window.document);
},{"./jquery.js":16}],10:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
module.exports = require('./jquery.js')('html');
},{"./jquery.js":16}],11:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
module.exports = require('./jquery.js')(window);
},{"./jquery.js":16}],12:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
module.exports = require('./window.js')['rainloopAppData'] || {};
},{"./window.js":20}],13:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
var
window = require('./window.js')
;
module.exports = window.Notification && window.Notification.requestPermission ? window.Notification : null;
},{"./window.js":20}],14:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
module.exports = crossroads;
},{}],15:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
module.exports = hasher;
},{}],16:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
module.exports = $;
},{}],17:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
var
$ = require('./jquery.js'),
_ = require('./underscore.js'),
window = require('./window.js'),
$window = require('./$window.js'),
$doc = require('./$doc.js'),
Globals = require('../Common/Globals.js'),
Utils = require('../Common/Utils.js')
;
ko.bindingHandlers.tooltip = {
'init': function (oElement, fValueAccessor) {
if (!Globals.bMobileDevice)
{
var
$oEl = $(oElement),
sClass = $oEl.data('tooltip-class') || '',
sPlacement = $oEl.data('tooltip-placement') || 'top'
;
$oEl.tooltip({
'delay': {
'show': 500,
'hide': 100
},
'html': true,
'container': 'body',
'placement': sPlacement,
'trigger': 'hover',
'title': function () {
return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' : '<span class="tooltip-class ' + sClass + '">' +
Utils.i18n(ko.utils.unwrapObservable(fValueAccessor())) + '</span>';
}
}).click(function () {
$oEl.tooltip('hide');
});
Globals.tooltipTrigger.subscribe(function () {
$oEl.tooltip('hide');
});
}
}
};
ko.bindingHandlers.tooltip2 = {
'init': function (oElement, fValueAccessor) {
var
$oEl = $(oElement),
sClass = $oEl.data('tooltip-class') || '',
sPlacement = $oEl.data('tooltip-placement') || 'top'
;
$oEl.tooltip({
'delay': {
'show': 500,
'hide': 100
},
'html': true,
'container': 'body',
'placement': sPlacement,
'title': function () {
return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' :
'<span class="tooltip-class ' + sClass + '">' + fValueAccessor()() + '</span>';
}
}).click(function () {
$oEl.tooltip('hide');
});
Globals.tooltipTrigger.subscribe(function () {
$oEl.tooltip('hide');
});
}
};
ko.bindingHandlers.tooltip3 = {
'init': function (oElement) {
var $oEl = $(oElement);
$oEl.tooltip({
'container': 'body',
'trigger': 'hover manual',
'title': function () {
return $oEl.data('tooltip3-data') || '';
}
});
$doc.click(function () {
$oEl.tooltip('hide');
});
Globals.tooltipTrigger.subscribe(function () {
$oEl.tooltip('hide');
});
},
'update': function (oElement, fValueAccessor) {
var sValue = ko.utils.unwrapObservable(fValueAccessor());
if ('' === sValue)
{
$(oElement).data('tooltip3-data', '').tooltip('hide');
}
else
{
$(oElement).data('tooltip3-data', sValue).tooltip('show');
}
}
};
ko.bindingHandlers.registrateBootstrapDropdown = {
'init': function (oElement) {
Globals.aBootstrapDropdowns.push($(oElement));
}
};
ko.bindingHandlers.openDropdownTrigger = {
'update': function (oElement, fValueAccessor) {
if (ko.utils.unwrapObservable(fValueAccessor()))
{
var $el = $(oElement);
if (!$el.hasClass('open'))
{
$el.find('.dropdown-toggle').dropdown('toggle');
Utils.detectDropdownVisibility();
}
fValueAccessor()(false);
}
}
};
ko.bindingHandlers.dropdownCloser = {
'init': function (oElement) {
$(oElement).closest('.dropdown').on('click', '.e-item', function () {
$(oElement).dropdown('toggle');
});
}
};
ko.bindingHandlers.popover = {
'init': function (oElement, fValueAccessor) {
$(oElement).popover(ko.utils.unwrapObservable(fValueAccessor()));
}
};
ko.bindingHandlers.csstext = {
'init': function (oElement, fValueAccessor) {
if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
{
oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
}
else
{
$(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
}
},
'update': function (oElement, fValueAccessor) {
if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
{
oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
}
else
{
$(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
}
}
};
ko.bindingHandlers.resizecrop = {
'init': function (oElement) {
$(oElement).addClass('resizecrop').resizecrop({
'width': '100',
'height': '100',
'wrapperCSS': {
'border-radius': '10px'
}
});
},
'update': function (oElement, fValueAccessor) {
fValueAccessor()();
$(oElement).resizecrop({
'width': '100',
'height': '100'
});
}
};
ko.bindingHandlers.onEnter = {
'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
$(oElement).on('keypress', function (oEvent) {
if (oEvent && 13 === window.parseInt(oEvent.keyCode, 10))
{
$(oElement).trigger('change');
fValueAccessor().call(oViewModel);
}
});
}
};
ko.bindingHandlers.onEsc = {
'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
$(oElement).on('keypress', function (oEvent) {
if (oEvent && 27 === window.parseInt(oEvent.keyCode, 10))
{
$(oElement).trigger('change');
fValueAccessor().call(oViewModel);
}
});
}
};
ko.bindingHandlers.clickOnTrue = {
'update': function (oElement, fValueAccessor) {
if (ko.utils.unwrapObservable(fValueAccessor()))
{
$(oElement).click();
}
}
};
ko.bindingHandlers.modal = {
'init': function (oElement, fValueAccessor) {
$(oElement).toggleClass('fade', !Globals.bMobileDevice).modal({
'keyboard': false,
'show': ko.utils.unwrapObservable(fValueAccessor())
})
.on('shown', function () {
Utils.windowResize();
})
.find('.close').click(function () {
fValueAccessor()(false);
});
},
'update': function (oElement, fValueAccessor) {
$(oElement).modal(ko.utils.unwrapObservable(fValueAccessor()) ? 'show' : 'hide');
}
};
ko.bindingHandlers.i18nInit = {
'init': function (oElement) {
Utils.i18nToNode(oElement);
}
};
ko.bindingHandlers.i18nUpdate = {
'update': function (oElement, fValueAccessor) {
ko.utils.unwrapObservable(fValueAccessor());
Utils.i18nToNode(oElement);
}
};
ko.bindingHandlers.link = {
'update': function (oElement, fValueAccessor) {
$(oElement).attr('href', ko.utils.unwrapObservable(fValueAccessor()));
}
};
ko.bindingHandlers.title = {
'update': function (oElement, fValueAccessor) {
$(oElement).attr('title', ko.utils.unwrapObservable(fValueAccessor()));
}
};
ko.bindingHandlers.textF = {
'init': function (oElement, fValueAccessor) {
$(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
}
};
ko.bindingHandlers.initDom = {
'init': function (oElement, fValueAccessor) {
fValueAccessor()(oElement);
}
};
ko.bindingHandlers.initResizeTrigger = {
'init': function (oElement, fValueAccessor) {
var aValues = ko.utils.unwrapObservable(fValueAccessor());
$(oElement).css({
'height': aValues[1],
'min-height': aValues[1]
});
},
'update': function (oElement, fValueAccessor) {
var
aValues = ko.utils.unwrapObservable(fValueAccessor()),
iValue = Utils.pInt(aValues[1]),
iSize = 0,
iOffset = $(oElement).offset().top
;
if (0 < iOffset)
{
iOffset += Utils.pInt(aValues[2]);
iSize = $window.height() - iOffset;
if (iValue < iSize)
{
iValue = iSize;
}
$(oElement).css({
'height': iValue,
'min-height': iValue
});
}
}
};
ko.bindingHandlers.appendDom = {
'update': function (oElement, fValueAccessor) {
$(oElement).hide().empty().append(ko.utils.unwrapObservable(fValueAccessor())).show();
}
};
ko.bindingHandlers.draggable = {
'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
if (!Globals.bMobileDevice)
{
var
iTriggerZone = 100,
iScrollSpeed = 3,
fAllValueFunc = fAllBindingsAccessor(),
sDroppableSelector = fAllValueFunc && fAllValueFunc['droppableSelector'] ? fAllValueFunc['droppableSelector'] : '',
oConf = {
'distance': 20,
'handle': '.dragHandle',
'cursorAt': {'top': 22, 'left': 3},
'refreshPositions': true,
'scroll': true
}
;
if (sDroppableSelector)
{
oConf['drag'] = function (oEvent) {
$(sDroppableSelector).each(function () {
var
moveUp = null,
moveDown = null,
$this = $(this),
oOffset = $this.offset(),
bottomPos = oOffset.top + $this.height()
;
window.clearInterval($this.data('timerScroll'));
$this.data('timerScroll', false);
if (oEvent.pageX >= oOffset.left && oEvent.pageX <= oOffset.left + $this.width())
{
if (oEvent.pageY >= bottomPos - iTriggerZone && oEvent.pageY <= bottomPos)
{
moveUp = function() {
$this.scrollTop($this.scrollTop() + iScrollSpeed);
Utils.windowResize();
};
$this.data('timerScroll', window.setInterval(moveUp, 10));
moveUp();
}
if (oEvent.pageY >= oOffset.top && oEvent.pageY <= oOffset.top + iTriggerZone)
{
moveDown = function() {
$this.scrollTop($this.scrollTop() - iScrollSpeed);
Utils.windowResize();
};
$this.data('timerScroll', window.setInterval(moveDown, 10));
moveDown();
}
}
});
};
oConf['stop'] = function() {
$(sDroppableSelector).each(function () {
window.clearInterval($(this).data('timerScroll'));
$(this).data('timerScroll', false);
});
};
}
oConf['helper'] = function (oEvent) {
return fValueAccessor()(oEvent && oEvent.target ? ko.dataFor(oEvent.target) : null);
};
$(oElement).draggable(oConf).on('mousedown', function () {
Utils.removeInFocus();
});
}
}
};
ko.bindingHandlers.droppable = {
'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
if (!Globals.bMobileDevice)
{
var
fValueFunc = fValueAccessor(),
fAllValueFunc = fAllBindingsAccessor(),
fOverCallback = fAllValueFunc && fAllValueFunc['droppableOver'] ? fAllValueFunc['droppableOver'] : null,
fOutCallback = fAllValueFunc && fAllValueFunc['droppableOut'] ? fAllValueFunc['droppableOut'] : null,
oConf = {
'tolerance': 'pointer',
'hoverClass': 'droppableHover'
}
;
if (fValueFunc)
{
oConf['drop'] = function (oEvent, oUi) {
fValueFunc(oEvent, oUi);
};
if (fOverCallback)
{
oConf['over'] = function (oEvent, oUi) {
fOverCallback(oEvent, oUi);
};
}
if (fOutCallback)
{
oConf['out'] = function (oEvent, oUi) {
fOutCallback(oEvent, oUi);
};
}
$(oElement).droppable(oConf);
}
}
}
};
ko.bindingHandlers.nano = {
'init': function (oElement) {
if (!Globals.bDisableNanoScroll)
{
$(oElement)
.addClass('nano')
.nanoScroller({
'iOSNativeScrolling': false,
'preventPageScrolling': true
})
;
}
}
};
ko.bindingHandlers.saveTrigger = {
'init': function (oElement) {
var $oEl = $(oElement);
$oEl.data('save-trigger-type', $oEl.is('input[type=text],input[type=email],input[type=password],select,textarea') ? 'input' : 'custom');
if ('custom' === $oEl.data('save-trigger-type'))
{
$oEl.append(
'&nbsp;&nbsp;<i class="icon-spinner animated"></i><i class="icon-remove error"></i><i class="icon-ok success"></i>'
).addClass('settings-saved-trigger');
}
else
{
$oEl.addClass('settings-saved-trigger-input');
}
},
'update': function (oElement, fValueAccessor) {
var
mValue = ko.utils.unwrapObservable(fValueAccessor()),
$oEl = $(oElement)
;
if ('custom' === $oEl.data('save-trigger-type'))
{
switch (mValue.toString())
{
case '1':
$oEl
.find('.animated,.error').hide().removeClass('visible')
.end()
.find('.success').show().addClass('visible')
;
break;
case '0':
$oEl
.find('.animated,.success').hide().removeClass('visible')
.end()
.find('.error').show().addClass('visible')
;
break;
case '-2':
$oEl
.find('.error,.success').hide().removeClass('visible')
.end()
.find('.animated').show().addClass('visible')
;
break;
default:
$oEl
.find('.animated').hide()
.end()
.find('.error,.success').removeClass('visible')
;
break;
}
}
else
{
switch (mValue.toString())
{
case '1':
$oEl.addClass('success').removeClass('error');
break;
case '0':
$oEl.addClass('error').removeClass('success');
break;
case '-2':
// $oEl;
break;
default:
$oEl.removeClass('error success');
break;
}
}
}
};
ko.bindingHandlers.emailsTags = {
'init': function(oElement, fValueAccessor) {
var
$oEl = $(oElement),
fValue = fValueAccessor(),
fFocusCallback = function (bValue) {
if (fValue && fValue.focusTrigger)
{
fValue.focusTrigger(bValue);
}
}
;
$oEl.inputosaurus({
'parseOnBlur': true,
'allowDragAndDrop': true,
'focusCallback': fFocusCallback,
'inputDelimiters': [',', ';'],
'autoCompleteSource': function (oData, fResponse) {
RL.getAutocomplete(oData.term, function (aData) {
fResponse(_.map(aData, function (oEmailItem) {
return oEmailItem.toLine(false);
}));
});
},
'parseHook': function (aInput) {
return _.map(aInput, function (sInputValue) {
var
sValue = Utils.trim(sInputValue),
oEmail = null
;
if ('' !== sValue)
{
oEmail = new EmailModel();
oEmail.mailsoParse(sValue);
oEmail.clearDuplicateName();
return [oEmail.toLine(false), oEmail];
}
return [sValue, null];
});
},
'change': _.bind(function (oEvent) {
$oEl.data('EmailsTagsValue', oEvent.target.value);
fValue(oEvent.target.value);
}, this)
});
},
'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
var
$oEl = $(oElement),
fAllValueFunc = fAllBindingsAccessor(),
fEmailsTagsFilter = fAllValueFunc['emailsTagsFilter'] || null,
sValue = ko.utils.unwrapObservable(fValueAccessor())
;
if ($oEl.data('EmailsTagsValue') !== sValue)
{
$oEl.val(sValue);
$oEl.data('EmailsTagsValue', sValue);
$oEl.inputosaurus('refresh');
}
if (fEmailsTagsFilter && ko.utils.unwrapObservable(fEmailsTagsFilter))
{
$oEl.inputosaurus('focus');
}
}
};
ko.bindingHandlers.contactTags = {
'init': function(oElement, fValueAccessor) {
var
$oEl = $(oElement),
fValue = fValueAccessor(),
fFocusCallback = function (bValue) {
if (fValue && fValue.focusTrigger)
{
fValue.focusTrigger(bValue);
}
}
;
$oEl.inputosaurus({
'parseOnBlur': true,
'allowDragAndDrop': false,
'focusCallback': fFocusCallback,
'inputDelimiters': [',', ';'],
'outputDelimiter': ',',
'autoCompleteSource': function (oData, fResponse) {
RL.getContactTagsAutocomplete(oData.term, function (aData) { // TODO cjs
fResponse(_.map(aData, function (oTagItem) {
return oTagItem.toLine(false);
}));
});
},
'parseHook': function (aInput) {
return _.map(aInput, function (sInputValue) {
var
sValue = Utils.trim(sInputValue),
oTag = null
;
if ('' !== sValue)
{
oTag = new ContactTagModel();
oTag.name(sValue);
return [oTag.toLine(false), oTag];
}
return [sValue, null];
});
},
'change': _.bind(function (oEvent) {
$oEl.data('ContactTagsValue', oEvent.target.value);
fValue(oEvent.target.value);
}, this)
});
},
'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
var
$oEl = $(oElement),
fAllValueFunc = fAllBindingsAccessor(),
fContactTagsFilter = fAllValueFunc['contactTagsFilter'] || null,
sValue = ko.utils.unwrapObservable(fValueAccessor())
;
if ($oEl.data('ContactTagsValue') !== sValue)
{
$oEl.val(sValue);
$oEl.data('ContactTagsValue', sValue);
$oEl.inputosaurus('refresh');
}
if (fContactTagsFilter && ko.utils.unwrapObservable(fContactTagsFilter))
{
$oEl.inputosaurus('focus');
}
}
};
ko.bindingHandlers.command = {
'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
var
jqElement = $(oElement),
oCommand = fValueAccessor()
;
if (!oCommand || !oCommand.enabled || !oCommand.canExecute)
{
throw new Error('You are not using command function');
}
jqElement.addClass('command');
ko.bindingHandlers[jqElement.is('form') ? 'submit' : 'click'].init.apply(oViewModel, arguments);
},
'update': function (oElement, fValueAccessor) {
var
bResult = true,
jqElement = $(oElement),
oCommand = fValueAccessor()
;
bResult = oCommand.enabled();
jqElement.toggleClass('command-not-enabled', !bResult);
if (bResult)
{
bResult = oCommand.canExecute();
jqElement.toggleClass('command-can-not-be-execute', !bResult);
}
jqElement.toggleClass('command-disabled disable disabled', !bResult).toggleClass('no-disabled', !!bResult);
if (jqElement.is('input') || jqElement.is('button'))
{
jqElement.prop('disabled', !bResult);
}
}
};
ko.extenders.trimmer = function (oTarget)
{
var oResult = ko.computed({
'read': oTarget,
'write': function (sNewValue) {
oTarget(Utils.trim(sNewValue.toString()));
},
'owner': this
});
oResult(oTarget());
return oResult;
};
ko.extenders.posInterer = function (oTarget, iDefault)
{
var oResult = ko.computed({
'read': oTarget,
'write': function (sNewValue) {
var iNew = Utils.pInt(sNewValue.toString(), iDefault);
if (0 >= iNew)
{
iNew = iDefault;
}
if (iNew === oTarget() && '' + iNew !== '' + sNewValue)
{
oTarget(iNew + 1);
}
oTarget(iNew);
}
});
oResult(oTarget());
return oResult;
};
ko.extenders.reversible = function (oTarget)
{
var mValue = oTarget();
oTarget.commit = function ()
{
mValue = oTarget();
};
oTarget.reverse = function ()
{
oTarget(mValue);
};
oTarget.commitedValue = function ()
{
return mValue;
};
return oTarget;
};
ko.extenders.toggleSubscribe = function (oTarget, oOptions)
{
oTarget.subscribe(oOptions[1], oOptions[0], 'beforeChange');
oTarget.subscribe(oOptions[2], oOptions[0]);
return oTarget;
};
ko.extenders.falseTimeout = function (oTarget, iOption)
{
oTarget.iTimeout = 0;
oTarget.subscribe(function (bValue) {
if (bValue)
{
window.clearTimeout(oTarget.iTimeout);
oTarget.iTimeout = window.setTimeout(function () {
oTarget(false);
oTarget.iTimeout = 0;
}, Utils.pInt(iOption));
}
});
return oTarget;
};
ko.observable.fn.validateNone = function ()
{
this.hasError = ko.observable(false);
return this;
};
ko.observable.fn.validateEmail = function ()
{
this.hasError = ko.observable(false);
this.subscribe(function (sValue) {
sValue = Utils.trim(sValue);
this.hasError('' !== sValue && !(/^[^@\s]+@[^@\s]+$/.test(sValue)));
}, this);
this.valueHasMutated();
return this;
};
ko.observable.fn.validateSimpleEmail = function ()
{
this.hasError = ko.observable(false);
this.subscribe(function (sValue) {
sValue = Utils.trim(sValue);
this.hasError('' !== sValue && !(/^.+@.+$/.test(sValue)));
}, this);
this.valueHasMutated();
return this;
};
ko.observable.fn.validateFunc = function (fFunc)
{
this.hasFuncError = ko.observable(false);
if (Utils.isFunc(fFunc))
{
this.subscribe(function (sValue) {
this.hasFuncError(!fFunc(sValue));
}, this);
this.valueHasMutated();
}
return this;
};
module.exports = ko;
}(module));
},{"../Common/Globals.js":6,"../Common/Utils.js":8,"./$doc.js":9,"./$window.js":11,"./jquery.js":16,"./underscore.js":19,"./window.js":20}],18:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
module.exports = ssm;
},{}],19:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
module.exports = window;
},{}],20:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
'use strict';
module.exports = window;
},{}],21:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
var
$ = require('../External/jquery.js'),
_ = require('../External/underscore.js'),
ko = require('../External/ko.js'),
hasher = require('../External/hasher.js'),
crossroads = require('../External/crossroads.js'),
$html = require('../External/$html.js'),
Utils = require('../Common/Utils.js'),
Globals = require('../Common/Globals.js'),
Enums = require('../Common/Enums.js')
;
/**
* @constructor
*/
function Knoin()
{
this.sDefaultScreenName = '';
this.oScreens = {};
this.oCurrentScreen = null;
}
/**
* @param {Object} thisObject
*/
Knoin.constructorEnd = function (thisObject)
{
if (Utils.isFunc(thisObject['__constructor_end']))
{
thisObject['__constructor_end'].call(thisObject);
}
};
Knoin.prototype.sDefaultScreenName = '';
Knoin.prototype.oScreens = {};
Knoin.prototype.oCurrentScreen = null;
Knoin.prototype.hideLoading = function ()
{
$('#rl-loading').hide();
};
Knoin.prototype.routeOff = function ()
{
hasher.changed.active = false;
};
Knoin.prototype.routeOn = function ()
{
hasher.changed.active = true;
};
/**
* @param {string} sScreenName
* @return {?Object}
*/
Knoin.prototype.screen = function (sScreenName)
{
return ('' !== sScreenName && !Utils.isUnd(this.oScreens[sScreenName])) ? this.oScreens[sScreenName] : null;
};
/**
* @param {Function} ViewModelClass
* @param {Object=} oScreen
*/
Knoin.prototype.buildViewModel = function (ViewModelClass, oScreen)
{
if (ViewModelClass && !ViewModelClass.__builded)
{
var
oViewModel = new ViewModelClass(oScreen),
sPosition = oViewModel.viewModelPosition(),
oViewModelPlace = $('#rl-content #rl-' + sPosition.toLowerCase()),
oViewModelDom = null
;
ViewModelClass.__builded = true;
ViewModelClass.__vm = oViewModel;
oViewModel.data = RL.data(); // TODO cjs
oViewModel.viewModelName = ViewModelClass.__name;
if (oViewModelPlace && 1 === oViewModelPlace.length)
{
oViewModelDom = $('<div></div>').addClass('rl-view-model').addClass('RL-' + oViewModel.viewModelTemplate()).hide();
oViewModelDom.appendTo(oViewModelPlace);
oViewModel.viewModelDom = oViewModelDom;
ViewModelClass.__dom = oViewModelDom;
if ('Popups' === sPosition)
{
oViewModel.cancelCommand = oViewModel.closeCommand = Utils.createCommand(oViewModel, function () {
kn.hideScreenPopup(ViewModelClass); // TODO cjs
});
oViewModel.modalVisibility.subscribe(function (bValue) {
var self = this;
if (bValue)
{
this.viewModelDom.show();
this.storeAndSetKeyScope();
RL.popupVisibilityNames.push(this.viewModelName); // TODO cjs
oViewModel.viewModelDom.css('z-index', 3000 + RL.popupVisibilityNames().length + 10); // TODO cjs
Utils.delegateRun(this, 'onFocus', [], 500);
}
else
{
Utils.delegateRun(this, 'onHide');
this.restoreKeyScope();
RL.popupVisibilityNames.remove(this.viewModelName); // TODO cjs
oViewModel.viewModelDom.css('z-index', 2000);
Globals.tooltipTrigger(!Globals.tooltipTrigger());
_.delay(function () {
self.viewModelDom.hide();
}, 300);
}
}, oViewModel);
}
Plugins.runHook('view-model-pre-build', [ViewModelClass.__name, oViewModel, oViewModelDom]); // TODO cjs
ko.applyBindingAccessorsToNode(oViewModelDom[0], {
'i18nInit': true,
'template': function () { return {'name': oViewModel.viewModelTemplate()};}
}, oViewModel);
Utils.delegateRun(oViewModel, 'onBuild', [oViewModelDom]);
if (oViewModel && 'Popups' === sPosition)
{
oViewModel.registerPopupKeyDown();
}
Plugins.runHook('view-model-post-build', [ViewModelClass.__name, oViewModel, oViewModelDom]); // TODO cjs
}
else
{
Utils.log('Cannot find view model position: ' + sPosition);
}
}
return ViewModelClass ? ViewModelClass.__vm : null;
};
/**
* @param {Object} oViewModel
* @param {Object} oViewModelDom
*/
Knoin.prototype.applyExternal = function (oViewModel, oViewModelDom)
{
if (oViewModel && oViewModelDom)
{
ko.applyBindings(oViewModel, oViewModelDom);
}
};
/**
* @param {Function} ViewModelClassToHide
*/
Knoin.prototype.hideScreenPopup = function (ViewModelClassToHide)
{
if (ViewModelClassToHide && ViewModelClassToHide.__vm && ViewModelClassToHide.__dom)
{
ViewModelClassToHide.__vm.modalVisibility(false);
Plugins.runHook('view-model-on-hide', [ViewModelClassToHide.__name, ViewModelClassToHide.__vm]); // TODO cjs
}
};
/**
* @param {Function} ViewModelClassToShow
* @param {Array=} aParameters
*/
Knoin.prototype.showScreenPopup = function (ViewModelClassToShow, aParameters)
{
if (ViewModelClassToShow)
{
this.buildViewModel(ViewModelClassToShow);
if (ViewModelClassToShow.__vm && ViewModelClassToShow.__dom)
{
ViewModelClassToShow.__vm.modalVisibility(true);
Utils.delegateRun(ViewModelClassToShow.__vm, 'onShow', aParameters || []);
Plugins.runHook('view-model-on-show', [ViewModelClassToShow.__name, ViewModelClassToShow.__vm, aParameters || []]); // TODO cjs
}
}
};
/**
* @param {Function} ViewModelClassToShow
* @return {boolean}
*/
Knoin.prototype.isPopupVisible = function (ViewModelClassToShow)
{
return ViewModelClassToShow && ViewModelClassToShow.__vm ? ViewModelClassToShow.__vm.modalVisibility() : false;
};
/**
* @param {string} sScreenName
* @param {string} sSubPart
*/
Knoin.prototype.screenOnRoute = function (sScreenName, sSubPart)
{
var
self = this,
oScreen = null,
oCross = null
;
if ('' === Utils.pString(sScreenName))
{
sScreenName = this.sDefaultScreenName;
}
if ('' !== sScreenName)
{
oScreen = this.screen(sScreenName);
if (!oScreen)
{
oScreen = this.screen(this.sDefaultScreenName);
if (oScreen)
{
sSubPart = sScreenName + '/' + sSubPart;
sScreenName = this.sDefaultScreenName;
}
}
if (oScreen && oScreen.__started)
{
if (!oScreen.__builded)
{
oScreen.__builded = true;
if (Utils.isNonEmptyArray(oScreen.viewModels()))
{
_.each(oScreen.viewModels(), function (ViewModelClass) {
this.buildViewModel(ViewModelClass, oScreen);
}, this);
}
Utils.delegateRun(oScreen, 'onBuild');
}
_.defer(function () {
// hide screen
if (self.oCurrentScreen)
{
Utils.delegateRun(self.oCurrentScreen, 'onHide');
if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
{
_.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
if (ViewModelClass.__vm && ViewModelClass.__dom &&
'Popups' !== ViewModelClass.__vm.viewModelPosition())
{
ViewModelClass.__dom.hide();
ViewModelClass.__vm.viewModelVisibility(false);
Utils.delegateRun(ViewModelClass.__vm, 'onHide');
}
});
}
}
// --
self.oCurrentScreen = oScreen;
// show screen
if (self.oCurrentScreen)
{
Utils.delegateRun(self.oCurrentScreen, 'onShow');
Plugins.runHook('screen-on-show', [self.oCurrentScreen.screenName(), self.oCurrentScreen]); // TODO cjs
if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
{
_.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
if (ViewModelClass.__vm && ViewModelClass.__dom &&
'Popups' !== ViewModelClass.__vm.viewModelPosition())
{
ViewModelClass.__dom.show();
ViewModelClass.__vm.viewModelVisibility(true);
Utils.delegateRun(ViewModelClass.__vm, 'onShow');
Utils.delegateRun(ViewModelClass.__vm, 'onFocus', [], 200);
Plugins.runHook('view-model-on-show', [ViewModelClass.__name, ViewModelClass.__vm]); // TODO cjs
}
}, self);
}
}
// --
oCross = oScreen.__cross();
if (oCross)
{
oCross.parse(sSubPart);
}
});
}
}
};
/**
* @param {Array} aScreensClasses
*/
Knoin.prototype.startScreens = function (aScreensClasses)
{
$('#rl-content').css({
'visibility': 'hidden'
});
_.each(aScreensClasses, function (CScreen) {
var
oScreen = new CScreen(),
sScreenName = oScreen ? oScreen.screenName() : ''
;
if (oScreen && '' !== sScreenName)
{
if ('' === this.sDefaultScreenName)
{
this.sDefaultScreenName = sScreenName;
}
this.oScreens[sScreenName] = oScreen;
}
}, this);
_.each(this.oScreens, function (oScreen) {
if (oScreen && !oScreen.__started && oScreen.__start)
{
oScreen.__started = true;
oScreen.__start();
Plugins.runHook('screen-pre-start', [oScreen.screenName(), oScreen]); // TODO cjs
Utils.delegateRun(oScreen, 'onStart');
Plugins.runHook('screen-post-start', [oScreen.screenName(), oScreen]); // TODO cjs
}
}, this);
var oCross = crossroads.create();
oCross.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/, _.bind(this.screenOnRoute, this));
hasher.initialized.add(oCross.parse, oCross);
hasher.changed.add(oCross.parse, oCross);
hasher.init();
$('#rl-content').css({
'visibility': 'visible'
});
_.delay(function () {
$html.removeClass('rl-started-trigger').addClass('rl-started');
}, 50);
};
/**
* @param {string} sHash
* @param {boolean=} bSilence = false
* @param {boolean=} bReplace = false
*/
Knoin.prototype.setHash = function (sHash, bSilence, bReplace)
{
sHash = '#' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
sHash = '/' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
bReplace = Utils.isUnd(bReplace) ? false : !!bReplace;
if (Utils.isUnd(bSilence) ? false : !!bSilence)
{
hasher.changed.active = false;
hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
hasher.changed.active = true;
}
else
{
hasher.changed.active = true;
hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
hasher.setHash(sHash);
}
};
/**
* @return {Knoin}
*/
Knoin.prototype.bootstart = function (RL)
{
var
window = require('../External/window.js'),
$window = require('../External/$window.js'),
$html = require('../External/$html.js'),
Plugins = require('../Common/Plugins.js'),
EmailModel = require('../Models/EmailModel.js')
;
$html.addClass(Globals.bMobileDevice ? 'mobile' : 'no-mobile');
$window.keydown(Utils.killCtrlAandS).keyup(Utils.killCtrlAandS);
$window.unload(function () {
Globals.bUnload = true;
});
$html.on('click.dropdown.data-api', function () {
Utils.detectDropdownVisibility();
});
// export
window['rl'] = window['rl'] || {};
window['rl']['addHook'] = Plugins.addHook;
window['rl']['settingsGet'] = Plugins.mainSettingsGet;
window['rl']['remoteRequest'] = Plugins.remoteRequest;
window['rl']['pluginSettingsGet'] = Plugins.settingsGet;
window['rl']['addSettingsViewModel'] = Utils.addSettingsViewModel;
window['rl']['createCommand'] = Utils.createCommand;
window['rl']['EmailModel'] = EmailModel;
window['rl']['Enums'] = Enums;
window['__RLBOOT'] = function (fCall) {
// boot
$(function () {
if (window['rainloopTEMPLATES'] && window['rainloopTEMPLATES'][0])
{
$('#rl-templates').html(window['rainloopTEMPLATES'][0]);
_.delay(function () {
RL.bootstart();
$html.removeClass('no-js rl-booted-trigger').addClass('rl-booted');
}, 50);
}
else
{
fCall(false);
}
window['__RLBOOT'] = null;
});
};
};
module.exports = new Knoin();
}(module));
},{"../Common/Enums.js":5,"../Common/Globals.js":6,"../Common/Plugins.js":7,"../Common/Utils.js":8,"../External/$html.js":10,"../External/$window.js":11,"../External/crossroads.js":14,"../External/hasher.js":15,"../External/jquery.js":16,"../External/ko.js":17,"../External/underscore.js":19,"../External/window.js":20,"../Models/EmailModel.js":23}],22:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
/**
* @constructor
*/
function KnoinAbstractBoot()
{
}
KnoinAbstractBoot.prototype.bootstart = function ()
{
};
module.exports = KnoinAbstractBoot;
}(module));
},{}],23:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (module) {
'use strict';
var
Enums = require('../Common/Enums.js'),
Utils = require('../Common/Utils.js')
;
/**
* @param {string=} sEmail
* @param {string=} sName
*
* @constructor
*/
function EmailModel(sEmail, sName)
{
this.email = sEmail || '';
this.name = sName || '';
this.privateType = null;
this.clearDuplicateName();
}
/**
* @static
* @param {AjaxJsonEmail} oJsonEmail
* @return {?EmailModel}
*/
EmailModel.newInstanceFromJson = function (oJsonEmail)
{
var oEmailModel = new EmailModel();
return oEmailModel.initByJson(oJsonEmail) ? oEmailModel : null;
};
/**
* @type {string}
*/
EmailModel.prototype.name = '';
/**
* @type {string}
*/
EmailModel.prototype.email = '';
/**
* @type {(number|null)}
*/
EmailModel.prototype.privateType = null;
EmailModel.prototype.clear = function ()
{
this.email = '';
this.name = '';
this.privateType = null;
};
/**
* @returns {boolean}
*/
EmailModel.prototype.validate = function ()
{
return '' !== this.name || '' !== this.email;
};
/**
* @param {boolean} bWithoutName = false
* @return {string}
*/
EmailModel.prototype.hash = function (bWithoutName)
{
return '#' + (bWithoutName ? '' : this.name) + '#' + this.email + '#';
};
EmailModel.prototype.clearDuplicateName = function ()
{
if (this.name === this.email)
{
this.name = '';
}
};
/**
* @return {number}
*/
EmailModel.prototype.type = function ()
{
if (null === this.privateType)
{
if (this.email && '@facebook.com' === this.email.substr(-13))
{
this.privateType = Enums.EmailType.Facebook;
}
if (null === this.privateType)
{
this.privateType = Enums.EmailType.Default;
}
}
return this.privateType;
};
/**
* @param {string} sQuery
* @return {boolean}
*/
EmailModel.prototype.search = function (sQuery)
{
return -1 < (this.name + ' ' + this.email).toLowerCase().indexOf(sQuery.toLowerCase());
};
/**
* @param {string} sString
*/
EmailModel.prototype.parse = function (sString)
{
this.clear();
sString = Utils.trim(sString);
var
mRegex = /(?:"([^"]+)")? ?<?(.*?@[^>,]+)>?,? ?/g,
mMatch = mRegex.exec(sString)
;
if (mMatch)
{
this.name = mMatch[1] || '';
this.email = mMatch[2] || '';
this.clearDuplicateName();
}
else if ((/^[^@]+@[^@]+$/).test(sString))
{
this.name = '';
this.email = sString;
}
};
/**
* @param {AjaxJsonEmail} oJsonEmail
* @return {boolean}
*/
EmailModel.prototype.initByJson = function (oJsonEmail)
{
var bResult = false;
if (oJsonEmail && 'Object/Email' === oJsonEmail['@Object'])
{
this.name = Utils.trim(oJsonEmail.Name);
this.email = Utils.trim(oJsonEmail.Email);
bResult = '' !== this.email;
this.clearDuplicateName();
}
return bResult;
};
/**
* @param {boolean} bFriendlyView
* @param {boolean=} bWrapWithLink = false
* @param {boolean=} bEncodeHtml = false
* @return {string}
*/
EmailModel.prototype.toLine = function (bFriendlyView, bWrapWithLink, bEncodeHtml)
{
var sResult = '';
if ('' !== this.email)
{
bWrapWithLink = Utils.isUnd(bWrapWithLink) ? false : !!bWrapWithLink;
bEncodeHtml = Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml;
if (bFriendlyView && '' !== this.name)
{
sResult = bWrapWithLink ? '<a href="mailto:' + Utils.encodeHtml('"' + this.name + '" <' + this.email + '>') +
'" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.name) + '</a>' :
(bEncodeHtml ? Utils.encodeHtml(this.name) : this.name);
}
else
{
sResult = this.email;
if ('' !== this.name)
{
if (bWrapWithLink)
{
sResult = Utils.encodeHtml('"' + this.name + '" <') +
'<a href="mailto:' + Utils.encodeHtml('"' + this.name + '" <' + this.email + '>') + '" target="_blank" tabindex="-1">' + Utils.encodeHtml(sResult) + '</a>' + Utils.encodeHtml('>');
}
else
{
sResult = '"' + this.name + '" <' + sResult + '>';
if (bEncodeHtml)
{
sResult = Utils.encodeHtml(sResult);
}
}
}
else if (bWrapWithLink)
{
sResult = '<a href="mailto:' + Utils.encodeHtml(this.email) + '" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.email) + '</a>';
}
}
}
return sResult;
};
/**
* @param {string} $sEmailAddress
* @return {boolean}
*/
EmailModel.prototype.mailsoParse = function ($sEmailAddress)
{
$sEmailAddress = Utils.trim($sEmailAddress);
if ('' === $sEmailAddress)
{
return false;
}
var
substr = function (str, start, len) {
str += '';
var end = str.length;
if (start < 0) {
start += end;
}
end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
return start >= str.length || start < 0 || start > end ? false : str.slice(start, end);
},
substr_replace = function (str, replace, start, length) {
if (start < 0) {
start = start + str.length;
}
length = length !== undefined ? length : str.length;
if (length < 0) {
length = length + str.length - start;
}
return str.slice(0, start) + replace.substr(0, length) + replace.slice(length) + str.slice(start + length);
},
$sName = '',
$sEmail = '',
$sComment = '',
$bInName = false,
$bInAddress = false,
$bInComment = false,
$aRegs = null,
$iStartIndex = 0,
$iEndIndex = 0,
$iCurrentIndex = 0
;
while ($iCurrentIndex < $sEmailAddress.length)
{
switch ($sEmailAddress.substr($iCurrentIndex, 1))
{
case '"':
if ((!$bInName) && (!$bInAddress) && (!$bInComment))
{
$bInName = true;
$iStartIndex = $iCurrentIndex;
}
else if ((!$bInAddress) && (!$bInComment))
{
$iEndIndex = $iCurrentIndex;
$sName = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
$sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
$iEndIndex = 0;
$iCurrentIndex = 0;
$iStartIndex = 0;
$bInName = false;
}
break;
case '<':
if ((!$bInName) && (!$bInAddress) && (!$bInComment))
{
if ($iCurrentIndex > 0 && $sName.length === 0)
{
$sName = substr($sEmailAddress, 0, $iCurrentIndex);
}
$bInAddress = true;
$iStartIndex = $iCurrentIndex;
}
break;
case '>':
if ($bInAddress)
{
$iEndIndex = $iCurrentIndex;
$sEmail = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
$sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
$iEndIndex = 0;
$iCurrentIndex = 0;
$iStartIndex = 0;
$bInAddress = false;
}
break;
case '(':
if ((!$bInName) && (!$bInAddress) && (!$bInComment))
{
$bInComment = true;
$iStartIndex = $iCurrentIndex;
}
break;
case ')':
if ($bInComment)
{
$iEndIndex = $iCurrentIndex;
$sComment = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
$sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
$iEndIndex = 0;
$iCurrentIndex = 0;
$iStartIndex = 0;
$bInComment = false;
}
break;
case '\\':
$iCurrentIndex++;
break;
}
$iCurrentIndex++;
}
if ($sEmail.length === 0)
{
$aRegs = $sEmailAddress.match(/[^@\s]+@\S+/i);
if ($aRegs && $aRegs[0])
{
$sEmail = $aRegs[0];
}
else
{
$sName = $sEmailAddress;
}
}
if ($sEmail.length > 0 && $sName.length === 0 && $sComment.length === 0)
{
$sName = $sEmailAddress.replace($sEmail, '');
}
$sEmail = Utils.trim($sEmail).replace(/^[<]+/, '').replace(/[>]+$/, '');
$sName = Utils.trim($sName).replace(/^["']+/, '').replace(/["']+$/, '');
$sComment = Utils.trim($sComment).replace(/^[(]+/, '').replace(/[)]+$/, '');
// Remove backslash
$sName = $sName.replace(/\\\\(.)/, '$1');
$sComment = $sComment.replace(/\\\\(.)/, '$1');
this.name = $sName;
this.email = $sEmail;
this.clearDuplicateName();
return true;
};
/**
* @return {string}
*/
EmailModel.prototype.inputoTagLine = function ()
{
return 0 < this.name.length ? this.name + ' (' + this.email + ')' : this.email;
};
module.exports = EmailModel;
}(module));
},{"../Common/Enums.js":5,"../Common/Utils.js":8}]},{},[1]);