<commit_before>'use strict';

var request = require('request');
var assert = require('assert');
var config = require('../config');

var SUPPORTED_CURRENCIES = ['USD', 'CAD'];
var SUPPORTED_FINANCIAL_TYPES = ['checking', 'savings'];

function Vogogo(options) {
  checkOptions(options);

  this.clientId = options.clientId;
  this.clientSecret = options.clientSecret;

  this.apiPrefix = options.apiPrefix || config.environments.production.apiPrefix;
}

function checkOptions(options) {
  assert(options.clientId, 'you must supply a clientId in the constructor options');
  assert(options.clientSecret, 'you must supply a clientSecret in the constructor options');
  assert(typeof options.clientId === 'string', 'clientId must be a string');
  assert(typeof options.clientSecret === 'string', 'clientSecret must be a string');

  if (options.apiPrefix) {
    assert(typeof options.apiPrefix === 'string', 'apiPrefix must be a string');
  }
}

Vogogo.prototype.pay = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;
  var url = '/pay';
  self._post(url, params, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode === 403) {
      return callback(new Error('403 FORBIDDEN - ' + body.error_message));
    }

    if (res.statusCode === 409) {
      return callback(new Error('409 CONFLICT - ' + body.error_message));
    }

    if (res.statusCode !== 200 && res.statusCode !== 201) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    callback();
  });

  function validateParams(params) {
    assert(params.id !== undefined, 'id is a required parameter');
    assert(params.account_id !== undefined, 'account_id is a required parameter');
    assert(params.amount !== undefined, 'amount is a required parameter');
    assert(params.currency !== undefined, 'currency is a required parameter');
    assert(params.ip !== undefined, 'ip is a required parameter');
    assert(params.customerAccessToken, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');

    assert(typeof params.id === 'string', 'id must be a string');
    assert(params.id.length <= 36, 'id must be 36 characters or less');
    assert(typeof params.account_id === 'string', 'account_id must be a string');
    var amount = parseFloat(params.amount);
    assert(!isNaN(amount) && isFinite(amount) && amount > 0, 'invalid amount');
    assert(typeof params.currency === 'string', 'currency must be a string');
    assert(SUPPORTED_CURRENCIES.indexOf(params.currency) !== -1, params.currency + ' is not a supported currency');
    assert(typeof params.ip === 'string', 'ip must be a string');
    assert(params.ip.length <= 32, 'ip must be 32 characters or less');
  }
};

Vogogo.prototype.getTransaction = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;
  var url = '/transactions/' + params.id;
  self._get(url, {}, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode !== 200) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    callback(null, body);
  });

  function validateParams(params) {
    assert(params.id, 'id is a required parameter');
    assert(typeof params.id === 'string', 'id must be a string');
    assert(params.customerAccessToken, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');
  }
};

Vogogo.prototype.listTransactions = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;
  var url = '/transactions';
  self._get(url, params, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode !== 200) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    if (!body.transactions) {
      return callback(new Error('no transactions array in response from Vogogo'));
    }

    callback(null, body.transactions);
  });

  function validateParams(params) {
    if (params.currency) {
      assert(SUPPORTED_CURRENCIES.indexOf(params.currency) !== -1, params.currency + ' is not a supported currency');
    }
    assert(params.customerAccessToken, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');
  }
};

Vogogo.prototype.addBankAccount = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;
  var url = '/accounts';
  self._post(url, params, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode !== 200 && res.statusCode !== 201) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    callback(null, body);
  });

  function validateParams(params) {
    assert(params.name, 'name is a required parameter');
    assert(typeof params.name === 'string' && params.name.length <= 50, 'invalid name');
    assert(params.number, 'number is a required parameter');
    assert(params.currency, 'currency is a required parameter');
    assert(SUPPORTED_CURRENCIES.indexOf(params.currency) !== -1, 'invalid currency');
    assert(params.financial_type, 'financial_type is a required parameter');
    assert(SUPPORTED_FINANCIAL_TYPES.indexOf(params.financial_type) !== -1, 'invalid financial_type');
    assert(params.customerAccessToken, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');

    if (params.currency === 'USD') {
      assert(params.routing, 'routing is a required parameter for USD accounts');
      assert(typeof params.routing === 'string' && params.routing.length === 9, 'invalid routing');
      assert(typeof params.number === 'string' && params.number.length >= 6 && params.number.length <= 17,
        'invalid number');
    }

    if (params.currency === 'CAD') {
      assert(params.institution, 'institution is a required parameter for CAD accounts');
      assert(typeof params.institution === 'string' && params.institution.length === 3, 'invalid institution');
      assert(params.transit, 'transit is a required parameter for CAD accounts');
      assert(typeof params.transit === 'string' && params.transit.length === 5, 'invalid transit');
      assert(typeof params.number === 'string' && params.number.length >= 7 && params.number.length <= 15,
        'invalid number');
    }
  }
};

Vogogo.prototype.createCustomer = function(params, callback) {
  var self = this;
  validateParams(params);

  var url = '/customers';
  self._post(url, params, {}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode === 403) {
      return callback(new Error('403 FORBIDDEN - ' + body.error_message));
    }

    if (res.statusCode !== 200 && res.statusCode !== 201) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    callback(null, body);
  });

  function validateParams(params) {
    assert(params.address_city !== undefined, 'address_city is a required param');
    assert(params.address_country !== undefined, 'address_country is a required param');
    assert(params.address_postal_code !== undefined, 'address_postal_code is a required param');
    assert(params.address_state !== undefined, 'address_state is a required param');
    assert(params.address_street_1 !== undefined, 'address_street_1 is a required param');
    assert(params.cell_phone_country !== undefined, 'cell_phone_country is a required param');
    assert(params.cell_phone !== undefined, 'cell_phone is a required param');
    assert(params.ip !== undefined, 'ip is a required param');
    assert(params.is_business !== undefined, 'is_business is a required param');
    assert(params.email !== undefined, 'email is a required param');
    assert(params.last_name !== undefined, 'last_name is a required param');
    assert(params.first_name !== undefined, 'first_name is a required param');
    assert(params.date_of_birth !== undefined, 'date_of_birth is a required param');
    if (params.address_country === 'CA') {
      assert(params.occupation_id !== undefined, 'occupation_id is a required param for Canadian customers');
    }
  }
};

Vogogo.prototype.getAccounts = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;
  var url = '/accounts';
  self._get(url, params, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode !== 200) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    if (!body.accounts) {
      return callback(new Error('no accounts array in response from Vogogo'));
    }

    callback(null, body.accounts);
  });

  function validateParams(params) {
    assert(params.currency, 'currency is a required parameter');
    assert(SUPPORTED_CURRENCIES.indexOf(params.currency) !== -1, 'invalid currency');
    assert(params.customerAccessToken, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');
  }
};

Vogogo.prototype.verifyMicroDeposit = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;

  var url = '/accounts/' + params.id + '/verify';

  self._post(url, params, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode !== 200) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    if (body.status !== 'verified') {
      return callback(new Error('account not verified - status: ' + body.status));
    }

    callback();
  });

  function validateParams(params) {
    assert(params.id !== undefined, 'id is a required parameter');
    assert(typeof params.id === 'string', 'id must be a string');
    assert(params.amount !== undefined, 'amount is a required parameter');
    var amount = parseFloat(params.amount);
    assert(!isNaN(amount) && isFinite(amount) && amount > 0, 'invalid amount');
    assert(params.customerAccessToken, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');
  }
};

/**
* HTTP basic auth
*/
Vogogo.prototype._generateAuthToken = function(params) {
  var username = this.clientSecret;
  var password = (params && params.customerAccessToken) || '';
  var userpass = username + ':' + password;
  var encodedUserPass = new Buffer(userpass, 'UTF-8').toString('base64');
  var authToken = 'Basic ' + encodedUserPass;
  return authToken;
};

Vogogo.prototype._post = function(url, params, authParams, callback) {
  request.post({
    url: this.apiPrefix + url,
    headers: {
      Authorization: this._generateAuthToken(authParams),
      'Content-Type': 'application/json'
    },
    qs: params
  }, function(err, res, body) {
    if (body) {
      try {
        body = JSON.parse(body);
      } catch(e) {
        return callback(new Error('failed to parse response from Vogogo'));
      }
    }

    callback(err, res, body);
  });
};

Vogogo.prototype._get = function(url, params, authParams, callback) {
  request.get({
    url: this.apiPrefix + url,
    headers: {
      'Authorization': this._generateAuthToken(authParams),
      'Content-Type': 'application/json'
    },
    qs: params
  }, function(err, res, body) {
    if (body) {
      try {
        body = JSON.parse(body);
      } catch(e) {
        return callback(new Error('failed to parse response from Vogogo'));
      }
    }

    callback(err, res, body);
  });
};

module.exports = Vogogo;
<commit_msg>truthiness<commit_after>'use strict';

var request = require('request');
var assert = require('assert');
var config = require('../config');

var SUPPORTED_CURRENCIES = ['USD', 'CAD'];
var SUPPORTED_FINANCIAL_TYPES = ['checking', 'savings'];

function Vogogo(options) {
  checkOptions(options);

  this.clientId = options.clientId;
  this.clientSecret = options.clientSecret;

  this.apiPrefix = options.apiPrefix || config.environments.production.apiPrefix;
}

function checkOptions(options) {
  assert(options.clientId !== undefined, 'you must supply a clientId in the constructor options');
  assert(options.clientSecret !== undefined, 'you must supply a clientSecret in the constructor options');
  assert(typeof options.clientId === 'string', 'clientId must be a string');
  assert(typeof options.clientSecret === 'string', 'clientSecret must be a string');

  if (options.apiPrefix) {
    assert(typeof options.apiPrefix === 'string', 'apiPrefix must be a string');
  }
}

Vogogo.prototype.pay = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;
  var url = '/pay';
  self._post(url, params, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode === 403) {
      return callback(new Error('403 FORBIDDEN - ' + body.error_message));
    }

    if (res.statusCode === 409) {
      return callback(new Error('409 CONFLICT - ' + body.error_message));
    }

    if (res.statusCode !== 200 && res.statusCode !== 201) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    callback();
  });

  function validateParams(params) {
    assert(params.id !== undefined, 'id is a required parameter');
    assert(params.account_id !== undefined, 'account_id is a required parameter');
    assert(params.amount !== undefined, 'amount is a required parameter');
    assert(params.currency !== undefined, 'currency is a required parameter');
    assert(params.ip !== undefined, 'ip is a required parameter');
    assert(params.customerAccessToken !== undefined, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');

    assert(typeof params.id === 'string', 'id must be a string');
    assert(params.id.length <= 36, 'id must be 36 characters or less');
    assert(typeof params.account_id === 'string', 'account_id must be a string');
    var amount = parseFloat(params.amount);
    assert(!isNaN(amount) && isFinite(amount) && amount > 0, 'invalid amount');
    assert(typeof params.currency === 'string', 'currency must be a string');
    assert(SUPPORTED_CURRENCIES.indexOf(params.currency) !== -1, params.currency + ' is not a supported currency');
    assert(typeof params.ip === 'string', 'ip must be a string');
    assert(params.ip.length <= 32, 'ip must be 32 characters or less');
  }
};

Vogogo.prototype.getTransaction = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;
  var url = '/transactions/' + params.id;
  self._get(url, {}, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode !== 200) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    callback(null, body);
  });

  function validateParams(params) {
    assert(params.id !== undefined, 'id is a required parameter');
    assert(typeof params.id === 'string', 'id must be a string');
    assert(params.customerAccessToken !== undefined, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');
  }
};

Vogogo.prototype.listTransactions = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;
  var url = '/transactions';
  self._get(url, params, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode !== 200) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    if (!body.transactions) {
      return callback(new Error('no transactions array in response from Vogogo'));
    }

    callback(null, body.transactions);
  });

  function validateParams(params) {
    if (params.currency) {
      assert(SUPPORTED_CURRENCIES.indexOf(params.currency) !== -1, params.currency + ' is not a supported currency');
    }
    assert(params.customerAccessToken !== undefined, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');
  }
};

Vogogo.prototype.addBankAccount = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;
  var url = '/accounts';
  self._post(url, params, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode !== 200 && res.statusCode !== 201) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    callback(null, body);
  });

  function validateParams(params) {
    assert(params.name !== undefined, 'name is a required parameter');
    assert(typeof params.name === 'string' && params.name.length <= 50, 'invalid name');
    assert(params.number !== undefined, 'number is a required parameter');
    assert(params.currency !== undefined, 'currency is a required parameter');
    assert(SUPPORTED_CURRENCIES.indexOf(params.currency) !== -1, 'invalid currency');
    assert(params.financial_type !== undefined, 'financial_type is a required parameter');
    assert(SUPPORTED_FINANCIAL_TYPES.indexOf(params.financial_type) !== -1, 'invalid financial_type');
    assert(params.customerAccessToken !== undefined, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');

    if (params.currency === 'USD') {
      assert(params.routing !== undefined, 'routing is a required parameter for USD accounts');
      assert(typeof params.routing === 'string' && params.routing.length === 9, 'invalid routing');
      assert(typeof params.number === 'string' && params.number.length >= 6 && params.number.length <= 17,
        'invalid number');
    }

    if (params.currency === 'CAD') {
      assert(params.institution !== undefined, 'institution is a required parameter for CAD accounts');
      assert(typeof params.institution === 'string' && params.institution.length === 3, 'invalid institution');
      assert(params.transit !== undefined, 'transit is a required parameter for CAD accounts');
      assert(typeof params.transit === 'string' && params.transit.length === 5, 'invalid transit');
      assert(typeof params.number === 'string' && params.number.length >= 7 && params.number.length <= 15,
        'invalid number');
    }
  }
};

Vogogo.prototype.createCustomer = function(params, callback) {
  var self = this;
  validateParams(params);

  var url = '/customers';
  self._post(url, params, {}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode === 403) {
      return callback(new Error('403 FORBIDDEN - ' + body.error_message));
    }

    if (res.statusCode !== 200 && res.statusCode !== 201) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    callback(null, body);
  });

  function validateParams(params) {
    assert(params.address_city !== undefined, 'address_city is a required param');
    assert(params.address_country !== undefined, 'address_country is a required param');
    assert(params.address_postal_code !== undefined, 'address_postal_code is a required param');
    assert(params.address_state !== undefined, 'address_state is a required param');
    assert(params.address_street_1 !== undefined, 'address_street_1 is a required param');
    assert(params.cell_phone_country !== undefined, 'cell_phone_country is a required param');
    assert(params.cell_phone !== undefined, 'cell_phone is a required param');
    assert(params.ip !== undefined, 'ip is a required param');
    assert(params.is_business !== undefined, 'is_business is a required param');
    assert(params.email !== undefined, 'email is a required param');
    assert(params.last_name !== undefined, 'last_name is a required param');
    assert(params.first_name !== undefined, 'first_name is a required param');
    assert(params.date_of_birth !== undefined, 'date_of_birth is a required param');
    if (params.address_country === 'CA') {
      assert(params.occupation_id !== undefined, 'occupation_id is a required param for Canadian customers');
    }
  }
};

Vogogo.prototype.getAccounts = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;
  var url = '/accounts';
  self._get(url, params, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode !== 200) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    if (!body.accounts) {
      return callback(new Error('no accounts array in response from Vogogo'));
    }

    callback(null, body.accounts);
  });

  function validateParams(params) {
    assert(params.currency !== undefined, 'currency is a required parameter');
    assert(SUPPORTED_CURRENCIES.indexOf(params.currency) !== -1, 'invalid currency');
    assert(params.customerAccessToken !== undefined, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');
  }
};

Vogogo.prototype.verifyMicroDeposit = function(params, callback) {
  var self = this;
  validateParams(params);
  var customerAccessToken = params.customerAccessToken;
  delete params.customerAccessToken;

  var url = '/accounts/' + params.id + '/verify';

  self._post(url, params, {customerAccessToken: customerAccessToken}, function(err, res, body) {
    if (err) {
      return callback(err);
    }

    if (res.statusCode !== 200) {
      return callback(new Error('bad status code: ' + res.statusCode + ' - ' + body.error_message));
    }

    if (body.status !== 'verified') {
      return callback(new Error('account not verified - status: ' + body.status));
    }

    callback();
  });

  function validateParams(params) {
    assert(params.id !== undefined, 'id is a required parameter');
    assert(typeof params.id === 'string', 'id must be a string');
    assert(params.amount !== undefined, 'amount is a required parameter');
    var amount = parseFloat(params.amount);
    assert(!isNaN(amount) && isFinite(amount) && amount > 0, 'invalid amount');
    assert(params.customerAccessToken, 'customerAccessToken is a required parameter');
    assert(typeof params.customerAccessToken === 'string', 'customerAccessToken must be a string');
  }
};

/**
* HTTP basic auth
*/
Vogogo.prototype._generateAuthToken = function(params) {
  var username = this.clientSecret;
  var password = (params && params.customerAccessToken) || '';
  var userpass = username + ':' + password;
  var encodedUserPass = new Buffer(userpass, 'UTF-8').toString('base64');
  var authToken = 'Basic ' + encodedUserPass;
  return authToken;
};

Vogogo.prototype._post = function(url, params, authParams, callback) {
  request.post({
    url: this.apiPrefix + url,
    headers: {
      Authorization: this._generateAuthToken(authParams),
      'Content-Type': 'application/json'
    },
    qs: params
  }, function(err, res, body) {
    if (body) {
      try {
        body = JSON.parse(body);
      } catch(e) {
        return callback(new Error('failed to parse response from Vogogo'));
      }
    }

    callback(err, res, body);
  });
};

Vogogo.prototype._get = function(url, params, authParams, callback) {
  request.get({
    url: this.apiPrefix + url,
    headers: {
      'Authorization': this._generateAuthToken(authParams),
      'Content-Type': 'application/json'
    },
    qs: params
  }, function(err, res, body) {
    if (body) {
      try {
        body = JSON.parse(body);
      } catch(e) {
        return callback(new Error('failed to parse response from Vogogo'));
      }
    }

    callback(err, res, body);
  });
};

module.exports = Vogogo;
<|endoftext|>


<commit_before>/*global define $ TweenMax Quad Quint TimelineMax iScroll Linear*/

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

define([], function (require) {

    var FilterElement;

    FilterElement = function (element, scroll) {
        var instance = this,
            $el = $(element),
            $body,
            $container,
            $filterEl,
            $resolveEl,
            filterPath = 'assets/shaders/',
            opening = false,
            timeline,
            foldtimeline,
            unfoldTween,
            closeTween,
            openTween,
            filter = {},
            animating = false,
            dragging = false,
            deltaMidpoint = {x: 0, y: 0},
            deltaDistance = 0,
            deltaAngle = 0,
            deltaRotation = 0,
            SCALE_DIVIDER = 100,
            basefilter = {
                ambient: 1,
                vert: filterPath + 'max-fold.vs',
                frag: filterPath + 'max-fold.fs',
                x: $el.data('filter-x'),
                y: $el.data('filter-y'),
                z: 0,
                scale: 0.93,//0.93,
                rotateY: -90,
                rotateX: 0,
                rotateZ: 0
            };

        function getAngle(p1, p2) {
            var angle,
                dx, dy;

            dx = p1.x - p2.x;
            dy = p1.y - p2.y;
            angle = Math.atan2(dy, dx) * 180 / Math.PI;

            return angle;
        }

        function getMidpoint(p1, p2) {
            var midpoint = {};

            midpoint.x = (p1.x + p2.x) / 2;
            midpoint.y = (p1.y + p2.y) / 2;

            return midpoint;
        }

        function getDistance(p1, p2) {
            var distance,
                dx, dy;

            dx = p1.x - p2.x;
            dy = p1.y - p2.y;
            distance = Math.sqrt(dx * dx + dy * dy);

            return distance;
        }

        function resetFilter() {
            for (var i in basefilter) {
                filter[i] = basefilter[i];
            }
        }

        function updateFilter() {
            $filterEl.css({
                'webkitFilter':
                    'custom(url(' + filter.vert + ') mix(url(' + filter.frag + ') multiply source-atop), 20 8 border-box, ' +
                    'ambientLight ' + filter.ambient + ', ' +
                    'perspective 5000, ' +
                    'translation ' + filter.x + ' ' + filter.y + ' 0, ' +
                    'rotation ' + filter.rotateX + ' ' + filter.rotateY + ' ' + filter.rotateZ + ', ' +
                    'scale ' + filter.scale + ', ' +
                    'lightPosition 0 0 1, ' +
                    'anchorIndex 10, ' +
                    'a0 ' + filter.a[0].value + ', ' +
                    'a1 ' + filter.a[1].value + ', ' +
                    'a2 ' + filter.a[2].value + ', ' +
                    'a3 ' + filter.a[3].value + ', ' +
                    'a4 ' + filter.a[4].value + ', ' +
                    'a5 ' + filter.a[5].value + ', ' +
                    'a6 ' + filter.a[6].value + ', ' +
                    'a7 ' + filter.a[7].value + ', ' +
                    'a8 ' + filter.a[8].value + ', ' +
                    'a9 ' + filter.a[9].value + ', ' +
                    'a10 ' + filter.a[10].value + ', ' +
                    'a11 ' + filter.a[11].value + ', ' +
                    'a12 ' + filter.a[12].value + ', ' +
                    'a13 ' + filter.a[13].value + ', ' +
                    'a14 ' + filter.a[14].value + ', ' +
                    'a15 ' + filter.a[15].value + ', ' +
                    'a16 ' + filter.a[16].value + ', ' +
                    'a17 ' + filter.a[17].value + ', ' +
                    'a18 ' + filter.a[18].value + ', ' +
                    'a19 ' + filter.a[19].value + ')'
            });
        }

        function addContainer() {
            $container = $('<div>');
            $container.addClass('transition-container');
            $body.append($container);
        }

        function addTimeline() {
            var i,
                key,
                time,
                delay;

            //fold
            foldtimeline = new TimelineMax();
            foldtimeline.insert(new TweenMax.to(filter.a[9], 1, {value: -70}));
            foldtimeline.insert(new TweenMax.to(filter.a[10], 1, {value: 70}));

            foldtimeline.insert(new TweenMax.to(filter.a[9], 2, {value: 0, delay: 1}));
            foldtimeline.insert(new TweenMax.to(filter.a[10], 2, {value: 0, delay: 1}));

            for (i = 0; i < 20; i += 1) {
                if (i < 9) {
                    foldtimeline.insert(new TweenMax.fromTo(filter.a[i], 1, {value: 0}, {value: 9 - i}));
                    foldtimeline.insert(new TweenMax.to(filter.a[i], 2, {value: 0, delay: 1}));
                } else if (i > 10) {
                    foldtimeline.insert(new TweenMax.fromTo(filter.a[i], 1, {value: 0}, {value: 10 - i}));
                    foldtimeline.insert(new TweenMax.to(filter.a[i], 2, {value: 0, delay: 1}));
                }
            }

            //rotation
            timeline = new TimelineMax();
            timeline.insert(foldtimeline);
            timeline.insert(new TweenMax.to(filter, 1, {rotateY: 0, ambient: 0.3, ease: Quint.easeOut}));

            //timeline.insert(new TweenMax(filter, 2, {scale: 1, ease: Linear.easeNone}));
            timeline.pause();
        }

        function addFilterElement() {

            console.log('add filter element');

            $filterEl = $('<div>');
            $filterEl.addClass('transition-filter');
            $filterEl.css({
                'background-image': $el.css('background-image'),
                'opacity': '0'
            });
            updateFilter();
            $container.append($filterEl);

            $resolveEl = $filterEl.clone();
            $resolveEl.css({'webkitFilter': 'none', 'opacity': '0'});
            $container.append($resolveEl);
        }

        function showFilterElement() {

            console.log('show filter element');

            $el.css({opacity: 0});
            $filterEl.css({opacity: 1});
        }

        function openResolve() {

            dragging = false;

            $container.css({'pointer-events': 'auto'});
            $resolveEl.css({opacity: 1, 'pointer-events': 'auto'});
            $resolveEl.bind('touchstart', handle_resolveEl_TOUCHSTART);
            $resolveEl.bind('click', handle_resolveEl_CLICK);

            $filterEl.css({opacity: 0});
        }

        function closeResolve() {

            console.log('close resolve');

            dragging = false;
            $container.css({'pointer-events': 'none'});
            $filterEl.css({opacity: 0});
            $el.css({opacity: 1});
            scroll.enable();
        }

        function handle_filter_TOUCHEND(e) {

            console.log('filter: touch end');

            e.preventDefault();
            e.stopPropagation();

            $body.unbind('touchend');
            $body.unbind('touchmove');

            timeline.pause();

            if (opening) {
                timeline.tweenTo(3, {onComplete: openResolve});
                openTween = new TweenMax.to(filter, 0.5, {
                    x: 0,
                    y: 0,
                    scale: 1
                });
            } else {
                timeline.tweenTo(0, {onComplete: closeResolve});
                closeTween = new TweenMax.to(filter, 0.5, {
                    x: basefilter.x,
                    y: basefilter.y,
                    scale: basefilter.scale
                });
            }
        }

        function handle_filter_TOUCHMOVE(e) {
            var touches = e.originalEvent.touches,
                t1, t2,
                newAngle,
                newMidpoint,
                newDistance,
                distance,
                distanceDifference,
                timelinePosition;

            e.preventDefault();
            e.stopPropagation();

            if (touches.length == 2) {

                t1 = {x: touches[0].pageX, y: touches[0].pageY};
                t2 = {x: touches[1].pageX, y: touches[1].pageY};

                newDistance = getDistance(t1, t2);
                distanceDifference = newDistance - deltaDistance;
                distanceDifference = distanceDifference > 0 ? distanceDifference : 0;

                //get timline position
                timelinePosition = newDistance / 100;
                timelinePosition = timelinePosition > 1 ? timelinePosition : 1;
                opening = timelinePosition > 2 ? true : false;

                //calculate transform
                newMidpoint = getMidpoint(t1, t2);
                filter.x = (newMidpoint.x - deltaMidpoint.x) / 1000; // / filter.scale;
                filter.y = (newMidpoint.y - deltaMidpoint.y) / 1000; // / filter.scale;

                distance = getDistance(deltaMidpoint, newMidpoint);
                opening = distance > 100 ? true : opening;

                console.log('filter: touch move');

                unfoldTween.kill();
                timeline.seek(timelinePosition);
            }
        }

        function calculateMidpoint(t1, t2) {
            deltaMidpoint = getMidpoint(t1, t2);
            deltaDistance = getDistance(t1, t2);
            deltaMidpoint = {x: deltaMidpoint.x - filter.x, y: deltaMidpoint.y - filter.y};
        }

        function handle_el_TOUCHSTART(e) {
            var touches = e.originalEvent.touches,
                t1, t2;

            if (touches.length == 2) {

                console.log('el touchstart');

                e.preventDefault();
                e.stopPropagation();

                t1 = {x: touches[0].pageX, y: touches[0].pageY};
                t2 = {x: touches[1].pageX, y: touches[1].pageY};

                dragging = true;
                animating = true;

                resetFilter();
                showFilterElement();
                calculateMidpoint(t1, t2);
                addTimeline();

                instance.startRequestAnimationFrame();
                scroll.disable();

                $body.bind('touchend', handle_filter_TOUCHEND);
                $body.bind('touchmove', handle_filter_TOUCHMOVE);

                unfoldTween = timeline.tweenTo(1);
            }
        }

        function handle_resolveEl_TOUCHSTART(e) {
            var touches = e.originalEvent.touches,
                t1, t2;

            //e.preventDefault();
            e.stopPropagation();

            if (touches.length == 2) {

                console.log('resolve touchstart');

                t1 = {x: touches[0].pageX, y: touches[0].pageY};
                t2 = {x: touches[1].pageX, y: touches[1].pageY};

                dragging = true;

                timeline.seek(3);

                updateFilter();
                $resolveEl.css({opacity: 0, 'pointer-events': 'none'});
                $filterEl.css({'opacity': 1});

                calculateMidpoint(t1, t2);
                instance.startRequestAnimationFrame();

                $body.bind('touchend', handle_filter_TOUCHEND);
                $body.bind('touchmove', handle_filter_TOUCHMOVE);

                $resolveEl.unbind('touchstart');
            }
        }

        function handle_resolveEl_CLICK(e) {

            console.log('resolve click');

            dragging = true;
            animating = true;

            $resolveEl.css({opacity: 0, 'pointer-events': 'none'});
            $filterEl.css({'opacity': 1});

            timeline.timeScale(2);
            timeline.reverse();
            new TweenMax.to(filter, 2, {x: basefilter.x, y: basefilter.y, scale: basefilter.scale, onComplete: closeResolve});
            instance.startRequestAnimationFrame();
        }

        function handle_el_CLICK(e) {

            console.log('el click');

            dragging = true;
            animating = true;

            resetFilter();
            showFilterElement();

            addTimeline();
            timeline.seek(0);
            //timeline.timeScale(2);
            timeline.play();
            new TweenMax.to(filter, 2, {x: 0, y: 0, scale: 1, onComplete: openResolve});

            scroll.disable();

            instance.startRequestAnimationFrame();
        }

        instance.init = function () {
            var i;

            $body = $('body');
            $el.bind('touchstart', handle_el_TOUCHSTART);
            $el.bind('click', handle_el_CLICK);

            basefilter.a = [];
            for (i = 0; i < 20; i += 1) {
                basefilter.a.push({value: 0});
            }
            basefilter.a[9].value = -89;
            basefilter.a[10].value = 90;

            addContainer();
            resetFilter();
            addFilterElement();
            instance.waitingRequestAnimationFrame = false;
        };

        instance.startRequestAnimationFrame = function () {
            if (instance.waitingRequestAnimationFrame)
                return;
            instance.waitingRequestAnimationFrame = true;
            requestAnimationFrame(instance.draw);
        };

        instance.draw = function () {
            instance.waitingRequestAnimationFrame = false;
            if (!dragging)
                return;
            updateFilter();
            instance.startRequestAnimationFrame();
        };

        instance.render = function () {

        };

        instance.animOut = function () {

        };

        instance.destroy = function () {
            dragging = false;
            animating = false;
            $container.empty();
            $container.remove();
        };

        instance.init();
    };

	return FilterElement;
});

<commit_msg>fixing timeline click animation<commit_after>/*global define $ TweenMax Quad Quint TimelineMax iScroll Linear*/

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

define([], function (require) {

    var FilterElement;

    FilterElement = function (element, scroll) {
        var instance = this,
            $el = $(element),
            $body,
            $container,
            $filterEl,
            $resolveEl,
            filterPath = 'assets/shaders/',
            opening = false,
            timeline,
            foldtimeline,
            unfoldTween,
            closeTween,
            openTween,
            filter = {},
            animating = false,
            dragging = false,
            deltaMidpoint = {x: 0, y: 0},
            deltaDistance = 0,
            deltaAngle = 0,
            deltaRotation = 0,
            SCALE_DIVIDER = 100,
            basefilter = {
                ambient: 1,
                vert: filterPath + 'max-fold.vs',
                frag: filterPath + 'max-fold.fs',
                x: $el.data('filter-x'),
                y: $el.data('filter-y'),
                z: 0,
                scale: 0.93,//0.93,
                rotateY: -90,
                rotateX: 0,
                rotateZ: 0
            };

        function getAngle(p1, p2) {
            var angle,
                dx, dy;

            dx = p1.x - p2.x;
            dy = p1.y - p2.y;
            angle = Math.atan2(dy, dx) * 180 / Math.PI;

            return angle;
        }

        function getMidpoint(p1, p2) {
            var midpoint = {};

            midpoint.x = (p1.x + p2.x) / 2;
            midpoint.y = (p1.y + p2.y) / 2;

            return midpoint;
        }

        function getDistance(p1, p2) {
            var distance,
                dx, dy;

            dx = p1.x - p2.x;
            dy = p1.y - p2.y;
            distance = Math.sqrt(dx * dx + dy * dy);

            return distance;
        }

        function resetFilter() {
            for (var i in basefilter) {
                filter[i] = basefilter[i];
            }
        }

        function updateFilter() {
            $filterEl.css({
                'webkitFilter':
                    'custom(url(' + filter.vert + ') mix(url(' + filter.frag + ') multiply source-atop), 20 8 border-box, ' +
                    'ambientLight ' + filter.ambient + ', ' +
                    'perspective 5000, ' +
                    'translation ' + filter.x + ' ' + filter.y + ' 0, ' +
                    'rotation ' + filter.rotateX + ' ' + filter.rotateY + ' ' + filter.rotateZ + ', ' +
                    'scale ' + filter.scale + ', ' +
                    'lightPosition 0 0 1, ' +
                    'anchorIndex 10, ' +
                    'a0 ' + filter.a[0].value + ', ' +
                    'a1 ' + filter.a[1].value + ', ' +
                    'a2 ' + filter.a[2].value + ', ' +
                    'a3 ' + filter.a[3].value + ', ' +
                    'a4 ' + filter.a[4].value + ', ' +
                    'a5 ' + filter.a[5].value + ', ' +
                    'a6 ' + filter.a[6].value + ', ' +
                    'a7 ' + filter.a[7].value + ', ' +
                    'a8 ' + filter.a[8].value + ', ' +
                    'a9 ' + filter.a[9].value + ', ' +
                    'a10 ' + filter.a[10].value + ', ' +
                    'a11 ' + filter.a[11].value + ', ' +
                    'a12 ' + filter.a[12].value + ', ' +
                    'a13 ' + filter.a[13].value + ', ' +
                    'a14 ' + filter.a[14].value + ', ' +
                    'a15 ' + filter.a[15].value + ', ' +
                    'a16 ' + filter.a[16].value + ', ' +
                    'a17 ' + filter.a[17].value + ', ' +
                    'a18 ' + filter.a[18].value + ', ' +
                    'a19 ' + filter.a[19].value + ')'
            });
        }

        function addContainer() {
            $container = $('<div>');
            $container.addClass('transition-container');
            $body.append($container);
        }

        function addTimeline() {
            var i,
                key,
                time,
                delay;

            //fold
            foldtimeline = new TimelineMax();
            foldtimeline.insert(new TweenMax.to(filter.a[9], 2, {value: -70}));
            foldtimeline.insert(new TweenMax.to(filter.a[10], 2, {value: 70}));

            foldtimeline.insert(new TweenMax.to(filter.a[9], 4, {value: 0, delay: 2}));
            foldtimeline.insert(new TweenMax.to(filter.a[10], 4, {value: 0, delay: 2}));

            for (i = 0; i < 20; i += 1) {
                if (i < 9) {
                    foldtimeline.insert(new TweenMax.to(filter.a[i], 2, {value: 0}, {value: 9 - i}));
                    foldtimeline.insert(new TweenMax.to(filter.a[i], 2, {value: 0, delay: 2, ease: Quad.easeOut}));
                } else if (i > 10) {
                    foldtimeline.insert(new TweenMax.to(filter.a[i], 2, {value: 0}, {value: 10 - i}));
                    foldtimeline.insert(new TweenMax.to(filter.a[i], 2, {value: 0, delay: 2, ease: Quad.easeOut}));
                }
            }

            //rotation
            timeline = new TimelineMax();
            timeline.insert(foldtimeline);
            timeline.insert(new TweenMax.to(filter, 2, {rotateY: 0, ambient: 0.3, ease: Quint.easeOut}));

            timeline.pause();
        }

        function addFilterElement() {

            console.log('add filter element');

            $filterEl = $('<div>');
            $filterEl.addClass('transition-filter');
            $filterEl.css({
                'background-image': $el.css('background-image'),
                'opacity': '0'
            });
            updateFilter();
            $container.append($filterEl);

            $resolveEl = $filterEl.clone();
            $resolveEl.css({'webkitFilter': 'none', 'opacity': '0'});
            $container.append($resolveEl);
        }

        function showFilterElement() {

            console.log('show filter element');

            $el.css({opacity: 0});
            $filterEl.css({opacity: 1});
        }

        function openResolve() {

            dragging = false;

            $container.css({'pointer-events': 'auto'});
            $resolveEl.css({opacity: 1, 'pointer-events': 'auto'});
            //$resolveEl.bind('touchstart', handle_resolveEl_TOUCHSTART);
            $resolveEl.bind('click', handle_resolveEl_CLICK);

            $filterEl.css({opacity: 0});
        }

        function closeResolve() {

            console.log('close resolve');

            dragging = false;
            $container.css({'pointer-events': 'none'});
            $filterEl.css({opacity: 0});
            $el.css({opacity: 1});
            scroll.enable();
        }

        function handle_filter_TOUCHEND(e) {

            console.log('filter: touch end');

            e.preventDefault();
            e.stopPropagation();

            $body.unbind('touchend');
            $body.unbind('touchmove');

            timeline.pause();

            if (opening) {
                timeline.tweenTo(timeline.totalDuration(), {onComplete: openResolve});
                openTween = new TweenMax.to(filter, 0.5, {
                    x: 0,
                    y: 0,
                    scale: 1
                });
            } else {
                timeline.tweenTo(0, {onComplete: closeResolve});
                closeTween = new TweenMax.to(filter, 0.5, {
                    x: basefilter.x,
                    y: basefilter.y,
                    scale: basefilter.scale
                });
            }
        }

        function handle_filter_TOUCHMOVE(e) {
            var touches = e.originalEvent.touches,
                t1, t2,
                newAngle,
                newMidpoint,
                newDistance,
                distance,
                distanceDifference,
                timelinePosition;

            e.preventDefault();
            e.stopPropagation();

            if (touches.length == 2) {

                t1 = {x: touches[0].pageX, y: touches[0].pageY};
                t2 = {x: touches[1].pageX, y: touches[1].pageY};

                newDistance = getDistance(t1, t2);
                distanceDifference = newDistance - deltaDistance;
                distanceDifference = distanceDifference > 0 ? distanceDifference : 0;

                //get timline position
                timelinePosition = newDistance / 100;
                timelinePosition = timelinePosition > 1 ? timelinePosition : 1;
                opening = timelinePosition > 2 ? true : false;

                //calculate transform
                newMidpoint = getMidpoint(t1, t2);
                filter.x = (newMidpoint.x - deltaMidpoint.x) / 1000; // / filter.scale;
                filter.y = (newMidpoint.y - deltaMidpoint.y) / 1000; // / filter.scale;

                distance = getDistance(deltaMidpoint, newMidpoint);
                opening = distance > 100 ? true : opening;

                console.log('filter: touch move');

                unfoldTween.kill();
                timeline.seek(timelinePosition);
            }
        }

        function calculateMidpoint(t1, t2) {
            deltaMidpoint = getMidpoint(t1, t2);
            deltaDistance = getDistance(t1, t2);
            deltaMidpoint = {x: deltaMidpoint.x - filter.x, y: deltaMidpoint.y - filter.y};
        }

        function handle_el_TOUCHSTART(e) {
            var touches = e.originalEvent.touches,
                t1, t2;

            if (touches.length == 2) {

                console.log('el touchstart');

                e.preventDefault();
                e.stopPropagation();

                t1 = {x: touches[0].pageX, y: touches[0].pageY};
                t2 = {x: touches[1].pageX, y: touches[1].pageY};

                dragging = true;
                animating = true;

                resetFilter();
                showFilterElement();
                calculateMidpoint(t1, t2);
                //addTimeline();

                instance.startRequestAnimationFrame();
                scroll.disable();

                $body.bind('touchend', handle_filter_TOUCHEND);
                $body.bind('touchmove', handle_filter_TOUCHMOVE);

                unfoldTween = timeline.tweenTo(1);
            }
        }

        function handle_resolveEl_TOUCHSTART(e) {
            var touches = e.originalEvent.touches,
                t1, t2;

            //e.preventDefault();
            e.stopPropagation();

            if (touches.length == 2) {

                console.log('resolve touchstart');

                t1 = {x: touches[0].pageX, y: touches[0].pageY};
                t2 = {x: touches[1].pageX, y: touches[1].pageY};

                dragging = true;

                timeline.seek(3);

                updateFilter();
                $resolveEl.css({opacity: 0, 'pointer-events': 'none'});
                $filterEl.css({'opacity': 1});

                calculateMidpoint(t1, t2);
                instance.startRequestAnimationFrame();

                $body.bind('touchend', handle_filter_TOUCHEND);
                $body.bind('touchmove', handle_filter_TOUCHMOVE);

                $resolveEl.unbind('touchstart');
            }
        }

        function handle_resolveEl_CLICK(e) {
            var speed = 2;

            console.log('resolve click');

            dragging = true;
            animating = true;

            $resolveEl.css({opacity: 0, 'pointer-events': 'none'});
            $filterEl.css({'opacity': 1});

            //animate from end to beginning
            timeline.seek(timeline.totalDuration());
            timeline.timeScale(speed);
            timeline.tweenTo(0, {onComplete: closeResolve});
            new TweenMax.to(filter, timeline.totalDuration() / speed, {x: basefilter.x, y: basefilter.y, scale: basefilter.scale});
            instance.startRequestAnimationFrame();
        }

        function handle_el_CLICK(e) {
            var speed = 2;

            console.log('el click');

            dragging = true;
            animating = true;

            resetFilter();
            showFilterElement();

            //animate from beginning to end
            timeline.seek(0);
            timeline.timeScale(2);
            timeline.tweenTo(timeline.totalDuration(), {onComplete: openResolve});
            new TweenMax.to(filter, timeline.totalDuration() / speed, {x: 0, y: 0, scale: 1});
            instance.startRequestAnimationFrame();

            scroll.disable();
        }

        instance.init = function () {
            var i;

            $body = $('body');
            //$el.bind('touchstart', handle_el_TOUCHSTART);
            $el.bind('click', handle_el_CLICK);

            basefilter.a = [];
            for (i = 0; i < 20; i += 1) {
                basefilter.a.push({value: 0});
            }
            basefilter.a[9].value = -89;
            basefilter.a[10].value = 90;

            addContainer();
            resetFilter();
            addTimeline();
            addFilterElement();
            instance.waitingRequestAnimationFrame = false;
        };

        instance.startRequestAnimationFrame = function () {
            if (instance.waitingRequestAnimationFrame)
                return;
            instance.waitingRequestAnimationFrame = true;
            requestAnimationFrame(instance.draw);
        };

        instance.draw = function () {
            instance.waitingRequestAnimationFrame = false;
            if (!dragging)
                return;
            updateFilter();
            instance.startRequestAnimationFrame();
        };

        instance.render = function () {

        };

        instance.animOut = function () {

        };

        instance.destroy = function () {
            dragging = false;
            animating = false;
            $container.empty();
            $container.remove();
        };

        instance.init();
    };

	return FilterElement;
});

<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.document.page_snippet");
pimcore.document.page_snippet = Class.create(pimcore.document.document, {

    addTab: function () {

        var tabTitle = this.data.key;
        if (tabTitle.length < 1) {
            tabTitle = "home";
        }

        this.tabPanel = Ext.getCmp("pimcore_panel_tabs");
        var tabId = "document_" + this.id;

        this.tab = new Ext.Panel({
            id: tabId,
            title: tabTitle,
            closable:true,
            hideMode: "offsets",
            layout: "border",
            items: [
                this.getLayoutToolbar(),
                this.getTabPanel()
            ],
            iconCls: "pimcore_icon_" + this.data.type,
            document: this
        });

        // remove this instance when the panel is closed
        this.tab.on("beforedestroy", function () {
            Ext.Ajax.request({
                url: "/admin/misc/unlock-element",
                params: {
                    id: this.data.id,
                    type: "document"
                }
            });

            this.cleanUpOnDestroy();
        }.bind(this));

        this.tab.on("destroy", function () {
            pimcore.globalmanager.remove("document_" + this.id);
        }.bind(this));

        this.tab.on("activate", function () {
            this.tab.doLayout();
            pimcore.layout.refresh();
        }.bind(this));

        this.tab.on("afterrender", function (tabId) {
            this.tabPanel.activate(tabId);
            pimcore.plugin.broker.fireEvent("postOpenDocument", this, this.data.type);
        }.bind(this, tabId));

        this.removeLoadingPanel();

        this.tabPanel.add(this.tab);

        // recalculate the layout
        pimcore.layout.refresh();
    },

    cleanUpOnDestroy: function () {
        if (this.edit) {
            if (typeof this.edit.onClose == "function") {
                this.edit.onClose();
            }
        }
        if (this.settings) {
            if (typeof this.settings.onClose == "function") {
                this.settings.onClose();
            }
        }
        if (this.properties) {
            if (typeof this.properties.onClose == "function") {
                this.properties.onClose();
            }
        }
        this.removeFromSession();
    },

    maskFrames: function () {
        if (this.edit) {
            this.edit.maskFrames();
        }
    },

    unmaskFrames: function () {
        if (this.edit) {
            this.edit.unmaskFrames();
        }
    },

    getLayoutToolbar : function () {

        if (!this.toolbar) {

            this.toolbarButtons = {};

            this.toolbarButtons.save = new Ext.SplitButton({
                text: t('save'),
                iconCls: "pimcore_icon_save_medium",
                scale: "medium",
                handler: this.save.bind(this),
                menu: [{
                        text: t('save_close'),
                        iconCls: "pimcore_icon_save",
                        handler: this.saveClose.bind(this)
                    }]
            });

            this.toolbarButtons.publish = new Ext.SplitButton({
                text: t('save_and_publish'),
                iconCls: "pimcore_icon_publish_medium",
                scale: "medium",
                handler: this.publish.bind(this),
                menu: [
                    {
                        text: t('save_pubish_close'),
                        iconCls: "pimcore_icon_save",
                        handler: this.publishClose.bind(this)
                    },{
                        text: t('save_only_new_version'),
                        iconCls: "pimcore_icon_save",
                        handler: this.save.bind(this)
                    },
                    {
                        text: t('save_only_scheduled_tasks'),
                        iconCls: "pimcore_icon_save",
                        handler: this.save.bind(this, "scheduler","scheduler")
                    }
                ]
            });

            this.toolbarButtons.unpublish = new Ext.Button({
                text: t('unpublish'),
                iconCls: "pimcore_icon_unpublish_medium",
                scale: "medium",
                handler: this.unpublish.bind(this)
            });

            this.toolbarButtons.reload = new Ext.Button({
                text: t('reload'),
                iconCls: "pimcore_icon_reload_medium",
                scale: "medium",
                handler: this.reload.bind(this)
            });

            // extras menu
            var extrasMenu = [];

            // translation menu
            if(pimcore.settings.google_translate_api_key) {
                var translationMenu = [];
                for (var p=0; p<pimcore.settings.websiteLanguages.length; p++) {

                    translationMenu.push({
                        text: pimcore.available_languages[pimcore.settings.websiteLanguages[p]],
                        handler: function (lang) {
                            Ext.Ajax.request({
                                url: '/admin/' + this.getType() + '/translate/language/' + lang,
                                method: "post",
                                params: this.getSaveData(),
                                success: function () {
                                    this.edit.reload(true);
                                }.bind(this)
                            });
                        }.bind(this, pimcore.settings.websiteLanguages[p])
                    });
                }

                if(translationMenu.length > 0) {
                    extrasMenu.push({
                        text: t("translate_content_to"),
                        iconCls: "pimcore_icon_translations",
                        hideOnClick: false,
                        menu: translationMenu
                    });
                }
            }

            if(extrasMenu.length > 0) {
                this.toolbarButtons.extras = new Ext.Button({
                    text: t('extras'),
                    iconCls: "pimcore_icon_extras_medium",
                    scale: "medium",
                    hideOnClick: false,
                    menu: extrasMenu
                });
            }

            /*this.toolbarButtons.remove = new Ext.Button({
             text: t('delete'),
             iconCls: "pimcore_icon_delete_medium",
             scale: "medium",
             handler: this.remove.bind(this)
             });*/

            var buttons = [];

            if (this.isAllowed("save")) {
                buttons.push(this.toolbarButtons.save);
            }
            if (this.isAllowed("publish")) {
                buttons.push(this.toolbarButtons.publish);
            }
            if (this.isAllowed("unpublish")) {
                buttons.push(this.toolbarButtons.unpublish);
            }

            /*if(this.isAllowed("delete")) {
             buttons.push(this.toolbarButtons.remove);
             }*/

            buttons.push(this.toolbarButtons.reload);

            if(typeof this.toolbarButtons.extras != "undefined") {
                buttons.push("-");
                buttons.push(this.toolbarButtons.extras);
            }

            buttons.push("-");
            buttons.push({
                text: this.data.path + this.data.key,
                iconCls: "pimcore_icon_cursor_medium",
                scale: "medium",
                handler: function () {
                    window.open(this.data.path + this.data.key);
                }.bind(this)
            });
            buttons.push("-");
            buttons.push({
                xtype: 'tbtext',
                text: this.data.id,
                scale: "medium"
            });

            // version notification
            buttons.push("-");
            this.newerVersionNotification = new Ext.Toolbar.TextItem({
                xtype: 'tbtext',
                text: '  ' + t("this_is_a_newer_not_published_version"),
                scale: "medium",
                hidden: true
            });

            buttons.push(this.newerVersionNotification);

            // check for newer version than the published
            if (this.data.versions.length > 1) {
                if (this.data.modificationDate != this.data.versions[0].date) {
                    this.newerVersionNotification.show();
                }
            }

            this.toolbar = new Ext.Toolbar({
                id: "document_toolbar_" + this.id,
                region: "north",
                border: false,
                cls: "document_toolbar",
                items: buttons
            });

            this.toolbar.on("afterrender", function () {
                window.setTimeout(function () {
                    if (!this.data.published) {
                        this.toolbarButtons.unpublish.hide();
                    } else if (this.isAllowed("publish")) {
                        this.toolbarButtons.save.hide();
                    }
                }.bind(this), 500);
            }.bind(this));
        }

        return this.toolbar;
    },

    saveToSession: function (onComplete) {

        if (typeof onComplete != "function") {
            onComplete = function () {
            }
        }

        Ext.Ajax.request({
            url: '/admin/' + this.getType() + '/save-to-session/',
            method: "post",
            params: this.getSaveData(),
            success: onComplete
        });
    },

    removeFromSession: function () {
        Ext.Ajax.request({
            url: '/admin/' + this.getType() + '/remove-from-session/',
            params: {id: this.data.id}
        });
    },

    reload: function () {

        this.saveToSession(function () {
            if (this.edit && this.edit.layout.rendered) {
                this.edit.reload(true);
            }

            if (this.preview && this.preview.layout.rendered) {
                this.preview.loadCurrentPreview();
            }

        }.bind(this));
    }
});
<commit_msg>PIMCORE-1274 - Inherited properties in documents do not show up upon reload<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.document.page_snippet");
pimcore.document.page_snippet = Class.create(pimcore.document.document, {

    addTab: function () {

        var tabTitle = this.data.key;
        if (tabTitle.length < 1) {
            tabTitle = "home";
        }

        this.tabPanel = Ext.getCmp("pimcore_panel_tabs");
        var tabId = "document_" + this.id;

        this.tab = new Ext.Panel({
            id: tabId,
            title: tabTitle,
            closable:true,
            hideMode: "offsets",
            layout: "border",
            items: [
                this.getLayoutToolbar(),
                this.getTabPanel()
            ],
            iconCls: "pimcore_icon_" + this.data.type,
            document: this
        });

        // remove this instance when the panel is closed
        this.tab.on("beforedestroy", function () {
            Ext.Ajax.request({
                url: "/admin/misc/unlock-element",
                params: {
                    id: this.data.id,
                    type: "document"
                }
            });

            this.cleanUpOnDestroy();
        }.bind(this));

        this.tab.on("destroy", function () {
            pimcore.globalmanager.remove("document_" + this.id);
        }.bind(this));

        this.tab.on("activate", function () {
            this.tab.doLayout();
            pimcore.layout.refresh();
        }.bind(this));

        this.tab.on("afterrender", function (tabId) {
            this.tabPanel.activate(tabId);
            pimcore.plugin.broker.fireEvent("postOpenDocument", this, this.data.type);
        }.bind(this, tabId));

        this.removeLoadingPanel();

        this.tabPanel.add(this.tab);

        // recalculate the layout
        pimcore.layout.refresh();
    },

    cleanUpOnDestroy: function () {
        if (this.edit) {
            if (typeof this.edit.onClose == "function") {
                this.edit.onClose();
            }
        }
        if (this.settings) {
            if (typeof this.settings.onClose == "function") {
                this.settings.onClose();
            }
        }
        if (this.properties) {
            if (typeof this.properties.onClose == "function") {
                this.properties.onClose();
            }
        }
        this.removeFromSession();
    },

    maskFrames: function () {
        if (this.edit) {
            this.edit.maskFrames();
        }
    },

    unmaskFrames: function () {
        if (this.edit) {
            this.edit.unmaskFrames();
        }
    },

    getLayoutToolbar : function () {

        if (!this.toolbar) {

            this.toolbarButtons = {};

            this.toolbarButtons.save = new Ext.SplitButton({
                text: t('save'),
                iconCls: "pimcore_icon_save_medium",
                scale: "medium",
                handler: this.save.bind(this),
                menu: [{
                        text: t('save_close'),
                        iconCls: "pimcore_icon_save",
                        handler: this.saveClose.bind(this)
                    }]
            });

            this.toolbarButtons.publish = new Ext.SplitButton({
                text: t('save_and_publish'),
                iconCls: "pimcore_icon_publish_medium",
                scale: "medium",
                handler: this.publish.bind(this),
                menu: [
                    {
                        text: t('save_pubish_close'),
                        iconCls: "pimcore_icon_save",
                        handler: this.publishClose.bind(this)
                    },{
                        text: t('save_only_new_version'),
                        iconCls: "pimcore_icon_save",
                        handler: this.save.bind(this)
                    },
                    {
                        text: t('save_only_scheduled_tasks'),
                        iconCls: "pimcore_icon_save",
                        handler: this.save.bind(this, "scheduler","scheduler")
                    }
                ]
            });

            this.toolbarButtons.unpublish = new Ext.Button({
                text: t('unpublish'),
                iconCls: "pimcore_icon_unpublish_medium",
                scale: "medium",
                handler: this.unpublish.bind(this)
            });

            this.toolbarButtons.reload = new Ext.Button({
                text: t('reload'),
                iconCls: "pimcore_icon_reload_medium",
                scale: "medium",
                handler: this.reload.bind(this)
            });

            // extras menu
            var extrasMenu = [];

            // translation menu
            if(pimcore.settings.google_translate_api_key) {
                var translationMenu = [];
                for (var p=0; p<pimcore.settings.websiteLanguages.length; p++) {

                    translationMenu.push({
                        text: pimcore.available_languages[pimcore.settings.websiteLanguages[p]],
                        handler: function (lang) {
                            Ext.Ajax.request({
                                url: '/admin/' + this.getType() + '/translate/language/' + lang,
                                method: "post",
                                params: this.getSaveData(),
                                success: function () {
                                    this.edit.reload(true);
                                }.bind(this)
                            });
                        }.bind(this, pimcore.settings.websiteLanguages[p])
                    });
                }

                if(translationMenu.length > 0) {
                    extrasMenu.push({
                        text: t("translate_content_to"),
                        iconCls: "pimcore_icon_translations",
                        hideOnClick: false,
                        menu: translationMenu
                    });
                }
            }

            if(extrasMenu.length > 0) {
                this.toolbarButtons.extras = new Ext.Button({
                    text: t('extras'),
                    iconCls: "pimcore_icon_extras_medium",
                    scale: "medium",
                    hideOnClick: false,
                    menu: extrasMenu
                });
            }

            /*this.toolbarButtons.remove = new Ext.Button({
             text: t('delete'),
             iconCls: "pimcore_icon_delete_medium",
             scale: "medium",
             handler: this.remove.bind(this)
             });*/

            var buttons = [];

            if (this.isAllowed("save")) {
                buttons.push(this.toolbarButtons.save);
            }
            if (this.isAllowed("publish")) {
                buttons.push(this.toolbarButtons.publish);
            }
            if (this.isAllowed("unpublish")) {
                buttons.push(this.toolbarButtons.unpublish);
            }

            /*if(this.isAllowed("delete")) {
             buttons.push(this.toolbarButtons.remove);
             }*/

            buttons.push(this.toolbarButtons.reload);

            if(typeof this.toolbarButtons.extras != "undefined") {
                buttons.push("-");
                buttons.push(this.toolbarButtons.extras);
            }

            buttons.push("-");
            buttons.push({
                text: this.data.path + this.data.key,
                iconCls: "pimcore_icon_cursor_medium",
                scale: "medium",
                handler: function () {
                    window.open(this.data.path + this.data.key);
                }.bind(this)
            });
            buttons.push("-");
            buttons.push({
                xtype: 'tbtext',
                text: this.data.id,
                scale: "medium"
            });

            // version notification
            buttons.push("-");
            this.newerVersionNotification = new Ext.Toolbar.TextItem({
                xtype: 'tbtext',
                text: '  ' + t("this_is_a_newer_not_published_version"),
                scale: "medium",
                hidden: true
            });

            buttons.push(this.newerVersionNotification);

            // check for newer version than the published
            if (this.data.versions.length > 1) {
                if (this.data.modificationDate != this.data.versions[0].date) {
                    this.newerVersionNotification.show();
                }
            }

            this.toolbar = new Ext.Toolbar({
                id: "document_toolbar_" + this.id,
                region: "north",
                border: false,
                cls: "document_toolbar",
                items: buttons
            });

            this.toolbar.on("afterrender", function () {
                window.setTimeout(function () {
                    if (!this.data.published) {
                        this.toolbarButtons.unpublish.hide();
                    } else if (this.isAllowed("publish")) {
                        this.toolbarButtons.save.hide();
                    }
                }.bind(this), 500);
            }.bind(this));
        }

        return this.toolbar;
    },

    saveToSession: function (onComplete) {

        if (typeof onComplete != "function") {
            onComplete = function () {
            }
        }

        Ext.Ajax.request({
            url: '/admin/' + this.getType() + '/save-to-session/',
            method: "post",
            params: this.getSaveData(),
            success: onComplete
        });
    },

    removeFromSession: function () {
        Ext.Ajax.request({
            url: '/admin/' + this.getType() + '/remove-from-session/',
            params: {id: this.data.id}
        });
    },

    reloadEditmode: function () {

        this.saveToSession(function () {
            if (this.edit && this.edit.layout.rendered) {
                this.edit.reload(true);
            }

            if (this.preview && this.preview.layout.rendered) {
                this.preview.loadCurrentPreview();
            }

        }.bind(this));
    }
});
<|endoftext|>


<commit_before>import axios from "axios";
import router from "./router";
import store from "./store";

axios.defaults.timeout = 8000;

// set global authorization token
axios.interceptors.request.use(
  (config) => {
    let token = store.getters.token;
    if (token) {
      config.headers.Authorization = "Token " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response) => {
    if (response.status === 401) {
      store.commit("clearToken");
      router.push({ path: "/login" });
    } else if (response.status === 403) {
      router.push({ path: "/home" });
    }
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default axios;
<commit_msg>fix auth<commit_after>import axios from "axios";
import router from "./router";
import store from "./store";

axios.defaults.timeout = 8000;

// set global authorization token
axios.interceptors.request.use(
  (config) => {
    let token = store.getters.token;
    if (token) {
      config.headers.Authorization = "Token " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response.status === 401) {
      store.commit("clearToken");
      router.push({ path: "/login" });
    } else if (error.response.status === 403) {
      router.push({ path: "/home" });
    }
    return Promise.reject(error);
  }
);

export default axios;
<|endoftext|>