<commit_before>/*
 * Copyright 2017 Red Hat Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var filters = require('rhea/lib/filter.js');
var Utils = require('./utils.js');
var fs = require('fs');

//static class Core client contains help method for clients
var CoreClient = function () {};

CoreClient.timeout;
CoreClient.timeoutFunction;
CoreClient.reconnectCount = 0;
CoreClient.arrHosts = [];
CoreClient.arrPorts = [];
CoreClient.logstats;

CoreClient.Close = function (context, closeSleep, isListener) {
    if(closeSleep) {
        CoreClient.TimeoutClose(context, closeSleep);
    }else{
        if (CoreClient.logStats === 'endpoints') {
            Utils.PrintStatistic(context);
        }

        if(isListener) {
            process.exit(Utils.ReturnCodes.OK);
        }
        context.sender && context.sender.detach();
        context.receiver && context.receiver.detach();
        context.connection.close();
    }
};

CoreClient.Reply = function (context) {
    var sender = context.connection.open_sender({target: {address: context.message['reply_to']},
        autosettle: false});
    sender.send(context.message);
    sender.set_drained(true);
};

CoreClient.TimeoutClose = function (context, timeout, isListener) {
    if(timeout > 0) {
        CoreClient.timeout = timeout;
        CoreClient.timeoutFunction = setTimeout(function(context, isListener) {
            CoreClient.Close(context, null, isListener);
        }, timeout,
        context, isListener);
    }
};

CoreClient.OnDisconnect = function (context) {
    CoreClient.CancelTimeout();
    CoreClient.reconnectCount++;
    if(CoreClient.reconnectCount === context.connection.options.reconnect_limit) {
        process.exit(Utils.ReturnCodes.Error);
    }
};

CoreClient.OnConnError = function (context) {
    if(context.connection.get_error().condition !== 'amqp:connection:forced') {
        Utils.PrintError(JSON.stringify(context.connection.get_error()));
        process.exit(Utils.ReturnCodes.Error);
    }
};

CoreClient.OnRejected = function (context) {
    Utils.PrintError(context.delivery.remote_state.error.value);
    context.connection.close();
    process.exit(Utils.ReturnCodes.Error);
};

CoreClient.OnReleased = function (context) {
    Utils.PrintError('Message released');
    context.connection.close();
    process.exit(Utils.ReturnCodes.Error);
};

CoreClient.OnProtocolError = function (context) {
    Utils.PrintError(JSON.stringify(context));
    process.exit(Utils.ReturnCodes.Error);
};

CoreClient.RegistryUnhandledError = function() {
    process.on('uncaughtException', function(err) {
        // handle the error safely
        Utils.PrintError(err);
        process.exit(Utils.ReturnCodes.Error);
    });
};

CoreClient.CancelTimeout = function () {
    clearTimeout(CoreClient.timeoutFunction);
};

CoreClient.ResetTimeout = function (context, isListener) {
    CoreClient.CancelTimeout();
    CoreClient.TimeoutClose(context, CoreClient.timeout, isListener);
};

CoreClient.SetUpSSL = function (options) {
    var sslDict = {};

    sslDict['transport'] = 'tls';
    if (options.sslPrivateKey) sslDict['key'] = fs.readFileSync(options.sslPrivateKey);
    if (options.sslCertificate) sslDict['cert'] = fs.readFileSync(options.sslCertificate);
    if (options.sslTrustStore) sslDict['ca'] = fs.readFileSync(options.sslTrustStore);
    if (options.sslPassword) sslDict['passphrase'] = options.sslPassword;

    return sslDict;
};

CoreClient.BuildFailoverHandler = function(options) {
    CoreClient.arrHosts.push(options.url);
    CoreClient.arrPorts.push(options.port);

    try{
        var connUrls = JSON.parse(options.connUrls);
        for(var i = 0; i < connUrls.length; i++) {
            var splitUrl = connUrls[i].split(':');
            CoreClient.arrHosts.push(splitUrl[0]);
            CoreClient.arrPorts.push(splitUrl[1]);
        }

        return function() {
            return {host: CoreClient.arrHosts[CoreClient.reconnectCount % CoreClient.arrHosts.length],
                port: CoreClient.arrPorts[CoreClient.reconnectCount % CoreClient.arrPorts.length]};
        };
    }catch(err) {
        Utils.PrintError('conn-urls has wrong format, try help fo show how use it');
        process.exit(Utils.ReturnCodes.Error_ARGS);
    }
};

//connection options
CoreClient.BuildConnectionOptionsDict = function(options) {
    var connectionDict = {};

    //destination setting
    if(options.connUrls) {
        //failover
        connectionDict['connection_details'] = CoreClient.BuildFailoverHandler(options);
    }else{
        //standart
        connectionDict['host'] = options.url;
        connectionDict['port'] = options.port;
    }

    //sasl
    connectionDict['username'] = options.username;
    connectionDict['password'] = options.password;

    //reconnect
    if(options.reconnect) {
        if (options.reconnectLimit) {
            connectionDict['reconnect_limit'] = options.reconnectLimit;
        }
        if(options.reconnectInterval) {
            connectionDict['initial_reconnect_delay'] = options.reconnectInterval;
            connectionDict['max_reconnect_delay'] = options.reconnectInterval;
        }
    }else if (!options.reconnect) {
        connectionDict['reconnect'] = false;
    }
    //max frame size
    connectionDict['max_frame_size'] = options.frameSize;
    //heartbeat
    if (options.heartbeat) {
        connectionDict['idle_time_out'] = options.heartbeat;
    }

    //ssl setting
    if (options.sslCertificate || options.sslTrustStore) {
        var sslOptions = CoreClient.SetUpSSL(options);
        for (var opt in sslOptions) {
            connectionDict[opt] = sslOptions[opt];
        }
    }
    return connectionDict;
};

CoreClient.BuildReceiverOptionsDict = function(options) {
    var receiverOptions = {};
    var source = {};
    source['address'] = options.address;                                                            //address of queue
    source['distribution_mode'] = options.recvBrowse ? 'copy' : '';                                 //message browse options
    source['durable'] = options.durable;                                                            //durable subscription
    source['filter'] = (options.msgSelector) ? filters.selector(options.msgSelector) : '';          //message selector options

    if (options.action !== 'acknowledge') {
        receiverOptions['autoaccept'] = false;
    }
    receiverOptions['credit_window'] = (options.recvBrowse || options.count === 0) ? 0 : undefined;  //disable automatic credit windows for recv browse or read all messages from queue
    receiverOptions['source'] = source;

    return receiverOptions;
};

CoreClient.BuildSenderOptionsDict = function(options) {
    var senderOptions = {};
    var target = {};
    target['address'] = options.address;
    target['durable'] = options.durable;

    if (options.linkAtMostOnce) {
        senderOptions['snd_settle_mode'] = 1;
    } else if (options.linkAtLeastOnce) {
        senderOptions['snd_settle_mode'] = 0;
    }
    senderOptions['target'] = target;
    senderOptions['autosettle'] = !options.autoSettleOff;

    return senderOptions;
};

CoreClient.BuildWebSocketConnString = function(options) {
    var connTemplate = 'ws://%BROKER:%PORT';
    return connTemplate.replace('%BROKER', options.url).replace('%PORT', options.port);
};

CoreClient.BuildWebSocketConnectionDict = function(ws, options) {
    var connectionDict = {};

    //destination setting
    connectionDict['connection_details'] = ws(CoreClient.BuildWebSocketConnString(options), ['binary', 'AMQPWSB10', 'amqp']);

    //sasl
    connectionDict['username'] = options.username;
    connectionDict['password'] = options.password;

     //reconnect
    if(options.reconnect) {
        if (options.reconnectLimit) {
            connectionDict['reconnect_limit'] = options.reconnectLimit;
        }
        if(options.reconnectInterval) {
            connectionDict['initial_reconnect_delay'] = options.reconnectInterval;
            connectionDict['max_reconnect_delay'] = options.reconnectInterval;
        }
    }else if (!options.reconnect) {
        connectionDict['reconnect'] = false;
    }
    //max frame size
    connectionDict['max_frame_size'] = options.frameSize;
    //heartbeat
    if (options.heartbeat) {
        connectionDict['idle_time_out'] = options.heartbeat;
    }

    return connectionDict;
};

//===========================================================================
exports.CoreClient = CoreClient;
<commit_msg>FIX: Cancel next send request when timeout end<commit_after>/*
 * Copyright 2017 Red Hat Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var filters = require('rhea/lib/filter.js');
var Utils = require('./utils.js');
var fs = require('fs');

//static class Core client contains help method for clients
var CoreClient = function () {};

CoreClient.timeout;
CoreClient.timeoutFunction;
CoreClient.reconnectCount = 0;
CoreClient.arrHosts = [];
CoreClient.arrPorts = [];
CoreClient.logstats;

CoreClient.Close = function (context, closeSleep, isListener) {
    if(closeSleep) {
        CoreClient.TimeoutClose(context, closeSleep);
    }else{
        if (CoreClient.logStats === 'endpoints') {
            Utils.PrintStatistic(context);
        }

        if(isListener) {
            process.exit(Utils.ReturnCodes.OK);
        }
        clearTimeout(context.container.timer_task);
        context.sender && context.sender.detach();
        context.receiver && context.receiver.detach();
        context.connection.close();
    }
};

CoreClient.Reply = function (context) {
    var sender = context.connection.open_sender({target: {address: context.message['reply_to']},
        autosettle: false});
    sender.send(context.message);
    sender.set_drained(true);
};

CoreClient.TimeoutClose = function (context, timeout, isListener) {
    if(timeout > 0) {
        CoreClient.timeout = timeout;
        CoreClient.timeoutFunction = setTimeout(function(context, isListener) {
            CoreClient.Close(context, null, isListener);
        }, timeout,
        context, isListener);
    }
};

CoreClient.OnDisconnect = function (context) {
    CoreClient.CancelTimeout();
    CoreClient.reconnectCount++;
    if(CoreClient.reconnectCount === context.connection.options.reconnect_limit) {
        process.exit(Utils.ReturnCodes.Error);
    }
};

CoreClient.OnConnError = function (context) {
    if(context.connection.get_error().condition !== 'amqp:connection:forced') {
        Utils.PrintError(JSON.stringify(context.connection.get_error()));
        process.exit(Utils.ReturnCodes.Error);
    }
};

CoreClient.OnRejected = function (context) {
    Utils.PrintError(context.delivery.remote_state.error.value);
    context.connection.close();
    process.exit(Utils.ReturnCodes.Error);
};

CoreClient.OnReleased = function (context) {
    Utils.PrintError('Message released');
    context.connection.close();
    process.exit(Utils.ReturnCodes.Error);
};

CoreClient.OnProtocolError = function (context) {
    Utils.PrintError(JSON.stringify(context));
    process.exit(Utils.ReturnCodes.Error);
};

CoreClient.RegistryUnhandledError = function() {
    process.on('uncaughtException', function(err) {
        // handle the error safely
        Utils.PrintError(err);
        process.exit(Utils.ReturnCodes.Error);
    });
};

CoreClient.CancelTimeout = function () {
    clearTimeout(CoreClient.timeoutFunction);
};

CoreClient.ResetTimeout = function (context, isListener) {
    CoreClient.CancelTimeout();
    CoreClient.TimeoutClose(context, CoreClient.timeout, isListener);
};

CoreClient.SetUpSSL = function (options) {
    var sslDict = {};

    sslDict['transport'] = 'tls';
    if (options.sslPrivateKey) sslDict['key'] = fs.readFileSync(options.sslPrivateKey);
    if (options.sslCertificate) sslDict['cert'] = fs.readFileSync(options.sslCertificate);
    if (options.sslTrustStore) sslDict['ca'] = fs.readFileSync(options.sslTrustStore);
    if (options.sslPassword) sslDict['passphrase'] = options.sslPassword;

    return sslDict;
};

CoreClient.BuildFailoverHandler = function(options) {
    CoreClient.arrHosts.push(options.url);
    CoreClient.arrPorts.push(options.port);

    try{
        var connUrls = JSON.parse(options.connUrls);
        for(var i = 0; i < connUrls.length; i++) {
            var splitUrl = connUrls[i].split(':');
            CoreClient.arrHosts.push(splitUrl[0]);
            CoreClient.arrPorts.push(splitUrl[1]);
        }

        return function() {
            return {host: CoreClient.arrHosts[CoreClient.reconnectCount % CoreClient.arrHosts.length],
                port: CoreClient.arrPorts[CoreClient.reconnectCount % CoreClient.arrPorts.length]};
        };
    }catch(err) {
        Utils.PrintError('conn-urls has wrong format, try help fo show how use it');
        process.exit(Utils.ReturnCodes.Error_ARGS);
    }
};

//connection options
CoreClient.BuildConnectionOptionsDict = function(options) {
    var connectionDict = {};

    //destination setting
    if(options.connUrls) {
        //failover
        connectionDict['connection_details'] = CoreClient.BuildFailoverHandler(options);
    }else{
        //standart
        connectionDict['host'] = options.url;
        connectionDict['port'] = options.port;
    }

    //sasl
    connectionDict['username'] = options.username;
    connectionDict['password'] = options.password;

    //reconnect
    if(options.reconnect) {
        if (options.reconnectLimit) {
            connectionDict['reconnect_limit'] = options.reconnectLimit;
        }
        if(options.reconnectInterval) {
            connectionDict['initial_reconnect_delay'] = options.reconnectInterval;
            connectionDict['max_reconnect_delay'] = options.reconnectInterval;
        }
    }else if (!options.reconnect) {
        connectionDict['reconnect'] = false;
    }
    //max frame size
    connectionDict['max_frame_size'] = options.frameSize;
    //heartbeat
    if (options.heartbeat) {
        connectionDict['idle_time_out'] = options.heartbeat;
    }

    //ssl setting
    if (options.sslCertificate || options.sslTrustStore) {
        var sslOptions = CoreClient.SetUpSSL(options);
        for (var opt in sslOptions) {
            connectionDict[opt] = sslOptions[opt];
        }
    }
    return connectionDict;
};

CoreClient.BuildReceiverOptionsDict = function(options) {
    var receiverOptions = {};
    var source = {};
    source['address'] = options.address;                                                            //address of queue
    source['distribution_mode'] = options.recvBrowse ? 'copy' : '';                                 //message browse options
    source['durable'] = options.durable;                                                            //durable subscription
    source['filter'] = (options.msgSelector) ? filters.selector(options.msgSelector) : '';          //message selector options

    if (options.action !== 'acknowledge') {
        receiverOptions['autoaccept'] = false;
    }
    receiverOptions['credit_window'] = (options.recvBrowse || options.count === 0) ? 0 : undefined;  //disable automatic credit windows for recv browse or read all messages from queue
    receiverOptions['source'] = source;

    return receiverOptions;
};

CoreClient.BuildSenderOptionsDict = function(options) {
    var senderOptions = {};
    var target = {};
    target['address'] = options.address;
    target['durable'] = options.durable;

    if (options.linkAtMostOnce) {
        senderOptions['snd_settle_mode'] = 1;
    } else if (options.linkAtLeastOnce) {
        senderOptions['snd_settle_mode'] = 0;
    }
    senderOptions['target'] = target;
    senderOptions['autosettle'] = !options.autoSettleOff;

    return senderOptions;
};

CoreClient.BuildWebSocketConnString = function(options) {
    var connTemplate = 'ws://%BROKER:%PORT';
    return connTemplate.replace('%BROKER', options.url).replace('%PORT', options.port);
};

CoreClient.BuildWebSocketConnectionDict = function(ws, options) {
    var connectionDict = {};

    //destination setting
    connectionDict['connection_details'] = ws(CoreClient.BuildWebSocketConnString(options), ['binary', 'AMQPWSB10', 'amqp']);

    //sasl
    connectionDict['username'] = options.username;
    connectionDict['password'] = options.password;

     //reconnect
    if(options.reconnect) {
        if (options.reconnectLimit) {
            connectionDict['reconnect_limit'] = options.reconnectLimit;
        }
        if(options.reconnectInterval) {
            connectionDict['initial_reconnect_delay'] = options.reconnectInterval;
            connectionDict['max_reconnect_delay'] = options.reconnectInterval;
        }
    }else if (!options.reconnect) {
        connectionDict['reconnect'] = false;
    }
    //max frame size
    connectionDict['max_frame_size'] = options.frameSize;
    //heartbeat
    if (options.heartbeat) {
        connectionDict['idle_time_out'] = options.heartbeat;
    }

    return connectionDict;
};

//===========================================================================
exports.CoreClient = CoreClient;
<|endoftext|>


<commit_before>const alt = require('../alt')
const actions = require('./settingsActions')
const storage = require('../storage')
const ipc = window.nativeRequire('electron').ipcRenderer

const SETTINGS_KEY = 'App_settings'

class SettingsStore {
  /* **************************************************************************/
  // Lifecycle
  /* **************************************************************************/

  constructor () {
    this.__settings__ = {}
    this.__onloadSettings__ = {}

    /* ****************************************/
    // Helpers
    /* ****************************************/

    /**
    * @param key: the key to fetch
    * @param def: the default value to return
    * @return the value from settings or the default value
    */
    this.__value__ = (key, def) => {
      return this.__settings__[key] === undefined ? def : this.__settings__[key]
    }

    /**
    * @param key: the key to fetch
    * @param def: the default value to return
    * @return the value from load setting or the default value
    */
    this.__onloadvalue__ = (key, def) => {
      return this.__onloadSettings__[key] === undefined ? def : this.__onloadSettings__[key]
    }

    /**
    * @param key: the key to check
    * @param def: the default value
    * @return true if the value is different to the onload value
    */
    this.__valuediff__ = (key, def) => {
      return this.__value__(key, def) !== this.__onloadvalue__(key, def)
    }

    /* ****************************************/
    // Proxy Server
    /* ****************************************/
    this.getProxyServer = () => {
      return this.__value__('proxyServer', { enabled: false })
    }
    this.proxyServerUrl = () => {
      const proxy = this.getProxyServer()
      return proxy.host + ':' + proxy.port
    }

    /* ****************************************/
    // OS level settings
    /* ****************************************/

    this.showTitlebar = () => {
      return this.__value__('showTitlebar', false)
    }
    this.showTitlebarChanged = () => {
      return this.__valuediff__('showTitlebar', false)
    }
    this.showAppBadge = () => {
      return this.__value__('showAppBadge', true)
    }
    this.showAppMenu = () => {
      return this.__value__('showAppMenu', true)
    }

    /* ****************************************/
    // Tray
    /* ****************************************/

    this.showTrayIcon = () => {
      return this.__value__('showTrayIcon', true)
    }

    this.showTrayUnreadCount = () => {
      return this.__value__('showTrayUnreadCount', true)
    }

    this.trayReadColor = () => {
      return this.__value__('trayReadColor')
    }

    this.trayUnreadColor = () => {
      return this.__value__('trayUnreadColor')
    }

    /* ****************************************/
    // Spell checker
    /* ****************************************/

    this.spellcheckerEnabled = () => {
      return this.__value__('spellcheckerEnabled', true)
    }
    this.spellcheckerChanged = () => {
      return this.__valuediff__('spellcheckerEnabled', true)
    }

    /* ****************************************/
    // Downloads
    /* ****************************************/

    this.alwaysAskDownloadLocation = () => {
      return this.__value__('alwaysAskDownloadLocation', true)
    }
    this.defaultDownloadLocation = () => {
      return this.__value__('defaultDownloadLocation', undefined)
    }

    /* ****************************************/
    // Sidebar
    /* ****************************************/

    this.sidebarEnabled = () => {
      return this.__value__('sidebarEnabled', true)
    }

    /* ****************************************/
    // Notifications
    /* ****************************************/

    this.notificationsEnabled = () => {
      return this.__value__('notificationsEnabled', true)
    }
    this.notificationsSilent = () => {
      return this.__value__('notificationsSilent', false)
    }

    /* ****************************************/
    // Interactions
    /* ****************************************/

    this.openLinksInBackground = () => {
      return this.__value__('openLinksInBackground', false)
    }

    /* ****************************************/
    // Higher order
    /* ****************************************/

    /**
    * @return true if the app needs to be restarted to apply the settings
    */
    this.requiresRestart = () => {
      return this.showTitlebarChanged() || this.spellcheckerChanged()
    }

    this.bindListeners({
      handleLoad: actions.LOAD,
      handleSetProxyServer: actions.SET_PROXY_SERVER,
      handleMergeUpdates: actions.MERGE_UPDATES,
      handleToggleSidebar: actions.TOGGLE_SIDEBAR,
      handleToggleAppMenu: actions.TOGGLE_APP_MENU
    })
  }

  /* **************************************************************************/
  // Disk
  /* **************************************************************************/

  persist () {
    storage.set(SETTINGS_KEY, this.__settings__)
    ipc.send('settings-update', this.__settings__)
  }

  /* **************************************************************************/
  // Handlers
  /* **************************************************************************/
  /**
  * Loads the storage from disk
  */
  handleLoad () {
    this.__settings__ = storage.get(SETTINGS_KEY, {})
    this.__onloadSettings__ = Object.freeze(storage.get(SETTINGS_KEY, {}))
  }

  /**
  * Sets the proxy server
  * @param host: the host or undefined
  * @param port: the port or undefined
  */
  handleSetProxyServer ({ host, port, enabled }) {
    if (!enabled) {
      delete this.__settings__.proxyServer
    } else {
      this.__settings__.proxyServer = { host: host, port: port, enabled: true }
    }
    this.persist()
  }

  /**
  * Merges the updates
  * @param updates: the dictionary to merge in
  */
  handleMergeUpdates ({ updates }) {
    this.__settings__ = Object.assign(this.__settings__, updates)
    this.persist()
  }

  /**
  * Toggles the sidebar
  */
  handleToggleSidebar () {
    this.handleMergeUpdates({ updates: { sidebarEnabled: !this.sidebarEnabled() } })
  }

  /**
  * Toggles the app menu
  */
  handleToggleAppMenu () {
    this.handleMergeUpdates({ updates: { showAppMenu: !this.showAppMenu() } })
  }
}

module.exports = alt.createStore(SettingsStore, 'SettingsStore')
<commit_msg>Default settings for windows<commit_after>const alt = require('../alt')
const actions = require('./settingsActions')
const storage = require('../storage')
const ipc = window.nativeRequire('electron').ipcRenderer

const SETTINGS_KEY = 'App_settings'

class SettingsStore {
  /* **************************************************************************/
  // Lifecycle
  /* **************************************************************************/

  constructor () {
    this.__settings__ = {}
    this.__onloadSettings__ = {}

    /* ****************************************/
    // Helpers
    /* ****************************************/

    /**
    * @param key: the key to fetch
    * @param def: the default value to return
    * @return the value from settings or the default value
    */
    this.__value__ = (key, def) => {
      return this.__settings__[key] === undefined ? def : this.__settings__[key]
    }

    /**
    * @param key: the key to fetch
    * @param def: the default value to return
    * @return the value from load setting or the default value
    */
    this.__onloadvalue__ = (key, def) => {
      return this.__onloadSettings__[key] === undefined ? def : this.__onloadSettings__[key]
    }

    /**
    * @param key: the key to check
    * @param def: the default value
    * @return true if the value is different to the onload value
    */
    this.__valuediff__ = (key, def) => {
      return this.__value__(key, def) !== this.__onloadvalue__(key, def)
    }

    /* ****************************************/
    // Proxy Server
    /* ****************************************/
    this.getProxyServer = () => {
      return this.__value__('proxyServer', { enabled: false })
    }
    this.proxyServerUrl = () => {
      const proxy = this.getProxyServer()
      return proxy.host + ':' + proxy.port
    }

    /* ****************************************/
    // OS level settings
    /* ****************************************/

    this.showTitlebar = () => {
      return this.__value__('showTitlebar', false)
    }
    this.showTitlebarChanged = () => {
      return this.__valuediff__('showTitlebar', false)
    }
    this.showAppBadge = () => {
      return this.__value__('showAppBadge', true)
    }
    this.showAppMenu = () => {
      if (process.platform === 'win32') {
        return this.__value__('showAppMenu', false)
      } else {
        return this.__value__('showAppMenu', true)
      }
    }

    /* ****************************************/
    // Tray
    /* ****************************************/

    this.showTrayIcon = () => {
      return this.__value__('showTrayIcon', true)
    }

    this.showTrayUnreadCount = () => {
      return this.__value__('showTrayUnreadCount', true)
    }

    this.trayReadColor = () => {
      return this.__value__('trayReadColor')
    }

    this.trayUnreadColor = () => {
      return this.__value__('trayUnreadColor')
    }

    /* ****************************************/
    // Spell checker
    /* ****************************************/

    this.spellcheckerEnabled = () => {
      return this.__value__('spellcheckerEnabled', true)
    }
    this.spellcheckerChanged = () => {
      return this.__valuediff__('spellcheckerEnabled', true)
    }

    /* ****************************************/
    // Downloads
    /* ****************************************/

    this.alwaysAskDownloadLocation = () => {
      return this.__value__('alwaysAskDownloadLocation', true)
    }
    this.defaultDownloadLocation = () => {
      return this.__value__('defaultDownloadLocation', undefined)
    }

    /* ****************************************/
    // Sidebar
    /* ****************************************/

    this.sidebarEnabled = () => {
      return this.__value__('sidebarEnabled', true)
    }

    /* ****************************************/
    // Notifications
    /* ****************************************/

    this.notificationsEnabled = () => {
      return this.__value__('notificationsEnabled', true)
    }
    this.notificationsSilent = () => {
      return this.__value__('notificationsSilent', false)
    }

    /* ****************************************/
    // Interactions
    /* ****************************************/

    this.openLinksInBackground = () => {
      return this.__value__('openLinksInBackground', false)
    }

    /* ****************************************/
    // Higher order
    /* ****************************************/

    /**
    * @return true if the app needs to be restarted to apply the settings
    */
    this.requiresRestart = () => {
      return this.showTitlebarChanged() || this.spellcheckerChanged()
    }

    this.bindListeners({
      handleLoad: actions.LOAD,
      handleSetProxyServer: actions.SET_PROXY_SERVER,
      handleMergeUpdates: actions.MERGE_UPDATES,
      handleToggleSidebar: actions.TOGGLE_SIDEBAR,
      handleToggleAppMenu: actions.TOGGLE_APP_MENU
    })
  }

  /* **************************************************************************/
  // Disk
  /* **************************************************************************/

  persist () {
    storage.set(SETTINGS_KEY, this.__settings__)
    ipc.send('settings-update', this.__settings__)
  }

  /* **************************************************************************/
  // Handlers
  /* **************************************************************************/
  /**
  * Loads the storage from disk
  */
  handleLoad () {
    this.__settings__ = storage.get(SETTINGS_KEY, {})
    this.__onloadSettings__ = Object.freeze(storage.get(SETTINGS_KEY, {}))
  }

  /**
  * Sets the proxy server
  * @param host: the host or undefined
  * @param port: the port or undefined
  */
  handleSetProxyServer ({ host, port, enabled }) {
    if (!enabled) {
      delete this.__settings__.proxyServer
    } else {
      this.__settings__.proxyServer = { host: host, port: port, enabled: true }
    }
    this.persist()
  }

  /**
  * Merges the updates
  * @param updates: the dictionary to merge in
  */
  handleMergeUpdates ({ updates }) {
    this.__settings__ = Object.assign(this.__settings__, updates)
    this.persist()
  }

  /**
  * Toggles the sidebar
  */
  handleToggleSidebar () {
    this.handleMergeUpdates({ updates: { sidebarEnabled: !this.sidebarEnabled() } })
  }

  /**
  * Toggles the app menu
  */
  handleToggleAppMenu () {
    this.handleMergeUpdates({ updates: { showAppMenu: !this.showAppMenu() } })
  }
}

module.exports = alt.createStore(SettingsStore, 'SettingsStore')
<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  generic pattern: event  */
$cs.pattern.event = $cs.clazz({
    mixin: [
        $cs.pattern.spec
    ],
    dynamics: {
        /*  attributes  */
        target:      $cs.attribute("target",      null),        /*  target object the event is send to  */
        propagation: $cs.attribute("propagation", true),        /*  whether event propagation should continue  */
        processing:  $cs.attribute("processing",  true),        /*  whether final default event processing should be performed  */
        dispatched:  $cs.attribute("dispatched",  false),       /*  whether event was dispatched at least once to a subscriber  */
        decline:     $cs.attribute("decline",     false),       /*  whether event was declined by subscriber  */
        state:       $cs.attribute("state",       "targeting"), /*  state of dispatching: capturing, targeting, spreading, bubbling */
        result:      $cs.attribute("result",      undefined),   /*  optional result value event subscribers can provide  */
        async:       $cs.attribute("async",       false)        /*  whether event is dispatched asynchronously  */
    }
});

/*  event factory  */
$cs.event = function () {
    /*  determine parameters  */
    var params = $cs.params("event", arguments, {
        name:        { pos: 0,     def: null, req: true  },
        spec:        {             def: {}               },
        target:      { pos: 1,     def: null, req: true  },
        propagation: { pos: 2,     def: true             },
        processing:  { pos: 3,     def: true             },
        dispatched:  { pos: 4,     def: false            },
        decline:     { pos: 5,     def: false            },
        state:       { pos: 6,     def: "targeting"      },
        result:      { pos: 7,     def: undefined        },
        async:       { pos: 8,     def: false            }
    });

    /*  create new event  */
    var ev = new $cs.pattern.event();

    /*  configure event  */
    ev.name       (params.name);
    ev.target     (params.target);
    ev.propagation(params.propagation);
    ev.processing (params.processing);
    ev.dispatched (params.dispatched);
    ev.decline    (params.decline);
    ev.state      (params.state);
    ev.result     (params.result);
    ev.spec       (params.spec);
    ev.async      (params.async);

    return ev;
};

/*  generic pattern: eventing  */
$cs.pattern.eventing = $cs.trait({
    dynamics: {
        __subscription: {}
    },
    protos: {
        /*  subscribe on an event  */
        subscribe: function () {
            /*  determine parameters  */
            var params = $cs.params("subscribe", arguments, {
                name:      { pos: 0,     def: null,    req: true },
                spec:      {             def: {}                 },
                ctx:       {             def: this               },
                func:      { pos: 1,     def: $cs.nop, req: true },
                args:      { pos: "...", def: []                 },
                capturing: {             def: false              },
                spreading: {             def: false              },
                bubbling:  {             def: true               },
                noevent:   {             def: false              },
                exclusive: {             def: false              },
                origin:    {             def: false              },
                spool:     {             def: null               }
            });

            /*  honor exclusive request  */
            if (params.exclusive) {
                var subscribers = this.subscribers(params.name, params.spec);
                if (subscribers.length > 0)
                    throw _cs.exception("subscribe", "multiple exclusive subscribers not allowed");
            }

            /*  attach parameters to component  */
            var id = _cs.cid();
            this.__subscription[id] = params;

            /*  optionally spool reverse operation  */
            if (params.spool !== null)
                this.spool(params.spool, this, "unsubscribe", id);

            return id;
        },

        /*  unsubscribe from an event  */
        unsubscribe: function () {
            /*  determine parameters  */
            var params = $cs.params("unsubscribe", arguments, {
                id: { pos: 0, req: true }
            });

            /*  detach parameters from component  */
            if (typeof this.__subscription[params.id] === "undefined")
                throw _cs.exception("unsubscribe", "subscription not found");
            delete this.__subscription[params.id];
            return;
        },

        /*  determine subscription existence  */
        subscription: function () {
            /*  determine parameters  */
            var params = $cs.params("subscription", arguments, {
                id: { pos: 0, req: true }
            });

            /*  determine whether subscription exists  */
            return (typeof this.__subscription[params.id] !== "undefined");
        },

        /*  determine subscribers  */
        subscribers: function () {
            /*  determine parameters  */
            var params = $cs.params("subscribers", arguments, {
                name:  { pos: 0, def: null, req: true },
                spec:  { pos: 1, def: {}              }
            });

            /*  make an event for matching only  */
            var ev = $cs.event({
                name: params.name,
                spec: params.spec
            });

            /*  find and return all matching subscribers  */
            var subscribers = [];
            for (var id in this.__subscription) {
                if (!_cs.isown(this.__subscription, id))
                    continue;
                var s = this.__subscription[id];
                if (ev.matches(s.name, s.spec))
                    subscribers.push(s);
            }
            return subscribers;
        },

        /*  publish an event */
        publish: function () {
            var i;
            var self = this;

            /*  determine parameters  */
            var params = $cs.params("publish", arguments, {
                name:         { pos: 0,     def: null, req: true },
                spec:         {             def: {}              },
                async:        {             def: false           },
                capturing:    {             def: true            },
                spreading:    {             def: true            },
                bubbling:     {             def: true            },
                completed:    {             def: $cs.nop         },
                resultinit:   {             def: undefined       },
                resultstep:   {             def: function (a, b) { return b; } },
                directresult: {             def: false           },
                noresult:     {             def: false           },
                firstonly:    {             def: false           },
                silent:       {             def: false           },
                args:         { pos: "...", def: []              }
            });

            /*  short-circuit processing (1/2) to speed up cases
                where no subscribers exist for a local event  */
            var short_circuit = false;
            if (!params.capturing && !params.spreading && !params.bubbling) {
                var subscribers = false;
                for (var id in this.__subscription) {
                    if (!_cs.isown(this.__subscription, id))
                        continue;
                    subscribers = true;
                    break;
                }
                if (!subscribers) {
                    if (params.noresult)
                        return;
                    else if (params.directresult)
                        return params.resultinit;
                    else
                        short_circuit = true;
                }
            }

            /*  create event  */
            var ev = $cs.event({
                name:        params.name,
                spec:        params.spec,
                async:       params.async,
                result:      params.resultinit,
                target:      self,
                propagation: true,
                processing:  true,
                dispatched:  false
            });

            /*  short-circuit processing (2/2)  */
            if (short_circuit)
                return ev;

            /*  tracing  */
            if (!params.silent) {
                $cs.debug(1, "event:" +
                    " " + ev.target().path("/") + ": publish:" +
                    " name=" + ev.name() +
                    " async=" + ev.async() +
                    " capturing=" + params.capturing +
                    " spreading=" + params.spreading +
                    " bubbling=" + params.bubbling +
                    " directresult=" + params.directresult +
                    " noresult=" + params.noresult +
                    " firstonly=" + params.firstonly
                );
            }

            /*  helper function for dispatching event to single component  */
            var event_dispatch_single = function (ev, origin, comp, params, state) {
                for (var id in comp.__subscription) {
                    if (!_cs.isown(comp.__subscription, id))
                        continue;
                    var s = comp.__subscription[id];
                    if (   (   (state === "capturing" && s.capturing)
                            || (state === "targeting"               )
                            || (state === "spreading" && s.spreading)
                            || (state === "bubbling"  && s.bubbling ))
                        && ev.matches(s.name, s.spec)                 ) {
                        if (!params.silent)
                            $cs.debug(1, "event: " + comp.path("/") + ": dispatch on " + state);
                        ev.state(state);
                        ev.decline(false);
                        var args = _cs.concat(
                            s.origin  ? [ origin ] : [],
                            s.noevent ? [] : [ ev ],
                            s.args,
                            params.args
                        );
                        var result = s.func.apply(s.ctx, args);
                        if (s.noevent && _cs.isdefined(result))
                            ev.result(params.resultstep(ev.result(), result));
                        if (!ev.decline()) {
                            ev.dispatched(true);
                            if (params.firstonly)
                                ev.propagation(false);
                        }
                    }
                }
            };

            /*  helper function for dispatching event to all components on hierarchy path  */
            var event_dispatch_all = function (ev, comp, params) {
                /*  determine component tree path  */
                var comp_path;
                if (params.capturing || params.bubbling)
                    comp_path = comp.path();

                /*  phase 1: CAPTURING
                    optionally dispatch event downwards from root component
                    towards target component for capturing subscribers  */
                if (params.capturing) {
                    for (i = comp_path.length - 1; i >= 1; i--) {
                        event_dispatch_single(ev, comp, comp_path[i], params, "capturing");
                        if (!ev.propagation())
                            break;
                    }
                }

                /*  phase 2: TARGETING
                    dispatch event to target component  */
                if (ev.propagation())
                    event_dispatch_single(ev, comp, comp, params, "targeting");

                /*  phase 3: SPREADING
                    dispatch event to all descendant components  */
                if (params.spreading && ev.propagation()) {
                    var visit = function (origin, comp, isTarget) {
                        var cont = true;
                        if (!isTarget) {
                            /*  dispatch on non-target component  */
                            event_dispatch_single(ev, origin, comp, params, "spreading");
                            if (!ev.propagation()) {
                                /*  if propagation should stop, reset the flag again
                                    as in the spreading phase propagation stops only(!)
                                    for the particular sub-tree, not the propagation
                                    process as a whole!  */
                                ev.propagation(true);
                                cont = false;
                            }
                        }
                        if (cont) {
                            /*  dispatch onto all direct child components  */
                            var children = comp.children();
                            for (var i = 0; i < children.length; i++)
                                visit(origin, children[i], false);
                        }
                    };
                    visit(comp, comp, true);
                }

                /*  phase 4: BUBBLING
                    dispatch event upwards from target component towards
                    root component for bubbling (regular) subscribers  */
                if (params.bubbling && ev.propagation()) {
                    for (i = 1; i < comp_path.length; i++) {
                        event_dispatch_single(ev, comp, comp_path[i], params, "bubbling");
                        if (!ev.propagation())
                            break;
                    }
                }

                /*  notify publisher on dispatch completion  */
                params.completed.call(comp, ev);
            };

            /*  perform event publishing,
                either asynchronous or synchronous  */
            if (ev.async())
                /*global setTimeout:false */
                setTimeout(function () { event_dispatch_all(ev, self, params); }, 0);
            else
                event_dispatch_all(ev, self, params);

            /*  return the event, directly the result value or no result value at all  */
            if (params.noresult)
                return;
            else if (params.directresult)
                return ev.result();
            else
                return ev;
        }
    }
});

<commit_msg>improve 'exclusive' flag for event subscriptions<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  generic pattern: event  */
$cs.pattern.event = $cs.clazz({
    mixin: [
        $cs.pattern.spec
    ],
    dynamics: {
        /*  attributes  */
        target:      $cs.attribute("target",      null),        /*  target object the event is send to  */
        propagation: $cs.attribute("propagation", true),        /*  whether event propagation should continue  */
        processing:  $cs.attribute("processing",  true),        /*  whether final default event processing should be performed  */
        dispatched:  $cs.attribute("dispatched",  false),       /*  whether event was dispatched at least once to a subscriber  */
        decline:     $cs.attribute("decline",     false),       /*  whether event was declined by subscriber  */
        state:       $cs.attribute("state",       "targeting"), /*  state of dispatching: capturing, targeting, spreading, bubbling */
        result:      $cs.attribute("result",      undefined),   /*  optional result value event subscribers can provide  */
        async:       $cs.attribute("async",       false)        /*  whether event is dispatched asynchronously  */
    }
});

/*  event factory  */
$cs.event = function () {
    /*  determine parameters  */
    var params = $cs.params("event", arguments, {
        name:        { pos: 0,     def: null, req: true  },
        spec:        {             def: {}               },
        target:      { pos: 1,     def: null, req: true  },
        propagation: { pos: 2,     def: true             },
        processing:  { pos: 3,     def: true             },
        dispatched:  { pos: 4,     def: false            },
        decline:     { pos: 5,     def: false            },
        state:       { pos: 6,     def: "targeting"      },
        result:      { pos: 7,     def: undefined        },
        async:       { pos: 8,     def: false            }
    });

    /*  create new event  */
    var ev = new $cs.pattern.event();

    /*  configure event  */
    ev.name       (params.name);
    ev.target     (params.target);
    ev.propagation(params.propagation);
    ev.processing (params.processing);
    ev.dispatched (params.dispatched);
    ev.decline    (params.decline);
    ev.state      (params.state);
    ev.result     (params.result);
    ev.spec       (params.spec);
    ev.async      (params.async);

    return ev;
};

/*  generic pattern: eventing  */
$cs.pattern.eventing = $cs.trait({
    dynamics: {
        __subscription: {}
    },
    protos: {
        /*  subscribe on an event  */
        subscribe: function () {
            /*  determine parameters  */
            var params = $cs.params("subscribe", arguments, {
                name:      { pos: 0,     def: null,    req: true },
                spec:      {             def: {}                 },
                ctx:       {             def: this               },
                func:      { pos: 1,     def: $cs.nop, req: true },
                args:      { pos: "...", def: []                 },
                capturing: {             def: false              },
                spreading: {             def: false              },
                bubbling:  {             def: true               },
                noevent:   {             def: false              },
                exclusive: {             def: false              },
                origin:    {             def: false              },
                spool:     {             def: null               }
            });

            /*  honor exclusive request  */
            var subscribers = this.subscribers(params.name, params.spec);
            if (subscribers.length === 1 && subscribers[0].exclusive)
                throw _cs.exception("subscribe", "existing exclusive subscription prevents additional one");
            if (params.exclusive && subscribers.length > 0)
                throw _cs.exception("subscribe", "non-exclusive subscription(s) prevent exclusive one");

            /*  attach parameters to component  */
            var id = _cs.cid();
            this.__subscription[id] = params;

            /*  optionally spool reverse operation  */
            if (params.spool !== null)
                this.spool(params.spool, this, "unsubscribe", id);

            return id;
        },

        /*  unsubscribe from an event  */
        unsubscribe: function () {
            /*  determine parameters  */
            var params = $cs.params("unsubscribe", arguments, {
                id: { pos: 0, req: true }
            });

            /*  detach parameters from component  */
            if (typeof this.__subscription[params.id] === "undefined")
                throw _cs.exception("unsubscribe", "subscription not found");
            delete this.__subscription[params.id];
            return;
        },

        /*  determine subscription existence  */
        subscription: function () {
            /*  determine parameters  */
            var params = $cs.params("subscription", arguments, {
                id: { pos: 0, req: true }
            });

            /*  determine whether subscription exists  */
            return (typeof this.__subscription[params.id] !== "undefined");
        },

        /*  determine subscribers  */
        subscribers: function () {
            /*  determine parameters  */
            var params = $cs.params("subscribers", arguments, {
                name:  { pos: 0, def: null, req: true },
                spec:  { pos: 1, def: {}              }
            });

            /*  make an event for matching only  */
            var ev = $cs.event({
                name: params.name,
                spec: params.spec
            });

            /*  find and return all matching subscribers  */
            var subscribers = [];
            for (var id in this.__subscription) {
                if (!_cs.isown(this.__subscription, id))
                    continue;
                var s = this.__subscription[id];
                if (ev.matches(s.name, s.spec))
                    subscribers.push(s);
            }
            return subscribers;
        },

        /*  publish an event */
        publish: function () {
            var i;
            var self = this;

            /*  determine parameters  */
            var params = $cs.params("publish", arguments, {
                name:         { pos: 0,     def: null, req: true },
                spec:         {             def: {}              },
                async:        {             def: false           },
                capturing:    {             def: true            },
                spreading:    {             def: true            },
                bubbling:     {             def: true            },
                completed:    {             def: $cs.nop         },
                resultinit:   {             def: undefined       },
                resultstep:   {             def: function (a, b) { return b; } },
                directresult: {             def: false           },
                noresult:     {             def: false           },
                firstonly:    {             def: false           },
                silent:       {             def: false           },
                args:         { pos: "...", def: []              }
            });

            /*  short-circuit processing (1/2) to speed up cases
                where no subscribers exist for a local event  */
            var short_circuit = false;
            if (!params.capturing && !params.spreading && !params.bubbling) {
                var subscribers = false;
                for (var id in this.__subscription) {
                    if (!_cs.isown(this.__subscription, id))
                        continue;
                    subscribers = true;
                    break;
                }
                if (!subscribers) {
                    if (params.noresult)
                        return;
                    else if (params.directresult)
                        return params.resultinit;
                    else
                        short_circuit = true;
                }
            }

            /*  create event  */
            var ev = $cs.event({
                name:        params.name,
                spec:        params.spec,
                async:       params.async,
                result:      params.resultinit,
                target:      self,
                propagation: true,
                processing:  true,
                dispatched:  false
            });

            /*  short-circuit processing (2/2)  */
            if (short_circuit)
                return ev;

            /*  tracing  */
            if (!params.silent) {
                $cs.debug(1, "event:" +
                    " " + ev.target().path("/") + ": publish:" +
                    " name=" + ev.name() +
                    " async=" + ev.async() +
                    " capturing=" + params.capturing +
                    " spreading=" + params.spreading +
                    " bubbling=" + params.bubbling +
                    " directresult=" + params.directresult +
                    " noresult=" + params.noresult +
                    " firstonly=" + params.firstonly
                );
            }

            /*  helper function for dispatching event to single component  */
            var event_dispatch_single = function (ev, origin, comp, params, state) {
                for (var id in comp.__subscription) {
                    if (!_cs.isown(comp.__subscription, id))
                        continue;
                    var s = comp.__subscription[id];
                    if (   (   (state === "capturing" && s.capturing)
                            || (state === "targeting"               )
                            || (state === "spreading" && s.spreading)
                            || (state === "bubbling"  && s.bubbling ))
                        && ev.matches(s.name, s.spec)                 ) {
                        if (!params.silent)
                            $cs.debug(1, "event: " + comp.path("/") + ": dispatch on " + state);
                        ev.state(state);
                        ev.decline(false);
                        var args = _cs.concat(
                            s.origin  ? [ origin ] : [],
                            s.noevent ? [] : [ ev ],
                            s.args,
                            params.args
                        );
                        var result = s.func.apply(s.ctx, args);
                        if (s.noevent && _cs.isdefined(result))
                            ev.result(params.resultstep(ev.result(), result));
                        if (!ev.decline()) {
                            ev.dispatched(true);
                            if (params.firstonly)
                                ev.propagation(false);
                        }
                    }
                }
            };

            /*  helper function for dispatching event to all components on hierarchy path  */
            var event_dispatch_all = function (ev, comp, params) {
                /*  determine component tree path  */
                var comp_path;
                if (params.capturing || params.bubbling)
                    comp_path = comp.path();

                /*  phase 1: CAPTURING
                    optionally dispatch event downwards from root component
                    towards target component for capturing subscribers  */
                if (params.capturing) {
                    for (i = comp_path.length - 1; i >= 1; i--) {
                        event_dispatch_single(ev, comp, comp_path[i], params, "capturing");
                        if (!ev.propagation())
                            break;
                    }
                }

                /*  phase 2: TARGETING
                    dispatch event to target component  */
                if (ev.propagation())
                    event_dispatch_single(ev, comp, comp, params, "targeting");

                /*  phase 3: SPREADING
                    dispatch event to all descendant components  */
                if (params.spreading && ev.propagation()) {
                    var visit = function (origin, comp, isTarget) {
                        var cont = true;
                        if (!isTarget) {
                            /*  dispatch on non-target component  */
                            event_dispatch_single(ev, origin, comp, params, "spreading");
                            if (!ev.propagation()) {
                                /*  if propagation should stop, reset the flag again
                                    as in the spreading phase propagation stops only(!)
                                    for the particular sub-tree, not the propagation
                                    process as a whole!  */
                                ev.propagation(true);
                                cont = false;
                            }
                        }
                        if (cont) {
                            /*  dispatch onto all direct child components  */
                            var children = comp.children();
                            for (var i = 0; i < children.length; i++)
                                visit(origin, children[i], false);
                        }
                    };
                    visit(comp, comp, true);
                }

                /*  phase 4: BUBBLING
                    dispatch event upwards from target component towards
                    root component for bubbling (regular) subscribers  */
                if (params.bubbling && ev.propagation()) {
                    for (i = 1; i < comp_path.length; i++) {
                        event_dispatch_single(ev, comp, comp_path[i], params, "bubbling");
                        if (!ev.propagation())
                            break;
                    }
                }

                /*  notify publisher on dispatch completion  */
                params.completed.call(comp, ev);
            };

            /*  perform event publishing,
                either asynchronous or synchronous  */
            if (ev.async())
                /*global setTimeout:false */
                setTimeout(function () { event_dispatch_all(ev, self, params); }, 0);
            else
                event_dispatch_all(ev, self, params);

            /*  return the event, directly the result value or no result value at all  */
            if (params.noresult)
                return;
            else if (params.directresult)
                return ev.result();
            else
                return ev;
        }
    }
});

<|endoftext|>


<commit_before>'use strict';

var winston = require('winston');
var loaderPipeline = require('./loader-pipeline');

function run(options, stream, record, loaderCallback){

  if(!options.logger) options.logger = winston;
  var logger = options.logger;

  if(!loaderCallback){
    loaderCallback = function(err){
      if(err){
        if(typeof err === "object" && !(err instanceof Error)){
          err = new Error(JSON.stringify(err));
        }
        throw err;
      }
      logger.info("Loading complete.");
    }
  }

  logger.info("Streaming %s to elasticsearch on %s:%d.", record.name, options.host, options.port);

  loaderPipeline(options, stream, record, function(err, loader){
    if(err) loaderCallback(err);

    loader.on('error', function(err){
      loader.removeAllListeners();
      return loaderCallback(err)
    });

    loader.on('alias', function(){

      var count = loader.count;
      var expectedCount = record.count;

      if(expectedCount){
        if(count === expectedCount){
          logger.info("All %d expected records from %s loaded.", count, record.name);
          return loaderCallback(null);
        }else{
          return loaderCallback(new Error('Didn\'t load all features. Expected: ' + expectedCount + '. Actual: ' + count));
        }
      }else{
        if(options.alias !== 'census') logger.warn('No count in metadata to verify.');
        return loaderCallback(null);
      }
    });
  });

}

module.exports = run;
<commit_msg>Emit a more sensible event<commit_after>'use strict';

var winston = require('winston');
var loaderPipeline = require('./loader-pipeline');

function run(options, stream, record, loaderCallback){

  if(!options.logger) options.logger = winston;
  var logger = options.logger;

  if(!loaderCallback){
    loaderCallback = function(err){
      if(err){
        if(typeof err === "object" && !(err instanceof Error)){
          err = new Error(JSON.stringify(err));
        }
        throw err;
      }
      logger.info("Loading complete.");
    }
  }

  logger.info("Streaming %s to elasticsearch on %s:%d.", record.name, options.host, options.port);

  loaderPipeline(options, stream, record, function(err, loader){
    if(err) loaderCallback(err);

    loader.on('error', function(err){
      loader.removeAllListeners();
      return loaderCallback(err)
    });

    loader.on('loaded', function(){
      var count = loader.count;
      var expectedCount = record.count;

      if(expectedCount){
        if(count === expectedCount){
          logger.info("All %d expected records from %s loaded.", count, record.name);
          return loaderCallback(null);
        }else{
          return loaderCallback(new Error('Didn\'t load all features. Expected: ' + expectedCount + '. Actual: ' + count));
        }
      }
    });
  });

}

module.exports = run;
<|endoftext|>


<commit_before>fun.views.profile = Backbone.View.extend({

    /**
    * Bind the event functions to the different HTML elements
    */
    events: {
        'click #profile-new-contact': 'newContact',
        'click #act_1': 'oneDay',
        'click #act_2': 'threeDays',
        'click #act_3': 'oneWeek',
        'click #act_4': 'oneMonth',
        'click .view-contact-popup': 'viewContact',
        'click .edit-contact-popup': 'editContact',
        'click .delete-contact-pupup': 'deleteContact',
        'change #profile-contact-modal-mailing-address-different': 'showMailingAddressDifferent',
        'change #profile-contact-modal-marital-status': 'changeMaritalStatus',
        'change #profile-contact-modal-agent-home-insurance-checkbox': 'homeInsuranceTab',
        'change #profile-contact-modal-agent-health-insurance-checkbox': 'healthInsuranceTab',
        'change #profile-contact-modal-agent-auto-insurance-checkbox': 'autoInsuranceTab',
        'change #profile-contact-modal-agent-life-insurance-checkbox': 'lifeInsuranceTab',
        'change #profile-contact-modal-agent-ancilliary-insurance-checkbox': 'ancilliaryInsuranceTab',
        'change #profile-contact-modal-agent-number-of-children': 'changeNumberChildren',
        'change #profile-contact-modal-health-lead-status': 'showPaymentTab',
        'change #profile-contact-modal-home-lead-status': 'showPaymentTab',
        'change #profile-contact-modal-auto-lead-status': 'showPaymentTab',
        'change #profile-contact-modal-life-lead-status': 'showPaymentTab',
        'change #profile-contact-modal-ancilliary-lead-status': 'showPaymentTab'
    },

    /**
    * Class constructor
    */
    initialize: function(options){
        fun.containers.profile = this.$el;
    },

    viewContact: function(event){
        'use strict';
        event.preventDefault();
        console.log('view contact event');
        // view cache
        var view = this,
            name;
        $('#profileContactModal').modal({
            'show': true
        });
        this.renderContactModalForm();
    },

    editContact:function(event){
        'use strict';
        event.preventDefault();
        console.log('edit contact event');
        // view cache
        var view = this,
            name;
        $('#profileContactModal').modal({
            'show': true
        });
        this.renderContactModalForm();
    },

    deleteContact:function(event){
        'use strict';
        event.preventDefault();
        console.log('delete contact event');
        var confirm,
            callbacks;
        confirm = new fun.models.Contact({
            'uuid':'how',
            'account':'thefuck'
        });
        callbacks = {
            success: function(){
                console.log("inside success, but we don't see any of this shit.");
            },
            error: function(){
                fun.utils.redirect(fun.conf.hash.home);
            }
        };
        confirm.destroy();
        $('#deleteAccountModal').modal('hide');
        $('#deleteAccountModal').on('hidden.bs.modal', function(e){
            fun.utils.logout(callbacks);
        });

    },

    /**
    * Render view
    */
    render: function(){
        console.log('render profile view');
        var template,
            startDate,
            startTimestamp,
            i,
            total,
            results;

        template = _.template(fun.utils.getTemplate(fun.conf.templates.profile));

        this.$el.html(template);
        this.$el.removeClass("hide").addClass("show");

        startDate = new Date(2013, 6, 25);
        startTimestamp = new Date(2013, 6, 1).getTime() / 1000;

        options = {
            events_source: '/stochastics/',
            view: 'day',
            tmpl_path: '/static/tmpls/',
            tmpl_cache: false,
            // day: '2013-03-12',
            onAfterEventsLoad: function(events) {
                if(!events) {
                    return;
                }
                list = $('#eventlist');
                list.html('');

                $.each(events, function(key, val) {
                    $(document.createElement('li'))
                        .html('' + val.title + '')
                        .appendTo(list);
                });
            },
            onAfterViewLoad: function(view) {
                $('.page-header h3').text(this.getTitle());
                $('.btn-group button').removeClass('active');
                $('button[data-calendar-view="' + view + '"]').addClass('active');
            },
            classes: {
                months: {
                    general: 'label'
                }
            }
        };

        $('#profile-task-new-modal-reminder').datetimepicker();

        calendar = $('#test-calendar').calendar(options);

        $('.btn-group button[data-calendar-nav]').each(function() {
            var $this = $(this);
            $this.click(function() {
                calendar.navigate($this.data('calendar-nav'));
            });
        });

        $('.btn-group button[data-calendar-view]').each(function() {
            var $this = $(this);
            $this.click(function() {
                calendar.view($this.data('calendar-view'));
            });
        });

        $('#test-calendar').addClass('hide');

        function GAconverter(data) {
            var i, total, results = {};
            for(i = 0, total = data.length; i < total; i++) {
                results[+data[i].Hour * 3600 + startTimestamp] = +data[i].Visits;
            }
            return results;
        }

        $('#profile-task-new-modal-reminder').datepicker();
    },

    /*
    * Render Contact Modal Form
    */
    renderContactModalForm: function(){
        'use strict';
        var contactModalTabs;
        var template = _.template(
            fun.utils.getTemplate(fun.conf.templates.contactFormModal)
        );

        contactModalTabs = this.$('#profile-contact-modal-tabs');
        contactModalTabs.html(template);
        contactModalTabs.removeClass("hide").addClass("show");
    },

    /*
    * Render Inbound Campaign List
    */
    renderInboundCampaignList: function(campaigns){
        'use strict';
        var length,
            rows,
            template;
        if (campaigns) {
            this.inboundCampaigns = campaigns;
        }

        this.inboundListGroup = this.$('#profile-inbound-list');

        // campaigns length
        length = this.inboundCampaigns.length;

        if (length > 0){
            rows = this.inboundListGroup.html('');
            _.each(this.inboundCampaigns.toJSON(), function(value){
                template = _.template(
                    fun.utils.getTemplate(fun.conf.templates.campaignItem)
                )(value);
                rows.append(template);
            });
        } else {
            console.log('no inbound campaign list');
            /*this.noCampaigns();*/
        }

        /*this.$el.removeClass("hide").addClass("show");*/

    },

    renderAccountInformation: function(account){
        'use strict';
        console.log('now you are getting it');
        // view cache this
        var account = account,
            fullName,
            name = $('#profile-name'),
            email = $('#profile-email'),
            location = $('#profile-location'),
            company = $('#profile-company'),
            username = $('#profile-username'),
            url = $('#profile-url');

        // assign this variable values

        fullName = fun.utils.format('%s %s', account.get('first_name') || 'First', account.get('last_name') || 'Lastname');

        // get stuff from account profile

        name.html(fullName);
        username.html(account.get('account'));
        email.html(account.get('email') || 'Your email')
        location.html(account.get('location') || 'Mars');
        company.html(account.get('company') || 'UAC');
        url.html(account.get('url') || 'example.com');
    },

    renderOutboundCampaignList: function(campaigns){
        'use strict';
        var length,
            rows,
            template;

        // Yes the lol is with this.campaigns but lets see just what happen
        if (campaigns) {
            this.outboundCampaigns = campaigns;
        }
        // again with this.shit? what is wrong with you!
        this.listgroup = this.$('#profile-outbound-list');

        // campaigns length
        length = this.outboundCampaigns.length;

        if (length > 0) {
            rows = this.listgroup.html('');
            _.each(this.outboundCampaigns.toJSON(), function(value){
                template = _.template(
                    fun.utils.getTemplate(fun.conf.templates.outboundCampaignItem)
                )(value);
                rows.append(template);
            });
        } else {
            console.log('no outbound campaign list');
            /*this.noCampaigns();*/
        }

    },

    renderTaskList: function(tasks){
        'use strict';
        var length,
            rows,
            template;

        // Yes the lol is with this.campaigns but lets see just what happen
        if (tasks) {
            this.profileTasks = tasks;
        }
        // again with this.shit? what is wrong with you!
        this.taskList = this.$('#profile-task-list');
        console.log('render profile tasks list');

        // campaigns length
        length = this.profileTasks.length;

        if (length > 0) {
            rows = this.taskList.html('');
            _.each(this.profileTasks.toJSON(), function(value){
                template = _.template(
                    fun.utils.getTemplate(fun.conf.templates.profileTaskItem)
                )(value);
                rows.append(template);
            });
        } else {
            console.log('no profile contact list');
        }
    },

    renderContactList: function(contacts){
        'use strict';
        var length,
            rows,
            template;

        // Yes the lol is with this.campaigns but lets see just what happen
        if (contacts) {
            this.profileContacts = contacts;
        }
        // again with this.shit? what is wrong with you!
        this.contactList = this.$('#profile-contact-list');

        // campaigns length
        length = this.profileContacts.length;

        if (length > 0) {
            rows = this.contactList.html('');
            _.each(this.profileContacts.toJSON(), function(value){
                template = _.template(
                    fun.utils.getTemplate(fun.conf.templates.profileContactItem)
                )(value);
                rows.append(template);
            });
        } else {
            console.log('no profile contact list');
            /*this.noCampaigns();*/
        }
    },

    oneDay: function(event){
        console.log('one day event');
    },

    threeDays: function(event){
        console.log('three days event');
    },

    oneWeek: function(event){
        console.log('one week event');
    },

    oneMonth: function(event){
        console.log('one month event');
    },

    newContact: function(event){
        console.log('new contact and stuff get the popup in here');
        'use strict';
        event.preventDefault();

        //view cache
        var view = this,
            name;

        $('#profileContactModal').modal({
            'show': true
        });

        this.renderContactModalForm();

        /*name = $(event.target).data('name');

        task = new fun.models.Task({'uuid':name});

        task.fetch({
            success: function(response){

                //console.log(response)

                taskUuid.html(response.get('uuid'));
                taskTitle.html(response.get('title') || "Where's the title boy?");
                taskAssigned.html(response.get('assigned'));
                taskLabel.html(response.get('label'));
                taskSource.html(response.get('source'));
                taskStatus.html(response.get('status'));
                taskPriority.html(response.get('priority'));
                taskSeverity.html(response.get('severity'));
                taskDescription.html(response.get('description'));

                $('#taskModal').modal({
                    'show': true
                });
            },
            error: function(error){
                console.log(error);
            }
        });*/
    },

    showMailingAddressDifferent: function(event){
        var value = $('#mailing-address-different').val();
        if(value===true||value==='true'){
            $('#mailingAddressDifferentDiv').removeClass('hide');
            $('#mailingAddressDifferentDiv').addClass('show');
        } else {
            $('#mailingAddressDifferentDiv').removeClass('show');
            $('#mailingAddressDifferentDiv').addClass('hide');
        }
    },

    changeMaritalStatus: function(event){

        if($('#marital-status').val()==='none'||$('#marital-status').val()==='single'){
            $('#contactSpouseInfoTab').removeClass('show');
            $('#contactSpouseInfoTab').addClass('hide');
        } else {
            $('#contactSpouseInfoTab').removeClass('hide');
            $('#contactSpouseInfoTab').addClass('show');
        }
    },

    healthInsuranceTab: function(event){
        console.log('IN HEALTH INSURANCE!!!',$('#agent-health-insurance-checkbox').val());
        if($('#agent-health-insurance-checkbox').val()==="true"){
            $('#healthInsuranceTab').removeClass('hide');
            $('#healthInsuranceTab').addClass('show');
        } else {
            $('#healthInsuranceTab').removeClass('show');
            $('#healthInsuranceTab').addClass('hide');
        }
    },

    homeInsuranceTab: function(event){
        if($('#agent-home-insurance-checkbox').val()==="true"){
            $('#homeOwnersInsuranceTab').removeClass('hide');
            $('#homeOwnersInsuranceTab').addClass('show');
        } else {
            $('#homeOwnersInsuranceTab').removeClass('show');
            $('#homeOwnersInsuranceTab').addClass('hide');
        }
    },

    autoInsuranceTab: function(event){
        if($('#agent-auto-insurance-checkbox').val()==="true"){
            $('#automobileInsuranceTab').removeClass('hide');
            $('#automobileInsuranceTab').addClass('show');
        } else {
            $('#automobileInsuranceTab').removeClass('show');
            $('#automobileInsuranceTab').addClass('hide');
        }
    },

    lifeInsuranceTab: function(event){
        if($('#agent-life-insurance-checkbox').val()==="true"){
            $('#lifeInsuranceTab').removeClass('hide');
            $('#lifeInsuranceTab').addClass('show');
        } else {
            $('#lifeInsuranceTab').removeClass('show');
            $('#lifeInsuranceTab').addClass('hide');
        }
    },

    ancilliaryInsuranceTab: function(event){
        if($('#agent-ancilliary-insurance-checkbox').val()==="true"){
            $('#ancilliaryInsuranceTab').removeClass('hide');
            $('#ancilliaryInsuranceTab').addClass('show');
        } else {
            $('#ancilliaryInsuranceTab').removeClass('show');
            $('#ancilliaryInsuranceTab').addClass('hide');
        }
    },

    changeNumberChildren: function(event){
        switch($('#agent-number-of-children').val()){

            case '0':
                $('#childrenInfoTab').removeClass('show');
                $('#childrenInfoTab').addClass('hide');
                $('#childrenInfoGroup-1').removeClass('show');
                $('#childrenInfoGroup-1').addClass('hide');
                $('#childrenInfoGroup-2').removeClass('show');
                $('#childrenInfoGroup-2').addClass('hide');
                $('#childrenInfoGroup-3').removeClass('show');
                $('#childrenInfoGroup-3').addClass('hide');
                $('#childrenInfoGroup-4').removeClass('show');
                $('#childrenInfoGroup-4').addClass('hide');
                break;

            case '1':
                $('#childrenInfoTab').removeClass('hide');
                $('#childrenInfoTab').addClass('show');
                $('#childrenInfoGroup-1').removeClass('hide');
                $('#childrenInfoGroup-1').addClass('show');
                break;

            case '2':
                $('#childrenInfoTab').removeClass('hide');
                $('#childrenInfoTab').addClass('show');
                $('#childrenInfoGroup-2').removeClass('hide');
                $('#childrenInfoGroup-2').addClass('show');
                break;

            case '3':
                $('#childrenInfoTab').removeClass('hide');
                $('#childrenInfoTab').addClass('show');
                $('#childrenInfoGroup-3').removeClass('hide');
                $('#childrenInfoGroup-3').addClass('show');
                break;

            case '4':
                $('#childrenInfoTab').removeClass('hide');
                $('#childrenInfoTab').addClass('show');
                $('#childrenInfoGroup-4').removeClass('hide');
                $('#childrenInfoGroup-4').addClass('show');
                break;
        }
    },

    showPaymentTab: function(event){
        if(event.currentTarget.value === 'sold'){
            $('#paymentInfoTab').removeClass('hide');
            $('#paymentInfoTab').addClass('show');
        } else {
            $('#paymentInfoTab').removeClass('show');
            $('#paymentInfoTab').addClass('hide');
        }
    }
});<commit_msg>run run run<commit_after>fun.views.profile = Backbone.View.extend({

    /**
    * Bind the event functions to the different HTML elements
    */
    events: {
        'click #profile-new-contact': 'newContact',
        'click #act_1': 'oneDay',
        'click #act_2': 'threeDays',
        'click #act_3': 'oneWeek',
        'click #act_4': 'oneMonth',
        'click .view-contact-popup': 'viewContact',
        'click .edit-contact-popup': 'editContact',
        'click .delete-contact-pupup': 'deleteContact',
        'change #profile-contact-modal-mailing-address-different': 'showMailingAddressDifferent',
        'change #profile-contact-modal-marital-status': 'changeMaritalStatus',
        'change #profile-contact-modal-agent-home-insurance-checkbox': 'homeInsuranceTab',
        'change #profile-contact-modal-agent-health-insurance-checkbox': 'healthInsuranceTab',
        'change #profile-contact-modal-agent-auto-insurance-checkbox': 'autoInsuranceTab',
        'change #profile-contact-modal-agent-life-insurance-checkbox': 'lifeInsuranceTab',
        'change #profile-contact-modal-agent-ancilliary-insurance-checkbox': 'ancilliaryInsuranceTab',
        'change #profile-contact-modal-agent-number-of-children': 'changeNumberChildren',
        'change #profile-contact-modal-health-lead-status': 'showPaymentTab',
        'change #profile-contact-modal-home-lead-status': 'showPaymentTab',
        'change #profile-contact-modal-auto-lead-status': 'showPaymentTab',
        'change #profile-contact-modal-life-lead-status': 'showPaymentTab',
        'change #profile-contact-modal-ancilliary-lead-status': 'showPaymentTab'
    },

    /**
    * Class constructor
    */
    initialize: function(options){
        fun.containers.profile = this.$el;
    },

    viewContact: function(event){
        'use strict';
        event.preventDefault();
        console.log('view contact event');
        // view cache
        var view = this,
            name;
        $('#profileContactModal').modal({
            'show': true
        });
        this.renderContactModalForm();
    },

    editContact:function(event){
        'use strict';
        event.preventDefault();
        console.log('edit contact event');
        // view cache
        var view = this,
            name;
        $('#profileContactModal').modal({
            'show': true
        });
        this.renderContactModalForm();
    },

    deleteContact:function(event){
        'use strict';
        event.preventDefault();
        console.log('delete contact event');
        var confirm,
            name_uuid,
            callbacks;

        name_uuid = $(event.target).data('name');

        console.log(name_uuid);

        confirm = new fun.models.Contact({
            'uuid':'how',
            'account':'thefuck'
        });
        callbacks = {
            success: function(){
                console.log("inside success, but we don't see any of this shit.");
            },
            error: function(){
                fun.utils.redirect(fun.conf.hash.home);
            }
        };
        confirm.destroy();
        $('#deleteAccountModal').modal('hide');
        $('#deleteAccountModal').on('hidden.bs.modal', function(e){
            fun.utils.logout(callbacks);
        });

    },

    /**
    * Render view
    */
    render: function(){
        console.log('render profile view');
        var template,
            startDate,
            startTimestamp,
            i,
            total,
            results;

        template = _.template(fun.utils.getTemplate(fun.conf.templates.profile));

        this.$el.html(template);
        this.$el.removeClass("hide").addClass("show");

        startDate = new Date(2013, 6, 25);
        startTimestamp = new Date(2013, 6, 1).getTime() / 1000;

        options = {
            events_source: '/stochastics/',
            view: 'day',
            tmpl_path: '/static/tmpls/',
            tmpl_cache: false,
            // day: '2013-03-12',
            onAfterEventsLoad: function(events) {
                if(!events) {
                    return;
                }
                list = $('#eventlist');
                list.html('');

                $.each(events, function(key, val) {
                    $(document.createElement('li'))
                        .html('' + val.title + '')
                        .appendTo(list);
                });
            },
            onAfterViewLoad: function(view) {
                $('.page-header h3').text(this.getTitle());
                $('.btn-group button').removeClass('active');
                $('button[data-calendar-view="' + view + '"]').addClass('active');
            },
            classes: {
                months: {
                    general: 'label'
                }
            }
        };

        $('#profile-task-new-modal-reminder').datetimepicker();

        calendar = $('#test-calendar').calendar(options);

        $('.btn-group button[data-calendar-nav]').each(function() {
            var $this = $(this);
            $this.click(function() {
                calendar.navigate($this.data('calendar-nav'));
            });
        });

        $('.btn-group button[data-calendar-view]').each(function() {
            var $this = $(this);
            $this.click(function() {
                calendar.view($this.data('calendar-view'));
            });
        });

        $('#test-calendar').addClass('hide');

        function GAconverter(data) {
            var i, total, results = {};
            for(i = 0, total = data.length; i < total; i++) {
                results[+data[i].Hour * 3600 + startTimestamp] = +data[i].Visits;
            }
            return results;
        }

        $('#profile-task-new-modal-reminder').datepicker();
    },

    /*
    * Render Contact Modal Form
    */
    renderContactModalForm: function(){
        'use strict';
        var contactModalTabs;
        var template = _.template(
            fun.utils.getTemplate(fun.conf.templates.contactFormModal)
        );

        contactModalTabs = this.$('#profile-contact-modal-tabs');
        contactModalTabs.html(template);
        contactModalTabs.removeClass("hide").addClass("show");
    },

    /*
    * Render Inbound Campaign List
    */
    renderInboundCampaignList: function(campaigns){
        'use strict';
        var length,
            rows,
            template;
        if (campaigns) {
            this.inboundCampaigns = campaigns;
        }

        this.inboundListGroup = this.$('#profile-inbound-list');

        // campaigns length
        length = this.inboundCampaigns.length;

        if (length > 0){
            rows = this.inboundListGroup.html('');
            _.each(this.inboundCampaigns.toJSON(), function(value){
                template = _.template(
                    fun.utils.getTemplate(fun.conf.templates.campaignItem)
                )(value);
                rows.append(template);
            });
        } else {
            console.log('no inbound campaign list');
            /*this.noCampaigns();*/
        }

        /*this.$el.removeClass("hide").addClass("show");*/

    },

    renderAccountInformation: function(account){
        'use strict';
        console.log('now you are getting it');
        // view cache this
        var account = account,
            fullName,
            name = $('#profile-name'),
            email = $('#profile-email'),
            location = $('#profile-location'),
            company = $('#profile-company'),
            username = $('#profile-username'),
            url = $('#profile-url');

        // assign this variable values

        fullName = fun.utils.format('%s %s', account.get('first_name') || 'First', account.get('last_name') || 'Lastname');

        // get stuff from account profile

        name.html(fullName);
        username.html(account.get('account'));
        email.html(account.get('email') || 'Your email')
        location.html(account.get('location') || 'Mars');
        company.html(account.get('company') || 'UAC');
        url.html(account.get('url') || 'example.com');
    },

    renderOutboundCampaignList: function(campaigns){
        'use strict';
        var length,
            rows,
            template;

        // Yes the lol is with this.campaigns but lets see just what happen
        if (campaigns) {
            this.outboundCampaigns = campaigns;
        }
        // again with this.shit? what is wrong with you!
        this.listgroup = this.$('#profile-outbound-list');

        // campaigns length
        length = this.outboundCampaigns.length;

        if (length > 0) {
            rows = this.listgroup.html('');
            _.each(this.outboundCampaigns.toJSON(), function(value){
                template = _.template(
                    fun.utils.getTemplate(fun.conf.templates.outboundCampaignItem)
                )(value);
                rows.append(template);
            });
        } else {
            console.log('no outbound campaign list');
            /*this.noCampaigns();*/
        }

    },

    renderTaskList: function(tasks){
        'use strict';
        var length,
            rows,
            template;

        // Yes the lol is with this.campaigns but lets see just what happen
        if (tasks) {
            this.profileTasks = tasks;
        }
        // again with this.shit? what is wrong with you!
        this.taskList = this.$('#profile-task-list');
        console.log('render profile tasks list');

        // campaigns length
        length = this.profileTasks.length;

        if (length > 0) {
            rows = this.taskList.html('');
            _.each(this.profileTasks.toJSON(), function(value){
                template = _.template(
                    fun.utils.getTemplate(fun.conf.templates.profileTaskItem)
                )(value);
                rows.append(template);
            });
        } else {
            console.log('no profile contact list');
        }
    },

    renderContactList: function(contacts){
        'use strict';
        var length,
            rows,
            template;

        // Yes the lol is with this.campaigns but lets see just what happen
        if (contacts) {
            this.profileContacts = contacts;
        }
        // again with this.shit? what is wrong with you!
        this.contactList = this.$('#profile-contact-list');

        // campaigns length
        length = this.profileContacts.length;

        if (length > 0) {
            rows = this.contactList.html('');
            _.each(this.profileContacts.toJSON(), function(value){
                template = _.template(
                    fun.utils.getTemplate(fun.conf.templates.profileContactItem)
                )(value);
                rows.append(template);
            });
        } else {
            console.log('no profile contact list');
            /*this.noCampaigns();*/
        }
    },

    oneDay: function(event){
        console.log('one day event');
    },

    threeDays: function(event){
        console.log('three days event');
    },

    oneWeek: function(event){
        console.log('one week event');
    },

    oneMonth: function(event){
        console.log('one month event');
    },

    newContact: function(event){
        console.log('new contact and stuff get the popup in here');
        'use strict';
        event.preventDefault();

        //view cache
        var view = this,
            name;

        $('#profileContactModal').modal({
            'show': true
        });

        this.renderContactModalForm();

        /*name = $(event.target).data('name');

        task = new fun.models.Task({'uuid':name});

        task.fetch({
            success: function(response){

                //console.log(response)

                taskUuid.html(response.get('uuid'));
                taskTitle.html(response.get('title') || "Where's the title boy?");
                taskAssigned.html(response.get('assigned'));
                taskLabel.html(response.get('label'));
                taskSource.html(response.get('source'));
                taskStatus.html(response.get('status'));
                taskPriority.html(response.get('priority'));
                taskSeverity.html(response.get('severity'));
                taskDescription.html(response.get('description'));

                $('#taskModal').modal({
                    'show': true
                });
            },
            error: function(error){
                console.log(error);
            }
        });*/
    },

    showMailingAddressDifferent: function(event){
        var value = $('#mailing-address-different').val();
        if(value===true||value==='true'){
            $('#mailingAddressDifferentDiv').removeClass('hide');
            $('#mailingAddressDifferentDiv').addClass('show');
        } else {
            $('#mailingAddressDifferentDiv').removeClass('show');
            $('#mailingAddressDifferentDiv').addClass('hide');
        }
    },

    changeMaritalStatus: function(event){

        if($('#marital-status').val()==='none'||$('#marital-status').val()==='single'){
            $('#contactSpouseInfoTab').removeClass('show');
            $('#contactSpouseInfoTab').addClass('hide');
        } else {
            $('#contactSpouseInfoTab').removeClass('hide');
            $('#contactSpouseInfoTab').addClass('show');
        }
    },

    healthInsuranceTab: function(event){
        console.log('IN HEALTH INSURANCE!!!',$('#agent-health-insurance-checkbox').val());
        if($('#agent-health-insurance-checkbox').val()==="true"){
            $('#healthInsuranceTab').removeClass('hide');
            $('#healthInsuranceTab').addClass('show');
        } else {
            $('#healthInsuranceTab').removeClass('show');
            $('#healthInsuranceTab').addClass('hide');
        }
    },

    homeInsuranceTab: function(event){
        if($('#agent-home-insurance-checkbox').val()==="true"){
            $('#homeOwnersInsuranceTab').removeClass('hide');
            $('#homeOwnersInsuranceTab').addClass('show');
        } else {
            $('#homeOwnersInsuranceTab').removeClass('show');
            $('#homeOwnersInsuranceTab').addClass('hide');
        }
    },

    autoInsuranceTab: function(event){
        if($('#agent-auto-insurance-checkbox').val()==="true"){
            $('#automobileInsuranceTab').removeClass('hide');
            $('#automobileInsuranceTab').addClass('show');
        } else {
            $('#automobileInsuranceTab').removeClass('show');
            $('#automobileInsuranceTab').addClass('hide');
        }
    },

    lifeInsuranceTab: function(event){
        if($('#agent-life-insurance-checkbox').val()==="true"){
            $('#lifeInsuranceTab').removeClass('hide');
            $('#lifeInsuranceTab').addClass('show');
        } else {
            $('#lifeInsuranceTab').removeClass('show');
            $('#lifeInsuranceTab').addClass('hide');
        }
    },

    ancilliaryInsuranceTab: function(event){
        if($('#agent-ancilliary-insurance-checkbox').val()==="true"){
            $('#ancilliaryInsuranceTab').removeClass('hide');
            $('#ancilliaryInsuranceTab').addClass('show');
        } else {
            $('#ancilliaryInsuranceTab').removeClass('show');
            $('#ancilliaryInsuranceTab').addClass('hide');
        }
    },

    changeNumberChildren: function(event){
        switch($('#agent-number-of-children').val()){

            case '0':
                $('#childrenInfoTab').removeClass('show');
                $('#childrenInfoTab').addClass('hide');
                $('#childrenInfoGroup-1').removeClass('show');
                $('#childrenInfoGroup-1').addClass('hide');
                $('#childrenInfoGroup-2').removeClass('show');
                $('#childrenInfoGroup-2').addClass('hide');
                $('#childrenInfoGroup-3').removeClass('show');
                $('#childrenInfoGroup-3').addClass('hide');
                $('#childrenInfoGroup-4').removeClass('show');
                $('#childrenInfoGroup-4').addClass('hide');
                break;

            case '1':
                $('#childrenInfoTab').removeClass('hide');
                $('#childrenInfoTab').addClass('show');
                $('#childrenInfoGroup-1').removeClass('hide');
                $('#childrenInfoGroup-1').addClass('show');
                break;

            case '2':
                $('#childrenInfoTab').removeClass('hide');
                $('#childrenInfoTab').addClass('show');
                $('#childrenInfoGroup-2').removeClass('hide');
                $('#childrenInfoGroup-2').addClass('show');
                break;

            case '3':
                $('#childrenInfoTab').removeClass('hide');
                $('#childrenInfoTab').addClass('show');
                $('#childrenInfoGroup-3').removeClass('hide');
                $('#childrenInfoGroup-3').addClass('show');
                break;

            case '4':
                $('#childrenInfoTab').removeClass('hide');
                $('#childrenInfoTab').addClass('show');
                $('#childrenInfoGroup-4').removeClass('hide');
                $('#childrenInfoGroup-4').addClass('show');
                break;
        }
    },

    showPaymentTab: function(event){
        if(event.currentTarget.value === 'sold'){
            $('#paymentInfoTab').removeClass('hide');
            $('#paymentInfoTab').addClass('show');
        } else {
            $('#paymentInfoTab').removeClass('show');
            $('#paymentInfoTab').addClass('hide');
        }
    }
});<|endoftext|>