<commit_before>'use strict';

import gulp from 'gulp';
import browserSync from 'browser-sync';
import paths from '../paths';

gulp.task('watch', () => {

    gulp.watch([paths.app.images, paths.app.fonts], [browserSync.reload]);

    gulp.watch(paths.app.styles, ['less', browserSync.reload]);

    gulp.watch([paths.app.html, paths.app.templates], [browserSync.reload]);

    gulp.watch([paths.app.scripts], ['es6', browserSync.reload]);

});
<commit_msg>Fix less watch<commit_after>'use strict';

import gulp from 'gulp';
import browserSync from 'browser-sync';
import paths from '../paths';

gulp.task('watch', () => {

    gulp.watch([paths.app.images, paths.app.fonts], [browserSync.reload]);

    gulp.watch(paths.app.less, ['less', browserSync.reload]);

    gulp.watch([paths.app.html, paths.app.templates], [browserSync.reload]);

    gulp.watch([paths.app.scripts], ['es6', browserSync.reload]);

});
<|endoftext|>


<commit_before>import ActiveSymbols from './activeSymbols';
import config from '../../common/const';
import { getObjectValue } from '../../../common/utils/tools';
import { getTokenList } from '../../../common/utils/storageManager';

const noop = () => {};

let parsedAssetIndex;

const parseAssetIndex = assetIndex => {
    const parsed = {};

    assetIndex.forEach(symbol => {
        parsed[symbol[0].toLowerCase()] = {};

        symbol[2].forEach(category => {
            [, , parsed[symbol[0].toLowerCase()][category[0].toLowerCase()]] = category;
        });
    });
    return parsed;
};

const getAllowedConditionsOrCategoriesForSymbol = symbol => {
    let conditions = [];
    const categories = [];
    const index = parsedAssetIndex[symbol.toLowerCase()];
    if (index) {
        Object.keys(config.conditionsCategory).forEach(conditionName => {
            if (conditionName in index) {
                conditions = conditions.concat(config.conditionsCategory[conditionName]);
                categories.push(conditionName);
            }
        });
    }
    return { conditions, categories };
};

const getCategoryForCondition = condition =>
    Object.keys(config.conditionsCategory).find(
        category => config.conditionsCategory[category].indexOf(condition.toLowerCase()) >= 0
    );

export default class _Symbol {
    constructor(api) {
        this.api = api;
        this.initPromise = new Promise(resolve => {
            // Authorize when possible for accurate offered symbols, assetindex
            const promises = [];
            const tokenList = getTokenList();
            if (tokenList.length) {
                promises.push(this.api.authorize(tokenList[0]));
            }
            Promise.all(promises).finally(() => {
                this.api.getActiveSymbolsBrief().then(r => {
                    this.activeSymbols = new ActiveSymbols(r.active_symbols);
                    this.api.getAssetIndex().then(r2 => {
                        parsedAssetIndex = parseAssetIndex(r2.asset_index);
                        resolve();
                    }, noop);
                }, noop);
            }, noop);
        });
    }
    /* eslint-disable class-methods-use-this */
    getLimitation(symbol, condition) {
        const category = getCategoryForCondition(condition);
        return {
            minDuration: parsedAssetIndex[symbol.toLowerCase()][category],
        };
    }
    isConditionAllowedInSymbol(symbol, condition) {
        const { conditions } = getAllowedConditionsOrCategoriesForSymbol(symbol);
        return conditions.includes(condition);
    }
    getConditionName(condition) {
        const [con1, con2] = config.opposites[condition.toUpperCase()];
        return `${getObjectValue(con1)}/${getObjectValue(con2)}`;
    }
    getCategoryNameForCondition(condition) {
        return config.conditionsCategoryName[getCategoryForCondition(condition)];
    }
    getAllowedCategories(symbol) {
        return getAllowedConditionsOrCategoriesForSymbol(symbol).categories;
    }
    getAllowedCategoryNames(symbol) {
        const { categories } = getAllowedConditionsOrCategoriesForSymbol(symbol);
        return categories.map(el => config.conditionsCategoryName[el]);
    }
    /* eslint-enable */
}
<commit_msg>Send token.token, not token-object<commit_after>import ActiveSymbols from './activeSymbols';
import config from '../../common/const';
import { getObjectValue } from '../../../common/utils/tools';
import { getTokenList } from '../../../common/utils/storageManager';

const noop = () => {};

let parsedAssetIndex;

const parseAssetIndex = assetIndex => {
    const parsed = {};

    assetIndex.forEach(symbol => {
        parsed[symbol[0].toLowerCase()] = {};

        symbol[2].forEach(category => {
            [, , parsed[symbol[0].toLowerCase()][category[0].toLowerCase()]] = category;
        });
    });
    return parsed;
};

const getAllowedConditionsOrCategoriesForSymbol = symbol => {
    let conditions = [];
    const categories = [];
    const index = parsedAssetIndex[symbol.toLowerCase()];
    if (index) {
        Object.keys(config.conditionsCategory).forEach(conditionName => {
            if (conditionName in index) {
                conditions = conditions.concat(config.conditionsCategory[conditionName]);
                categories.push(conditionName);
            }
        });
    }
    return { conditions, categories };
};

const getCategoryForCondition = condition =>
    Object.keys(config.conditionsCategory).find(
        category => config.conditionsCategory[category].indexOf(condition.toLowerCase()) >= 0
    );

export default class _Symbol {
    constructor(api) {
        this.api = api;
        this.initPromise = new Promise(resolve => {
            // Authorize when possible for accurate offered symbols, assetindex
            const promises = [];
            const tokenList = getTokenList();
            if (tokenList.length) {
                promises.push(this.api.authorize(tokenList[0].token));
            }
            Promise.all(promises).finally(() => {
                this.api.getActiveSymbolsBrief().then(r => {
                    this.activeSymbols = new ActiveSymbols(r.active_symbols);
                    this.api.getAssetIndex().then(r2 => {
                        parsedAssetIndex = parseAssetIndex(r2.asset_index);
                        resolve();
                    }, noop);
                }, noop);
            }, noop);
        });
    }
    /* eslint-disable class-methods-use-this */
    getLimitation(symbol, condition) {
        const category = getCategoryForCondition(condition);
        return {
            minDuration: parsedAssetIndex[symbol.toLowerCase()][category],
        };
    }
    isConditionAllowedInSymbol(symbol, condition) {
        const { conditions } = getAllowedConditionsOrCategoriesForSymbol(symbol);
        return conditions.includes(condition);
    }
    getConditionName(condition) {
        const [con1, con2] = config.opposites[condition.toUpperCase()];
        return `${getObjectValue(con1)}/${getObjectValue(con2)}`;
    }
    getCategoryNameForCondition(condition) {
        return config.conditionsCategoryName[getCategoryForCondition(condition)];
    }
    getAllowedCategories(symbol) {
        return getAllowedConditionsOrCategoriesForSymbol(symbol).categories;
    }
    getAllowedCategoryNames(symbol) {
        const { categories } = getAllowedConditionsOrCategoriesForSymbol(symbol);
        return categories.map(el => config.conditionsCategoryName[el]);
    }
    /* eslint-enable */
}
<|endoftext|>


<commit_before>React = require('react');

var DisplayBox = React.createClass({
  getInitialState: function() {
    return {data: []};
  },
  handleQuerySubmit: function(query) {
    $.ajax({
      url: 'general-query',
      dataType: 'json',
      type: 'POST',
      data: query,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  render: function() {
    return (

        <SearchForm onQuerySubmit={this.handleQuerySubmit} />

Related Results

        <GeneralResultsList data={this.state.data} />

    );
  }
});

var GeneralResultsList = React.createClass({
  render: function() {
    return (

test

    );
  }
});

var SearchForm = React.createClass({
  handleSubmit: function(e) {
    e.preventDefault();

    var query = React.findDOMNode(this.refs.query).value.trim();

    this.props.onQuerySubmit({query: query});

    React.findDOMNode(this.refs.query).value = '';
  },
  render: function() {
    return (

ShopChimp, at your service.

        <form className="query-form" onSubmit={this.handleSubmit}>
          <input type="text" placeholder="Enter a product" className="form-control" ref="query" />

          <button className="btn btn-primary">Submit</button>
        </form>

    );
  }
});

var Home = React.createClass({
	render: function() {
		return (

        <DisplayBox />

		);
	}
});

module.exports = Home;
<commit_msg>(feat) add changes to Home.js<commit_after>React = require('react');

var DisplayBox = React.createClass({
  getInitialState: function() {
    return {data: []};
  },
  handleQuerySubmit: function(query) {
    $.ajax({
      url: 'general-query',
      dataType: 'json',
      type: 'POST',
      data: query,
      success: function(data) {
        console.log('success!', data);
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  render: function() {
    return (

        <SearchForm onQuerySubmit={this.handleQuerySubmit} />

Related Results

        <GeneralResultsList data={this.state.data} />

    );
  }
});

var GeneralResultsList = React.createClass({
  render: function() {
    return (

test

    );
  }
});

var SearchForm = React.createClass({
  handleSubmit: function(e) {
    e.preventDefault();

    var query = React.findDOMNode(this.refs.query).value.trim();

    this.props.onQuerySubmit({query: query});

    React.findDOMNode(this.refs.query).value = '';
  },
  render: function() {
    return (

ShopChimp, at your service.

        <form className="query-form" onSubmit={this.handleSubmit}>
          <input type="text" placeholder="Enter a product" className="form-control" ref="query" />

          <button className="btn btn-primary">Submit</button>
        </form>

    );
  }
});

var Home = React.createClass({
	render: function() {
		return (

        <DisplayBox />

		);
	}
});

module.exports = Home;
<|endoftext|>


<commit_before>jest.mock('./http');
import { fetchPosts, createPost, fetchPost } from './http';

describe('fetchPosts', () => {
  it('should sould fetch posts',  async () => {
    const posts = await fetchPosts(3);
    expect(posts.length).toBe(3);
    posts.forEach(post => expect(post.id).toBeDefined());
  });
  it('should return a default number of posts', async () => {
    const posts = await fetchPosts();
    expect(posts.length).toBe(5);
  });
  it('should return posts with an ID', async () => {
    const posts = await fetchPosts();
    expect(posts[0]).toBeDefined();
  });
});

describe('createPost', () => {
  it('should let you create a post', async () => {
    const newPost = await createPost({ content: 'A post!' });
    expect(newPost).not.toBe(null);
    expect(newPost.id).toBeDefined();
  });
});

describe('fetchPost', () => {
  it('should fetch a post for you', async () => {
    const newPost = await fetchPost('12345');
    expect(newPost.id).toBeDefined();
  });
  it('should throw an error without an ID', async () => {
    expect(() => fetchPost()).toThrow();
  });
});
<commit_msg>more test updates<commit_after>jest.mock('./http');
import { fetchPosts, createPost, fetchPost } from './http';

describe('fetchPosts', () => {
  it('should sould fetch posts',  async () => {
    const posts = await fetchPosts(3);
    expect(posts.length).toBe(3);
    posts.forEach(post => expect(post.id).toBeDefined());
  });
  it('should return a default number of posts', async () => {
    const posts = await fetchPosts();
    expect(posts.length).toBe(5);
  });
  it('should return posts with an ID', async () => {
    const posts = await fetchPosts();
    expect(posts[0].id).toBeDefined();
  });
});

describe('createPost', () => {
  it('should let you create a post', async () => {
    const newPost = await createPost({ content: 'A post!' });
    expect(newPost).not.toBe(null);
    expect(newPost.id).toBeDefined();
  });
});

describe('fetchPost', () => {
  it('should fetch a post for you', async () => {
    const newPost = await fetchPost('12345');
    expect(newPost.id).toBeDefined();
  });
  it('should throw an error without an ID', async () => {
    expect(() => fetchPost()).toThrow();
  });
});
<|endoftext|>


<commit_before>(function() {
  'use strict'

  var $ = window.jQuery
  var Waypoint = window.Waypoint

  /* http://imakewebthings.com/waypoints/shortcuts/sticky-elements */
  function Sticky(options) {
    this.options = $.extend({}, Waypoint.defaults, Sticky.defaults, options)
    this.element = this.options.element
    this.$element = $(this.element)
    this.createWrapper()
    this.createWaypoint()
  }

  /* Private */
  Sticky.prototype.createWaypoint = function() {
    var originalHandler = this.options.handler

    this.waypoint = new Waypoint($.extend({}, this.options, {
      element: this.wrapper,
      handler: $.proxy(function(direction) {
        var shouldBeStuck = this.options.direction.indexOf(direction) > -1
        var wrapperHeight = shouldBeStuck ? this.$element.outerHeight(true) : ''

        this.$wrapper.height(wrapperHeight)
        this.$element.toggleClass(this.options.stuckClass, shouldBeStuck)

        if (originalHandler) {
          originalHandler.call(this, direction)
        }
      }, this)
    }))
  }

  /* Private */
  Sticky.prototype.createWrapper = function() {
    this.$element.wrap(this.options.wrapper)
    this.$wrapper = this.$element.parent()
    this.wrapper = this.$wrapper[0]
  }

  /* Public */
  Sticky.prototype.destroy = function() {
    if (this.$element.parent()[0] === this.wrapper) {
      this.waypoint.destroy()
      this.$element.removeClass(this.options.stuckClass).unwrap()
    }
  }

  Sticky.defaults = {
    wrapper: '
',
    stuckClass: 'stuck',
    direction: 'down right'
  }

  Waypoint.Sticky = Sticky
}())
<commit_msg>Allow for pre-existing wrapper<commit_after>(function() {
  'use strict'

  var $ = window.jQuery
  var Waypoint = window.Waypoint

  /* http://imakewebthings.com/waypoints/shortcuts/sticky-elements */
  function Sticky(options) {
    this.options = $.extend({}, Waypoint.defaults, Sticky.defaults, options)
    this.element = this.options.element
    this.$element = $(this.element)
    this.createWrapper()
    this.createWaypoint()
  }

  /* Private */
  Sticky.prototype.createWaypoint = function() {
    var originalHandler = this.options.handler

    this.waypoint = new Waypoint($.extend({}, this.options, {
      element: this.wrapper,
      handler: $.proxy(function(direction) {
        var shouldBeStuck = this.options.direction.indexOf(direction) > -1
        var wrapperHeight = shouldBeStuck ? this.$element.outerHeight(true) : ''

        this.$wrapper.height(wrapperHeight)
        this.$element.toggleClass(this.options.stuckClass, shouldBeStuck)

        if (originalHandler) {
          originalHandler.call(this, direction)
        }
      }, this)
    }))
  }

  /* Private */
  Sticky.prototype.createWrapper = function() {
    if (this.options.wrapper !== false) {
      this.$element.wrap(this.options.wrapper)
    }
    this.$wrapper = this.$element.parent()
    this.wrapper = this.$wrapper[0]
  }

  /* Public */
  Sticky.prototype.destroy = function() {
    if (this.$element.parent()[0] === this.wrapper) {
      this.waypoint.destroy()
      this.$element.removeClass(this.options.stuckClass).unwrap()
    }
  }

  Sticky.defaults = {
    wrapper: '
',
    stuckClass: 'stuck',
    direction: 'down right'
  }

  Waypoint.Sticky = Sticky
}())
<|endoftext|>


<commit_before>
/* Contains all source code modules assigned to RG. */

const RG = require('./rg.js');

RG.Random = require('./random.js');

RG.Object = require('./object.js');
RG.Item = require('./item.js');
RG.Time = require('./time.js');
RG.Component = require('./component.js');
RG.System = require('./system.js');
RG.BTree = require('./aisequence.js');
RG.Brain = require('./brain.js');
RG.Inv = require('./inv.js');
RG.Actor = require('./actor.js');
RG.Element = require('./element.js');
RG.Map = require('./map.js');
RG.World = require('./world.js');

RG.Effects = require('../data/effects.js');
RG.ObjectShellParser = require('./objectshellparser.js');

RG.Game = require('./game.js');
RG.Factory = require('./factory.js');

RG.Names = require('../data/name-gen.js');
RG.Overworld = require('./overworld.js');

RG.Game.FromJSON = require('./game.fromjson.js');

RG.Factory.Game = require('./factory.game.js');

module.exports = RG;

<commit_msg>Added elem templates.<commit_after>
/* Contains all source code modules assigned to RG. */

const RG = require('./rg.js');

RG.Random = require('./random.js');

RG.Object = require('./object.js');
RG.Item = require('./item.js');
RG.Time = require('./time.js');
RG.Component = require('./component.js');
RG.System = require('./system.js');
RG.BTree = require('./aisequence.js');
RG.Brain = require('./brain.js');
RG.Inv = require('./inv.js');
RG.Actor = require('./actor.js');
RG.Element = require('./element.js');

RG.Template = require('./template.js');

RG.Map = require('./map.js');
RG.World = require('./world.js');

RG.Effects = require('../data/effects.js');
RG.ObjectShellParser = require('./objectshellparser.js');

RG.Game = require('./game.js');
RG.Factory = require('./factory.js');

RG.Names = require('../data/name-gen.js');
RG.Overworld = require('./overworld.js');

RG.Game.FromJSON = require('./game.fromjson.js');

RG.Factory.Game = require('./factory.game.js');

module.exports = RG;

<|endoftext|>


<commit_before>var request = require('request'),
    xml = require('./xml'),
    Q = require('q');

exports.serviceURL = process.env.CONCUR_BASE_URI || "https://www.concursolutions.com";

var DEFAULTS = {
    userAgent:'Concur-platform-sdk-js',
    contentType: 'application/json'

};

exports.delete = function(options) {
    var deferred = Q.defer();

    var headers = {
        'Authorization': 'Oauth '+ options.oauthToken || options.token || options.oAuthToken,
        'Accept':options.contentType || DEFAULTS.contentType,
        'User-Agent': DEFAULTS.userAgent
    };

    var tempURL = options.resourceURL;
    if (options.id) {
        tempURL = tempURL +'/'+options.id;
    }

    request.del({url: tempURL, headers:headers}, function(error, response, body) {
        // Error with the actual request
        if (error){
            return deferred.reject(error);
        }

        // Non-204 HTTP response code
        if (response.statusCode != 204){
            return deferred.reject({
                'statusCode':response.statusCode,
                'Message':body && body.Message && JSON.parse(body).Message
            });
        }

        deferred.resolve(response.statusCode);

    });
    return deferred.promise;
};

exports.send = function(options) {
    var deferred = Q.defer();

    var headers = {
        'Authorization' : 'OAuth '+ options.oauthToken,
        'Accept': options.contentType || DEFAULTS.contentType,
        'Content-Type': options.contentType || DEFAULTS.contentType,
        'User-Agent':DEFAULTS.userAgent
    };

    request.post({url:options.resourceURL, headers:headers, body:JSON.stringify(options.body)}, function(error, response, body) {
        // Error with the actual request
        if (error) {
            return deferred.reject(error);
        }

        // Non-200 HTTP response code
        if (response.statusCode != 200) {
            return deferred.reject({
                'statusCode':response.statusCode,
                'Message':body && body.Message && JSON.parse(body).Message
            });
        }

        var bodyJSON = JSON.parse(body);

        // 200, but Error in token payload
        if (bodyJSON.Error) return deferred.reject({'error':bodyJSON.Message});

        deferred.resolve(bodyJSON);
    });
    return deferred.promise;
};

exports.get = function(options) {
    var deferred = Q.defer();

    var headers = {
        'Authorization' : 'OAuth ' + options.oauthToken || options.token || options.oAuthToken,
        'Accept' : DEFAULTS.contentType,
        'User-Agent': DEFAULTS.userAgent
    };

    var tempURL = options.resourceURL;
    if (options.id) {
        tempURL = tempURL +'/'+options.id;
    }

    request({url:tempURL, qs:options.queryParameters, headers:headers}, function(error, response, body) {
        // Error with the actual request
        if (error) {
            return deferred.reject(error);
        }

        // Non-200 HTTP response code
        if (response.statusCode != 200) {
            return deferred.reject({
                'statusCode':response.statusCode,
                'Message':body && body.Message && JSON.parse(body).Message
            });
        }

        var parsedBody;
        if (options.contentType) {
            xml.getCleansedObjectFromXmlBody(body, function (err, result) {
                if (err){
                    parsedBody = err;
                } else {
                    parsedBody = result;
                }
            });
        } else {
            parsedBody = JSON.parse(body);
        }

        // 200, but Error in token payload
        if (parsedBody.Error) return deferred.reject({'error':parsedBody.Message});
        deferred.resolve(parsedBody);
    });
    return deferred.promise;
};

exports.put = function(options) {
    var deferred = Q.defer();

    var headers = {
        'Authorization' : 'OAuth '+ options.oauthToken || options.token || options.oAuthToken,
        'Accept': DEFAULTS.contentType,
        'Content-Type': options.contentType || DEFAULTS.contentType,
        'User-Agent': DEFAULTS.userAgent
    };

    var tempURL = options.resourceURL;
    if (options.id) {
        tempURL = tempURL +'/'+options.id;
    }

    request.put({url:tempURL, headers:headers, body:JSON.stringify(options.body)}, function(error, response, body) {
        // Error with the actual request
        if (error) {
            return deferred.reject(error);
        }

        // Non-204 HTTP response code
        if (response.statusCode != 204){
            return deferred.reject({
                'statusCode':response.statusCode,
                'Message':body && body.Message && JSON.parse(body).Message
            });
        }

        deferred.resolve(response.statusCode);

    });
    return deferred.promise;
};<commit_msg>Changes<commit_after>var request = require('request'),
    xml = require('./xml'),
    Q = require('q');

exports.serviceURL = process.env.CONCUR_BASE_URI || "https://www.concursolutions.com";

var DEFAULTS = {
    userAgent:'Concur-platform-sdk-js',
    contentType: 'application/json'

};

exports.delete = function(options) {
    var deferred = Q.defer();

    var headers = {
        'Authorization': 'Oauth '+ options.oauthToken || options.token || options.oAuthToken,
        'Accept':options.contentType || DEFAULTS.contentType,
        'User-Agent': DEFAULTS.userAgent
    };

    var tempURL = options.resourceURL;
    if (options.id) {
        tempURL = tempURL +'/'+options.id;
    }

    request.del({url: tempURL, headers:headers}, function(error, response, body) {
        // Error with the actual request
        if (error){
            return deferred.reject(error);
        }

        // Non-204 HTTP response code
        if (response.statusCode != 204){
            return deferred.reject({
                'statusCode':response.statusCode,
                'Message':body && body.Message && JSON.parse(body).Message
            });
        }

        deferred.resolve(response.statusCode);

    });
    return deferred.promise;
};

exports.send = function(options) {
    var deferred = Q.defer();

    var headers = {
        'Authorization': 'Oauth '+ options.oauthToken || options.token || options.oAuthToken,
        'Accept': options.contentType || DEFAULTS.contentType,
        'Content-Type': options.contentType || DEFAULTS.contentType,
        'User-Agent':DEFAULTS.userAgent
    };

    request.post({url:options.resourceURL, headers:headers, body:JSON.stringify(options.body)}, function(error, response, body) {
        // Error with the actual request
        if (error) {
            return deferred.reject(error);
        }

        // Non-200 HTTP response code
        if (response.statusCode != 200) {
            return deferred.reject({
                'statusCode':response.statusCode,
                'Message':body && body.Message && JSON.parse(body).Message
            });
        }

        var bodyJSON = JSON.parse(body);

        // 200, but Error in token payload
        if (bodyJSON.Error) return deferred.reject({'error':bodyJSON.Message});

        deferred.resolve(bodyJSON);
    });
    return deferred.promise;
};

exports.get = function(options) {
    var deferred = Q.defer();

    var headers = {
        'Authorization' : 'OAuth ' + options.oauthToken || options.token || options.oAuthToken,
        'Accept' : DEFAULTS.contentType,
        'User-Agent': DEFAULTS.userAgent
    };

    var tempURL = options.resourceURL;
    if (options.id) {
        tempURL = tempURL +'/'+options.id;
    }

    request({url:tempURL, qs:options.queryParameters, headers:headers}, function(error, response, body) {
        // Error with the actual request
        if (error) {
            return deferred.reject(error);
        }

        // Non-200 HTTP response code
        if (response.statusCode != 200) {
            return deferred.reject({
                'statusCode':response.statusCode,
                'Message':body && body.Message && JSON.parse(body).Message
            });
        }

        var parsedBody;
        if (options.contentType) {
            xml.getCleansedObjectFromXmlBody(body, function (err, result) {
                if (err){
                    parsedBody = err;
                } else {
                    parsedBody = result;
                }
            });
        } else {
            parsedBody = JSON.parse(body);
        }

        // 200, but Error in token payload
        if (parsedBody.Error) return deferred.reject({'error':parsedBody.Message});
        deferred.resolve(parsedBody);
    });
    return deferred.promise;
};

exports.put = function(options) {
    var deferred = Q.defer();

    var headers = {
        'Authorization' : 'OAuth '+ options.oauthToken || options.token || options.oAuthToken,
        'Accept': DEFAULTS.contentType,
        'Content-Type': options.contentType || DEFAULTS.contentType,
        'User-Agent': DEFAULTS.userAgent
    };

    var tempURL = options.resourceURL;
    if (options.id) {
        tempURL = tempURL +'/'+options.id;
    }

    request.put({url:tempURL, headers:headers, body:JSON.stringify(options.body)}, function(error, response, body) {
        // Error with the actual request
        if (error) {
            return deferred.reject(error);
        }

        // Non-204 HTTP response code
        if (response.statusCode != 204){
            return deferred.reject({
                'statusCode':response.statusCode,
                'Message':body && body.Message && JSON.parse(body).Message
            });
        }

        deferred.resolve(response.statusCode);

    });
    return deferred.promise;
};<|endoftext|>


<commit_before>UI.body.helpers({
  spacebarState: function() {
    return Session.get('spacebarToggleState') ? 'true' : 'false';
  },
  mouseXState: function() {
    return Session.get('mouseX') * 10 || '0';
  },
  mouseYState: function() {
    return Session.get('mouseY') * 10 || '0';
  },
  reticleState: function() {
    return Session.get('spacebarToggleState') ? 'active' : '';
  }
});

UI.body.rendered = function() {
  // The global application namespace.
  window.App = window.App || {};

  // Grab the main game container.
  App.container = $(document);

  // Initialize listeners for keyboard events.
  App.keyInit();

  // Another namespace to hold all the graphics stuff.
  App.three = App.three || App.THREEinit();

  // App.player is a THREE group containing the ship, the reticle,
  // and the camera.
  App.player = new THREE.Object3D();
  App.player.camera = App.three.camera;
  App.player.add(App.player.camera);

  App.three.scene.add(new THREE.AxisHelper(20));

  App.player.move = function(direction) {
    switch(direction) {
    case 'left':
      this.position.x += 0.1;
      break;
    case 'right':
      this.position.x -= 0.1;
      break;
    case 'up':
      this.position.z += 0.1;
      break;
    case 'down':
      this.position.z -= 0.1;
      break;
    }

    this.update();
  };

  App.player.update = function() {
    playerStream.emit('updatePlayer', this.position);
    // TODO: check if this is necessary.
    App.triggerEvent('playerChanged', this.position);
  };

  playerStream.on('updatePlayer', function(position) {
    App.player.position = position;

    App.triggerEvent('playerChanged', position);
  });

  App.player.rotate = function(direction, angle) {
    angle = angle || Math.PI / 180;

    switch(direction) {
    case 'left':
      this.rotation.y += angle;
      break;
    case 'right':
      this.rotation.y -= angle;
      break;
    case 'up':
      this.rotation.x -= angle;
      break;
    case 'down':
      this.rotation.x += angle;
      break;
    }
  };

  // Initialize easter egg.
  App.easterEgg.init();

  // Initialize touchscreen gestures.
  App.hammerInit();

  Players.find().observe({
    added: function(player) {
      App.player._id = player._id;
      App.player.position = player.position;

      App.triggerEvent('playerAdded', App.player);

      THREEx.SpaceShips.loadSpaceFighter03(function(object3d) {
        var ship = object3d;

        App.player.ship = ship;
        App.player.add(ship);

        App.player.camera.position.x = ship.position.x + 0;
        App.player.camera.position.y = ship.position.y + 2.3;
        App.player.camera.position.z = ship.position.z - 3.5;

        App.player.reticle = new THREE.Mesh(
          new THREE.RingGeometry(0.1, 0.12, 20),
          new THREE.MeshBasicMaterial({
            color: 0xffffff,
            side: THREE.DoubleSide
          })
        );

        App.player.reticle.position.x = ship.position.x;
        App.player.reticle.position.y = ship.position.y;
        App.player.reticle.position.z = ship.position.z + 2.0;

        App.player.reticle.lookAt(App.player.camera.position);
        App.player.camera.lookAt(App.player.reticle.position);

        App.player.add(App.player.reticle);

        App.three.scene.add(App.player);

        App.triggerEvent('playerLoaded', App.player);

        setInterval(function() {
          var player = _.pick(App.player, '_id', 'position');
          Players.update(player._id, player);
        }, 500);
      });
    }
  });

  App.three.onRenderFcts.push(function() {
    if (App.player.ship) {
      if (App.keyState('left') || App.keyState('a')) {
        App.player.move('left');
      }

      if (App.keyState('right') || App.keyState('d')) {
        App.player.move('right');
      }

      if (App.keyState('up') || App.keyState('w')) {
        App.player.move('up');
      }

      if (App.keyState('down') || App.keyState('s')) {
        App.player.move('down');
      }
    }
  });

  // Camera Controls.
  var mouse = {
    x: 0,
    y: 0
  };

  document.addEventListener('mousemove', function(event) {
    mouse.x = (event.clientX / window.innerWidth) - 0.5;
    Session.set('mouseX', mouse.x);

    mouse.y = (event.clientY / window.innerHeight) - 0.5;
    Session.set('mouseY', mouse.y);
  }, false);

  App.three.onRenderFcts.push(function(delta) {
    if (App.player.ship && App.keyToggleState('spacebar')) {
      var x = Session.get('mouseX');

      if (Math.abs(x * 10) > 0.2) {
        var angle = (Math.PI / 180) * (Math.abs(x) * 5);

        if (x < 0) {
          App.player.rotate('left', angle);
        } else {
          App.player.rotate('right', angle);
        }
      }

      var y = Session.get('mouseY');

      if (Math.abs(y * 10) > 0.2) {
        var angle = (Math.PI / 180) * (Math.abs(y) * 5);

        if (y < 0) {
          App.player.rotate('up', angle);
        } else {
          App.player.rotate('down', angle);
        }
      }
    }
  });

  // App.container.on('shipLoaded', function (ship) {
  //   App.three.camera.controls = new THREE.OrbitControls(App.three.camera);
  //   // Disable directional keys for OrbitControls.
  //   App.three.camera.controls.noKeys = true;
  //   App.three.camera.controls.noZoom = true;
  //
  //   App.three.camera.controls.syncTo = function(obj) {
  //     App.three.camera.controls.target.x = obj.position.x;
  //     App.three.camera.controls.target.y = obj.position.y;
  //     App.three.camera.controls.target.z = obj.position.z;
  //   }
  //
  //   App.three.camera.controls.syncTo(App.player.ship);
  //
  //   App.three.onRenderFcts.push(function () {
  //     App.three.camera.controls.update();
  //   });
  // });
};
<commit_msg>Finally get rotation+movement working.<commit_after>UI.body.helpers({
  spacebarState: function() {
    return Session.get('spacebarToggleState') ? 'true' : 'false';
  },
  mouseXState: function() {
    return Session.get('mouseX') * 10 || '0';
  },
  mouseYState: function() {
    return Session.get('mouseY') * 10 || '0';
  },
  reticleState: function() {
    return Session.get('spacebarToggleState') ? 'active' : '';
  }
});

UI.body.rendered = function() {
  // The global application namespace.
  window.App = window.App || {};

  // Grab the main game container.
  App.container = $(document);

  // Initialize listeners for keyboard events.
  App.keyInit();

  // Another namespace to hold all the graphics stuff.
  App.three = App.three || App.THREEinit();

  // App.player is a THREE group containing the ship, the reticle,
  // and the camera.
  App.player = new THREE.Object3D();
  App.player.camera = App.three.camera;
  App.player.add(App.player.camera);

  App.three.scene.add(new THREE.AxisHelper(20));

  App.player.move = function(direction) {
    var distance = 0.1;

    var dir;

    switch(direction) {
    case 'left':
      dir = new THREE.Vector3(distance, 0, 0);
      break;
    case 'right':
      dir = new THREE.Vector3(-distance, 0, 0);
      break;
    case 'up':
      dir = new THREE.Vector3(0, 0, distance);
      break;
    case 'down':
      dir = new THREE.Vector3(0, 0, -distance);
      break;
    }

    var matrix = new THREE.Matrix4();
    matrix.extractRotation(this.matrix);

    dir = dir.applyProjection(matrix);

    this.position.x += dir.x;
    this.position.y += dir.y;
    this.position.z += dir.z;

    this.update();
  };

  App.player.update = function() {
    playerStream.emit('updatePlayer', this.position);
    // TODO: check if this is necessary.
    App.triggerEvent('playerChanged', this.position);
  };

  App.player.reset = function() {
    this.position = new THREE.Vector3();
  };

  playerStream.on('updatePlayer', function(position) {
    App.player.position = position;

    App.triggerEvent('playerChanged', position);
  });

  App.player.rotate = function(direction, angle) {
    angle = angle || Math.PI / 180;

    switch(direction) {
    case 'left':
      this.rotation.y += angle;
      break;
    case 'right':
      this.rotation.y -= angle;
      break;
    case 'up':
      this.rotation.x -= angle;
      break;
    case 'down':
      this.rotation.x += angle;
      break;
    }
  };

  // Initialize easter egg.
  App.easterEgg.init();

  // Initialize touchscreen gestures.
  App.hammerInit();

  Players.find().observe({
    added: function(player) {
      App.player._id = player._id;
      App.player.position = player.position;

      App.triggerEvent('playerAdded', App.player);

      THREEx.SpaceShips.loadSpaceFighter03(function(object3d) {
        var ship = object3d;

        App.player.ship = ship;
        App.player.add(ship);

        App.player.camera.position.x = ship.position.x + 0;
        App.player.camera.position.y = ship.position.y + 2.3;
        App.player.camera.position.z = ship.position.z - 3.5;

        App.player.reticle = new THREE.Mesh(
          new THREE.RingGeometry(0.1, 0.12, 20),
          new THREE.MeshBasicMaterial({
            color: 0xffffff,
            side: THREE.DoubleSide
          })
        );

        App.player.reticle.position.x = ship.position.x;
        App.player.reticle.position.y = ship.position.y;
        App.player.reticle.position.z = ship.position.z + 2.0;

        App.player.reticle.lookAt(App.player.camera.position);
        App.player.camera.lookAt(App.player.reticle.position);

        App.player.add(App.player.reticle);

        App.three.scene.add(App.player);

        App.triggerEvent('playerLoaded', App.player);

        setInterval(function() {
          var player = _.pick(App.player, '_id', 'position');
          Players.update(player._id, player);
        }, 500);
      });
    }
  });

  App.three.onRenderFcts.push(function() {
    if (App.player.ship) {
      if (App.keyState('left') || App.keyState('a')) {
        App.player.move('left');
      }

      if (App.keyState('right') || App.keyState('d')) {
        App.player.move('right');
      }

      if (App.keyState('up') || App.keyState('w')) {
        App.player.move('up');
      }

      if (App.keyState('down') || App.keyState('s')) {
        App.player.move('down');
      }
    }
  });

  // Camera Controls.
  var mouse = {
    x: 0,
    y: 0
  };

  document.addEventListener('mousemove', function(event) {
    mouse.x = (event.clientX / window.innerWidth) - 0.5;
    Session.set('mouseX', mouse.x);

    mouse.y = (event.clientY / window.innerHeight) - 0.5;
    Session.set('mouseY', mouse.y);
  }, false);

  App.three.onRenderFcts.push(function(delta) {
    if (App.player.ship && App.keyToggleState('spacebar')) {
      var x = Session.get('mouseX');

      if (Math.abs(x * 10) > 0.2) {
        var angle = (Math.PI / 180) * (Math.abs(x) * 5);

        if (x < 0) {
          App.player.rotate('left', angle);
        } else {
          App.player.rotate('right', angle);
        }
      }

      var y = Session.get('mouseY');

      if (Math.abs(y * 10) > 0.2) {
        var angle = (Math.PI / 180) * (Math.abs(y) * 5);

        if (y < 0) {
          App.player.rotate('up', angle);
        } else {
          App.player.rotate('down', angle);
        }
      }
    }
  });

  // App.container.on('shipLoaded', function (ship) {
  //   App.three.camera.controls = new THREE.OrbitControls(App.three.camera);
  //   // Disable directional keys for OrbitControls.
  //   App.three.camera.controls.noKeys = true;
  //   App.three.camera.controls.noZoom = true;
  //
  //   App.three.camera.controls.syncTo = function(obj) {
  //     App.three.camera.controls.target.x = obj.position.x;
  //     App.three.camera.controls.target.y = obj.position.y;
  //     App.three.camera.controls.target.z = obj.position.z;
  //   }
  //
  //   App.three.camera.controls.syncTo(App.player.ship);
  //
  //   App.three.onRenderFcts.push(function () {
  //     App.three.camera.controls.update();
  //   });
  // });
};
<|endoftext|>


<commit_before>define(['jquery','jquery-popup-overlay','app/utils','bootstrap.min'],function($,popup,utils) {

    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    window.BakbakEngine = function(debug,visitor) {
        var self = this;
        init = function () {
            if(typeof bakbaks === 'undefined') return;
            if(eval(decodeURI(bakbaks.bakbak_rule))) {
                self.showBakBak(bakbaks);
            } else {
                console.log("No bakbak to process!");
            }
        }

        this.showBakBak = function(bakbak) {
            var bakbakHtml = returnBakbakHtml(bakbak);
            if(bakbak.view_as == 'fullPagePopUp') {
                showFullPagePopUp(bakbakHtml,bakbak.name);
            } else {
                console.log("Incorrect view_as");
            }
        }

        showFullPagePopUp = function(html,subject) {
            console.log("Full page popup");
            $('body').append("

");
            $("#bakbakFullPagePopUpContainer").html(decodeURI(html));
            $("#bakbakFullPagePopUp").popup({closeelement: '.bakbakFullPagePopUp_close'});
            $("#bakbakFullPagePopUp").popup('show');
            $(document).trigger('bakbak_reporting_bakbak_show',subject);
            initializeEmailResponses(subject);
        }

        returnBakbakHtml = function(bakbak) {
            console.log("DisplayBakBak");
            var formHtml;
            if(bakbak.type == '0')
                formHtml =returnEmbedForm(bakbak.data);
            else if(bakbak.type == '1')
                formHtml = returnGoogleForm(decodeURI(bakbak.data));
            else
                formHtml = returnEmbedForm(decodeURI(bakbak.data));
            return formHtml;
        }

        returnEmbedForm = function(embedCode) {
            return embedCode;
        }

        returnGoogleForm = function(url) {
                var html;
                $.ajax({
                    url: url,
                    success: function(content) {
                                html = content;
                            },
                    async: false
                });
                return html;
        }

        returnDefaultForm = function(msg) {
            console.log("Showing Default Form!");
            var html = new EJS({url: bakbakUrl+'js/tpl/defaultForm.ejs'}).render({displayMsg:msg});
            return html;
        }

        initializeEmailResponses = function(subject) {
            $($('#bakbakFullPagePopUpContainer > form')[0]).on('submit',function(ev) {
                ev.preventDefault();
                self.sendContactUsForm($(this).serializeObject(),subject);
                return true;
            });
        };

        initializeBootStrapTabs = function() {
            $('#bakbak_tabs').tab();
        }

        this.sendContactUsForm = function(data,subject) {
            $('#bakbakEmailButton').attr('disabled',true);
            console.log(data);
            toSend = {};
            toSend['email'] = adminEmail;
            toSend['template'] = 'bakbakEmail';
            toSend['data'] = data;
            toSend['subject'] = subject;
            $.post( bakbakUrl + "email",toSend,'json')
                            .done(function(response) {
                                console.log("Attempted to send email");
                                if(response == "OK") {
                                    console.log('Email sent SUCCESS!');
                                    $('#bakbakFullPagePopUpContainer').prepend("
Thanks for interest!
");
                                    $('#bakbakFullPagePopUpContainer > form')[0].reset();
                                    $('#bakbakEmailButton').removeAttr('disabled');
                                } else {
                                    $('#bakbakFullPagePopUp').append("
Error Contacting the Server!
");
                                    $('#bakbakEmailButton').removeAttr('disabled');
                                }

                            });
        }

        init();

	};
}); <commit_msg>Bind to each form on bakbak<commit_after>define(['jquery','jquery-popup-overlay','app/utils','bootstrap.min'],function($,popup,utils) {

    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    window.BakbakEngine = function(debug,visitor) {
        var self = this;
        init = function () {
            if(typeof bakbaks === 'undefined') return;
            if(eval(decodeURI(bakbaks.bakbak_rule))) {
                self.showBakBak(bakbaks);
            } else {
                console.log("No bakbak to process!");
            }
        }

        this.showBakBak = function(bakbak) {
            var bakbakHtml = returnBakbakHtml(bakbak);
            if(bakbak.view_as == 'fullPagePopUp') {
                showFullPagePopUp(bakbakHtml,bakbak.name);
            } else {
                console.log("Incorrect view_as");
            }
        }

        showFullPagePopUp = function(html,subject) {
            console.log("Full page popup");
            $('body').append("

");
            $("#bakbakFullPagePopUpContainer").html(decodeURI(html));
            $("#bakbakFullPagePopUp").popup({closeelement: '.bakbakFullPagePopUp_close'});
            $("#bakbakFullPagePopUp").popup('show');
            $(document).trigger('bakbak_reporting_bakbak_show',subject);
            initializeEmailResponses(subject);
        }

        returnBakbakHtml = function(bakbak) {
            console.log("DisplayBakBak");
            var formHtml;
            if(bakbak.type == '0')
                formHtml =returnEmbedForm(bakbak.data);
            else if(bakbak.type == '1')
                formHtml = returnGoogleForm(decodeURI(bakbak.data));
            else
                formHtml = returnEmbedForm(decodeURI(bakbak.data));
            return formHtml;
        }

        returnEmbedForm = function(embedCode) {
            return embedCode;
        }

        returnGoogleForm = function(url) {
                var html;
                $.ajax({
                    url: url,
                    success: function(content) {
                                html = content;
                            },
                    async: false
                });
                return html;
        }

        returnDefaultForm = function(msg) {
            console.log("Showing Default Form!");
            var html = new EJS({url: bakbakUrl+'js/tpl/defaultForm.ejs'}).render({displayMsg:msg});
            return html;
        }

        initializeEmailResponses = function(subject) {
            $('#bakbakFullPagePopUpContainer form').each(function() {
                $(this).on('submit',function(ev) {
                ev.preventDefault();
                self.sendContactUsForm($(this).serializeObject(),subject);
                return true;
            });
        });
        }

        initializeBootStrapTabs = function() {
            $('#bakbak_tabs').tab();
        }

        this.sendContactUsForm = function(data,subject) {
            $('#bakbakEmailButton').attr('disabled',true);
            console.log(data);
            toSend = {};
            toSend['email'] = adminEmail;
            toSend['template'] = 'bakbakEmail';
            toSend['data'] = data;
            toSend['subject'] = subject;
            $.post( bakbakUrl + "email",toSend,'json')
                            .done(function(response) {
                                console.log("Attempted to send email");
                                if(response == "OK") {
                                    console.log('Email sent SUCCESS!');
                                    $('#bakbakFullPagePopUpContainer').prepend("
Thanks for interest!
");
                                    $('#bakbakFullPagePopUpContainer > form')[0].reset();
                                    $('#bakbakEmailButton').removeAttr('disabled');
                                } else {
                                    $('#bakbakFullPagePopUp').append("
Error Contacting the Server!
");
                                    $('#bakbakEmailButton').removeAttr('disabled');
                                }

                            });
        }

        init();

	};
}); <|endoftext|>


<commit_before>function getLoc() {
    var url = document.createElement("a");
    url.href=document.URL;
    var loc = url.search;
    if (loc.indexOf("loc=") === 1) {
				       loc = loc.substring(5);
				       console.log("LOC TO PARSE IS: " + loc);
				   }
    return loc;
}

var epeek_theme = function() {
    "use strict";

    // Regular expressions for user input
    // TODO: species:gene?
    // TODO: Duplicated in default.js
    var loc_re = /^(\w+):(\w+):(\d+)-(\d+)$/;
    var ens_re = /^ENS\w+\d+$/;

    var gBrowser;
    var gBrowserTheme = function(gB, div) {
	gBrowser = gB;

	// Callbacks:
	// TODO: gBrowserTheme.highlight needs to be exported? I don't think so, rename to highlight?
	gBrowser.highlight = gBrowserTheme.highlight;
	gBrowser.orthologues_callback = gBrowserTheme.orthologues_cbak;
	var loc = getLoc();

	if (gBrowserTheme.isLocation(loc)) {
	    gBrowserTheme.parseLocation(loc);
	} else {
	    gBrowser.gene(loc);
	}

	gBrowser(div);
	if (gBrowser.gene() !== undefined) {
	    gBrowser.get_gene(gBrowser.gene());
	} else {
	    gBrowser.start();
	}

	gBrowserTheme.orientationChange();

    };

    // TODO: What happens on error? i.e. if the string is not a valid location
    // TODO: We can make it smarter? allowing for examples species:gene?

    /** parseLocation takes a string as input and guesses a location
        The expected location should be on the form:
        species:chr:from-to
    */
    gBrowserTheme.parseLocation = function(loc) {
	var loc_arr = loc_re.exec(loc);
	gBrowser.species(loc_arr[1]);
	gBrowser.chr(loc_arr[2]);
	gBrowser.from(loc_arr[3]);
	gBrowser.to(loc_arr[4]);

	return gBrowserTheme;
    };

    // TODO: Can be abstracted out? (This is also defined in clients/lib/default.js)
    /** isLocation returns true if the argument looks like a location of the form
	species:chr:from-to or false otherwise
    */
    gBrowserTheme.isLocation = function(term) {
	if (term.match(loc_re)) {
	    return true;
	} else {
	    return false;
	}
    };

    /**
     */
    gBrowserTheme.orthologues_cbak = function (orthologues) {
	var orth_select = d3.select("#ePeek_orthologues_select")
	    .attr("id", "ePeek_orth_select");

	orth_select
	    .append("option")
	    .attr("class", "ePeek_orth_option")
	    .text("-- Jump to ortholog --")

	orth_select.selectAll("option2")
	    .data(orthologues, function(d){return d.id})
	    .enter()
	    .append("option")
	    .attr("class", "ePeek_orth_option")
	    .attr("value", function(d) {return d.id})
	    .text(function(d) {return d.id + " (" + d.species + " - " + d.type + ")"});

	// We fill the number of orthologues in the tab label
	d3.select("#ePeek_orthologues_label")
	    .html("Orthologues [" + (orthologues === undefined ? 0 : orthologues.length) + "]");

	// We listen on orthologues options
	orth_select.on("change", function() {
//	    d3.select("#ePeek_" + div_id + "_ensGene_select").remove();
	    gBrowser.ensGene_lookup(this.value);
	});

    };

    /** highlight shows the gene info pane
        This function can be shadowed by a custom - user created method
        to display the gene information in a different way -- or html element
        Its argument is a literal object having the following information:

external_name   => External name of the gene

ID              => Ensembl ID of the gene

description     => A short description of the gene

logic_name      => The source of the gene

feature_type    => This is always set to gene

seq_region_name => The chromosome or region name the gene is located

start           => The start coordinate in the seq_region_name

end             => The end coordinate in the seq_region_name

strand          => The strand in the seq_region_name

    */
    gBrowserTheme.highlight = function(gene) {
	// We first remove previous data and elements
//	d3.select("#gene_content div").remove();
	d3.select("#gene_content ul").remove();

	// We update the text of the header in the info div
	d3.select("#gene_info h1").text(gene.external_name);

	// We then populate the gene info
	var gene_info_items_list = d3.select("#gene_content")
	    .append("ul")
	    .attr("class", "edgetoedge scroll");

	gene_info_items_list
	    .append("li")
	    .attr("class", "sep")
	    .text("Gene Info")

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .html("Ensembl ID: " + gene.ID);

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .html("Description: " + gene.description);

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .html("Source: " + gene.logic_name);

	gene_info_items_list
	    .append("li")
	    .attr("class", "sep")
	    .html("Location");

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .html("Current species: " + gBrowser.species());

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .html("Location: " + gene.seq_region_name + ":" + gene.start + "-" + gene.end + " (Strand: " + (gene.strand === "1" ? "+" : "-") + ")");

	gene_info_items_list
	    .append("li")
	    .attr("class", "sep")
	    .attr("id", "ePeek_orthologues_label")
	    .html("Orthologues");

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .append("select")
	    .attr("id", "ePeek_orthologues_select");

	gene_info_items_list
	    .append("li")
	    .attr("class", "sep")
	    .html("Open " + gene.external_name + " in...");

	gene_info_items_list
	    .append("li")
	    .attr("class", "arrow")
	    .append("a")
	    .attr("href", gBrowserTheme.buildEnsemblGeneLink(gene.ID))
	    .attr("target", "_blank")
	    .append("img")
	    .attr("src", "ensembl_logo_small.png");

	// Fill the orthologues select
	gBrowser.orthologues(gene.ID);

	// TODO: This way of getting to the gene_info div prevents the use of
	// transitions. We may find a better way!
	window.location.href="#gene_info";

    };

    // TODO: Duplicated in default.js
    /** buildEnsemblGeneLink returns the Ensembl url pointing to the gene summary given in as argument
	The gene id shouuld be a valid ensembl gene id of the form "ENSG......XXXX"
    */
    gBrowserTheme.buildEnsemblGeneLink = function(ensID) {
	//"http://www.ensembl.org/Homo_sapiens/Gene/Summary?g=ENSG00000139618"
	var url = "http://www.ensembl.org/" + gBrowser.species() + "/Gene/Summary?g=" + ensID;
	return url;
    };

    gBrowserTheme.orientationChange = function() {

	// Default Android browser based on the WebKit engine
	// which also powers the Safari browser on desktops, laptops and Apple's iOS-based mobile devices
	// doesn't seem to understand window.matchMedia, so we need to use this alternative.
	window.onorientationchange = function() {
	    // Strangely enough, default android browser reverses clientWidth and clientHeight?
	    // TODO: Post a question somewhere? (StackOverflow?) -> DONE
	    // TODO: It seems that introducing a short delay (500ms) the clientWidth and clientHeight are properly set
            setTimeout(function() {
		// This may be needed for IE for mobiles?
		//        var w=window.innerWidth
		//           || document.documentElement.clientWidth
		//           || document.body.clientWidth;

		var w = document.documentElement.clientWidth;
		gBrowser.resize(w-20);
            }, 500);
	}
    };

    return gBrowserTheme;

};<commit_msg>fixed name for gene_info_callback<commit_after>function getLoc() {
    var url = document.createElement("a");
    url.href=document.URL;
    var loc = url.search;
    if (loc.indexOf("loc=") === 1) {
				       loc = loc.substring(5);
				       console.log("LOC TO PARSE IS: " + loc);
				   }
    return loc;
}

var epeek_theme = function() {
    "use strict";

    // Regular expressions for user input
    // TODO: species:gene?
    // TODO: Duplicated in default.js
    var loc_re = /^(\w+):(\w+):(\d+)-(\d+)$/;
    var ens_re = /^ENS\w+\d+$/;

    var gBrowser;
    var gBrowserTheme = function(gB, div) {
	gBrowser = gB;

	// Callbacks:
	// TODO: gBrowserTheme.highlight needs to be exported? I don't think so, rename to highlight?
	gBrowser.gene_info_callback = gene_info_callback;
	gBrowser.orthologues_callback = gBrowserTheme.orthologues_cbak;
	var loc = getLoc();

	if (gBrowserTheme.isLocation(loc)) {
	    gBrowserTheme.parseLocation(loc);
	} else {
	    gBrowser.gene(loc);
	}

	gBrowser(div);
	if (gBrowser.gene() !== undefined) {
	    gBrowser.get_gene(gBrowser.gene());
	} else {
	    gBrowser.start();
	}

	gBrowserTheme.orientationChange();

    };

    // TODO: What happens on error? i.e. if the string is not a valid location
    // TODO: We can make it smarter? allowing for examples species:gene?

    /** parseLocation takes a string as input and guesses a location
        The expected location should be on the form:
        species:chr:from-to
    */
    gBrowserTheme.parseLocation = function(loc) {
	var loc_arr = loc_re.exec(loc);
	gBrowser.species(loc_arr[1]);
	gBrowser.chr(loc_arr[2]);
	gBrowser.from(loc_arr[3]);
	gBrowser.to(loc_arr[4]);

	return gBrowserTheme;
    };

    // TODO: Can be abstracted out? (This is also defined in clients/lib/default.js)
    /** isLocation returns true if the argument looks like a location of the form
	species:chr:from-to or false otherwise
    */
    gBrowserTheme.isLocation = function(term) {
	if (term.match(loc_re)) {
	    return true;
	} else {
	    return false;
	}
    };

    /**
     */
    gBrowserTheme.orthologues_cbak = function (orthologues) {
	var orth_select = d3.select("#ePeek_orthologues_select")
	    .attr("id", "ePeek_orth_select");

	orth_select
	    .append("option")
	    .attr("class", "ePeek_orth_option")
	    .text("-- Jump to ortholog --")

	orth_select.selectAll("option2")
	    .data(orthologues, function(d){return d.id})
	    .enter()
	    .append("option")
	    .attr("class", "ePeek_orth_option")
	    .attr("value", function(d) {return d.id})
	    .text(function(d) {return d.id + " (" + d.species + " - " + d.type + ")"});

	// We fill the number of orthologues in the tab label
	d3.select("#ePeek_orthologues_label")
	    .html("Orthologues [" + (orthologues === undefined ? 0 : orthologues.length) + "]");

	// We listen on orthologues options
	orth_select.on("change", function() {
//	    d3.select("#ePeek_" + div_id + "_ensGene_select").remove();
	    gBrowser.ensGene_lookup(this.value);
	});

    };

    var gene_info_callback = function(gene) {
	// We first remove previous data and elements
//	d3.select("#gene_content div").remove();
	d3.select("#gene_content ul").remove();

	// We update the text of the header in the info div
	d3.select("#gene_info h1").text(gene.external_name);

	// We then populate the gene info
	var gene_info_items_list = d3.select("#gene_content")
	    .append("ul")
	    .attr("class", "edgetoedge scroll");

	gene_info_items_list
	    .append("li")
	    .attr("class", "sep")
	    .text("Gene Info")

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .html("Ensembl ID: " + gene.ID);

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .html("Description: " + gene.description);

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .html("Source: " + gene.logic_name);

	gene_info_items_list
	    .append("li")
	    .attr("class", "sep")
	    .html("Location");

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .html("Current species: " + gBrowser.species());

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .html("Location: " + gene.seq_region_name + ":" + gene.start + "-" + gene.end + " (Strand: " + (gene.strand === "1" ? "+" : "-") + ")");

	gene_info_items_list
	    .append("li")
	    .attr("class", "sep")
	    .attr("id", "ePeek_orthologues_label")
	    .html("Orthologues");

	gene_info_items_list
	    .append("li")
	    .attr("class", "rounded")
	    .append("select")
	    .attr("id", "ePeek_orthologues_select");

	gene_info_items_list
	    .append("li")
	    .attr("class", "sep")
	    .html("Open " + gene.external_name + " in...");

	gene_info_items_list
	    .append("li")
	    .attr("class", "arrow")
	    .append("a")
	    .attr("href", gBrowserTheme.buildEnsemblGeneLink(gene.ID))
	    .attr("target", "_blank")
	    .append("img")
	    .attr("src", "ensembl_logo_small.png");

	// Fill the orthologues select
	gBrowser.orthologues(gene.ID);

	// TODO: This way of getting to the gene_info div prevents the use of
	// transitions. We may find a better way!
	window.location.href="#gene_info";

    };

    // TODO: Duplicated in default.js
    /** buildEnsemblGeneLink returns the Ensembl url pointing to the gene summary given in as argument
	The gene id shouuld be a valid ensembl gene id of the form "ENSG......XXXX"
    */
    gBrowserTheme.buildEnsemblGeneLink = function(ensID) {
	//"http://www.ensembl.org/Homo_sapiens/Gene/Summary?g=ENSG00000139618"
	var url = "http://www.ensembl.org/" + gBrowser.species() + "/Gene/Summary?g=" + ensID;
	return url;
    };

    gBrowserTheme.orientationChange = function() {

	// Default Android browser based on the WebKit engine
	// which also powers the Safari browser on desktops, laptops and Apple's iOS-based mobile devices
	// doesn't seem to understand window.matchMedia, so we need to use this alternative.
	window.onorientationchange = function() {
	    // Strangely enough, default android browser reverses clientWidth and clientHeight?
	    // TODO: Post a question somewhere? (StackOverflow?) -> DONE
	    // TODO: It seems that introducing a short delay (500ms) the clientWidth and clientHeight are properly set
            setTimeout(function() {
		// This may be needed for IE for mobiles?
		//        var w=window.innerWidth
		//           || document.documentElement.clientWidth
		//           || document.body.clientWidth;

		var w = document.documentElement.clientWidth;
		gBrowser.resize(w-20);
            }, 500);
	}
    };

    return gBrowserTheme;

};<|endoftext|>


<commit_before>/****
* multipart message generation based on translated templates
****/

var mep, editor;
var txt_changed = false;
var language = 'en';

$(function () {

  // insert html inputs via templates
  $(get_tmpl("message_inputs")).Chevron("render", {}, reference_message_inputs);
  $(get_tmpl("mep_selection")).Chevron("render", {}, reference_mep_selection);

});

// send fax
function sendfax() {
  var msg;
  $('#full_message').val(msg = (nicEditors.findEditor('full_message').getContent()||''));
  if (msg != '' && msg.length > 140 && msg.length < 70000) {
    document.getElementById("faxform").submit();
  }
}

/**
* switch language
**/
function setLng(l) {
  if (l == 'en' || l == 'de') {
    language = l;
  }
}

function update_language () {
  setLng($('#language_selector').val());
  $(get_tmpl("message_inputs")).Chevron("render", {}, function (result) {
    removeEditor();
    reference_message_inputs(result);
    $('#id').val((mep||{}).id || '124935'); // sorry michel ;)
    load_user_input();
  });
}

/***
* loading and displaying html elements and bind actions to them
***/
function reference_mep_selection (result) {
  $('div.mepFilter').html(result);
  $('#language_selector').on('change', update_language);
  $('#country_selector,#group_selector').on('change', request_mep);
  $('#country_selector,#group_selector').on('change', refine_autocomplete);
  $('#mep_selector').autocomplete({
    source: current_autocomplete_meps
    , select: request_mep
  }).focus(function(){
    $('#mep_selector').autocomplete('search', $(this).val() || ' ');
  });
  $('#refresh_mep').on('click', function () {
    request_mep();
  });
  $('#language_selector').val(language);
}

function refine_autocomplete () {
  var c, g;
  current_autocomplete_meps = [];
  for (var i = 0; i < autocomplete_meps.length; i++) {
    if (((!(c = $('#country_selector').val())) || autocomplete_meps[i].country == c) && (!(g = $('#group_selector').val()) || autocomplete_meps[i].group == g)) {
      current_autocomplete_meps.push(autocomplete_meps[i]);
    }
  }
  $('#mep_selector').autocomplete('option', 'source', current_autocomplete_meps);
}

function reference_message_inputs (result) {
  $('#faxform').html(result);
  $('#name,#hometown,#whycare1,#whycare2,#age').on('change', formulate_message);
  $('#name,#hometown,#whycare1,#whycare2,#age').on('change', showEditor);
  $('#sendfax').on('click', function () {
    // piwik tracking then send
    jQuery.ajax({
        'url': 'https://piwik.netzfreiheit.org/piwik.php?idsite=11&rec=1&url=https%3A%2F%2Fsavetheinternet.eu&idgoal=4&e_c=contact&e_n=fax&e_v=' + (txt_changed ? 1 : 0)
        , 'complete': sendfax
      });
  });
}

/***
* AJAX request MEPs
***/
function request_mep () {
  if ($('#country_selector').val()) {
    //$.ajax('/sti/choose_mep/', {
    $.ajax('https://faxjh.savetheinternet.eu/sti/choose_mep/', {
      data: {'country': $('#country_selector').val(), 'group': $('#group_selector').val(), 'id': $('#mep_selector').val()}
      , success: receive_mep
      , dataType: 'json'
    });
  } else {
    clear_mep();
  }
}

function clear_mep () {
  mep = null;
  $('#mep_infos_top').html();
  $('#id').val('');
  $('#name,#hometown,#whycare1,#whycare2,#age').hide();
  removeEditor();
}

function receive_mep (data, status, jqXHR) {
  if (data && data.id) {
    mep = data;
    $(get_tmpl('mep_infos')).Chevron('render', data, '#mep_infos_top');
    $('#id').val(data['id']);
    $('#group_selector,#mep_selector,#refresh_mep,#language_selector').show();
    load_user_input();
  } else {
    clear_mep();
  }
}

/***
* handle html-editor ncEditor for main message box
***/
function showEditor () {
  if (!editor) {
    $('#full_message').show();
    editor = new nicEditor({buttonList : ['bold','italic','underline','left','center','right','justify','ol','ul','subscript','superscript','strikethrough','removeformat','indent','outdent'], iconsPath: '/static/images/nicEditorIcons.gif'}).panelInstance('full_message').addEvent('blur', function () {
    txt_changed = true;
    });
    $('#sendfax').show();
  }
}

function removeEditor () {
  if (editor) {
    editor.removeInstance('full_message');
    editor = null;
  }
  $('#full_message').hide();
  $('#sendfax').hide();
}

/***
* persist and load user input
***/
function load_user_input () {
  $('#name,#hometown,#whycare1,#whycare2,#age').show();
  if (typeof window !== 'undefined' && window.localStorage) {
    $('#age').val(window.localStorage.getItem('age'));
    $('#name').val(window.localStorage.getItem('name'));
    $('#hometown').val(window.localStorage.getItem('hometown'));
    if (!$('#whycare1').val()) {
      $('#whycare1').val(window.localStorage.getItem('whycare1-'+language));
    }
    if (!$('#whycare2').val()) {
      $('#whycare2').val(window.localStorage.getItem('whycare2-'+language));
    }
    if ($('#whycare1').val() || $('#whycare2').val()) {
      showEditor();
      formulate_message();
    }
  }
}

function check_and_persist(o, simple) {
  var s;
  if (typeof window !== 'undefined' && window.localStorage) {
    for (var e in o) {
      s = simple ? e : e + '-' + language;
      window.localStorage.setItem(s, o[e]);
    }
  }
}

/***
* formulate full message based on user input and templates
***/
function formulate_message(){
  var args = {'name': trim($('#name').val())
      , 'age': trim($('#age').val())
      , 'hometown': trim($('#hometown').val())};
  if(args.name && args.hometown && args.age) {
    args.has_name_age_hometown = true;
  }
  else if (args.name && args.hometown) {
    args.has_name_hometown = true;
  }
  else if (args.name && args.age) {
    args.has_name_age = true;
  }
  else if (args.name) {
    args.has_name = true;
  }
  else if (args.hometown && args.age) {
    args.has_hometown_age = true;
  }
  else if (args.hometown) {
    args.has_hometown = true;
  }
  else if (args.age) {
    args.has_age = true;
  }
  if (args.name || args.age || args.hometown) {
    check_and_persist(args, true);
    $(get_tmpl("intro")).Chevron("render", args, formulate_body);
  } else {
    formulate_body('');
  }
}

function formulate_body (intro) {
  var args = {Introduction: intro
      , whycare1: $('#whycare1').val() || ''
      , whycare2: $('#whycare2').val() || ''
      , age: $('#age').val() || ''
      , Greeting: getMEPName()
      , goodbye: $('#name').val() || 'A concerned citizen'};
  args.haswhycare = args.whycare1 || args.whycare2;
  check_and_persist({'whycare1': args.whycare1, 'whycare2': args.whycare2});
  $(get_tmpl("message")).Chevron("render", args, render_body);
}

function get_tmpl (tmpl_uri) {
  return '#tmpl_' + language + '_' + tmpl_uri;
}

function render_body (full_message) {;
  nicEditors.findEditor('full_message').setContent(full_message);
}

function getMEPName () {
  if (mep && mep.name) {
    return mep.name;
  }
  return '';
}

function trim(str) {
  return (str || '').replace(/^\s+/,'').replace(/\s+$/,'')
}<commit_msg>missing id bug persists<commit_after>/****
* multipart message generation based on translated templates
****/

var mep, editor;
var txt_changed = false;
var language = 'en';

$(function () {

  // insert html inputs via templates
  $(get_tmpl("message_inputs")).Chevron("render", {}, reference_message_inputs);
  $(get_tmpl("mep_selection")).Chevron("render", {}, reference_mep_selection);

});

// send fax
function sendfax() {
  var msg;
  $('#full_message').val(msg = (nicEditors.findEditor('full_message').getContent()||''));
  $('#id').val($('#id').val() || (mep||{}).id || '124935'); // sorry michel ;)
  if (msg != '' && msg.length > 140 && msg.length < 70000) {
    document.getElementById("faxform").submit();
  }
}

/**
* switch language
**/
function setLng(l) {
  if (l == 'en' || l == 'de') {
    language = l;
  }
}

function update_language () {
  setLng($('#language_selector').val());
  $(get_tmpl("message_inputs")).Chevron("render", {}, function (result) {
    removeEditor();
    reference_message_inputs(result);
    load_user_input();
    $('#id').val((mep||{}).id || '124935'); // sorry michel ;)
  });
}

/***
* loading and displaying html elements and bind actions to them
***/
function reference_mep_selection (result) {
  $('div.mepFilter').html(result);
  $('#language_selector').on('change', update_language);
  $('#country_selector,#group_selector').on('change', request_mep);
  $('#country_selector,#group_selector').on('change', refine_autocomplete);
  $('#mep_selector').autocomplete({
    source: current_autocomplete_meps
    , select: request_mep
  }).focus(function(){
    $('#mep_selector').autocomplete('search', $(this).val() || ' ');
  });
  $('#refresh_mep').on('click', function () {
    request_mep();
  });
  $('#language_selector').val(language);
}

function refine_autocomplete () {
  var c, g;
  current_autocomplete_meps = [];
  for (var i = 0; i < autocomplete_meps.length; i++) {
    if (((!(c = $('#country_selector').val())) || autocomplete_meps[i].country == c) && (!(g = $('#group_selector').val()) || autocomplete_meps[i].group == g)) {
      current_autocomplete_meps.push(autocomplete_meps[i]);
    }
  }
  $('#mep_selector').autocomplete('option', 'source', current_autocomplete_meps);
}

function reference_message_inputs (result) {
  $('#faxform').html(result);
  $('#name,#hometown,#whycare1,#whycare2,#age').on('change', formulate_message);
  $('#name,#hometown,#whycare1,#whycare2,#age').on('change', showEditor);
  $('#sendfax').on('click', function () {
    // piwik tracking then send
    jQuery.ajax({
        'url': 'https://piwik.netzfreiheit.org/piwik.php?idsite=11&rec=1&url=https%3A%2F%2Fsavetheinternet.eu&idgoal=4&e_c=contact&e_n=fax&e_v=' + (txt_changed ? 1 : 0)
        , 'complete': sendfax
      });
  });
}

/***
* AJAX request MEPs
***/
function request_mep () {
  if ($('#country_selector').val()) {
    //$.ajax('/sti/choose_mep/', {
    $.ajax('https://faxjh.savetheinternet.eu/sti/choose_mep/', {
      data: {'country': $('#country_selector').val(), 'group': $('#group_selector').val(), 'id': $('#mep_selector').val()}
      , success: receive_mep
      , dataType: 'json'
    });
  } else {
    clear_mep();
  }
}

function clear_mep () {
  mep = null;
  $('#mep_infos_top').html();
  $('#id').val('');
  $('#name,#hometown,#whycare1,#whycare2,#age').hide();
  removeEditor();
}

function receive_mep (data, status, jqXHR) {
  if (data && data.id) {
    mep = data;
    $(get_tmpl('mep_infos')).Chevron('render', data, '#mep_infos_top');
    $('#id').val(data['id']);
    $('#group_selector,#mep_selector,#refresh_mep,#language_selector').show();
    load_user_input();
  } else {
    clear_mep();
  }
}

/***
* handle html-editor ncEditor for main message box
***/
function showEditor () {
  if (!editor) {
    $('#full_message').show();
    editor = new nicEditor({buttonList : ['bold','italic','underline','left','center','right','justify','ol','ul','subscript','superscript','strikethrough','removeformat','indent','outdent'], iconsPath: '/static/images/nicEditorIcons.gif'}).panelInstance('full_message').addEvent('blur', function () {
    txt_changed = true;
    });
    $('#sendfax').show();
  }
}

function removeEditor () {
  if (editor) {
    editor.removeInstance('full_message');
    editor = null;
  }
  $('#full_message').hide();
  $('#sendfax').hide();
}

/***
* persist and load user input
***/
function load_user_input () {
  $('#name,#hometown,#whycare1,#whycare2,#age').show();
  if (typeof window !== 'undefined' && window.localStorage) {
    $('#age').val(window.localStorage.getItem('age'));
    $('#name').val(window.localStorage.getItem('name'));
    $('#hometown').val(window.localStorage.getItem('hometown'));
    if (!$('#whycare1').val()) {
      $('#whycare1').val(window.localStorage.getItem('whycare1-'+language));
    }
    if (!$('#whycare2').val()) {
      $('#whycare2').val(window.localStorage.getItem('whycare2-'+language));
    }
    if ($('#whycare1').val() || $('#whycare2').val()) {
      showEditor();
      formulate_message();
    }
  }
}

function check_and_persist(o, simple) {
  var s;
  if (typeof window !== 'undefined' && window.localStorage) {
    for (var e in o) {
      s = simple ? e : e + '-' + language;
      window.localStorage.setItem(s, o[e]);
    }
  }
}

/***
* formulate full message based on user input and templates
***/
function formulate_message(){
  var args = {'name': trim($('#name').val())
      , 'age': trim($('#age').val())
      , 'hometown': trim($('#hometown').val())};
  if(args.name && args.hometown && args.age) {
    args.has_name_age_hometown = true;
  }
  else if (args.name && args.hometown) {
    args.has_name_hometown = true;
  }
  else if (args.name && args.age) {
    args.has_name_age = true;
  }
  else if (args.name) {
    args.has_name = true;
  }
  else if (args.hometown && args.age) {
    args.has_hometown_age = true;
  }
  else if (args.hometown) {
    args.has_hometown = true;
  }
  else if (args.age) {
    args.has_age = true;
  }
  if (args.name || args.age || args.hometown) {
    check_and_persist(args, true);
    $(get_tmpl("intro")).Chevron("render", args, formulate_body);
  } else {
    formulate_body('');
  }
}

function formulate_body (intro) {
  var args = {Introduction: intro
      , whycare1: $('#whycare1').val() || ''
      , whycare2: $('#whycare2').val() || ''
      , age: $('#age').val() || ''
      , Greeting: getMEPName()
      , goodbye: $('#name').val() || 'A concerned citizen'};
  args.haswhycare = args.whycare1 || args.whycare2;
  check_and_persist({'whycare1': args.whycare1, 'whycare2': args.whycare2});
  $(get_tmpl("message")).Chevron("render", args, render_body);
}

function get_tmpl (tmpl_uri) {
  return '#tmpl_' + language + '_' + tmpl_uri;
}

function render_body (full_message) {;
  nicEditors.findEditor('full_message').setContent(full_message);
}

function getMEPName () {
  if (mep && mep.name) {
    return mep.name;
  }
  return '';
}

function trim(str) {
  return (str || '').replace(/^\s+/,'').replace(/\s+$/,'')
}<|endoftext|>