<commit_before>import SPELLS from 'common/SPELLS/index';
import { EventType } from 'parser/core/Events';

const thisPlayer = 1;
const enemy = 2;

// Damage taken: amount: 224, absorbed: 16, overkill: 0
export const staggerTicks = [
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 1000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 1500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 2000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 2500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 3000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 1, absorbed: 9, timestamp: 3500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 4000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 4500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 5000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 5500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 8, absorbed: 7, timestamp: 6000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 15, timestamp: 6500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 15, timestamp: 7000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 15, timestamp: 7500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 15, timestamp: 8000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 13, timestamp: 8500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 13, timestamp: 9000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 13, timestamp: 9500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 13, timestamp: 10000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 13, timestamp: 10500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
];

// 599 will be removed by the stagger array below when combined
// Damage taken: amount: 1200, absorbed: 599, overkill: 0
export const incomingDamage = [
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 400, timestamp: 1, ability: { guid: 1 } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 400, absorbed: 300, timestamp: 500, ability: { guid: 1 } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 400, absorbed: 299, timestamp: 5700, ability: { guid: 4 } },
];

// Damage taken: amount: 0, absorbed: 0, overkill: 0
export const casts = [
  { type: EventType.Cast, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 100, ability: { guid: SPELLS.GIFT_OF_THE_OX_1.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 204, ability: { guid: SPELLS.GIFT_OF_THE_OX_1.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 4700, ability: { guid: SPELLS.GIFT_OF_THE_OX_1.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 8200, ability: { guid: SPELLS.PURIFYING_BREW.id } },
];

export const dpsCasts = [
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 3500, ability: { guid: SPELLS.BLACKOUT_STRIKE.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 4500, ability: { guid: SPELLS.KEG_SMASH.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 4700, ability: { guid: SPELLS.KEG_SMASH.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 6500, ability: { guid: SPELLS.BLACKOUT_STRIKE.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 8500, ability: { guid: SPELLS.BLACKOUT_STRIKE.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 9000, ability: { guid: SPELLS.BLACKOUT_STRIKE.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 9700, ability: { guid: SPELLS.BREATH_OF_FIRE.id } },
];

// Damage taken: amount: 0, absorbed: 0, overkill: 0
export const isbCasts = [
  { type: EventType.Cast, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 200, ability: { guid: SPELLS.IRONSKIN_BREW.id } },
];

// Damage taken: amount: 0, absorbed: 0, overkill: 0
export const applybuff = [
  { type: EventType.ApplyBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 200, ability: { guid: SPELLS.IRONSKIN_BREW_BUFF.id } },
  { type: EventType.ApplyBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 3500, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
  { type: EventType.ApplyBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 6500, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
  { type: EventType.ApplyBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 8500, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
];

export const refreshBuff = [
  { type: EventType.RefreshBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 9000, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
];

export const removebuff = [
  { type: EventType.RemoveDebuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 4500, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
  { type: EventType.RemoveDebuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 8200, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
  { type: EventType.RemoveDebuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 9700, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
];

// This absorb is used from the damage line
// Damage taken: amount: 0, absorbed: 0, overkill: 0
export const absorbed = [
  { type: EventType.Absorbed, sourceID: enemy, targetid: thisPlayer, amount: 9, timestamp: 3500, ability: { guid: 99999 }, extraAbility: { guid: 1, type: 1 } },
  { type: EventType.Absorbed, sourceID: enemy, targetid: thisPlayer, amount: 7, timestamp: 6000, ability: { guid: 99999 }, extraAbility: { guid: 1, type: 1 } },
];

// Damage taken: amount: 0, absorbed: 0, overkill: 0
// Stagger damage taken: amount: 0, absorbed: -599, overkill: 0
export const staggerAbsorbed = [
  { type: EventType.Absorbed, sourceID: enemy, targetid: thisPlayer, amount: 300, timestamp: 500, ability: { guid: SPELLS.STAGGER.id }, extraAbility: { guid: 1, type: 1 } },
  { type: EventType.Absorbed, sourceID: enemy, targetid: thisPlayer, amount: 299, timestamp: 5700, ability: { guid: SPELLS.STAGGER.id }, extraAbility: { guid: 4, type: 4 } },
];

// Damage taken: amount: 0, absorbed: 0, overkill: 0
export const heal = [
  { type: EventType.Heal, sourceID: thisPlayer, targetid: thisPlayer, amount: 10, timestamp: 6700, ability: { guid: SPELLS.GIFT_OF_THE_OX_1.id } },
];

export const SimpleFight = [
  ...staggerTicks,
  ...incomingDamage,
  ...casts,
  ...applybuff,
  ...absorbed,
  ...staggerAbsorbed,
  ...heal,
  ...isbCasts,
  ...dpsCasts,
  ...refreshBuff,
  ...removebuff,
].sort((a, b) => a.timestamp - b.timestamp);

export const EarlyFinish = [
  ...staggerTicks,
  ...incomingDamage,
  ...casts,
  ...applybuff,
  ...absorbed,
  ...staggerAbsorbed,
  ...heal,
  ...isbCasts,
  ...dpsCasts,
  ...refreshBuff,
  ...removebuff,
].sort((a, b) => a.timestamp - b.timestamp).filter(event => event.timestamp <= 6000);
<commit_msg>Fixer previous PR issue<commit_after>import SPELLS from 'common/SPELLS/index';
import { EventType } from 'parser/core/Events';

const thisPlayer = 1;
const enemy = 2;

// Damage taken: amount: 224, absorbed: 16, overkill: 0
export const staggerTicks = [
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 1000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 1500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 2000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 2500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 3000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 1, absorbed: 9, timestamp: 3500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 4000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 4500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 5000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 10, timestamp: 5500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 8, absorbed: 7, timestamp: 6000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 15, timestamp: 6500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 15, timestamp: 7000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 15, timestamp: 7500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 15, timestamp: 8000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 13, timestamp: 8500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 13, timestamp: 9000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 13, timestamp: 9500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 13, timestamp: 10000, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 13, timestamp: 10500, ability: { guid: SPELLS.STAGGER_TAKEN.id } },
];

// 599 will be removed by the stagger array below when combined
// Damage taken: amount: 1200, absorbed: 599, overkill: 0
export const incomingDamage = [
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 400, timestamp: 1, ability: { guid: 1 } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 400, absorbed: 300, timestamp: 500, ability: { guid: 1 } },
  { type: EventType.Damage, sourceID: enemy, targetid: thisPlayer, amount: 400, absorbed: 299, timestamp: 5700, ability: { guid: 4 } },
];

// Damage taken: amount: 0, absorbed: 0, overkill: 0
export const casts = [
  { type: EventType.Cast, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 100, ability: { guid: SPELLS.GIFT_OF_THE_OX_1.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 204, ability: { guid: SPELLS.GIFT_OF_THE_OX_1.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 4700, ability: { guid: SPELLS.GIFT_OF_THE_OX_1.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 8200, ability: { guid: SPELLS.PURIFYING_BREW.id } },
];

export const dpsCasts = [
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 3500, ability: { guid: SPELLS.BLACKOUT_STRIKE.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 4500, ability: { guid: SPELLS.KEG_SMASH.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 4700, ability: { guid: SPELLS.KEG_SMASH.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 6500, ability: { guid: SPELLS.BLACKOUT_STRIKE.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 8500, ability: { guid: SPELLS.BLACKOUT_STRIKE.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 9000, ability: { guid: SPELLS.BLACKOUT_STRIKE.id } },
  { type: EventType.Cast, sourceID: thisPlayer, targetid: enemy, timestamp: 9700, ability: { guid: SPELLS.BREATH_OF_FIRE.id } },
];

// Damage taken: amount: 0, absorbed: 0, overkill: 0
export const isbCasts = [
  { type: EventType.Cast, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 200, ability: { guid: SPELLS.IRONSKIN_BREW.id } },
];

// Damage taken: amount: 0, absorbed: 0, overkill: 0
export const applybuff = [
  { type: EventType.ApplyBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 200, ability: { guid: SPELLS.IRONSKIN_BREW_BUFF.id } },
  { type: EventType.ApplyBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 3500, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
  { type: EventType.ApplyBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 6500, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
  { type: EventType.ApplyBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 8500, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
];

export const refreshBuff = [
  { type: EventType.RefreshBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 9000, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
];

export const removebuff = [
  { type: EventType.RemoveBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 4500, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
  { type: EventType.RemoveBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 8200, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
  { type: EventType.RemoveBuff, sourceID: thisPlayer, targetid: thisPlayer, timestamp: 9700, ability: { guid: SPELLS.BLACKOUT_COMBO_BUFF.id } },
];

// This absorb is used from the damage line
// Damage taken: amount: 0, absorbed: 0, overkill: 0
export const absorbed = [
  { type: EventType.Absorbed, sourceID: enemy, targetid: thisPlayer, amount: 9, timestamp: 3500, ability: { guid: 99999 }, extraAbility: { guid: 1, type: 1 } },
  { type: EventType.Absorbed, sourceID: enemy, targetid: thisPlayer, amount: 7, timestamp: 6000, ability: { guid: 99999 }, extraAbility: { guid: 1, type: 1 } },
];

// Damage taken: amount: 0, absorbed: 0, overkill: 0
// Stagger damage taken: amount: 0, absorbed: -599, overkill: 0
export const staggerAbsorbed = [
  { type: EventType.Absorbed, sourceID: enemy, targetid: thisPlayer, amount: 300, timestamp: 500, ability: { guid: SPELLS.STAGGER.id }, extraAbility: { guid: 1, type: 1 } },
  { type: EventType.Absorbed, sourceID: enemy, targetid: thisPlayer, amount: 299, timestamp: 5700, ability: { guid: SPELLS.STAGGER.id }, extraAbility: { guid: 4, type: 4 } },
];

// Damage taken: amount: 0, absorbed: 0, overkill: 0
export const heal = [
  { type: EventType.Heal, sourceID: thisPlayer, targetid: thisPlayer, amount: 10, timestamp: 6700, ability: { guid: SPELLS.GIFT_OF_THE_OX_1.id } },
];

export const SimpleFight = [
  ...staggerTicks,
  ...incomingDamage,
  ...casts,
  ...applybuff,
  ...absorbed,
  ...staggerAbsorbed,
  ...heal,
  ...isbCasts,
  ...dpsCasts,
  ...refreshBuff,
  ...removebuff,
].sort((a, b) => a.timestamp - b.timestamp);

export const EarlyFinish = [
  ...staggerTicks,
  ...incomingDamage,
  ...casts,
  ...applybuff,
  ...absorbed,
  ...staggerAbsorbed,
  ...heal,
  ...isbCasts,
  ...dpsCasts,
  ...refreshBuff,
  ...removebuff,
].sort((a, b) => a.timestamp - b.timestamp).filter(event => event.timestamp <= 6000);
<|endoftext|>


<commit_before>const { decode, parse } = require('./response')

describe('Protocol > Requests > DeleteRecords > v0', () => {
  test('response - success', async () => {
    const data = await decode(Buffer.from(require('../fixtures/v0_response.json')))
    expect(data).toEqual({
      throttleTime: 0,
      topics: [
        {
          topic: 'test-topic-5da683fa3b1898223498-97119-d06829e3-35d2-4b97-b4b4-7c03d4ad7cc8',
          partitions: [
            {
              partition: 0,
              lowWatermark: 7n,
              errorCode: 0,
            },
          ],
        },
      ],
    })

    await expect(parse(data)).resolves.toBeTruthy()
  })
})
<commit_msg>deleteRecords Protocol - update test to call response fn<commit_after>const response = require('./response')

describe('Protocol > Requests > DeleteRecords > v0', () => {
  test('response - success', async () => {
    const { decode, parse } = response({})
    const data = await decode(Buffer.from(require('../fixtures/v0_response.json')))
    expect(data).toEqual({
      throttleTime: 0,
      topics: [
        {
          topic: 'test-topic-5da683fa3b1898223498-97119-d06829e3-35d2-4b97-b4b4-7c03d4ad7cc8',
          partitions: [
            {
              partition: 0,
              lowWatermark: 7n,
              errorCode: 0,
            },
          ],
        },
      ],
    })

    await expect(parse(data)).resolves.toBeTruthy()
  })
})
<|endoftext|>


<commit_before>'use strict';

import mongoose from 'mongoose';
const User = mongoose.model('User');
const Profile = mongoose.model('Profile');
const Preference = mongoose.model('Preference');

/**
 * Controller that process user profile/settings request.
 *
 * @author C Killua
 * @module Konko/Users/Controllers/User
 */
export default class UserController {

  /**
   * @constructs
   */
  constructor() {}

  /**
   * Response an user.
   *
   * @param {Object} req - HTTP request.
   * @param {Object} res - HTTP response.
   * @static
   */
  static get(req, res) {
    req.user.populate('profile preference', (err, user) => {
      if (err) {
        return res.status(500).send(err);
      }

      res.json(user);
    });
  }

  /**
   * Update an user profile.
   *
   * @param {Object} req - HTTP request.
   * @param {Object} res - HTTP response.
   * @static
   */
  static updateProfile(req, res) {
    if (!req.user._id.equals(req.payload._id)) {
      return res.status(401).send('Unauthorized');
    }

    Profile.findById(req.user.profile).exec()
      .then(profile => {
        // profile.username = req.body.profile.username || profile.username;
        // profile.avatar = req.body.profile.avatar || profile.avatar;
        // profile.banner = req.body.profile.banner || profile.banner;
        // profile.gender = req.body.profile.gender || profile.gender;
        // profile.dob = req.body.profile.dob || profile.dob;
        profile = req.body.profile;
        profile.save()
          .then(profile => res.json(profile))
          .catch(err => res.status(500).send({ message: err }));
      })
      .catch(err => res.status(500).send({ message: err }));
  }

  /**
   * Update an user profile.
   *
   * @param {Object} req - HTTP request.
   * @param {Object} res - HTTP response.
   * @static
   */
  static updatePreference(req, res) {
    if (!req.user._id.equals(req.payload._id)) {
      return res.status(401).send('Unauthorized');
    }

    Preference.findById(req.user.preference).exec()
      .then(preference => {
        preference = req.body.preference;
        preference.save()
          .then(preference => res.json(preference))
          .catch(err => res.status(500).send({ message: err }));
      })
      .catch(err => res.status(500).send({ message: err }));
  }

  /**
   * Middleware that finds a user with given id.
   *
   * @param {Object} req - HTTP request.
   * @param {Object} res - HTTP response.
   * @param {nextCallback} next - A callback to run.
   * @param {String} id - Mongo object id.
   * @static
   */
  static findUserById(req, res, next, id) {
    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).send({ message: 'User ID is invalid' });
    }

    User.findById(id).select('_id joined profile preference').exec()
      .then(user => (req.user = user) ? next() : res.status(404).send({ message: 'User is not found' }))
      .catch(err => next(err));
  }
}

/**
 * Callback that calls next middleware.
 *
 * @callback nextCallback
 * @param {Object} error - Error, if has any.
 */
<commit_msg>Fixed profile update<commit_after>'use strict';

import mongoose from 'mongoose';
const User = mongoose.model('User');
const Profile = mongoose.model('Profile');
const Preference = mongoose.model('Preference');

/**
 * Controller that process user profile/settings request.
 *
 * @author C Killua
 * @module Konko/Users/Controllers/User
 */
export default class UserController {

  /**
   * @constructs
   */
  constructor() {}

  /**
   * Response an user.
   *
   * @param {Object} req - HTTP request.
   * @param {Object} res - HTTP response.
   * @static
   */
  static get(req, res) {
    req.user.populate('profile preference', (err, user) => {
      if (err) {
        return res.status(500).send(err);
      }

      res.json(user);
    });
  }

  /**
   * Update an user profile.
   *
   * @param {Object} req - HTTP request.
   * @param {Object} res - HTTP response.
   * @static
   */
  static updateProfile(req, res) {
    if (!req.user._id.equals(req.payload._id)) {
      return res.status(401).send('Unauthorized');
    }

    Profile.findById(req.user.profile).exec()
      .then(profile => {
        profile.username = req.body.profile.username || profile.username;
        profile.avatar = req.body.profile.avatar || profile.avatar;
        profile.banner = req.body.profile.banner || profile.banner;
        profile.gender = req.body.profile.gender || profile.gender;
        profile.dob = req.body.profile.dob || profile.dob;
        profile.save()
          .then(profile => res.json(profile))
          .catch(err => res.status(500).send({ message: err }));
      })
      .catch(err => res.status(500).send({ message: err }));
  }

  /**
   * Update an user profile.
   *
   * @param {Object} req - HTTP request.
   * @param {Object} res - HTTP response.
   * @static
   */
  static updatePreference(req, res) {
    if (!req.user._id.equals(req.payload._id)) {
      return res.status(401).send('Unauthorized');
    }

    Preference.findById(req.user.preference).exec()
      .then(preference => {
        preference = req.body.preference;
        preference.save()
          .then(preference => res.json(preference))
          .catch(err => res.status(500).send({ message: err }));
      })
      .catch(err => res.status(500).send({ message: err }));
  }

  /**
   * Middleware that finds a user with given id.
   *
   * @param {Object} req - HTTP request.
   * @param {Object} res - HTTP response.
   * @param {nextCallback} next - A callback to run.
   * @param {String} id - Mongo object id.
   * @static
   */
  static findUserById(req, res, next, id) {
    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).send({ message: 'User ID is invalid' });
    }

    User.findById(id).select('_id joined profile preference').exec()
      .then(user => (req.user = user) ? next() : res.status(404).send({ message: 'User is not found' }))
      .catch(err => next(err));
  }
}

/**
 * Callback that calls next middleware.
 *
 * @callback nextCallback
 * @param {Object} error - Error, if has any.
 */
<|endoftext|>


<commit_before>import { Constants } from "../constants";
import { Composer } from "../views/composer";

Composer.RegisterKeyboardHandler(function(e) {
  return (
    e.type === "keydown" &&
    e.keyCode == Constants.BACKSPACE_KEY
  );
}, function(editor, composer, e) {
  var range = composer.selection.getRange();
  if (range && range.collapsed) {
    var selectedNode = composer.selection.getSelectedNode();
    if (
      selectedNode &&
      selectedNode === composer.element.firstElementChild &&
      selectedNode === composer.element.lastElementChild &&
      composer.selection.caretIsAtStartOfNode(selectedNode)
    ) {
      e.preventDefault();
    }
  }
})
<commit_msg>Ensure paragraph isn't deleted when cmd-a + text<commit_after>import { Constants } from "../constants";
import { Composer } from "../views/composer";
import { isNonPrintableKey } from "../helpers/is_non_printable_key";

Composer.RegisterKeyboardHandler(function(e) {
  return (
    e.type === "keydown" &&
    !e.ctrlKey &&
    !e.metaKey &&
    !e.altKey &&
    !isNonPrintableKey(e.keyCode)
  );
}, function(editor, composer, e) {
    var range = composer.selection.getRange();
    var selection = composer.selection.getSelection();
    if (range) {
      var selectedNode = composer.selection.getSelectedNode();
      if (
        selectedNode &&
        ((selectedNode === composer.element.firstElementChild &&
        selectedNode === composer.element.lastElementChild) || selectedNode === composer.element) &&
        composer.selection.caretIsAtStartOfNode(selectedNode)
      ) {
        if (range.collapsed && e.keyCode === wysihtml5$constants$$Constants.BACKSPACE_KEY) {
          e.preventDefault();
        } else if (selection && e.keyCode !== wysihtml5$constants$$Constants.BACKSPACE_KEY && composer.element.textContent === selection.toString()) {
          composer.element.innerHTML = "";
          composer.ensureParagraph();
        }
      }
    }
})
<|endoftext|>


<commit_before>@import '~/github/movingimages_sketch/MovingImages.js';

log('This is the mi log text');

log(context);

var documentName = context.document.displayName();
log('The current document is named: ' + documentName);

var selectedLayers = context.selection;
var selectedCount = selectedLayers.count();

if (selectedCount == 0) {
  log('No layers are selected.');
} else {
  log('Selected layers:');
  var exporter = SketchSVGExporter.new()
  for (var i = 0; i < selectedCount; i++) {
    var layer = selectedLayers[i];
    log((i+1) + '. ' + layer.class());
    if (layer.class() == 'MSShapeGroup') {
      // log(layer.treeAsDictionary())
      var frame = layer.frame()
      log(miConvertMSRect(frame))
      var rect = frame.rect()

      var bezier = layer.bezierPathInRect(rect) // This returns an NSBezierPath
      // var rect = [[layer frame] rect];
      // var bezier = [layer bezierPathInRect:rect];
      var svgPath = bezier.svgPathAttribute()
      log(svgPath)

      log(layer.immutableModelObject().svgPathAttribute(exporter))
      log('Frame origin.x: ' + frame.x() + ' .y: ' + frame.y())
      // log(miConvertMSRect(frame))
      var borders = layer.style().borders()
      // log(borders.objectAtIndex(0).treeAsDictionary())
      var gradient = borders.objectAtIndex(0).gradient()
      log(gradient.treeAsDictionary())
      var gradientPoints = gradient.points()
      log(gradientPoints.class())
      var point0 = gradientPoints.points().objectAtIndex(0)
      log(point0)
      log(miConvertStringToPoint(point0))
      log(point0.class())
      log(miConvertPointsToLine(gradientPoints))
      // log(borders.treeAsDictionary())
      // log(layer.layers())
      // log(layer.treeAsDictionary())
      // var subLayers = layer.layers()
      // var subLayersCount = subLayers.count()
      // log(subLayers)
      // log('Num subLayers: ' + subLayersCount)
      // log(subLayers.treeAsDictionary())
      // subLayer = subLayers[0]
      // log(subLayer)
      // log(subLayer.class())
//      for (var j = 0; j < subLayersCount; ++j) {
//        log('i: ' + i 'j: ' + j + subLayers[j].class())
//      }
    }
    log('I am here')
    fill = layer.style().fills().objectAtIndex(0);
    log(fill.color())
    // fill.color = MSColor.colorWithSVGString("#d00");
    log(miConvertMSColor(fill.color()))
    var newColor = fill.color().colorWithAlpha(0.5);
    log(miConvertMSColor(newColor))
    log(newColor);
    log(newColor.hexValue());
    log(newColor.alpha());
  }
};
<commit_msg>Removing commented out cruft<commit_after>@import '~/github/movingimages_sketch/MovingImages.js';

log('This is the mi log text');

log(context);

var documentName = context.document.displayName();
log('The current document is named: ' + documentName);

var selectedLayers = context.selection;
var selectedCount = selectedLayers.count();

if (selectedCount == 0) {
  log('No layers are selected.');
} else {
  log('Selected layers:');
  var exporter = SketchSVGExporter.new()
  for (var i = 0; i < selectedCount; i++) {
    var layer = selectedLayers[i];
    log((i+1) + '. ' + layer.class());
    if (layer.class() == 'MSShapeGroup') {
      // log(layer.treeAsDictionary())
      var frame = layer.frame()
      log(miConvertMSRect(frame))
      var rect = frame.rect()

      var bezier = layer.bezierPathInRect(rect) // This returns an NSBezierPath
      var svgPath = bezier.svgPathAttribute()
      log(svgPath)

      log(layer.immutableModelObject().svgPathAttribute(exporter))
      log('Frame origin.x: ' + frame.x() + ' .y: ' + frame.y())
      var borders = layer.style().borders()
      var gradient = borders.objectAtIndex(0).gradient()
      log(gradient.treeAsDictionary())
      var gradientPoints = gradient.points()
      log(gradientPoints.class())
      var point0 = gradientPoints.points().objectAtIndex(0)
      log(point0)
      log(miConvertStringToPoint(point0))
      log(point0.class())
      log(miConvertPointsToLine(gradientPoints))
    }
    log('I am here')
    fill = layer.style().fills().objectAtIndex(0);
    log(fill.color())
    // fill.color = MSColor.colorWithSVGString("#d00");
    log(miConvertMSColor(fill.color()))
    var newColor = fill.color().colorWithAlpha(0.5);
    log(miConvertMSColor(newColor))
    log(newColor);
    log(newColor.hexValue());
    log(newColor.alpha());
  }
};
<|endoftext|>


<commit_before>require("should");
var KanbanDataUtil = require('../../../data-util/production/finishing-printing/kanban-data-util');
var SppDataUtil = require('../../../data-util/sales/production-order-data-util');
var helper = require("../../../helper");
var validate = require("dl-models").validator.production.finishingPrinting.kanban;
var moment = require('moment');

var KanbanManager = require("../../../../src/managers/production/finishing-printing/kanban-manager");
var UomManager = require("../../../../src/managers/master/uom-manager");
var SppManager = require("../../../../src/managers/sales/production-order-manager");
var kanbanManager = null;
var uomManager = null;
var sppManager = null;

before('#00. connect db', function (done) {
    helper.getDb()
        .then(db => {
            kanbanManager = new KanbanManager(db, {
                username: 'dev'
            });
            uomManager = new UomManager(db, {
                username: 'dev'
            });
            sppManager = new SppManager(db, {
                username: 'dev'
            });
            done();
        })
        .catch(e => {
            done(e);
        });
});

var uom;
it('#01. should success when create data "MTR" on uom', function (done) {
    uomManager.getSingleByQueryOrDefault({"unit" : "MTR"})
        .then(result => {
            if(result){
                uom = result;
                done();
            }else{
                uomManager.create({"unit" : "MTR"})
                    .then(id => {
                        uomManager.getSingleById(id)
                            .then(data=>{
                                uom = data;
                                done();
                            })
                            .catch(e => {
                                done(e);
                            });
                    })
                    .catch(e => {
                        done(e);
                    });
            }
        })
        .catch(e => {
            done(e);
        });
});

var productionOrder;
it('#02. should success when create data production order with "MTR" uom', function (done) {
    SppDataUtil.getNewData()
        .then(data => {
            data.uom = uom;
            data.uomId = uom._id;
            var detail = [];
            for(var a of data.details){
                a.uom = uom;
                a.uomId = uom._id;
                detail.push(a);
            }
            data.details = detail;
            sppManager.create(data)
                .then(id => {
                    sppManager.getSingleById(id)
                        .then(production => {
                            productionOrder = production;
                            done();
                        })
                        .catch(e => {
                            done(e);
                        });
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

it('#03. should error when create with empty data ', function (done) {
    kanbanManager.create({})
        .then(id => {
            done("should error when create with empty data");
        })
        .catch(e => {
            try {
                e.errors.should.have.property('productionOrder');
                e.errors.should.have.property('selectedProductionOrderDetail');
                e.errors.should.have.property('cart');
                e.errors.should.have.property('grade');
                e.errors.should.have.property('instruction');
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});

it('#04. should error when create new data with non existent productionOrder, instruction', function (done) {
    KanbanDataUtil.getNewData()
        .then(kanban => {

            kanban.productionOrderId = 'randomId';
            kanban.instructionId = 'randomId';

            kanbanManager.create(kanban)
                .then(id => {
                    done("should error when create new data with non existent productionOrder, instruction");
                })
                .catch(e => {
                    try {
                        e.errors.should.have.property('productionOrder');
                        e.errors.should.have.property('instruction');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch(e => {
            done(e);
        });
});

it('#05. should error when create new data with empty step', function (done) {
    KanbanDataUtil.getNewData()
        .then(kanban => {
            kanban.instruction.steps.push({ process: "" });

            kanbanManager.create(kanban)
                .then(id => {
                    done("should error when create new data with empty step");
                })
                .catch(e => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property('errors');
                        e.errors.should.instanceof(Object);
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch(e => {
            done(e);
        });
});

// it('#05. should error when create new data with overlimit qty and uom non "MTR"', function (done) {
//     KanbanDataUtil.getNewData()
//         .then(kanban => {

//             kanban.cart.qty = kanban.selectedProductionOrderDetail.quantity + 5;

//             kanbanManager.create(kanban)
//                 .then(id => {
//                     done('should error when create new data with overlimit qty and uom non "MTR"');
//                 })
//                 .catch(e => {
//                     try {
//                         e.errors.should.have.property('cart');
//                         done();
//                     }
//                     catch (ex) {
//                         done(ex);
//                     }
//                 });
//         })
//         .catch(e => {
//             done(e);
//         });
// });

// it('#06. should error when create new data with overlimit qty and "MTR" uom', function (done) {
//     KanbanDataUtil.getNewData()
//         .then(kanban => {
//             kanban.productionOrder = productionOrder;
//             kanban.productionOrderId = productionOrder._id;
//             var detail = {};
//             for(var a of productionOrder.details){
//                 detail = a;
//             }
//             kanban.selectedProductionOrderDetail = detail;
//             kanban.cart.qty = kanban.selectedProductionOrderDetail.quantity + 5;
//             kanbanManager.create(kanban)
//                 .then(id => {
//                     done('should error when create new data with overlimit qty and "MTR" uom');
//                 })
//                 .catch(e => {
//                     try {
//                         e.errors.should.have.property('cart');
//                         done();
//                     }
//                     catch (ex) {
//                         done(ex);
//                     }
//                 });
//         })
//         .catch(e => {
//             done(e);
//         });
// });

/* Lepas validasi ini karena tambah flow reprocess */
// it('#05. should error when set isComplete true with incomplete steps', function (done) {
//     KanbanDataUtil.getNewData()
//         .then(kanban => {
//             kanbanManager.create(kanban)
//                 .then(id => {
//                     kanbanManager.getSingleById(id)
//                         .then(toBeCompletedKanban =>{
//                             toBeCompletedKanban.isComplete = true;
//                             toBeCompletedKanban.currentStepIndex = toBeCompletedKanban.instruction.steps.length - 1;
//                             kanbanManager.update(toBeCompletedKanban)
//                                 .then(completeKanbanId => {
//                                     done("should error when set isComplete true with incomplete steps");
//                                 })
//                                 .catch(e =>{
//                                     e.errors.should.have.property('isComplete');
//                                     done();
//                                 });
//                         })
//                         .catch(e => {
//                             done(e);
//                         });
//                 })
//                 .catch(e => {
//                     done(e);
//                 });
//         })
//         .catch(e => {
//             done(e);
//         });
// });<commit_msg>Validasi Kanban<commit_after>require("should");
var KanbanDataUtil = require('../../../data-util/production/finishing-printing/kanban-data-util');
var SppDataUtil = require('../../../data-util/sales/production-order-data-util');
var helper = require("../../../helper");
var validate = require("dl-models").validator.production.finishingPrinting.kanban;
var moment = require('moment');

var KanbanManager = require("../../../../src/managers/production/finishing-printing/kanban-manager");
var UomManager = require("../../../../src/managers/master/uom-manager");
var SppManager = require("../../../../src/managers/sales/production-order-manager");
var kanbanManager = null;
var uomManager = null;
var sppManager = null;

before('#00. connect db', function (done) {
    helper.getDb()
        .then(db => {
            kanbanManager = new KanbanManager(db, {
                username: 'dev'
            });
            uomManager = new UomManager(db, {
                username: 'dev'
            });
            sppManager = new SppManager(db, {
                username: 'dev'
            });
            done();
        })
        .catch(e => {
            done(e);
        });
});

var uom;
it('#01. should success when create data "MTR" on uom', function (done) {
    uomManager.getSingleByQueryOrDefault({"unit" : "MTR"})
        .then(result => {
            if(result){
                uom = result;
                done();
            }else{
                uomManager.create({"unit" : "MTR"})
                    .then(id => {
                        uomManager.getSingleById(id)
                            .then(data=>{
                                uom = data;
                                done();
                            })
                            .catch(e => {
                                done(e);
                            });
                    })
                    .catch(e => {
                        done(e);
                    });
            }
        })
        .catch(e => {
            done(e);
        });
});

var productionOrder;
it('#02. should success when create data production order with "MTR" uom', function (done) {
    SppDataUtil.getNewData()
        .then(data => {
            data.uom = uom;
            data.uomId = uom._id;
            var detail = [];
            for(var a of data.details){
                a.uom = uom;
                a.uomId = uom._id;
                detail.push(a);
            }
            data.details = detail;
            sppManager.create(data)
                .then(id => {
                    sppManager.getSingleById(id)
                        .then(production => {
                            productionOrder = production;
                            done();
                        })
                        .catch(e => {
                            done(e);
                        });
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

it('#03. should error when create with empty data ', function (done) {
    kanbanManager.create({})
        .then(id => {
            done("should error when create with empty data");
        })
        .catch(e => {
            try {
                e.errors.should.have.property('productionOrder');
                e.errors.should.have.property('selectedProductionOrderDetail');
                e.errors.should.have.property('cart');
                e.errors.should.have.property('grade');
                e.errors.should.have.property('instruction');
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});

it('#04. should error when create new data with non existent productionOrder, instruction', function (done) {
    KanbanDataUtil.getNewData()
        .then(kanban => {

            kanban.productionOrderId = 'randomId';
            kanban.instructionId = 'randomId';

            kanbanManager.create(kanban)
                .then(id => {
                    done("should error when create new data with non existent productionOrder, instruction");
                })
                .catch(e => {
                    try {
                        e.errors.should.have.property('productionOrder');
                        e.errors.should.have.property('instruction');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch(e => {
            done(e);
        });
});

it('#05. should error when create new data with empty step', function (done) {
    KanbanDataUtil.getNewData()
        .then(kanban => {
            kanban.instruction.steps.push({ process: "" });
            kanban.oldKanbanId = {};

            kanbanManager.create(kanban)
                .then(id => {
                    done("should error when create new data with empty step");
                })
                .catch(e => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property('errors');
                        e.errors.should.instanceof(Object);
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch(e => {
            done(e);
        });
});

// it('#05. should error when create new data with overlimit qty and uom non "MTR"', function (done) {
//     KanbanDataUtil.getNewData()
//         .then(kanban => {

//             kanban.cart.qty = kanban.selectedProductionOrderDetail.quantity + 5;

//             kanbanManager.create(kanban)
//                 .then(id => {
//                     done('should error when create new data with overlimit qty and uom non "MTR"');
//                 })
//                 .catch(e => {
//                     try {
//                         e.errors.should.have.property('cart');
//                         done();
//                     }
//                     catch (ex) {
//                         done(ex);
//                     }
//                 });
//         })
//         .catch(e => {
//             done(e);
//         });
// });

// it('#06. should error when create new data with overlimit qty and "MTR" uom', function (done) {
//     KanbanDataUtil.getNewData()
//         .then(kanban => {
//             kanban.productionOrder = productionOrder;
//             kanban.productionOrderId = productionOrder._id;
//             var detail = {};
//             for(var a of productionOrder.details){
//                 detail = a;
//             }
//             kanban.selectedProductionOrderDetail = detail;
//             kanban.cart.qty = kanban.selectedProductionOrderDetail.quantity + 5;
//             kanbanManager.create(kanban)
//                 .then(id => {
//                     done('should error when create new data with overlimit qty and "MTR" uom');
//                 })
//                 .catch(e => {
//                     try {
//                         e.errors.should.have.property('cart');
//                         done();
//                     }
//                     catch (ex) {
//                         done(ex);
//                     }
//                 });
//         })
//         .catch(e => {
//             done(e);
//         });
// });

/* Lepas validasi ini karena tambah flow reprocess */
// it('#05. should error when set isComplete true with incomplete steps', function (done) {
//     KanbanDataUtil.getNewData()
//         .then(kanban => {
//             kanbanManager.create(kanban)
//                 .then(id => {
//                     kanbanManager.getSingleById(id)
//                         .then(toBeCompletedKanban =>{
//                             toBeCompletedKanban.isComplete = true;
//                             toBeCompletedKanban.currentStepIndex = toBeCompletedKanban.instruction.steps.length - 1;
//                             kanbanManager.update(toBeCompletedKanban)
//                                 .then(completeKanbanId => {
//                                     done("should error when set isComplete true with incomplete steps");
//                                 })
//                                 .catch(e =>{
//                                     e.errors.should.have.property('isComplete');
//                                     done();
//                                 });
//                         })
//                         .catch(e => {
//                             done(e);
//                         });
//                 })
//                 .catch(e => {
//                     done(e);
//                 });
//         })
//         .catch(e => {
//             done(e);
//         });
// });<|endoftext|>


<commit_before>$(document).ready(function () {
    $("div").mousedown(function () {
        $(this).hide(400);
    });
    $(".div").click(function () {
        $(this).hide(400);
    });
});
<commit_msg>Fix the "quit" handler<commit_after>$(document).ready(function () {
    $("div").mousedown(function () {
        $(this).hide(400);
    });
    $("#quit").click(function () {
        Qt.quit();
    });
});
<|endoftext|>


<commit_before>"use strict";
var platformsServices = soajsApp.components;
platformsServices.service('envPlatforms', ['ngDataApi', '$timeout', '$modal', '$cookies', 'Upload', function (ngDataApi, $timeout, $modal, $cookies, Upload) {

	var access_token = $cookies.get('access_token');

	function listPlatforms(currentScope, env, cb) {
		getSendDataFromServer(currentScope, ngDataApi, {
			"method": "get",
			"routeName": "/dashboard/environment/platforms/list",
			"params": {
				env: env
			}
		}, function (error, response) {
			if (error) {
				currentScope.$parent.displayAlert("danger", error.code, true, 'dashboard', error.message);
			} else {
				renderDisplay(currentScope, response, cb);
			}
		});
	}

	function renderDisplay(currentScope, record, cb) {
		currentScope.deployer.type = record.type;
		currentScope.originalDeployerType = record.type;//used to detect changes in type on UI level
		currentScope.currentSelected = record.selected.split('.');

		if (currentScope.currentSelected[0] === 'container') {
			currentScope.deployer.selected = currentScope.currentSelected[1] + '.' + currentScope.currentSelected[2];
			currentScope.deployer.platform = currentScope.currentSelected[1];
		}

		currentScope.allowSelect = currentScope.deployer.type === 'container';

		currentScope.availableCerts = {}; //used later to view available certificates and allow user to choose them for other drivers
		record.certs.forEach(function (oneCert) {
			if (!currentScope.availableCerts[oneCert.metadata.platform]) {
				currentScope.availableCerts[oneCert.metadata.platform] = [];
			}

			currentScope.availableCerts[oneCert.metadata.platform].push(oneCert);
		});

		currentScope.platforms = record.container;

		//filling in certificates
		for (var platform in currentScope.platforms) {
			var onePlatform = currentScope.platforms[platform];
			for (var driver in onePlatform) {
				onePlatform[driver].certs = [];
				for (var i = 0; i < record.certs.length; i++) {
					if (record.certs[i].metadata.platform === platform && record.certs[i].metadata.env[currentScope.envCode] && record.certs[i].metadata.env[currentScope.envCode].indexOf(platform + '.' + driver) !== -1) {
						currentScope.platforms[platform][driver].certs.push({
							_id: record.certs[i]._id,
							filename: record.certs[i].filename,
							certType: record.certs[i].metadata.certType
						});
					}
				}
			}
		}

		if (cb) {
			return cb();
		}
	}

	function uploadCerts(currentScope, platform, driverName) {
		var upload = $modal.open({
			templateUrl: "uploadCerts.tmpl",
			backdrop: true,
			keyboard: true,
			controller: function ($scope) {
				fixBackDrop();

				$scope.title = translation.uploadCertificates[LANG];
				$scope.outerScope = currentScope;
				$scope.formData = {
					certificates: {}
				};
				$scope.certs = {
					selected: {},
					types: ['ca', 'cert', 'key']
				};

				$scope.platform = platform;
				$scope.driver = driverName;
				if (platform === 'nginx') {
					$scope.nginxRequiredCerts = angular.copy(environmentsConfig.nginxRequiredCerts);
					currentScope.nginx.certs.forEach(function (oneCert) {
						if ($scope.nginxRequiredCerts[oneCert.metadata.label]) {
							delete $scope.nginxRequiredCerts[oneCert.metadata.label];
						}
					});
					$scope.nginxRequiredCertsLength = Object.keys($scope.nginxRequiredCerts).length;
				}

				$scope.onSubmit = function () {
					if ($scope.formData && $scope.formData.certificates && Object.keys($scope.formData.certificates).length > 0) {
						upload.close();
						var uploadInfo = $modal.open({
							templateUrl: 'uploadCertsInfo.html',
							backdrop: true,
							keyboard: false,
							controller: function ($scope) {
								fixBackDrop();
								$scope.text = "
" + translation.uploadingCertificates[LANG] + "

" + translation.thisMightTakeFewMinutesPleaseWait[LANG] + "
";
							}
						});
						//create array index to go through certificates list
						$scope.index = [];
						for (var i in $scope.formData.certificates) {
							$scope.index.push(i);
						}

						$scope.uploadFiles(platform, driverName, 0, uploadInfo, function () {
							$scope.formData.certificates = {};
							$scope.index = [];
							uploadInfo.close();
							var uploadDone = $modal.open({
								templateUrl: 'uploadCertsInfo.html',
								backdrop: true,
								keyboard: true,
								controller: function ($scope, $modalInstance) {
									fixBackDrop();
									$scope.text = "
" + translation.certificateAddedSuccessfully[LANG] + "
";
								}
							});
							$timeout(function () {
								uploadDone.dismiss();
							}, 1500);

							currentScope.listPlatforms(currentScope.envCode);
						});
					}
				};

				$scope.chooseCerts = function () {
					var certIds = [];
					var certsArr = Object.keys($scope.certs.selected);
					certsArr.forEach(function (oneCertId) {
						if ($scope.certs.selected[oneCertId]) {
							certIds.push(oneCertId);
						}
					});

					var options = {
						method: "put",
						routeName: "/dashboard/environment/platforms/cert/choose",
						params: {
							env: currentScope.envCode,
							platform: platform,
							driverName: driverName
						},
						data: {
							certIds: certIds
						}
					};

					if (platform === 'nginx') {
						options.routeName = '/dashboard/environment/nginx/cert/choose';
						delete options.params.driverName;
					}

					getSendDataFromServer(currentScope, ngDataApi, options, function (error, response) {
						if (error) {
							currentScope.$parent.displayAlert("danger", error.code, true, 'dashboard', error.message);
							upload.close();
						} else {
							currentScope.$parent.displayAlert('success', translation.chosenCertificatesSavedSuccessfully[LANG]);
							upload.close();
							currentScope.listPlatforms(currentScope.envCode);
						}
					});
				};

				$scope.getAvailableCerts = function () {
					$scope.certsToDisplay = [];
					$scope.availableCertTypes = [];
					if (currentScope.availableCerts[$scope.platform]) {
						currentScope.availableCerts[$scope.platform].forEach(function (oneCert) {
							if (oneCert.metadata.platform === $scope.platform) {
								$scope.certsToDisplay.push({
									_id: oneCert._id,
									name: oneCert.filename,
									env: Object.keys(oneCert.metadata.env),
									certType: oneCert.metadata.certType
								});
							}
						});
					}
					//check the types of the certicates that are currently available for this driver
					//do not allow user to upload more than one certificate with the same type [ca, cert, key]
					if (currentScope.platforms[$scope.platform][$scope.driver].certs && currentScope.platforms[$scope.platform][$scope.driver].certs.length > 0) {
						currentScope.platforms[$scope.platform][$scope.driver].certs.forEach(function (oneCert) {
							$scope.availableCertTypes.push(oneCert.certType);
						});
					}
				};
				$scope.getAvailableCerts();

				$scope.closeModal = function () {
					upload.close();
				};

				$scope.uploadFiles = function(platform, driverName, counter, modal, cb) {
					if (!currentScope.envCode || !platform || !$scope.formData.certificates[$scope.index[counter]].name) {
						//to avoid incompatibiltiy issues when using safari browsers
						return cb();
					}

					var soajsauthCookie = $cookies.get('soajs_auth');
					var dashKeyCookie = $cookies.get('soajs_dashboard_key');
					var progress = {
						value: 0
					};

					var options = {
						url: apiConfiguration.domain + "/dashboard/environment/platforms/cert/upload",
						params: {
							envCode: currentScope.envCode,
							filename: $scope.formData.certificates[$scope.index[counter]].name,
							certType: $scope.index[counter],
							platform: platform,
							driver: driverName,
							access_token: access_token
						},
						file: $scope.formData.certificates[$scope.index[counter]],
						headers: {
							'soajsauth': soajsauthCookie,
							'key': dashKeyCookie
						}
					};

					Upload.upload(options).progress(function (evt) {
						var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
						progress.value = progressPercentage;
					}).success(function (response, status, headers, config) {
						if (!response.result) {
							currentScope.$parent.displayAlert('danger', response.errors.details[0].message);
							currentScope.listPlatforms(currentScope.envCode); //refresh view in case some files were uploaded successfully
							modal.close();
						}
						else {
							counter++;
							if (counter === Object.keys($scope.formData.certificates).length) {
								return cb();
							} else {
								$scope.uploadFiles(platform, driverName, counter, modal, cb);
							}
						}
					}).error(function (data, status, header, config) {
						currentScope.$parent.displayAlert('danger', translation.errorOccurredWhileUploadingFile[LANG] + " " + options.params.filename);
						modal.close();
					});
				}
			}
		});
	}

	function removeCert(currentScope, certId, platform, driverName) {
		getSendDataFromServer(currentScope, ngDataApi, {
			"method": "delete",
			"routeName": "/dashboard/environment/platforms/cert/delete",
			"params": {
				"id": certId,
				"env": currentScope.envCode,
				"driverName": platform + '.' + driverName
			}
		}, function (error, response) {
			if (error) {
				currentScope.$parent.displayAlert("danger", error.code, true, 'dashboard', error.message);
			} else {
				currentScope.$parent.displayAlert('success', translation.selectedCertificateRemoved[LANG]);
				currentScope.listPlatforms(currentScope.envCode);
			}
		});
	}

	function selectDriver(currentScope, platform, driverName, type) {
		var driver = type + "." + platform + '.' + driverName;
		getSendDataFromServer(currentScope, ngDataApi, {
			"method": "put",
			"routeName": "/dashboard/environment/platforms/driver/changeSelected",
			"params": {env: currentScope.envCode},
			"data": {selected: driver}
		}, function (error, response) {
			if (error) {
				currentScope.$parent.displayAlert("danger", error.code, true, 'dashboard', error.message);
			} else {
				currentScope.$parent.displayAlert('success', translation.selectedDriverUpdated[LANG]);
				currentScope.deployer.selected = platform + '.' + driverName;
				currentScope.deployer.platform = platform;
				currentScope.originalDeployer = currentScope.deployer.selected;
			}
		});
	}

	function changeDeployerType (currentScope) {
		//scope.allowSelect if type is container
		var postData = {
			deployerType: currentScope.deployer.type
		};
		getSendDataFromServer(currentScope, ngDataApi, {
			"method": "put",
			"routeName": "/dashboard/environment/platforms/deployer/type/change",
			"params": {
				env: currentScope.envCode
			},
			"data": postData
		}, function (error, response) {
			if (error) {
				currentScope.$parent.displayAlert("danger", error.code, true, 'dashboard', error.message);
			} else {
				currentScope.$parent.displayAlert('success', 'Deployer type changed successfully');
				currentScope.allowSelect = currentScope.deployer.type === 'container';
				currentScope.listPlatforms(currentScope.envCode);
			}
		});
	}

	function updateNamespaceConfig(currentScope, driver) {
		var currentConfig = currentScope.platforms.kubernetes[driver];
		var modal = $modal.open({
			templateUrl: "updateNamespaceConfig.tmpl",
			backdrop: true,
			keyboard: true,
			controller: function ($scope) {
				fixBackDrop();

				$scope.title = 'Update Namespace Configuration';
				$scope.namespaces = {
					ui: {
						selection: [
							{ value: 'existing', label: 'Choose Existing Namespace' },
							{ value: 'new', label: 'Create New Namespace' }
						],
						list: [],
						type: [
							{ value: 'global', label: 'Global' },
							{ value: 'perService', label: 'Per Service' }
						]
					},
					data: {
						selection: 'existing',
						default: currentConfig.namespace.default,
						type: ((currentConfig.namespace.perService) ? 'perService' : 'global')
					}
				};

				$scope.reset = function () {
					if ($scope.namespaces.data.selection === 'new') {
						$scope.namespaces.data.default = '';
					}
					else {
						$scope.namespaces.data.default = currentConfig.namespace.default;
					}
				};

				$scope.listNamespaces = function () {
					getSendDataFromServer(currentScope, ngDataApi, {
						method: 'get',
						routeName: '/dashboard/cloud/namespaces/list'
					}, function (error, namespaces) {
						if (error) {
							$scope.message = {
								danger: error.message
							};
							setTimeout(function () {
								$scope.message.danger = '';
							}, 5000);
						}
						else {
							namespaces.forEach(function (oneNamespace) {
								$scope.namespaces.ui.list.push({ value: oneNamespace.id, label: oneNamespace.name });
							});
						}
					});
				};

				$scope.onSubmit = function () {
					var newConfig = {
						namespace: {
							default: $scope.namespaces.data.default,
							perService: (($scope.namespaces.data.type === 'perService') ? true : false)
						}
					};
					getSendDataFromServer(currentScope, ngDataApi, {
						method: 'put',
						routeName: '/dashboard/environment/platforms/deployer/update',
						params: {
							env: currentScope.envCode.toLowerCase()
						},
						data: {
							driver: driver,
							config: newConfig
						}
					}, function (error, result) {
						if (error) {
							$scope.message = {
								danger: error.message
							};
							setTimeout(function () {
								$scope.message.danger = '';
							}, 5000);
						}
						else {
							$scope.namespaces.data = {};
							modal.close();
							currentScope.displayAlert('success', 'Namespace configuration updated successfully');
							currentScope.listPlatforms(currentScope.envCode);
						}
					});
				};

				$scope.closeModal = function () {
					$scope.namespaces.data = {};
					modal.close();
				};

				$scope.listNamespaces();
			}
		});
	}

	return {
		'listPlatforms': listPlatforms,
		'uploadCerts': uploadCerts,
		'removeCert': removeCert,
		'selectDriver': selectDriver,
		'changeDeployerType': changeDeployerType,
		'updateNamespaceConfig': updateNamespaceConfig
	}

}]);
<commit_msg>Minor UI update in updateNamespaceConfig()<commit_after>"use strict";
var platformsServices = soajsApp.components;
platformsServices.service('envPlatforms', ['ngDataApi', '$timeout', '$modal', '$cookies', 'Upload', function (ngDataApi, $timeout, $modal, $cookies, Upload) {

	var access_token = $cookies.get('access_token');

	function listPlatforms(currentScope, env, cb) {
		getSendDataFromServer(currentScope, ngDataApi, {
			"method": "get",
			"routeName": "/dashboard/environment/platforms/list",
			"params": {
				env: env
			}
		}, function (error, response) {
			if (error) {
				currentScope.$parent.displayAlert("danger", error.code, true, 'dashboard', error.message);
			} else {
				renderDisplay(currentScope, response, cb);
			}
		});
	}

	function renderDisplay(currentScope, record, cb) {
		currentScope.deployer.type = record.type;
		currentScope.originalDeployerType = record.type;//used to detect changes in type on UI level
		currentScope.currentSelected = record.selected.split('.');

		if (currentScope.currentSelected[0] === 'container') {
			currentScope.deployer.selected = currentScope.currentSelected[1] + '.' + currentScope.currentSelected[2];
			currentScope.deployer.platform = currentScope.currentSelected[1];
		}

		currentScope.allowSelect = currentScope.deployer.type === 'container';

		currentScope.availableCerts = {}; //used later to view available certificates and allow user to choose them for other drivers
		record.certs.forEach(function (oneCert) {
			if (!currentScope.availableCerts[oneCert.metadata.platform]) {
				currentScope.availableCerts[oneCert.metadata.platform] = [];
			}

			currentScope.availableCerts[oneCert.metadata.platform].push(oneCert);
		});

		currentScope.platforms = record.container;

		//filling in certificates
		for (var platform in currentScope.platforms) {
			var onePlatform = currentScope.platforms[platform];
			for (var driver in onePlatform) {
				onePlatform[driver].certs = [];
				for (var i = 0; i < record.certs.length; i++) {
					if (record.certs[i].metadata.platform === platform && record.certs[i].metadata.env[currentScope.envCode] && record.certs[i].metadata.env[currentScope.envCode].indexOf(platform + '.' + driver) !== -1) {
						currentScope.platforms[platform][driver].certs.push({
							_id: record.certs[i]._id,
							filename: record.certs[i].filename,
							certType: record.certs[i].metadata.certType
						});
					}
				}
			}
		}

		if (cb) {
			return cb();
		}
	}

	function uploadCerts(currentScope, platform, driverName) {
		var upload = $modal.open({
			templateUrl: "uploadCerts.tmpl",
			backdrop: true,
			keyboard: true,
			controller: function ($scope) {
				fixBackDrop();

				$scope.title = translation.uploadCertificates[LANG];
				$scope.outerScope = currentScope;
				$scope.formData = {
					certificates: {}
				};
				$scope.certs = {
					selected: {},
					types: ['ca', 'cert', 'key']
				};

				$scope.platform = platform;
				$scope.driver = driverName;
				if (platform === 'nginx') {
					$scope.nginxRequiredCerts = angular.copy(environmentsConfig.nginxRequiredCerts);
					currentScope.nginx.certs.forEach(function (oneCert) {
						if ($scope.nginxRequiredCerts[oneCert.metadata.label]) {
							delete $scope.nginxRequiredCerts[oneCert.metadata.label];
						}
					});
					$scope.nginxRequiredCertsLength = Object.keys($scope.nginxRequiredCerts).length;
				}

				$scope.onSubmit = function () {
					if ($scope.formData && $scope.formData.certificates && Object.keys($scope.formData.certificates).length > 0) {
						upload.close();
						var uploadInfo = $modal.open({
							templateUrl: 'uploadCertsInfo.html',
							backdrop: true,
							keyboard: false,
							controller: function ($scope) {
								fixBackDrop();
								$scope.text = "
" + translation.uploadingCertificates[LANG] + "

" + translation.thisMightTakeFewMinutesPleaseWait[LANG] + "
";
							}
						});
						//create array index to go through certificates list
						$scope.index = [];
						for (var i in $scope.formData.certificates) {
							$scope.index.push(i);
						}

						$scope.uploadFiles(platform, driverName, 0, uploadInfo, function () {
							$scope.formData.certificates = {};
							$scope.index = [];
							uploadInfo.close();
							var uploadDone = $modal.open({
								templateUrl: 'uploadCertsInfo.html',
								backdrop: true,
								keyboard: true,
								controller: function ($scope, $modalInstance) {
									fixBackDrop();
									$scope.text = "
" + translation.certificateAddedSuccessfully[LANG] + "
";
								}
							});
							$timeout(function () {
								uploadDone.dismiss();
							}, 1500);

							currentScope.listPlatforms(currentScope.envCode);
						});
					}
				};

				$scope.chooseCerts = function () {
					var certIds = [];
					var certsArr = Object.keys($scope.certs.selected);
					certsArr.forEach(function (oneCertId) {
						if ($scope.certs.selected[oneCertId]) {
							certIds.push(oneCertId);
						}
					});

					var options = {
						method: "put",
						routeName: "/dashboard/environment/platforms/cert/choose",
						params: {
							env: currentScope.envCode,
							platform: platform,
							driverName: driverName
						},
						data: {
							certIds: certIds
						}
					};

					if (platform === 'nginx') {
						options.routeName = '/dashboard/environment/nginx/cert/choose';
						delete options.params.driverName;
					}

					getSendDataFromServer(currentScope, ngDataApi, options, function (error, response) {
						if (error) {
							currentScope.$parent.displayAlert("danger", error.code, true, 'dashboard', error.message);
							upload.close();
						} else {
							currentScope.$parent.displayAlert('success', translation.chosenCertificatesSavedSuccessfully[LANG]);
							upload.close();
							currentScope.listPlatforms(currentScope.envCode);
						}
					});
				};

				$scope.getAvailableCerts = function () {
					$scope.certsToDisplay = [];
					$scope.availableCertTypes = [];
					if (currentScope.availableCerts[$scope.platform]) {
						currentScope.availableCerts[$scope.platform].forEach(function (oneCert) {
							if (oneCert.metadata.platform === $scope.platform) {
								$scope.certsToDisplay.push({
									_id: oneCert._id,
									name: oneCert.filename,
									env: Object.keys(oneCert.metadata.env),
									certType: oneCert.metadata.certType
								});
							}
						});
					}
					//check the types of the certicates that are currently available for this driver
					//do not allow user to upload more than one certificate with the same type [ca, cert, key]
					if (currentScope.platforms[$scope.platform][$scope.driver].certs && currentScope.platforms[$scope.platform][$scope.driver].certs.length > 0) {
						currentScope.platforms[$scope.platform][$scope.driver].certs.forEach(function (oneCert) {
							$scope.availableCertTypes.push(oneCert.certType);
						});
					}
				};
				$scope.getAvailableCerts();

				$scope.closeModal = function () {
					upload.close();
				};

				$scope.uploadFiles = function(platform, driverName, counter, modal, cb) {
					if (!currentScope.envCode || !platform || !$scope.formData.certificates[$scope.index[counter]].name) {
						//to avoid incompatibiltiy issues when using safari browsers
						return cb();
					}

					var soajsauthCookie = $cookies.get('soajs_auth');
					var dashKeyCookie = $cookies.get('soajs_dashboard_key');
					var progress = {
						value: 0
					};

					var options = {
						url: apiConfiguration.domain + "/dashboard/environment/platforms/cert/upload",
						params: {
							envCode: currentScope.envCode,
							filename: $scope.formData.certificates[$scope.index[counter]].name,
							certType: $scope.index[counter],
							platform: platform,
							driver: driverName,
							access_token: access_token
						},
						file: $scope.formData.certificates[$scope.index[counter]],
						headers: {
							'soajsauth': soajsauthCookie,
							'key': dashKeyCookie
						}
					};

					Upload.upload(options).progress(function (evt) {
						var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
						progress.value = progressPercentage;
					}).success(function (response, status, headers, config) {
						if (!response.result) {
							currentScope.$parent.displayAlert('danger', response.errors.details[0].message);
							currentScope.listPlatforms(currentScope.envCode); //refresh view in case some files were uploaded successfully
							modal.close();
						}
						else {
							counter++;
							if (counter === Object.keys($scope.formData.certificates).length) {
								return cb();
							} else {
								$scope.uploadFiles(platform, driverName, counter, modal, cb);
							}
						}
					}).error(function (data, status, header, config) {
						currentScope.$parent.displayAlert('danger', translation.errorOccurredWhileUploadingFile[LANG] + " " + options.params.filename);
						modal.close();
					});
				}
			}
		});
	}

	function removeCert(currentScope, certId, platform, driverName) {
		getSendDataFromServer(currentScope, ngDataApi, {
			"method": "delete",
			"routeName": "/dashboard/environment/platforms/cert/delete",
			"params": {
				"id": certId,
				"env": currentScope.envCode,
				"driverName": platform + '.' + driverName
			}
		}, function (error, response) {
			if (error) {
				currentScope.$parent.displayAlert("danger", error.code, true, 'dashboard', error.message);
			} else {
				currentScope.$parent.displayAlert('success', translation.selectedCertificateRemoved[LANG]);
				currentScope.listPlatforms(currentScope.envCode);
			}
		});
	}

	function selectDriver(currentScope, platform, driverName, type) {
		var driver = type + "." + platform + '.' + driverName;
		getSendDataFromServer(currentScope, ngDataApi, {
			"method": "put",
			"routeName": "/dashboard/environment/platforms/driver/changeSelected",
			"params": {env: currentScope.envCode},
			"data": {selected: driver}
		}, function (error, response) {
			if (error) {
				currentScope.$parent.displayAlert("danger", error.code, true, 'dashboard', error.message);
			} else {
				currentScope.$parent.displayAlert('success', translation.selectedDriverUpdated[LANG]);
				currentScope.deployer.selected = platform + '.' + driverName;
				currentScope.deployer.platform = platform;
				currentScope.originalDeployer = currentScope.deployer.selected;
			}
		});
	}

	function changeDeployerType (currentScope) {
		//scope.allowSelect if type is container
		var postData = {
			deployerType: currentScope.deployer.type
		};
		getSendDataFromServer(currentScope, ngDataApi, {
			"method": "put",
			"routeName": "/dashboard/environment/platforms/deployer/type/change",
			"params": {
				env: currentScope.envCode
			},
			"data": postData
		}, function (error, response) {
			if (error) {
				currentScope.$parent.displayAlert("danger", error.code, true, 'dashboard', error.message);
			} else {
				currentScope.$parent.displayAlert('success', 'Deployer type changed successfully');
				currentScope.allowSelect = currentScope.deployer.type === 'container';
				currentScope.listPlatforms(currentScope.envCode);
			}
		});
	}

	function updateNamespaceConfig(currentScope, driver) {
		var currentConfig = currentScope.platforms.kubernetes[driver];
		var modal = $modal.open({
			templateUrl: "updateNamespaceConfig.tmpl",
			backdrop: true,
			keyboard: true,
			controller: function ($scope) {
				fixBackDrop();

				$scope.title = 'Update Namespace Configuration';
				$scope.namespaces = {
					ui: {
						selection: [
							{ value: 'existing', label: 'Choose Existing Namespace' },
							{ value: 'new', label: 'Create New Namespace' }
						],
						list: [],
						type: [
							{ value: 'global', label: 'Global' },
							{ value: 'perService', label: 'Per Service' }
						]
					},
					data: {
						selection: 'existing',
						default: currentConfig.namespace.default,
						type: ((currentConfig.namespace.perService) ? 'perService' : 'global')
					}
				};

				$scope.reset = function () {
					if ($scope.namespaces.data.selection === 'new') {
						$scope.namespaces.data.default = '';
					}
					else {
						$scope.namespaces.data.default = currentConfig.namespace.default;
					}
				};

				$scope.listNamespaces = function () {
					getSendDataFromServer(currentScope, ngDataApi, {
						method: 'get',
						routeName: '/dashboard/cloud/namespaces/list'
					}, function (error, namespaces) {
						if (error) {
							$scope.message = {
								danger: error.message
							};
							setTimeout(function () {
								$scope.message.danger = '';
							}, 5000);
						}
						else {
							namespaces.forEach(function (oneNamespace) {
								$scope.namespaces.ui.list.push({ value: oneNamespace.id, label: oneNamespace.name });
							});
						}
					});
				};

				$scope.onSubmit = function () {
					var newConfig = {
						namespace: {
							default: $scope.namespaces.data.default,
							perService: (($scope.namespaces.data.type.value === 'perService') ? true : false)
						}
					};
					getSendDataFromServer(currentScope, ngDataApi, {
						method: 'put',
						routeName: '/dashboard/environment/platforms/deployer/update',
						params: {
							env: currentScope.envCode.toLowerCase()
						},
						data: {
							driver: driver,
							config: newConfig
						}
					}, function (error, result) {
						if (error) {
							$scope.message = {
								danger: error.message
							};
							setTimeout(function () {
								$scope.message.danger = '';
							}, 5000);
						}
						else {
							$scope.namespaces.data = {};
							modal.close();
							currentScope.displayAlert('success', 'Namespace configuration updated successfully');
							currentScope.listPlatforms(currentScope.envCode);
						}
					});
				};

				$scope.closeModal = function () {
					$scope.namespaces.data = {};
					modal.close();
				};

				$scope.listNamespaces();
			}
		});
	}

	return {
		'listPlatforms': listPlatforms,
		'uploadCerts': uploadCerts,
		'removeCert': removeCert,
		'selectDriver': selectDriver,
		'changeDeployerType': changeDeployerType,
		'updateNamespaceConfig': updateNamespaceConfig
	}

}]);
<|endoftext|>


<commit_before>/*
---

name: Slider

description: Provides a slider control with a knob.

license: MIT-style license.

authors:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- More/Class.Refactor
	- More/Slider
	- Control

provides:
	- Slider

...
*/

/*
---

name: Scale

description:

license:

authors:
	- Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)

requires:
	- Init

provides:
	- Scale

...
*/

/**
 * @see    http://moobilejs.com/doc/latest/Control/Slider
 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
 * @edited 0.2.0
 * @since  0.1.0
 */
Moobile.Slider = new Class({

	Extends: Moobile.Component,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_activeTouch: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_activeTouchOffsetX: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_activeTouchOffsetY: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_activeTouchInitialThumbX: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_activeTouchInitialThumbY: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_mode: 'horizontal',

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_position: {x: -1, y: -1},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1.0
	 */
	_value: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_valueRange: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_trackRange: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_trackLimit: {min: 0, max: 0},

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#trackElement
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1.0
	 */
	trackElement: null,

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#thumbElement
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1.0
	 */
	thumbElement: null,

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#hitAreaElement
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	hitAreaElement: null,

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#options
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @edited 0.2.0
	 * @since  0.1.0
	 */
	options: {
		value: 0,
		mode: null,
		snap: false,
		min: 0,
		max: 100
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @edited 0.2.0
	 * @since  0.1.0
	 */
	willBuild: function() {

		this.parent();

		this.element.addClass('slider');

		this.trackElement = document.createElement('div');
		this.trackElement.addClass('slider-track');
		this.trackElement.inject(this.element);

		this.thumbElement = document.createElement('div')
		this.thumbElement.addClass('slider-thumb');
		this.thumbElement.inject(this.trackElement);

		this.rangeElement = document.createElement('div');
		this.rangeElement.addClass('slider-range');
		this.rangeElement.inject(this.trackElement);

		this.valueElement = document.createElement('div');
		this.valueElement.addClass('slider-value');
		this.valueElement.inject(this.rangeElement);

		this.hitAreaElement = new Element('div.hit-area').inject(this.thumbElement);

		var mode = this.options.mode;
		if (mode) {
			this.element.addClass('slider-mode-' + mode);
		}

		this._mode = mode || 'horizontal';
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @edited 0.2.0
	 * @since  0.1.0
	 */
	didBuild: function() {

		this.parent();

		this.element.addEvent('touchstart', this.bound('_onTouchStart'));
		this.element.addEvent('touchmove', this.bound('_onTouchMove'));
		this.element.addEvent('touchend', this.bound('_onTouchEnd'));

		this.thumbElement.addEvent('touchcancel', this.bound('_onThumbTouchCancel'));
		this.thumbElement.addEvent('touchstart', this.bound('_onThumbTouchStart'));
		this.thumbElement.addEvent('touchmove', this.bound('_onThumbTouchMove'));
		this.thumbElement.addEvent('touchend', this.bound('_onThumbTouchEnd'));
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @edited 0.2.0
	 * @since  0.1.0
	 */
	didBecomeReady: function() {
		this.parent();
		this.refresh();
		this.setValue(this.options.value);
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1.0
	 */
	destroy: function() {

		this.element.removeEvent('touchstart', this.bound('_onTouchStart'));
		this.element.removeEvent('touchmove', this.bound('_onTouchMove'));
		this.element.removeEvent('touchend', this.bound('_onTouchEnd'));

		this.thumbElement.removeEvent('touchcancel', this.bound('_onThumbTouchCancel'));
		this.thumbElement.removeEvent('touchstart', this.bound('_onThumbTouchStart'));
		this.thumbElement.removeEvent('touchmove', this.bound('_onThumbTouchMove'));
		this.thumbElement.removeEvent('touchend', this.bound('_onThumbTouchEnd'));

		this.thumbElement = null;
		this.trackElement = null;
		this.valueElement = null;
		this.rangeElement = null;

		this.parent();
	},

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#setValue
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @edited 0.2.0
	 * @since  0.1.0
	 */
	setValue: function(value) {
		var pos = this._positionFromValue(value);
		this._move(pos.x, pos.y);
		return this;
	},

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#setValue
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1.0
	 */
	getValue: function() {
		return this._value;
	},

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#refresh
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	refresh: function() {

		var trackSize = this.trackElement.getSize();
		var thumbSize = this.thumbElement.getSize();

		var range = 0;

		switch (this._mode) {
			case 'horizontal':
				range = trackSize.x - thumbSize.x;
				break;
			case 'vertical':
				range = trackSize.y - thumbSize.y;
				break;
		}

		this._valueRange = this.options.max - this.options.min;
		this._trackRange = range;
		this._trackLimit = {
			min: 0,
			max: range
		};

		return this;
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_move: function(x, y) {

		switch (this._mode) {
			case 'horizontal':
				y = 0;
				if (x < this._trackLimit.min) x = this._trackLimit.min;
				if (x > this._trackLimit.max) x = this._trackLimit.max;
				break;
			case 'vertical':
				x = 0;
				if (y < this._trackLimit.min) y = this._trackLimit.min;
				if (y > this._trackLimit.max) y = this._trackLimit.max;
				break;
		}

		var value = this._valueFromPosition(x, y);

		if (this.options.snap) {
			value = value.round();
			var pos = this._positionFromValue(value);
			x = pos.x;
			y = pos.y;
		}

		if (this._position.x === x &&
			this._position.y === y) {
			return this;
		}

		this._value = value;

		this._position.x = x;
		this._position.y = y;
		this.thumbElement.setStyle('transform', 'translateX(' + x + 'px) translateY(' + y + 'px)');
		this.valueElement.setStyle('transform', 'translateX(' + x + 'px) translateY(' + y + 'px)');

		this.fireEvent('change', value);

		return this;
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_valueFromPosition: function(x, y) {
		return (this._mode === 'horizontal' ? x : y) * this._valueRange / this._trackRange + this.options.min;
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_positionFromValue: function(value) {

		var x = 0;
		var y = 0;

		var pos = (value - this.options.min) * this._trackRange / this._valueRange;

		switch (this._mode) {
			case 'horizontal': x = pos.round(2); break;
			case 'vertical':   y = pos.round(2); break;
		}

		return {x: x, y: y};
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onTouchStart: function(e) {
		e.stop();
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onTouchMove: function(e) {
		e.stop();
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onTouchEnd: function(e) {
		e.stop();
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onThumbTouchCancel: function(e) {
		this._activeTouch = null;
		this._activeTouchOffsetX = null;
		this._activeTouchOffsetY = null;
		this._activeTouchInitialThumbX = null;
		this._activeTouchInitialThumbY = null;
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onThumbTouchStart: function(e) {
		var touch = e.changedTouches[0];
		if (this._activeTouch === null) {
			this._activeTouch = touch
			this._activeTouchOffsetX = touch.pageX;
			this._activeTouchOffsetY = touch.pageY;
			this._activeTouchInitialThumbX = this._position.x;
			this._activeTouchInitialThumbY = this._position.y;
			this._bounds = {
				min: 0,
				max: this._trackRange
			};
		}
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onThumbTouchMove: function(e) {
		var touch = e.changedTouches[0];
		if (this._activeTouch.identifier === touch.identifier) {
			var x = touch.pageX - this._activeTouchOffsetX + this._activeTouchInitialThumbX;
			var y = touch.pageY - this._activeTouchOffsetY + this._activeTouchInitialThumbY;
			this._move(x, y);
		}
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onThumbTouchEnd: function(e) {
		if (this._activeTouch.identifier === e.changedTouches[0].identifier) {
			this._activeTouch = null;
			this._activeTouchOffsetX = null;
			this._activeTouchOffsetY = null;
			this._activeTouchInitialThumbX = null;
			this._activeTouchInitialThumbY = null;
		}
	}

});

//------------------------------------------------------------------------------
// Roles
//------------------------------------------------------------------------------

Moobile.Component.defineRole('slider', null, function(element) {
	this.addChildComponent(Moobile.Component.create(Moobile.Slider, element, 'data-slider'));
});
<commit_msg>Using translate3d, with iOS 6 translateX does not seem to be hardware accelerated<commit_after>/*
---

name: Slider

description: Provides a slider control with a knob.

license: MIT-style license.

authors:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- More/Class.Refactor
	- More/Slider
	- Control

provides:
	- Slider

...
*/

/*
---

name: Scale

description:

license:

authors:
	- Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)

requires:
	- Init

provides:
	- Scale

...
*/

/**
 * @see    http://moobilejs.com/doc/latest/Control/Slider
 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
 * @edited 0.2.0
 * @since  0.1.0
 */
Moobile.Slider = new Class({

	Extends: Moobile.Component,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_activeTouch: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_activeTouchOffsetX: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_activeTouchOffsetY: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_activeTouchInitialThumbX: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_activeTouchInitialThumbY: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_mode: 'horizontal',

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_position: {x: -1, y: -1},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1.0
	 */
	_value: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_valueRange: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_trackRange: null,

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_trackLimit: {min: 0, max: 0},

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#trackElement
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1.0
	 */
	trackElement: null,

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#thumbElement
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1.0
	 */
	thumbElement: null,

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#hitAreaElement
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	hitAreaElement: null,

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#options
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @edited 0.2.0
	 * @since  0.1.0
	 */
	options: {
		value: 0,
		mode: null,
		snap: false,
		min: 0,
		max: 100
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @edited 0.2.0
	 * @since  0.1.0
	 */
	willBuild: function() {

		this.parent();

		this.element.addClass('slider');

		this.trackElement = document.createElement('div');
		this.trackElement.addClass('slider-track');
		this.trackElement.inject(this.element);

		this.thumbElement = document.createElement('div')
		this.thumbElement.addClass('slider-thumb');
		this.thumbElement.inject(this.trackElement);

		this.rangeElement = document.createElement('div');
		this.rangeElement.addClass('slider-range');
		this.rangeElement.inject(this.trackElement);

		this.valueElement = document.createElement('div');
		this.valueElement.addClass('slider-value');
		this.valueElement.inject(this.rangeElement);

		this.hitAreaElement = new Element('div.hit-area').inject(this.thumbElement);

		var mode = this.options.mode;
		if (mode) {
			this.element.addClass('slider-mode-' + mode);
		}

		this._mode = mode || 'horizontal';
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @edited 0.2.0
	 * @since  0.1.0
	 */
	didBuild: function() {

		this.parent();

		this.element.addEvent('touchstart', this.bound('_onTouchStart'));
		this.element.addEvent('touchmove', this.bound('_onTouchMove'));
		this.element.addEvent('touchend', this.bound('_onTouchEnd'));

		this.thumbElement.addEvent('touchcancel', this.bound('_onThumbTouchCancel'));
		this.thumbElement.addEvent('touchstart', this.bound('_onThumbTouchStart'));
		this.thumbElement.addEvent('touchmove', this.bound('_onThumbTouchMove'));
		this.thumbElement.addEvent('touchend', this.bound('_onThumbTouchEnd'));
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @edited 0.2.0
	 * @since  0.1.0
	 */
	didBecomeReady: function() {
		this.parent();
		this.refresh();
		this.setValue(this.options.value);
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1.0
	 */
	destroy: function() {

		this.element.removeEvent('touchstart', this.bound('_onTouchStart'));
		this.element.removeEvent('touchmove', this.bound('_onTouchMove'));
		this.element.removeEvent('touchend', this.bound('_onTouchEnd'));

		this.thumbElement.removeEvent('touchcancel', this.bound('_onThumbTouchCancel'));
		this.thumbElement.removeEvent('touchstart', this.bound('_onThumbTouchStart'));
		this.thumbElement.removeEvent('touchmove', this.bound('_onThumbTouchMove'));
		this.thumbElement.removeEvent('touchend', this.bound('_onThumbTouchEnd'));

		this.thumbElement = null;
		this.trackElement = null;
		this.valueElement = null;
		this.rangeElement = null;

		this.parent();
	},

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#setValue
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @edited 0.2.0
	 * @since  0.1.0
	 */
	setValue: function(value) {
		var pos = this._positionFromValue(value);
		this._move(pos.x, pos.y);
		return this;
	},

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#setValue
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1.0
	 */
	getValue: function() {
		return this._value;
	},

	/**
	 * @see    http://moobilejs.com/doc/latest/Control/Slider#refresh
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	refresh: function() {

		var trackSize = this.trackElement.getSize();
		var thumbSize = this.thumbElement.getSize();

		var range = 0;

		switch (this._mode) {
			case 'horizontal':
				range = trackSize.x - thumbSize.x;
				break;
			case 'vertical':
				range = trackSize.y - thumbSize.y;
				break;
		}

		this._valueRange = this.options.max - this.options.min;
		this._trackRange = range;
		this._trackLimit = {
			min: 0,
			max: range
		};

		return this;
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_move: function(x, y) {

		switch (this._mode) {
			case 'horizontal':
				y = 0;
				if (x < this._trackLimit.min) x = this._trackLimit.min;
				if (x > this._trackLimit.max) x = this._trackLimit.max;
				break;
			case 'vertical':
				x = 0;
				if (y < this._trackLimit.min) y = this._trackLimit.min;
				if (y > this._trackLimit.max) y = this._trackLimit.max;
				break;
		}

		var value = this._valueFromPosition(x, y);

		if (this.options.snap) {
			value = value.round();
			var pos = this._positionFromValue(value);
			x = pos.x;
			y = pos.y;
		}

		if (this._position.x === x &&
			this._position.y === y) {
			return this;
		}

		this._value = value;

		this._position.x = x;
		this._position.y = y;
		this.thumbElement.setStyle('transform', 'translate3d(' + x + 'px, ' + y + 'px, 0)');
		this.valueElement.setStyle('transform', 'translate3d(' + x + 'px, ' + y + 'px, 0)');

		this.fireEvent('change', value);

		return this;
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_valueFromPosition: function(x, y) {
		return (this._mode === 'horizontal' ? x : y) * this._valueRange / this._trackRange + this.options.min;
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_positionFromValue: function(value) {

		var x = 0;
		var y = 0;

		var pos = (value - this.options.min) * this._trackRange / this._valueRange;

		switch (this._mode) {
			case 'horizontal': x = pos.round(2); break;
			case 'vertical':   y = pos.round(2); break;
		}

		return {x: x, y: y};
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onTouchStart: function(e) {
		e.stop();
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onTouchMove: function(e) {
		e.stop();
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onTouchEnd: function(e) {
		e.stop();
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onThumbTouchCancel: function(e) {
		this._activeTouch = null;
		this._activeTouchOffsetX = null;
		this._activeTouchOffsetY = null;
		this._activeTouchInitialThumbX = null;
		this._activeTouchInitialThumbY = null;
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onThumbTouchStart: function(e) {
		var touch = e.changedTouches[0];
		if (this._activeTouch === null) {
			this._activeTouch = touch
			this._activeTouchOffsetX = touch.pageX;
			this._activeTouchOffsetY = touch.pageY;
			this._activeTouchInitialThumbX = this._position.x;
			this._activeTouchInitialThumbY = this._position.y;
			this._bounds = {
				min: 0,
				max: this._trackRange
			};
		}
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onThumbTouchMove: function(e) {
		var touch = e.changedTouches[0];
		if (this._activeTouch.identifier === touch.identifier) {
			var x = touch.pageX - this._activeTouchOffsetX + this._activeTouchInitialThumbX;
			var y = touch.pageY - this._activeTouchOffsetY + this._activeTouchInitialThumbY;
			this._move(x, y);
		}
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onThumbTouchEnd: function(e) {
		if (this._activeTouch.identifier === e.changedTouches[0].identifier) {
			this._activeTouch = null;
			this._activeTouchOffsetX = null;
			this._activeTouchOffsetY = null;
			this._activeTouchInitialThumbX = null;
			this._activeTouchInitialThumbY = null;
		}
	}

});

//------------------------------------------------------------------------------
// Roles
//------------------------------------------------------------------------------

Moobile.Component.defineRole('slider', null, function(element) {
	this.addChildComponent(Moobile.Component.create(Moobile.Slider, element, 'data-slider'));
});
<|endoftext|>