<commit_before>/**
 * @name index.js<beez-touch/s>
 * @author Masaki Sueda <s.masaki07@gmail.com>
 * @overview Touch event plug-in for Beez (browser)
 * @license MIT
 */

var BEEZ_TOUCH_VERSION = '0.2.4';

if (typeof module !== 'undefined' && module.exports) { // node.js: main

    exports.VERSION = BEEZ_TOUCH_VERSION;

} else {

    (function (global) {

        define(function (require, exports, module) {

            var beez = require('beez'),
                logger = beez.getLogger('beez.touch');

            if (beez.touch) {
                logger.warn('beez.touch is already loaded.');
                return beez.touch;
            }

            // vendor
            var _ = beez.vendor._,
                $ = beez.vendor.$;

            // device flag
            var hasTouch = 'ontouchstart' in window,
                EVENT = {
                start: {
                    name: hasTouch ? 'touchstart' : 'mousedown',
                    callback: 'onBztchTapStart'
                },
                move: {
                    name: hasTouch ? 'touchmove' : 'mousemove',
                    callback: 'onBztchTapMove'
                },
                end: {
                    name: hasTouch ? 'touchend' : 'mouseup',
                    callback: 'onBztchTapEnd'
                }
            };

            /**
             * normalize position
             * @param  {Events} e event object
             */
            var normalizePosition = function normalizePosition(e) {
                var position;

                if (hasTouch) {
                    if (e.originalEvent) {
                        position = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                        position = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                    } else {
                        position = e.changedTouches[0] && e.changedTouches[0];
                    }
                } else {
                    position = e;
                }
                e.pageX = position.pageX;
                e.pageY = position.pageY;

                return e;
            };

            var Inheritance = (function (global) {
                Inheritance = function () {};
                Inheritance.prototype = {
                    /**
                     * initialize
                     */
                    initialize: function initialize(options) {
                        TouchView.__super__.initialize.apply(this, arguments);

                        options = options || {};
                        options.bztch = options.bztch || {};

                        /**
                         * Tap event data
                         * @type {Object}
                         */
                        this._bztchTaps = null;

                        /**
                         * Flag of enable to tap
                         * @type {Boolean}
                         */
                        this._bztchIsTappable = false;

                        /**
                         * Flag of unable to touch
                         * @type {Boolean}
                         */
                        this._bztchIsDisable = false;

                        /**
                         * Flag of mouse down
                         * @type {Boolean}
                         */
                        this._bztchIsTapMouseDown = false;

                        /**
                         * Base prefix
                         * @type {String}
                         */
                        this._bztchPrefix = _.isString(options.bztch.prefix) ? options.bztch.prefix : 'bztch';

                        /**
                         * Prefix for tap
                         * @type {String}
                         */
                        this._bztchTapPrefix = this._bztchPrefix + '-tap';

                        /**
                         * ClassName of hover
                         * @type {String}
                         */
                        this._bztchHoverClassName = _.isString(options.bztch.hoverClassName) ? options.bztch.hoverClassName : 'hover';

                        /**
                         * Flag of prevent default events
                         * @type {Boolean}
                         */
                        this._bztchPreventDefault = options.bztch.preventDefault || false;

                        /**
                         * Position of touchstart
                         * @type {Object}
                         */
                        this._bztchStartPosition = {};

                        /**
                         * Threshold of touch cancel
                         * @type {Number}
                         */
                        this._bztchThreshold = options.bztch.threshold || 10;

                        /**
                         * Hold duration
                         * @type {Number}
                         */
                        this._bztchHoldDuration = options.bztch.holdDuration || 1000;
                    },

                    /**
                     * Add tap events to the elements
                     * @param {Element} $elm
                     * @param {Function} callback
                     * @param {beez.View} context
                     * @param {Object} options
                     */
                    tap: function tap($elm, callback, context, options) {
                        var self = this,
                            uid;

                        options = _.defaults(options || {}, {
                            tapStart: beez.none,
                            tapMove: beez.none,
                            tapEnd: beez.none,
                            context: self
                        });

                        // multiple selector
                        if (beez.utils.isArray($elm) && $elm.length > 1) {
                            _.each($elm, function (list, i) {
                                self.tap($elm.eq(i), callback, context, options);
                            });
                            return;
                        }

                        // register events to tap
                        if (!self._bztchTaps) {
                            _.each(EVENT, function (evt) {
                                var eventName = evt.name + '.delegateEvents' + self.cid;
                                var callback = evt.callback;
                                if ($elm === self.$el) {
                                    self.$el.on(eventName, _.bind(self[callback], self) || beez.none);
                                } else {
                                    self.$el.on(eventName, '.' + self._bztchTapPrefix, _.bind(self[callback], self) || beez.none);
                                }
                            });
                            self._bztchTaps = {};
                        }

                        // unique id
                        uid = _.uniqueId(self._bztchTapPrefix + '-');

                        self._bztchTaps[uid] = {
                            callback : callback,
                            callbackStart : options.tapStart,
                            callbackMove : options.tapMove,
                            callbackEnd : options.tapEnd,
                            callbackHold: options.tapHold,
                            context : context
                        };

                        // enable to tap
                        $elm.addClass(this._bztchTapPrefix);
                        $elm.attr('data-' + this._bztchTapPrefix + 'Uid', uid);
                    },

                    /**
                     * touchstart start
                     * @param {Object} e
                     */
                    onBztchTapStart: function onBztchTapStart(e) {
                        var self = this,
                            target = $(e.currentTarget),
                            bztchId;

                        e = normalizePosition(e);
                        bztchId = self.bztchGetId(target);

                        if (self._bztchTaps[bztchId].callbackHold) {
                            setTimeout(function () {
                                self.onBztchTapHold.call(self, e);
                            }, self._bztchHoldDuration);
                        }

                        if (!bztchId || !self.bztchHasTap(bztchId)) {
                            return;
                        }

                        if (self._bztchPreventDefault) {
                            e.preventDefault();
                        }

                        self._bztchStartPosition = {
                            x: e.pageX,
                            y: e.pageY
                        };

                        // checklock
                        if (!target.hasClass(self._bztchDisableClassName)) {
                            // enable to tap
                            self._bztchIsTappable = true;
                            // execute
                            self._bztchTaps[bztchId].callbackStart.call(self._bztchTaps[bztchId].context, e);
                            // hover
                            target.addClass(self._bztchHoverClassName);
                        }

                    },

                    /**
                     * touch move
                     * @param {Object} e
                     */
                    onBztchTapMove: function onBztchTapMove(e) {
                        var target = $(e.currentTarget),
                            bztchId;

                        if (!this._bztchIsTappable) {
                            return;
                        }

                        e = normalizePosition(e);
                        bztchId = this.bztchGetId(target);

                        if (!bztchId || !this.bztchHasTap(bztchId)) {
                            return;
                        }

                        if (this._bztchPreventDefault) {
                            e.preventDefault();
                        }

                        // execute callback
                        this._bztchTaps[bztchId].callbackMove.call(this._bztchTaps[bztchId].context, e);

                        // threshold
                        if (
                            Math.abs(e.pageX - this._bztchStartPosition.x) > this._bztchThreshold ||
                            Math.abs(e.pageY - this._bztchStartPosition.y) > this._bztchThreshold
                        ) {
                            this._bztchIsTappable = false;
                            target.removeClass(this._bztchHoverClassName);
                        }
                    },

                    /**
                     * touch end
                     * @param {Object} e
                     */
                    onBztchTapEnd: function onBztchTapEnd(e) {
                        var target = $(e.currentTarget),
                            bztchId;

                        e = normalizePosition(e);
                        bztchId = this.bztchGetId(target);

                        if (!bztchId || !this.bztchHasTap(bztchId)) {
                            return;
                        }

                        if (this._bztchPreventDefault) {
                            e.preventDefault();
                        }

                        if (this._bztchIsTappable && !target.hasClass(this._bztchDisableClassName)) {
                            if (this._bztchTaps[bztchId].callback) {
                                this._bztchTaps[bztchId].callback.call(this._bztchTaps[bztchId].context, e);
                            }

                            if (!this._bztchTaps) {
                                return;
                            }

                            this._bztchTaps[bztchId].callbackEnd.call(this._bztchTaps[bztchId].context, e);
                        }

                        // reset
                        this._bztchIsTappable = false;
                        target.removeClass(this._bztchHoverClassName);
                    },

                    /**
                     * Tap Hold
                     * @param  {[type]} e [description]
                     * @return {[type]}   [description]
                     */
                    onBztchTapHold: function onBztchTapHold(e) {
                        var target = $(e.currentTarget),
                            bztchId;

                        e = normalizePosition(e);
                        bztchId = this.bztchGetId(target);

                        if (!bztchId || !this.bztchHasTap(bztchId)) {
                            return;
                        }
                        // execute
                        this._bztchTaps[bztchId].callbackHold.call(this._bztchTaps[bztchId].context, e);
                        this._bztchIsTappable = false;
                        target.removeClass(this._bztchHoverClassName);
                    },

                    /**
                     * get tap event data
                     */
                    bztchGetId: function bztchGetId(target) {
                        console.log(target);
                        return target.attr('data-' + this._bztchTapPrefix + 'Uid');
                    },

                    /**
                     * has tap data
                     */
                    bztchHasTap: function bztchHasTap(id) {
                        return _.has((this._bztchTaps ? this._bztchTaps : {}), id);
                    },

                    /**
                     * dispose
                     */
                    dispose: function dispose() {

                        _.each(this._bztchTaps, function (value, key) {
                            delete this._bztchTaps[key].callback;
                            delete this._bztchTaps[key].callbackStart;
                            delete this._bztchTaps[key].callbackMove;
                            delete this._bztchTaps[key].context;
                            delete this._bztchTaps[key];
                        }, this);
                        delete this._bztchTaps;
                        delete this._bztchIsTappable;
                        delete this._bztchIsTapMouseDown;
                        delete this._bztchPrefix;
                        delete this._bztchTapPrefix;
                        delete this._bztchHoverClassName;
                        delete this._bztchStartPosition;

                        // super
                        TouchView.__super__.dispose.apply(this, arguments);
                    }
                };

                return Inheritance;

            })(this);

            /**
             * Touch View class
             *
             * @class
             * @extends beez.View
             */
            var TouchView = beez.View.extend(
                'beez.Touch',
                Inheritance.prototype
            );

            beez.touch = {
                View: TouchView,
                __inheritance__: Inheritance
            };

            return beez.touch;
        });
    })(this);
}
<commit_msg>Small fix<commit_after>/**
 * @name index.js<beez-touch/s>
 * @author Masaki Sueda <s.masaki07@gmail.com>
 * @overview Touch event plug-in for Beez (browser)
 * @license MIT
 */

var BEEZ_TOUCH_VERSION = '0.2.4';

if (typeof module !== 'undefined' && module.exports) { // node.js: main

    exports.VERSION = BEEZ_TOUCH_VERSION;

} else {

    (function (global) {

        define(function (require, exports, module) {

            var beez = require('beez'),
                logger = beez.getLogger('beez.touch');

            if (beez.touch) {
                logger.warn('beez.touch is already loaded.');
                return beez.touch;
            }

            // vendor
            var _ = beez.vendor._,
                $ = beez.vendor.$;

            // device flag
            var hasTouch = 'ontouchstart' in window,
                EVENT = {
                start: {
                    name: hasTouch ? 'touchstart' : 'mousedown',
                    callback: 'onBztchTapStart'
                },
                move: {
                    name: hasTouch ? 'touchmove' : 'mousemove',
                    callback: 'onBztchTapMove'
                },
                end: {
                    name: hasTouch ? 'touchend' : 'mouseup',
                    callback: 'onBztchTapEnd'
                }
            };

            /**
             * normalize position
             * @param  {Events} e event object
             */
            var normalizePosition = function normalizePosition(e) {
                var position;

                if (hasTouch) {
                    if (e.originalEvent) {
                        position = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                        position = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                    } else {
                        position = e.changedTouches[0] && e.changedTouches[0];
                    }
                } else {
                    position = e;
                }
                e.pageX = position.pageX;
                e.pageY = position.pageY;

                return e;
            };

            var Inheritance = (function (global) {
                Inheritance = function () {};
                Inheritance.prototype = {
                    /**
                     * initialize
                     */
                    initialize: function initialize(options) {
                        TouchView.__super__.initialize.apply(this, arguments);

                        options = options || {};
                        options.bztch = options.bztch || {};

                        /**
                         * Tap event data
                         * @type {Object}
                         */
                        this._bztchTaps = null;

                        /**
                         * Flag of enable to tap
                         * @type {Boolean}
                         */
                        this._bztchIsTappable = false;

                        /**
                         * Flag of unable to touch
                         * @type {Boolean}
                         */
                        this._bztchIsDisable = false;

                        /**
                         * Flag of mouse down
                         * @type {Boolean}
                         */
                        this._bztchIsTapMouseDown = false;

                        /**
                         * Base prefix
                         * @type {String}
                         */
                        this._bztchPrefix = _.isString(options.bztch.prefix) ? options.bztch.prefix : 'bztch';

                        /**
                         * Prefix for tap
                         * @type {String}
                         */
                        this._bztchTapPrefix = this._bztchPrefix + '-tap';

                        /**
                         * ClassName of hover
                         * @type {String}
                         */
                        this._bztchHoverClassName = _.isString(options.bztch.hoverClassName) ? options.bztch.hoverClassName : 'hover';

                        /**
                         * Flag of prevent default events
                         * @type {Boolean}
                         */
                        this._bztchPreventDefault = options.bztch.preventDefault || false;

                        /**
                         * Position of touchstart
                         * @type {Object}
                         */
                        this._bztchStartPosition = {};

                        /**
                         * Threshold of touch cancel
                         * @type {Number}
                         */
                        this._bztchThreshold = options.bztch.threshold || 10;

                        /**
                         * Hold duration
                         * @type {Number}
                         */
                        this._bztchHoldDuration = options.bztch.holdDuration || 1000;
                    },

                    /**
                     * Add tap events to the elements
                     * @param {Element} $elm
                     * @param {Function} callback
                     * @param {beez.View} context
                     * @param {Object} options
                     */
                    tap: function tap($elm, callback, context, options) {
                        var self = this,
                            uid;

                        options = _.defaults(options || {}, {
                            tapStart: beez.none,
                            tapMove: beez.none,
                            tapEnd: beez.none,
                            context: self
                        });

                        // multiple selector
                        if (beez.utils.isArray($elm) && $elm.length > 1) {
                            _.each($elm, function (list, i) {
                                self.tap($elm.eq(i), callback, context, options);
                            });
                            return;
                        }

                        // register events to tap
                        if (!self._bztchTaps) {
                            _.each(EVENT, function (evt) {
                                var eventName = evt.name + '.delegateEvents' + self.cid;
                                var callback = evt.callback;
                                if ($elm === self.$el) {
                                    self.$el.on(eventName, _.bind(self[callback], self) || beez.none);
                                } else {
                                    self.$el.on(eventName, '.' + self._bztchTapPrefix, _.bind(self[callback], self) || beez.none);
                                }
                            });
                            self._bztchTaps = {};
                        }

                        // unique id
                        uid = _.uniqueId(self._bztchTapPrefix + '-');

                        self._bztchTaps[uid] = {
                            callback : callback,
                            callbackStart : options.tapStart,
                            callbackMove : options.tapMove,
                            callbackEnd : options.tapEnd,
                            callbackHold: options.tapHold,
                            context : context
                        };

                        // enable to tap
                        $elm.addClass(this._bztchTapPrefix);
                        $elm.attr('data-' + this._bztchTapPrefix + 'Uid', uid);
                    },

                    /**
                     * touchstart start
                     * @param {Object} e
                     */
                    onBztchTapStart: function onBztchTapStart(e) {
                        var self = this,
                            target = $(e.currentTarget),
                            bztchId;

                        e = normalizePosition(e);
                        bztchId = self.bztchGetId(target);

                        if (self._bztchTaps[bztchId].callbackHold) {
                            setTimeout(function () {
                                self.onBztchTapHold.call(self, e);
                            }, self._bztchHoldDuration);
                        }

                        if (!bztchId || !self.bztchHasTap(bztchId)) {
                            return;
                        }

                        if (self._bztchPreventDefault) {
                            e.preventDefault();
                        }

                        self._bztchStartPosition = {
                            x: e.pageX,
                            y: e.pageY
                        };

                        // checklock
                        if (!target.hasClass(self._bztchDisableClassName)) {
                            // enable to tap
                            self._bztchIsTappable = true;
                            // execute
                            self._bztchTaps[bztchId].callbackStart.call(self._bztchTaps[bztchId].context, e);
                            // hover
                            target.addClass(self._bztchHoverClassName);
                        }

                    },

                    /**
                     * touch move
                     * @param {Object} e
                     */
                    onBztchTapMove: function onBztchTapMove(e) {
                        var target = $(e.currentTarget),
                            bztchId;

                        if (!this._bztchIsTappable) {
                            return;
                        }

                        e = normalizePosition(e);
                        bztchId = this.bztchGetId(target);

                        if (!bztchId || !this.bztchHasTap(bztchId)) {
                            return;
                        }

                        if (this._bztchPreventDefault) {
                            e.preventDefault();
                        }

                        // execute callback
                        this._bztchTaps[bztchId].callbackMove.call(this._bztchTaps[bztchId].context, e);

                        // threshold
                        if (
                            Math.abs(e.pageX - this._bztchStartPosition.x) > this._bztchThreshold ||
                            Math.abs(e.pageY - this._bztchStartPosition.y) > this._bztchThreshold
                        ) {
                            this._bztchIsTappable = false;
                            target.removeClass(this._bztchHoverClassName);
                        }
                    },

                    /**
                     * touch end
                     * @param {Object} e
                     */
                    onBztchTapEnd: function onBztchTapEnd(e) {
                        var target = $(e.currentTarget),
                            bztchId;

                        e = normalizePosition(e);
                        bztchId = this.bztchGetId(target);

                        if (!bztchId || !this.bztchHasTap(bztchId)) {
                            return;
                        }

                        if (this._bztchPreventDefault) {
                            e.preventDefault();
                        }

                        if (this._bztchIsTappable && !target.hasClass(this._bztchDisableClassName)) {
                            if (this._bztchTaps[bztchId].callback) {
                                this._bztchTaps[bztchId].callback.call(this._bztchTaps[bztchId].context, e);
                            }

                            if (!this._bztchTaps) {
                                return;
                            }

                            this._bztchTaps[bztchId].callbackEnd.call(this._bztchTaps[bztchId].context, e);
                        }

                        // reset
                        this._bztchIsTappable = false;
                        target.removeClass(this._bztchHoverClassName);
                    },

                    /**
                     * Tap Hold
                     * @param  {[type]} e [description]
                     * @return {[type]}   [description]
                     */
                    onBztchTapHold: function onBztchTapHold(e) {
                        var target = $(e.currentTarget),
                            bztchId;

                        e = normalizePosition(e);
                        bztchId = this.bztchGetId(target);

                        if (!bztchId || !this.bztchHasTap(bztchId)) {
                            return;
                        }
                        // execute
                        this._bztchTaps[bztchId].callbackHold.call(this._bztchTaps[bztchId].context, e);
                        this._bztchIsTappable = false;
                        target.removeClass(this._bztchHoverClassName);
                    },

                    /**
                     * get tap event data
                     */
                    bztchGetId: function bztchGetId(target) {
                        return target.attr('data-' + this._bztchTapPrefix + 'Uid');
                    },

                    /**
                     * has tap data
                     */
                    bztchHasTap: function bztchHasTap(id) {
                        return _.has((this._bztchTaps ? this._bztchTaps : {}), id);
                    },

                    /**
                     * dispose
                     */
                    dispose: function dispose() {

                        _.each(this._bztchTaps, function (value, key) {
                            delete this._bztchTaps[key].callback;
                            delete this._bztchTaps[key].callbackStart;
                            delete this._bztchTaps[key].callbackMove;
                            delete this._bztchTaps[key].context;
                            delete this._bztchTaps[key];
                        }, this);
                        delete this._bztchTaps;
                        delete this._bztchIsTappable;
                        delete this._bztchIsTapMouseDown;
                        delete this._bztchPrefix;
                        delete this._bztchTapPrefix;
                        delete this._bztchHoverClassName;
                        delete this._bztchStartPosition;

                        // super
                        TouchView.__super__.dispose.apply(this, arguments);
                    }
                };

                return Inheritance;

            })(this);

            /**
             * Touch View class
             *
             * @class
             * @extends beez.View
             */
            var TouchView = beez.View.extend(
                'beez.Touch',
                Inheritance.prototype
            );

            beez.touch = {
                View: TouchView,
                __inheritance__: Inheritance
            };

            return beez.touch;
        });
    })(this);
}
<|endoftext|>


<commit_before>CATARSE.ProjectsNewView = Backbone.View.extend({
  initialize: function() {
    $('#header header nav.actions ul li.submit_project').addClass('selected');
    $('#add_reward').click(function(e){
      e.preventDefault()
      var new_reward = '

' + $($('.reward')[0]).html() + '
'
      new_reward = new_reward.replace(/\_0\_/g, '_' + rewards_id + '_')
      new_reward = new_reward.replace(/\[0\]/g, '[' + rewards_id + ']')
      new_reward = $(new_reward)
      new_reward.find('input').val(null)
      new_reward.find('.private').val("1").removeAttr('checked')
      new_reward.find('textarea').html(null)
      new_reward.find('input').numeric(false)
      new_reward.find('input, textarea').removeClass('ok').removeClass('error')
      $('#rewards_wrapper').append(new_reward)
      new_reward.find('textarea').focus()
      new_reward.find('.reward_expires_at').removeClass('hasDatepicker');
      new_reward.find('.reward_expires_at').datepicker({
        altFormat: 'dd/mm/yy',
        onSelect: everything_ok
      });

      rewards_count++
      rewards_id++
    })

    // A better selector for the cities
    $('#project_category_id').select2();

    function format (user) {
      if (user.loading) return user.name;

      var markup = "
" +
        "

" +
        "
" + user.name + "

";

      return markup;
    }

    function formatSelection (user) {
      return user.name;
    }

    $('#project_leader_id').select2({
      ajax: {
        url: "/users.json",
        dataType: 'json',
        delay: 500,
        data: function (params) {
          return {
            q: params.term,
            page: params.page
          };
        },
        processResults: function (data, params) {
          params.page = params.page || 1;

          return {
            results: data.items,
            pagination: {
              more: (params.page * 10) < data.total_count
            }
          };
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; },
      minimumInputLength: 0,
      templateResult: format,
      templateSelection: formatSelection
    }).on("select2:select", function(e) {
        if ($('#project_leader_bio').val() == '') {
         $('#project_leader_bio').val(e.params.data.bio);
       }
    });

    $('#add_dynamic_field').click(function(e){
      e.preventDefault()
      var new_dynamic_field = '

' + $($('.dynamic_field')[0]).html() + '
'
      new_dynamic_field = new_dynamic_field.replace(/\_0\_/g, '_' + dynamic_fields_id + '_')
      new_dynamic_field = new_dynamic_field.replace(/\[0\]/g, '[' + dynamic_fields_id + ']')
      new_dynamic_field = $(new_dynamic_field)
      new_dynamic_field.find('input').val(null)
      new_dynamic_field.find('input[type=checkbox]').attr('checked', false)
      new_dynamic_field.find('input, textarea').removeClass('ok').removeClass('error')
      $('#dynamic_fields_wrapper').append(new_dynamic_field)
      new_dynamic_field.find('textarea').focus()

      dynamic_fields_count++
      dynamic_fields_id++
    })

    // When clicking on a past location, set it as the event location
    $('span.past-location').click(function(e) {
      var past_location = e.currentTarget.innerText;
      $('#project_location').val(past_location);
    })

    var video_valid = null
    everything_ok = function(){
      var all_ok = true
      if(video_valid == null) {
        all_ok = false
        verify_video()
      }
      if(!ok('#project_name'))
        all_ok = false
      if(!video_ok())
        all_ok = false
      if(!ok('#project_about'))
        all_ok = false
      if(!headline_ok())
        all_ok = false
      if(!ok('#project_category_id'))
        all_ok = false
      if(!goal_ok())
        all_ok = false
      if(!expires_at_ok())
        all_ok = false
      if(!rewards_ok())
        all_ok = false
      if(!dynamic_fields_ok())
        all_ok = false
      if(!accepted_terms())
        all_ok = false
      if(!ok('#project_when_short'))
        all_ok = false
      if(!ok('#project_when_long'))
        all_ok = false
      if(!ok('#project_location'))
        all_ok = false
      $('#project_image_url, #project_leader_id, #project_leader_bio').addClass('ok')
      if(all_ok){
        $('#project_submit').attr('disabled', false)
      } else {
        $('#project_submit').attr('disabled', true)
      }
    }
    ok = function(id){
      var value = $(id).val()
      if(value && value.length > 0){
        $(id).addClass("ok").removeClass("error")
        return true
      } else {
        $(id).addClass("error").removeClass("ok")
        return false
      }
    }
    verify_video = function(){
      video_valid = false
      $('#project_video_url').val($('#project_video_url').val().replace("https", "http"))
      if(/http:\/\/(www\.)?vimeo.com\/(\d+)/.test($('#project_video_url').val())) {
        $('#project_video_url').removeClass("ok").removeClass("error").addClass('loading')
        $.get('/projects/vimeo/?url='+$('#project_video_url').val(), function(r){
          $('#project_video_url').removeClass("loading")
          if(r.id==false){
            video_valid = false
          } else {
            video_valid = true
          }
          everything_ok()
        })
      } else {
				if($('#project_video_url').val() == ""){
					video_valid = true;
				 $('#project_video_url').removeClass("ok").removeClass("error").addClass('ok')
				}
			}
      everything_ok()
    }
    video_ok = function(){
      if(video_valid){
        $('#project_video_url').addClass("ok").removeClass("error")
        return true
      } else {
        if(!$('#project_video_url').hasClass('loading'))
          $('#project_video_url').addClass("error").removeClass("ok")
        return false
      }
    }
    headline_ok = function(){
      var value = $('#project_headline').val()
      if(value && value.length > 0 && value.length <= 140){
        $('#project_headline').addClass("ok").removeClass("error")
        return true
      } else {
        $('#project_headline').addClass("error").removeClass("ok")
        return false
      }
    }
    goal_ok = function(){
      var value = $('#project_goal').val()
      if(/^(\d+)$/.test(value) && parseInt(value) > 0){
        $('#project_goal').addClass("ok").removeClass("error")
        return true
      } else {
        $('#project_goal').addClass("error").removeClass("ok")
        return false
      }
    }
    expires_at_ok = function(){
      var value = /^(\d{2})\/(\d{2})\/(\d{4})?$/.exec($('#project_expires_at').val())
      if(value && value.length == 4) {
        var year = parseFloat(value[3])
        var month = parseFloat(value[2])-1
        var day = parseFloat(value[1])
        var date = new Date(year, month, day)
        var current_date = new Date()
        if(((day==date.getDate()) && (month==date.getMonth()) && (year==date.getFullYear())) && date > current_date){
          $('#project_expires_at').addClass("ok").removeClass("error")
          return true
        } else {
          $('#project_expires_at').addClass("error").removeClass("ok")
          return false
        }
      } else {
        $('#project_expires_at').addClass("error").removeClass("ok")
        return false
      }
    }
    rewards_ok = function(){
      var okey = true
      $('.reward input').each(function(){
        if(/^(\d+)$/.test($(this).val())){
          if(/minimum_value/.test($(this).attr('id'))){
            if(parseInt($(this).val()) >= 0) {
              $(this).addClass("ok").removeClass("error")
            } else {
              $(this).addClass("error").removeClass("ok")
              okey = false
            }
          } else {
            $(this).addClass("ok").removeClass("error")
          }
        } else {
          if(/maximum_backers/.test($(this).attr('id')) && (!$(this).val())){
            $(this).addClass("ok").removeClass("error")
          } else if(/private/.test($(this).attr('id')) && (!$(this).val()) || $(this).attr('id') === undefined || /expires_at/.test($(this).attr('id')) && (!$(this).val() || /expires_at/.test($(this).attr('id')) && $(this).val() )){
            $(this).addClass("ok").removeClass("error")
          }else {
            $(this).addClass("error").removeClass("ok")
            okey = false
            console.log($(this).attr('id'));
          }
        }
      })
      $('.reward textarea').each(function(){
        if($(this).val() && $(this).val().length > 0){
          $(this).addClass("ok").removeClass("error")
        } else {
          $(this).addClass("error").removeClass("ok")
          okey = false
        }
      })
      return okey
    }

    dynamic_fields_ok = function(){
      if(!$('#has_dynamic_fields').is(':checked')){
        $('.dynamic_field input').each(function(){
          if(/input_name/.test($(this).attr('id'))){
              $(this).addClass("ok").removeClass("error")
          }
        })
        return true
      }
      var okey = true
      $('.dynamic_field input').each(function(){
          if(/input_name/.test($(this).attr('id'))){
             if($(this).val() && $(this).val().length > 0){
              $(this).addClass("ok").removeClass("error")
            } else {
              $(this).addClass("error").removeClass("ok")
              okey = false
            }
          }
      })
      return okey
    }

    accepted_terms = function(){
      return $('#accept').is(':checked')
    }
    $('#project_name').keyup(everything_ok)
    $('#project_video_url').keyup(function(){ video_valid = false; everything_ok() })
    $('#project_video_url').timedKeyup(verify_video)
    $('#project_about').keyup(everything_ok)
    $('#project_category_id').change(everything_ok)
    $('#project_goal').keyup(everything_ok)
    $('#project_expires_at').keyup(everything_ok)
    $('#project_headline').keyup(everything_ok)

    function date_text_from_datepicker(datepicker){
      var months = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
      return datepicker.selectedDay + " de " + months[datepicker.selectedMonth] + " de " + datepicker.selectedYear;
    }

    $('#project_when_short').datepicker({
      altFormat: 'dd/mm/yy',
      onSelect: function (text, datepicker) {
        if ($('#project_when_long').val() == '') {
          $('#project_when_long').val(date_text_from_datepicker(datepicker) + " ");
        }

        $('#project_when_long').focus();
        everything_ok(text, datepicker);
      }
    });

    $('#project_when_long').keyup(everything_ok)
    $('#project_location').keyup(everything_ok)
    $('#project_image_url').keyup(everything_ok)
    $('#project_leader_id').keyup(everything_ok)
    $('#project_leader_bio').keyup(everything_ok)
    $('#accept').click(everything_ok)
    $('.reward input,.reward textarea').live('keyup', everything_ok)
    $('.dynamic_field input').live('keyup', everything_ok)
    $('.dynamic_field input').live('keyup', function(){
      $('#has_dynamic_fields').attr('checked', true)
    })
    $('#has_dynamic_fields').click(everything_ok)

    $('#project_goal').numeric(false)
    $('.reward input').numeric(false)
    $('#project_expires_at, .reward_expires_at').datepicker({
      altFormat: 'dd/mm/yy',
      onSelect: everything_ok
    })
    $('#ui-datepicker-div').css('display', 'none')
    $('input,textarea,select').live('focus', function(){
      $('p.inline-hints').hide()
      $(this).next('p.inline-hints').show()
      $('.boolean p.inline-hints').show()
    })
    $('.reward').live('mouseover', function(){
      $('.remove_reward').hide()
      if(rewards_count > 1){
        $(this).find('.remove_reward').show()
      }
    })
    $('.reward').live('mouseout', function(){
      $(this).find('.remove_reward').hide()
    })
    $('.remove_reward').live('click', function(e){
      e.preventDefault()
      if(rewards_count > 1){
        reward = $(this).parentsUntil('.reward').parent()
        reward.remove()
        rewards_count--
      }
    })

    $('.dynamic_field').live('mouseover', function(){
      $('.remove_dynamic_field').hide()
      if(dynamic_fields_count > 1){
        $(this).find('.remove_dynamic_field').show()
      }
    })
    $('.dynamic_field').live('mouseout', function(){
      $(this).find('.remove_dynamic_field').hide()
    })
    $('.remove_dynamic_field').live('click', function(e){
      e.preventDefault()
      if(dynamic_fields_count > 1){
        dynamic_field = $(this).parentsUntil('.dynamic_field').parent()
        dynamic_field.remove()
        dynamic_fields_count--
        dynamic_fields_id--
      }
    })

    $('#project_name').focus()
    $('textarea').maxlength()
  }
})
<commit_msg>Revert date picker for project[when_short] field<commit_after>CATARSE.ProjectsNewView = Backbone.View.extend({
  initialize: function() {
    $('#header header nav.actions ul li.submit_project').addClass('selected');
    $('#add_reward').click(function(e){
      e.preventDefault()
      var new_reward = '

' + $($('.reward')[0]).html() + '
'
      new_reward = new_reward.replace(/\_0\_/g, '_' + rewards_id + '_')
      new_reward = new_reward.replace(/\[0\]/g, '[' + rewards_id + ']')
      new_reward = $(new_reward)
      new_reward.find('input').val(null)
      new_reward.find('.private').val("1").removeAttr('checked')
      new_reward.find('textarea').html(null)
      new_reward.find('input').numeric(false)
      new_reward.find('input, textarea').removeClass('ok').removeClass('error')
      $('#rewards_wrapper').append(new_reward)
      new_reward.find('textarea').focus()
      new_reward.find('.reward_expires_at').removeClass('hasDatepicker');
      new_reward.find('.reward_expires_at').datepicker({
        altFormat: 'dd/mm/yy',
        onSelect: everything_ok
      });

      rewards_count++
      rewards_id++
    })

    // A better selector for the cities
    $('#project_category_id').select2();

    function format (user) {
      if (user.loading) return user.name;

      var markup = "
" +
        "

" +
        "
" + user.name + "

";

      return markup;
    }

    function formatSelection (user) {
      return user.name;
    }

    $('#project_leader_id').select2({
      ajax: {
        url: "/users.json",
        dataType: 'json',
        delay: 500,
        data: function (params) {
          return {
            q: params.term,
            page: params.page
          };
        },
        processResults: function (data, params) {
          params.page = params.page || 1;

          return {
            results: data.items,
            pagination: {
              more: (params.page * 10) < data.total_count
            }
          };
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; },
      minimumInputLength: 0,
      templateResult: format,
      templateSelection: formatSelection
    }).on("select2:select", function(e) {
        if ($('#project_leader_bio').val() == '') {
         $('#project_leader_bio').val(e.params.data.bio);
       }
    });

    $('#add_dynamic_field').click(function(e){
      e.preventDefault()
      var new_dynamic_field = '

' + $($('.dynamic_field')[0]).html() + '
'
      new_dynamic_field = new_dynamic_field.replace(/\_0\_/g, '_' + dynamic_fields_id + '_')
      new_dynamic_field = new_dynamic_field.replace(/\[0\]/g, '[' + dynamic_fields_id + ']')
      new_dynamic_field = $(new_dynamic_field)
      new_dynamic_field.find('input').val(null)
      new_dynamic_field.find('input[type=checkbox]').attr('checked', false)
      new_dynamic_field.find('input, textarea').removeClass('ok').removeClass('error')
      $('#dynamic_fields_wrapper').append(new_dynamic_field)
      new_dynamic_field.find('textarea').focus()

      dynamic_fields_count++
      dynamic_fields_id++
    })

    // When clicking on a past location, set it as the event location
    $('span.past-location').click(function(e) {
      var past_location = e.currentTarget.innerText;
      $('#project_location').val(past_location);
    })

    var video_valid = null
    everything_ok = function(){
      var all_ok = true
      if(video_valid == null) {
        all_ok = false
        verify_video()
      }
      if(!ok('#project_name'))
        all_ok = false
      if(!video_ok())
        all_ok = false
      if(!ok('#project_about'))
        all_ok = false
      if(!headline_ok())
        all_ok = false
      if(!ok('#project_category_id'))
        all_ok = false
      if(!goal_ok())
        all_ok = false
      if(!expires_at_ok())
        all_ok = false
      if(!rewards_ok())
        all_ok = false
      if(!dynamic_fields_ok())
        all_ok = false
      if(!accepted_terms())
        all_ok = false
      if(!ok('#project_when_short'))
        all_ok = false
      if(!ok('#project_when_long'))
        all_ok = false
      if(!ok('#project_location'))
        all_ok = false
      $('#project_image_url, #project_leader_id, #project_leader_bio').addClass('ok')
      if(all_ok){
        $('#project_submit').attr('disabled', false)
      } else {
        $('#project_submit').attr('disabled', true)
      }
    }
    ok = function(id){
      var value = $(id).val()
      if(value && value.length > 0){
        $(id).addClass("ok").removeClass("error")
        return true
      } else {
        $(id).addClass("error").removeClass("ok")
        return false
      }
    }
    verify_video = function(){
      video_valid = false
      $('#project_video_url').val($('#project_video_url').val().replace("https", "http"))
      if(/http:\/\/(www\.)?vimeo.com\/(\d+)/.test($('#project_video_url').val())) {
        $('#project_video_url').removeClass("ok").removeClass("error").addClass('loading')
        $.get('/projects/vimeo/?url='+$('#project_video_url').val(), function(r){
          $('#project_video_url').removeClass("loading")
          if(r.id==false){
            video_valid = false
          } else {
            video_valid = true
          }
          everything_ok()
        })
      } else {
				if($('#project_video_url').val() == ""){
					video_valid = true;
				 $('#project_video_url').removeClass("ok").removeClass("error").addClass('ok')
				}
			}
      everything_ok()
    }
    video_ok = function(){
      if(video_valid){
        $('#project_video_url').addClass("ok").removeClass("error")
        return true
      } else {
        if(!$('#project_video_url').hasClass('loading'))
          $('#project_video_url').addClass("error").removeClass("ok")
        return false
      }
    }
    headline_ok = function(){
      var value = $('#project_headline').val()
      if(value && value.length > 0 && value.length <= 140){
        $('#project_headline').addClass("ok").removeClass("error")
        return true
      } else {
        $('#project_headline').addClass("error").removeClass("ok")
        return false
      }
    }
    goal_ok = function(){
      var value = $('#project_goal').val()
      if(/^(\d+)$/.test(value) && parseInt(value) > 0){
        $('#project_goal').addClass("ok").removeClass("error")
        return true
      } else {
        $('#project_goal').addClass("error").removeClass("ok")
        return false
      }
    }
    expires_at_ok = function(){
      var value = /^(\d{2})\/(\d{2})\/(\d{4})?$/.exec($('#project_expires_at').val())
      if(value && value.length == 4) {
        var year = parseFloat(value[3])
        var month = parseFloat(value[2])-1
        var day = parseFloat(value[1])
        var date = new Date(year, month, day)
        var current_date = new Date()
        if(((day==date.getDate()) && (month==date.getMonth()) && (year==date.getFullYear())) && date > current_date){
          $('#project_expires_at').addClass("ok").removeClass("error")
          return true
        } else {
          $('#project_expires_at').addClass("error").removeClass("ok")
          return false
        }
      } else {
        $('#project_expires_at').addClass("error").removeClass("ok")
        return false
      }
    }
    rewards_ok = function(){
      var okey = true
      $('.reward input').each(function(){
        if(/^(\d+)$/.test($(this).val())){
          if(/minimum_value/.test($(this).attr('id'))){
            if(parseInt($(this).val()) >= 0) {
              $(this).addClass("ok").removeClass("error")
            } else {
              $(this).addClass("error").removeClass("ok")
              okey = false
            }
          } else {
            $(this).addClass("ok").removeClass("error")
          }
        } else {
          if(/maximum_backers/.test($(this).attr('id')) && (!$(this).val())){
            $(this).addClass("ok").removeClass("error")
          } else if(/private/.test($(this).attr('id')) && (!$(this).val()) || $(this).attr('id') === undefined || /expires_at/.test($(this).attr('id')) && (!$(this).val() || /expires_at/.test($(this).attr('id')) && $(this).val() )){
            $(this).addClass("ok").removeClass("error")
          }else {
            $(this).addClass("error").removeClass("ok")
            okey = false
            console.log($(this).attr('id'));
          }
        }
      })
      $('.reward textarea').each(function(){
        if($(this).val() && $(this).val().length > 0){
          $(this).addClass("ok").removeClass("error")
        } else {
          $(this).addClass("error").removeClass("ok")
          okey = false
        }
      })
      return okey
    }

    dynamic_fields_ok = function(){
      if(!$('#has_dynamic_fields').is(':checked')){
        $('.dynamic_field input').each(function(){
          if(/input_name/.test($(this).attr('id'))){
              $(this).addClass("ok").removeClass("error")
          }
        })
        return true
      }
      var okey = true
      $('.dynamic_field input').each(function(){
          if(/input_name/.test($(this).attr('id'))){
             if($(this).val() && $(this).val().length > 0){
              $(this).addClass("ok").removeClass("error")
            } else {
              $(this).addClass("error").removeClass("ok")
              okey = false
            }
          }
      })
      return okey
    }

    accepted_terms = function(){
      return $('#accept').is(':checked')
    }
    $('#project_name').keyup(everything_ok)
    $('#project_video_url').keyup(function(){ video_valid = false; everything_ok() })
    $('#project_video_url').timedKeyup(verify_video)
    $('#project_about').keyup(everything_ok)
    $('#project_category_id').change(everything_ok)
    $('#project_goal').keyup(everything_ok)
    $('#project_expires_at').keyup(everything_ok)
    $('#project_headline').keyup(everything_ok)
    $('#project_when_short').keyup(everything_ok)
    $('#project_when_long').keyup(everything_ok)
    $('#project_location').keyup(everything_ok)
    $('#project_image_url').keyup(everything_ok)
    $('#project_leader_id').keyup(everything_ok)
    $('#project_leader_bio').keyup(everything_ok)
    $('#accept').click(everything_ok)
    $('.reward input,.reward textarea').live('keyup', everything_ok)
    $('.dynamic_field input').live('keyup', everything_ok)
    $('.dynamic_field input').live('keyup', function(){
      $('#has_dynamic_fields').attr('checked', true)
    })
    $('#has_dynamic_fields').click(everything_ok)

    $('#project_goal').numeric(false)
    $('.reward input').numeric(false)
    $('#project_expires_at, .reward_expires_at').datepicker({
      altFormat: 'dd/mm/yy',
      onSelect: everything_ok
    })
    $('#ui-datepicker-div').css('display', 'none')
    $('input,textarea,select').live('focus', function(){
      $('p.inline-hints').hide()
      $(this).next('p.inline-hints').show()
      $('.boolean p.inline-hints').show()
    })
    $('.reward').live('mouseover', function(){
      $('.remove_reward').hide()
      if(rewards_count > 1){
        $(this).find('.remove_reward').show()
      }
    })
    $('.reward').live('mouseout', function(){
      $(this).find('.remove_reward').hide()
    })
    $('.remove_reward').live('click', function(e){
      e.preventDefault()
      if(rewards_count > 1){
        reward = $(this).parentsUntil('.reward').parent()
        reward.remove()
        rewards_count--
      }
    })

    $('.dynamic_field').live('mouseover', function(){
      $('.remove_dynamic_field').hide()
      if(dynamic_fields_count > 1){
        $(this).find('.remove_dynamic_field').show()
      }
    })
    $('.dynamic_field').live('mouseout', function(){
      $(this).find('.remove_dynamic_field').hide()
    })
    $('.remove_dynamic_field').live('click', function(e){
      e.preventDefault()
      if(dynamic_fields_count > 1){
        dynamic_field = $(this).parentsUntil('.dynamic_field').parent()
        dynamic_field.remove()
        dynamic_fields_count--
        dynamic_fields_id--
      }
    })

    $('#project_name').focus()
    $('textarea').maxlength()
  }
})
<|endoftext|>


<commit_before>/**
 *  s3/upload_document.js
 *
 *  David Janes
 *  IOTDB
 *  2017-01-18
 *
 *  Copyright (2013-2017) David Janes
 */

"use strict";

const _ = require("iotdb-helpers");

const assert = require("assert");

const AWS = require("aws-sdk");
const mime = require("mime");

/**
 *  Accepts:
 *  Produces:
 */
const upload_document = (_self, done) => {
    const self = _.d.clone.shallow(_self);
    const method = "s3.upload_document";

    assert.ok(self.s3, `${method}: self.s3 is required`);
    assert.ok(_.is.String(self.bucket), `${method}: self.bucket must be a String`);
    assert.ok(_.is.String(self.key), `${method}: self.key must be a String`);
    assert.ok(_.is.String(self.document) || _.is.Buffer(self.document), `${method}: self.document must be a String or Buffer`);
    assert.ok(_.is.String(self.document_media_type) || !self.document_media_type, `${method}: self.document_media_type must be a String or Null`);
    assert.ok(_.is.String(self.document_encoding) || !self.document_encoding, `${method}: self.document_encoding must be a String or Null`);

    self.s3.upload({
        Bucket: self.bucket,
        Key: self.key,
        Body: self.document,
        ContentType: self.document_media_type || mime.lookup(self.key) || "application/octet-stream",
        ContentEncoding: self.document_encoding || null,
    }, (error, data) => {
        if (error) {
            return done(error);
        }

        done(null, self);
    });
}

/**
 *  API
 */
exports.upload_document = _.promise.denodeify(upload_document);
<commit_msg>mime version compatibility<commit_after>/**
 *  s3/upload_document.js
 *
 *  David Janes
 *  IOTDB
 *  2017-01-18
 *
 *  Copyright (2013-2017) David Janes
 */

"use strict";

const _ = require("iotdb-helpers");

const assert = require("assert");

const AWS = require("aws-sdk");
const mime = require("mime");
mime.getType = mime.getType || mime.lookup; // 2.0.3 vs 1.6.0

/**
 *  Accepts:
 *  Produces:
 */
const upload_document = (_self, done) => {
    const self = _.d.clone.shallow(_self);
    const method = "s3.upload_document";

    assert.ok(self.s3, `${method}: self.s3 is required`);
    assert.ok(_.is.String(self.bucket), `${method}: self.bucket must be a String`);
    assert.ok(_.is.String(self.key), `${method}: self.key must be a String`);
    assert.ok(_.is.String(self.document) || _.is.Buffer(self.document), `${method}: self.document must be a String or Buffer`);
    assert.ok(_.is.String(self.document_media_type) || !self.document_media_type, `${method}: self.document_media_type must be a String or Null`);
    assert.ok(_.is.String(self.document_encoding) || !self.document_encoding, `${method}: self.document_encoding must be a String or Null`);

    self.s3.upload({
        Bucket: self.bucket,
        Key: self.key,
        Body: self.document,
        ContentType: self.document_media_type || mime.lookup(self.key) || "application/octet-stream",
        ContentEncoding: self.document_encoding || null,
    }, (error, data) => {
        if (error) {
            return done(error);
        }

        done(null, self);
    });
}

/**
 *  API
 */
exports.upload_document = _.promise.denodeify(upload_document);
<|endoftext|>


<commit_before>//Taken from d3.gantt By Dimitry Kudrayvtsev
//START WORKING HERE -AT
var margin = { //MAY NEED TO ADJUST
    top : 20,
    right : 40,
    bottom : 20,
    left : 150
};
var timeDomainStart = d3.time.day.offset(new Date(),-3);
var timeDomainEnd = d3.time.hour.offset(new Date(),+3);
var timeDomainMode = "fixed";
var tickFormat = "%H:%M";
var xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(d3.time.format(tickFormat)).tickSubdivide(true)
        .tickSize(8).tickPadding(8);
var yAxis = d3.svg.axis().scale(y).orient("left").tickSize(0);
var x = d3.time.scale().domain([ timeDomainStart, timeDomainEnd ]).range([ 0, width ]).clamp(true);
var y = d3.scale.ordinal().rangeRoundBands([ 0, height - margin.top - margin.bottom ], .1); //SET DOMAIN
var timeDomain = 10; //ARBITRARY LENGTH FOR INITIAL TIMELINE, CHOOSE BETTER TIME
var initAxis = function() {
    x = d3.time.scale().domain([ timeDomainStart, timeDomainEnd ]).range([ 0, width ]).clamp(true);
    y = d3.scale.ordinal()rangeRoundBands([ 0, height - margin.top - margin.bottom ], .1); //SET DOMAIN
    xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(d3.time.format(tickFormat)).tickSubdivide(true)
        .tickSize(8).tickPadding(8);
    yAxis = d3.svg.axis().scale(y).orient("left").tickSize(0);
    };

//To go with restart(), task_rectangle() insert
/*.on('click', function() { //BREAKS AUTHORING OF RECTANGLES
            $(this).popover('toggle'){
            title: 'New Event',
            placement: 'right',
            content: '<button id="delete">Delete</button>'
            }).parent().delegate('button#delete', 'click', function() {
                //ADD DELETE CODE
            })
        })*/<commit_msg>Deleted experimental.js<commit_after><|endoftext|>


<commit_before>Travis.DataSource = SC.DataSource.extend({
  fetch: function(store, query) {
    var url = query.url || this._urlFor(query.get('recordType')) + '.json';

    $.ajax({ url: url, dataType: 'json' }).done(function(data) {
      store.loadRecords(query.get('recordType'), data); // , this._extractIds(data)
      store.dataSourceDidFetchQuery(query);
    });

    return YES;
  },

  retrieveRecord: function(store, storeKey) {
    var type = SC.Store.recordTypeFor(storeKey);
    var id   = store.idFor(storeKey);
    var url  = this._urlFor(type, id) + '.json';

    $.ajax({ url: url, dataType: 'json' }).done(function(data, status, response) {
      if (status == 'success') {
        store.loadRecords(store.recordTypeFor(storeKey), data.isEnumerable ? data : [data]);
      } else {
        store.dataSourceDidError(storeKey, response.get('body'));
      }
    });

    return YES;
  },

  updateRecord: function(store, storeKey, params) {
    var type = store.recordTypeFor(storeKey);
    var id   = store.idFor(storeKey);
    var data = $.extend(store.readDataHash(storeKey), params || {}, { _method: 'put' });
    var url  = this._urlFor(type, id);

    $.post(url, data).done(function(data, status, response) {
      if(status == 'success') {
        store.dataSourceDidComplete(storeKey);
      } else {
        store.dataSourceDidError(storeKey, response);
      }
    });

    return YES;
  },

updateRecordDidComplete: function(response, store, storeKey, id) {
},

  _urlFor: function(recordType, id) {
    return $.compact([recordType.resource, id]).join('/');
  },

  _extractIds: function() {
    return data.map(function(hash) {
      var id = hash.id;
      delete hash.id;
      return id;
    }, this);
  },
});
<commit_msg>Refactoring DataStore, separating response success and failure.<commit_after>Travis.DataSource = SC.DataSource.extend({
  fetch: function(store, query) {
    var url = query.url || this._urlFor(query.get('recordType')) + '.json';

    $.ajax({
      url: url,
      dataType: 'json',
      success: function(data) {
        store_keys = store.loadRecords(query.get('recordType'), data); // , this._extractIds(data)
        if(!query.get('isLocal')) store.loadQueryResults(query, store_keys);
        store.dataSourceDidFetchQuery(query);
      },
      error: function(data, status, response) {
        // Actually i'm not absolutely sure what to put here
        store.dataSourceDidError(query);
      }
    });

    return YES;
  },

  retrieveRecord: function(store, storeKey) {
    var type = SC.Store.recordTypeFor(storeKey);
    var id   = store.idFor(storeKey);
    var url  = this._urlFor(type, id) + '.json';

    $.ajax({
      url: url,
      dataType: 'json',
      success: function(data, status, response) {
        store.loadRecords(store.recordTypeFor(storeKey), data.isEnumerable ? data : [data]);
      },
      error: function(data, status, response) {
        store.dataSourceDidError(storeKey, response.get('body'));
      }
    });

    return YES;
  },

  updateRecord: function(store, storeKey, params) {
    var type = store.recordTypeFor(storeKey);
    var id   = store.idFor(storeKey);
    var data = $.extend(store.readDataHash(storeKey), params || {}, { _method: 'put' });
    var url  = this._urlFor(type, id);

    $.post(url, data).done(function(data, status, response) {
      if(status == 'success') {
        store.dataSourceDidComplete(storeKey);
      } else {
        store.dataSourceDidError(storeKey, response);
      }
    });

    return YES;
  },

updateRecordDidComplete: function(response, store, storeKey, id) {
},

  _urlFor: function(recordType, id) {
    return $.compact([recordType.resource, id]).join('/');
  },

  _extractIds: function() {
    return data.map(function(hash) {
      var id = hash.id;
      delete hash.id;
      return id;
    }, this);
  },
});
<|endoftext|>


<commit_before>function UserTempChart(){
  width: 900,
  height: 450,
  maxDataPointsForDots: 500,
  transitionDuration: 1000,
  svg: null,
  yAxisGroup: null,
  xAxisGroup: null,
  dataCirclesGroup: null,
  dataLinesGroup: null,
  data: this.createDataFrom(response),
  margin: 40,
  max: this.setChartMax(),
  min: this.setChartMin(),
  pointRadius: 4,
  x: setXValue(),
  y: setYValue(),
  xAxis: setXAxisValues(),
  yAxis: setYAxisValues(),
  t: null,
  circles: null,
  dataCirclesGroup: null
}

UserTempChart.prototype.setChartMax = function() {
  return d3.max(this.data, function(d) { return d.temp }) + 10;
};

UserTempChart.prototype.setChartMin = function() {
  return d3.min(this.data, function(d) { return d.temp }) - 10;
};

UserTempChart.prototype.setXValue = function() {
  return d3.time.scale().range([0, this.width - this.margin * 2])
    .domain([this.data[0].date, this.data[this.data.length - 1].date]);
};

UserTempChart.prototype.setYValue = function() {
  return d3.scale.linear().range([this.height - this.margin * 2, 0])
    .domain([this.min, this.max]);
};

UserTempChart.prototype.setXAxisValues = function() {
  return d3.svg.axis().scale(this.x).tickSize(this.h - this.margin * 2)
    .tickPadding(0).ticks(this.data.length);
};

UserTempChart.prototype.setYAxisValues = function() {
  return d3.svg.axis().scale(this.y).orient('left')
    .tickSize(-this.w + this.margin * 2).tickPadding(10);
};

UserTempChart.prototype.createDataFrom = function(ajaxResponse) {
  ajaxResponse.forEach(function(obj){
    obj.date = new Date(obj.created_at);
    obj.isDay = obj.date.getHours() >= 6 && obj.date.getHours() <= 22;
  });
  return ajaxResponse;
};

  function draw(response) {

    svg = d3.select('#d3-chart').select('svg').select('g');
    if (svg.empty()) {
      svg = d3.select('#d3-chart')
        .append('svg:svg')
        .attr('width', w)
        .attr('height', h)
        .attr('class', 'viz')
        .append('svg:g')
        .attr('transform', 'translate(' + margin + ',' + margin + ')');
    }

    t = svg.transition().duration(transitionDuration);

    // y ticks and labels
    // if (!yAxisGroup) {
    //   yAxisGroup = svg.append('svg:g')
    //     .attr('class', 'yTick')
    //     .call(yAxis);
    // }
    // else {
    //   t.select('.yTick').call(yAxis);
    // }
    function addLineStlying(){
      var $lines = $(".tick line"),
          length = data.length;

      for(var i = 0; i < length; i++){
        if(data[i].isDay === true){
          $($lines[i]).attr({'stroke': '#83A2AA', 'stroke-width': 4.5});
          if(i === 0){$($lines[i]).attr({'stroke-width': 12});}
        }else{
          $($lines[i]).attr({'stroke': '#535F62', 'stroke-width': 4.5});
          if(i === 0){$($lines[i]).attr({'stroke-width': 12});}
        }
      }
    }

    // x ticks and labels
    if (!xAxisGroup) {
      xAxisGroup = svg.append('svg:g')
        .attr('class', 'xTick')
        .call(xAxis);
      addLineStlying();
    }
    else {
      t.select('.xTick').call(xAxis);
    }

    // Draw the lines
    if (!dataLinesGroup) {
      dataLinesGroup = svg.append('svg:g');
    }

    var dataLines = dataLinesGroup.selectAll('.data-line').data([data]);

    var line = d3.svg.line()
      .x(function(d,i) {
        return x(d.date);
      })
      .y(function(d) {
        return y(d.temp);
      })
      .interpolate("linear");

       /*
       .attr("d", d3.svg.line()
       .x(function(d) { return x(d.date); })
       .y(function(d) { return y(0); }))
       .transition()
       .delay(transitionDuration / 2)
       .duration(transitionDuration)
       .style('opacity', 1)
       .attr("transform", function(d) { return "translate(" + x(d.date) + "," + y(d.temp) + ")"; });
        */

    var garea = d3.svg.area()
      .interpolate("linear")
      .x(function(d) {
        return x(d.date);
      })
      .y0(h - margin * 2)
      .y1(function(d) {
        return y(d.temp);
      });

    dataLines
      .enter()
      .append('svg:path')
      .attr("class", "area")
      .attr("d", garea(data));

    dataLines.enter().append('path')
      .attr('class', 'data-line')
      .style('opacity', 0.3)
      .attr("d", line(data))
      .transition()
      .delay(transitionDuration / 2)
      .duration(transitionDuration)
      .style('opacity', 1);
      // .attr('x1', function(d, i) { return (i > 0) ? xScale(data[i - 1].date) : xScale(d.date); })
      // .attr('y1', function(d, i) { return (i > 0) ? yScale(data[i - 1].temp) : yScale(d.temp); })
      // .attr('x2', function(d) { return xScale(d.date); })
      // .attr('y2', function(d) { return yScale(d.temp); });

  }

UserTempChart.prototype.method_name = function(first_argument) {
  this.dataLines.exit()
    .transition()
    .attr("d", line)
    .duration(transitionDuration)
    .attr("transform", function(d) { return "translate(" + x(d.date) + "," + y(0) + ")"; })
    .style('opacity', 1e-6)
    .remove();
};

UserTempChart.prototype.selectArea = function() {
  d3.selectAll(".area").transition()
    .duration(transitionDuration)
    .attr("d", garea(data));
};

UserTempChart.prototype.drawDataCircles = function() {
  if (!this.dataCirclesGroup) {
    this.dataCirclesGroup = svg.append('svg:g');
  }
};

UserTempChart.prototype.circles = function() {
  this.circles = dataCirclesGroup.selectAll('.data-point').data(this.data);
};

UserTempChart.prototype.days = [
  'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'
];

class_name.prototype.monthNames = [
  "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
  "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
];

UserTempChart.prototype.placeCirclesOnLine = function() {
  this.circles.enter()
    .append('svg:circle')
    .attr('class', 'data-point')
    .style('opacity', 1)
    .attr('cx', function(d) { return x(d.date) })
    .attr('cy', function() { return y(0) })
    .attr('r', function(d) {
      return d.violation ? pointRadius : 0;
    })
    .transition()
    .duration(transitionDuration)
    .style('opacity', 1)
    .attr('cx', function(d) {
      return x(d.date)
    })
    .attr('cy', function(d) { return y(d.temp) });
};

UserTempChart.prototype.exitAndRemoveCircles = function() {
  this.circles
    .exit()
    .transition()
    .duration(transitionDuration)
    .attr('cy', function() { return y(0) })
    .style("opacity", 1e-6)
    .remove();
};

UserTempChart.prototype.legalMinimumFor = function(reading) {
  if(reading.isDay === true){
    return '68';
  }else{
    return '55';
  }
};

UserTempChart.prototype.getCivilianTime = function(reading) {
  if (reading.getHours() > 12){
    return (reading.getHours() - 12) + ":"
      + (reading.getMinutes() >= 10 ?
        reading.getMinutes() : "0" + reading.getMinutes())
      + " PM";
  }else{
    return reading.getHours() + ":"
      + (reading.getMinutes() >= 10 ?
        reading.getMinutes() : "0" + reading.getMinutes())
      + " AM";
  }
};

UserTempChart.prototype.createTipsyMouseOver = function() {
  $('svg circle').tipsy({
    gravity: 's',
    html: true,
    topOffset: 2.8,
    leftOffset: 3.8,
    title: function() {
      var d = this.__data__;
      var pDate = d.date;
      return pDate.getDate() + ' '
        + this.monthNames[pDate.getMonth()] + ' '
        + pDate.getFullYear() + '
'
        + this.days[ pDate.getDay() ] + ' at '
        + this.getCivilianTime(pDate) + '
'
        + 'Temperature in Violation
'
        + '
Temperature in Apt: ' + d.temp + '°'
        + '
Temperature Outside: ' + d.outdoor_temp + '°'
        + '
Legal minimum: ' + this.legalMinimumFor(d) + '°';
    }
  });
};<commit_msg>further moves function into protype<commit_after>function UserTempChart(){
  width: 900,
  height: 450,
  maxDataPointsForDots: 500,
  transitionDuration: 1000,
  svg: setSvg(),
  yAxisGroup: null,
  xAxisGroup: null,
  dataCirclesGroup: null,
  dataLinesGroup: null,
  data: this.createDataFrom(response),
  margin: 40,
  max: this.setChartMax(),
  min: this.setChartMin(),
  pointRadius: 4,
  x: setXValue(),
  y: setYValue(),
  xAxis: setXAxisValues(),
  yAxis: setYAxisValues(),
  t: null,
  circles: null,
  dataCirclesGroup: null
}

UserTempChart.prototype.setChartMax = function() {
  return d3.max(this.data, function(d) { return d.temp }) + 10;
};

UserTempChart.prototype.setChartMin = function() {
  return d3.min(this.data, function(d) { return d.temp }) - 10;
};

UserTempChart.prototype.setXValue = function() {
  return d3.time.scale().range([0, this.width - this.margin * 2])
    .domain([this.data[0].date, this.data[this.data.length - 1].date]);
};

UserTempChart.prototype.setYValue = function() {
  return d3.scale.linear().range([this.height - this.margin * 2, 0])
    .domain([this.min, this.max]);
};

UserTempChart.prototype.setXAxisValues = function() {
  return d3.svg.axis().scale(this.x).tickSize(this.h - this.margin * 2)
    .tickPadding(0).ticks(this.data.length);
};

UserTempChart.prototype.setYAxisValues = function() {
  return d3.svg.axis().scale(this.y).orient('left')
    .tickSize(-this.w + this.margin * 2).tickPadding(10);
};

UserTempChart.prototype.createDataFrom = function(ajaxResponse) {
  ajaxResponse.forEach(function(obj){
    obj.date = new Date(obj.created_at);
    obj.isDay = obj.date.getHours() >= 6 && obj.date.getHours() <= 22;
  });
  return ajaxResponse;
};

UserTempChart.prototype.setSvg = function() {
  return d3.select('#d3-chart').select('svg').select('g');
};

UserTempChart.prototype.addStylingToSvg = function() {
  if (this.svg.empty()) {
    this.svg = d3.select('#d3-chart')
      .append('svg:svg')
      .attr('width', w)
      .attr('height', h)
      .attr('class', 'viz')
      .append('svg:g')
      .attr('transform', 'translate(' + this.margin + ',' + this.margin + ')');
  }
};

UserTempChart.prototype.setT = function() {
  return svg.transition().duration(this.transitionDuration);
};
// We don't actually use this method for the graph but we might need it later
UserTempChart.prototype.setYTicksAndLabels = function() {
  if (!this.yAxisGroup) {
    this.yAxisGroup = this.svg.append('svg:g')
      .attr('class', 'yTick')
      .call(this.yAxis);
  }
  else {
    this.t.select('.yTick').call(this.yAxis);
  }
};
// This method needs to be altered to so that the stroke-width is dynamic
UserTempChart.prototype.addVerticalLineStlying = function() {
  var $lines = $(".tick line"),
      length = data.length;

  for(var i = 0; i < length; i++){
    if(data[i].isDay === true){
      $($lines[i]).attr({'stroke': '#83A2AA', 'stroke-width': 4.5});
      if(i === 0){$($lines[i]).attr({'stroke-width': 12});}
    }else{
      $($lines[i]).attr({'stroke': '#535F62', 'stroke-width': 4.5});
      if(i === 0){$($lines[i]).attr({'stroke-width': 12});}
    }
  }
};

UserTempChart.prototype.setXTicksAndLabels = function() {
  if (!this.xAxisGroup) {
    this.xAxisGroup = svg.append('svg:g')
      .attr('class', 'xTick')
      .call(this.xAxis);
    this.addVerticalLineStlying();
  }
  else {
    this.t.select('.xTick').call(this.xAxis);
  }
};

UserTempChart.prototype.setDataLinesGroup = function() {
  if (!this.dataLinesGroup) {
    this.dataLinesGroup = svg.append('svg:g');
  }
};

UserTempChart.prototype.setDataLines = function() {
  this.dataLines = dataLinesGroup.selectAll('.data-line').data([data]);
};

UserTempChart.prototype.setLine = function() {
  this.line = d3.svg.line()
    .x(function(d,i) {
      return this.x(d.date);
    })
    .y(function(d) {
      return this.y(d.temp);
    })
    .interpolate("linear");
};

  function draw(response) {
    var garea = d3.svg.area()
      .interpolate("linear")
      .x(function(d) {
        return x(d.date);
      })
      .y0(h - margin * 2)
      .y1(function(d) {
        return y(d.temp);
      });

    dataLines
      .enter()
      .append('svg:path')
      .attr("class", "area")
      .attr("d", garea(data));

    dataLines.enter().append('path')
      .attr('class', 'data-line')
      .style('opacity', 0.3)
      .attr("d", line(data))
      .transition()
      .delay(transitionDuration / 2)
      .duration(transitionDuration)
      .style('opacity', 1);
      // .attr('x1', function(d, i) { return (i > 0) ? xScale(data[i - 1].date) : xScale(d.date); })
      // .attr('y1', function(d, i) { return (i > 0) ? yScale(data[i - 1].temp) : yScale(d.temp); })
      // .attr('x2', function(d) { return xScale(d.date); })
      // .attr('y2', function(d) { return yScale(d.temp); });

  }

UserTempChart.prototype.addStylingToDataLines = function() {
  this.dataLines.exit()
    .transition()
    .attr("d", line)
    .duration(transitionDuration)
    .attr("transform", function(d) { return "translate(" + x(d.date) + "," + y(0) + ")"; })
    .style('opacity', 1e-6)
    .remove();
};

UserTempChart.prototype.selectArea = function() {
  d3.selectAll(".area").transition()
    .duration(transitionDuration)
    .attr("d", garea(data));
};

UserTempChart.prototype.drawDataCircles = function() {
  if (!this.dataCirclesGroup) {
    this.dataCirclesGroup = svg.append('svg:g');
  }
};

UserTempChart.prototype.circles = function() {
  this.circles = dataCirclesGroup.selectAll('.data-point').data(this.data);
};

UserTempChart.prototype.days = [
  'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'
];

class_name.prototype.monthNames = [
  "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
  "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
];

UserTempChart.prototype.placeCirclesOnLine = function() {
  this.circles.enter()
    .append('svg:circle')
    .attr('class', 'data-point')
    .style('opacity', 1)
    .attr('cx', function(d) { return x(d.date) })
    .attr('cy', function() { return y(0) })
    .attr('r', function(d) {
      return d.violation ? pointRadius : 0;
    })
    .transition()
    .duration(transitionDuration)
    .style('opacity', 1)
    .attr('cx', function(d) {
      return x(d.date)
    })
    .attr('cy', function(d) { return y(d.temp) });
};

UserTempChart.prototype.exitAndRemoveCircles = function() {
  this.circles
    .exit()
    .transition()
    .duration(transitionDuration)
    .attr('cy', function() { return y(0) })
    .style("opacity", 1e-6)
    .remove();
};

UserTempChart.prototype.legalMinimumFor = function(reading) {
  if(reading.isDay === true){
    return '68';
  }else{
    return '55';
  }
};

UserTempChart.prototype.getCivilianTime = function(reading) {
  if (reading.getHours() > 12){
    return (reading.getHours() - 12) + ":"
      + (reading.getMinutes() >= 10 ?
        reading.getMinutes() : "0" + reading.getMinutes())
      + " PM";
  }else{
    return reading.getHours() + ":"
      + (reading.getMinutes() >= 10 ?
        reading.getMinutes() : "0" + reading.getMinutes())
      + " AM";
  }
};

UserTempChart.prototype.createTipsyMouseOver = function() {
  $('svg circle').tipsy({
    gravity: 's',
    html: true,
    topOffset: 2.8,
    leftOffset: 3.8,
    title: function() {
      var d = this.__data__;
      var pDate = d.date;
      return pDate.getDate() + ' '
        + this.monthNames[pDate.getMonth()] + ' '
        + pDate.getFullYear() + '
'
        + this.days[ pDate.getDay() ] + ' at '
        + this.getCivilianTime(pDate) + '
'
        + 'Temperature in Violation
'
        + '
Temperature in Apt: ' + d.temp + '°'
        + '
Temperature Outside: ' + d.outdoor_temp + '°'
        + '
Legal minimum: ' + this.legalMinimumFor(d) + '°';
    }
  });
};<|endoftext|>


<commit_before>/**
 *
 * MatchingReactions
 *
 */

import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

import ReactGA from 'react-ga';
import { Link } from 'react-router';
import * as Scroll from 'react-scroll';

import Table, {
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  TableFooter,
  TablePagination,
} from 'material-ui/Table';
import { LinearProgress } from 'material-ui/Progress';
import Hidden from 'material-ui/Hidden';
import { withStyles } from 'material-ui/styles';
import FaCube from 'react-icons/lib/fa/cube';

import cachios from 'cachios';
import { graphQLRoot } from 'utils/constants';

import * as actions from './actions';

const prettyPrintReaction = (reactants, products) => (`${Object.keys(JSON.parse(reactants)).join(' + ')}  ⇄  ${Object.keys(JSON.parse(products)).join(' + ')}`
  ).replace(/star/g, '*').replace(/gas/g, '(ℊ)');

const styles = () => ({
  tableFooter: {
    marginLeft: '-30px',
    div: {
      marginLeft: '-30px',
    },
  },

});

class MatchingReactions extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.fetchRow = this.fetchRow.bind(this);
    this.state = {
      order: 'asc',
      orderBy: 'energy',
      page: 0,
      rowsPerPage: 10,
      loading: false,
      pageInfo: {},
    };
  }

  fetchRow(reaction) {
    this.setState({
      loading: true,
    });
    let catappKeys;
    let catappIds;
    if (typeof reaction.aseIds !== 'undefined' && reaction.aseIds !== null) {
      catappIds = JSON.parse(reaction.aseIds);
      catappKeys = Object.keys(JSON.parse(reaction.aseIds));
    } else {
      catappIds = {};
      catappKeys = [];
      this.setState({
        loading: false,
      });
    }

    this.props.clearSystems();
    catappKeys.map((key) => {
      let aseId = catappIds[key];
      if (typeof aseId === 'object') {
        aseId = aseId[1];
      }
      const query = {
        query: `query{systems(uniqueId: "${aseId}") {
  edges {
    node {
    Formula
    energy
    Cifdata
    PublicationYear
    PublicationDoi
    PublicationAuthors
    PublicationTitle
    PublicationVolume
    PublicationUrl
    PublicationNumber
    PublicationJournal
    PublicationPages
    uniqueId
    volume
    mass
    Facet
    }
  }
}}`,
        ttl: 300,
      };
      return cachios.post(graphQLRoot, query).then((response) => {
        Scroll.animateScroll.scrollMore(900);
        const node = response.data.data.systems.edges[0].node;
        node.DFTCode = reaction.dftCode;
        node.DFTFunctional = reaction.dftFunctional;
        node.aseId = aseId;
        node.key = key
          .replace(/.*TSstar/g, '‡')
          .replace(/(.*)gas/g, (match, p1) => `${p1}(ℊ)`)
          .replace(/(.+)star/, (match, p1) => `${p1}/${reaction.surfaceComposition}`)
          .replace(/star/, reaction.surfaceComposition);

        node.full_key = node.key;
        if (typeof node.Facet !== 'undefined' && node.Facet !== '' && node.Facet !== null) {
          node.full_key = `${node.full_key} [${node.Facet}]`;
        }
        if (node.key.indexOf('(ℊ)') > -1) {
          node.full_key = `Molecule ${node.full_key}`;
        } else {
          node.full_key = `Surface ${node.full_key}`;
        }

        this.props.saveSystem(node);
        this.setState({
          loading: false,
        });
      }).catch(() => {
        this.setState({
          loading: false,
        });
      });
    });
  }
  handlePageChange = (event, page) => {
    this.setState({ page });
  };
  handleChangeRowsPerPage = (event) => {
    this.setState({ rowsPerPage: event.target.value });
  };

  render() {
    if (this.props.matchingReactions.length === 0) {
      if (this.props.searchSubmitted) {
        ReactGA.event({
          category: 'Search',
          action: 'Search',
          label: `No results: ${JSON.stringify(this.props.searchParams)} / ${this.props.searchString}`,
        });
        return (

Ooops!

            No reaction energies found. Please remove one or more filters.
            Or <Link to={`/catKitDemo/fcc/3.91/${this.props.searchParams.surfaceComposition}`}>construct</Link> your own.

        );
      }
      return null;
    }
    return (

Matching Reactions ({this.props.resultSize})

            <TableHead>
              <TableRow>
                <TableCell padding="none">Geometry</TableCell>
                <TableCell padding="none">Reaction</TableCell>
                <TableCell padding="none">Reaction Energy</TableCell>
                <Hidden smDown>
                  <TableCell>Activation Energy</TableCell>
                </Hidden>
                <TableCell padding="none">Surface</TableCell>
                <Hidden smDown>
                  <TableCell>Facet</TableCell>
                </Hidden>
              </TableRow>
            </TableHead>
            <TableBody>
              {
                /* eslint-disable arrow-body-style */
                this.props.matchingReactions
                  .slice(this.state.page * this.state.rowsPerPage, (this.state.page + 1) * this.state.rowsPerPage)
                  .map((result, i) => {
                    return (
                      <TableRow
                        hover
                        key={`row_${i}`}
                        onClick={() => {
                          this.props.selectReaction(result.node);
                          this.fetchRow(result.node);
                        }}
                      >
                        <TableCell padding="none">{result.node.aseIds !== null ? <FaCube /> : null}</TableCell>
                        <TableCell padding="dense">{prettyPrintReaction(result.node.reactants, result.node.products)}</TableCell>
                        <TableCell padding="none">{!result.node.reactionEnergy || `${result.node.reactionEnergy.toFixed(2)} eV` }</TableCell>
                        <Hidden smDown>
                          <TableCell>{!result.node.activationEnergy || `${result.node.activationEnergy.toFixed(2)} eV`}</TableCell>
                        </Hidden>
                        <TableCell padding="none">{result.node.surfaceComposition}</TableCell>
                        <Hidden smDown>
                          <TableCell>{result.node.facet}</TableCell>
                        </Hidden>
                      </TableRow>

                    );
                  })
                /* eslint-enable */
              }
            </TableBody>
            <TableFooter
              className={this.props.classes.tableFooter}
            >
              <TableRow>
                <TablePagination
                  count={this.props.resultSize}
                  rowsPerPage={this.state.rowsPerPage}
                  page={this.state.page}
                  onChangePage={this.handlePageChange}
                  onChangeRowsPerPage={this.handleChangeRowsPerPage}
                  rowsPerPageOptions={[10, 25, 100]}
                  className={this.props.classes.tableFooter}
                  labelRowsPerPage=""
                />
              </TableRow>
            </TableFooter>

        {this.state.loading ? <LinearProgress color="primary" /> : null }

    );
  }
}

MatchingReactions.propTypes = {
  selectReaction: PropTypes.func.isRequired,
  clearSystems: PropTypes.func.isRequired,
  saveSystem: PropTypes.func.isRequired,
  matchingReactions: PropTypes.array.isRequired,
  searchSubmitted: PropTypes.bool,
  searchParams: PropTypes.object,
  classes: PropTypes.object,
  resultSize: PropTypes.number,
  searchString: PropTypes.string,
};

MatchingReactions.defaultProps = {
  searchResults: [],
  searchString: '',
};

const mapStateToProps = (state) => ({
  filter: state.get('energiesPageReducer').filter,
  matchingReactions: state.get('energiesPageReducer').matchingReactions,
  searchSubmitted: state.get('energiesPageReducer').searchSubmitted,
  search: state.get('energiesPageReducer').search,
  resultSize: state.get('energiesPageReducer').resultSize,
  searchParams: state.get('energiesPageReducer').searchParams,

});

const mapDispatchToProps = (dispatch) => ({
  receiveReactions: (reactions) => {
    dispatch(actions.receiveReactions(reactions));
  },
  selectReaction: (reaction) => {
    dispatch(actions.selectReaction(reaction));
  },
  clearSystems: () => {
    dispatch(actions.clearSystems());
  },
  receiveSystems: (systems) => {
    dispatch(actions.receiveSystems(systems));
  },
  saveSystem: (system) => {
    dispatch(actions.saveSystem(system));
  },
});

export default withStyles(styles)(connect(mapStateToProps, mapDispatchToProps)(MatchingReactions));
<commit_msg>Added better check if any valid search was submitted<commit_after>/**
 *
 * MatchingReactions
 *
 */

import _ from 'lodash';
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

import ReactGA from 'react-ga';
import { Link } from 'react-router';
import * as Scroll from 'react-scroll';

import Table, {
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  TableFooter,
  TablePagination,
} from 'material-ui/Table';
import { LinearProgress } from 'material-ui/Progress';
import Hidden from 'material-ui/Hidden';
import { withStyles } from 'material-ui/styles';
import FaCube from 'react-icons/lib/fa/cube';

import cachios from 'cachios';
import { graphQLRoot } from 'utils/constants';

import * as actions from './actions';

const prettyPrintReaction = (reactants, products) => (`${Object.keys(JSON.parse(reactants)).join(' + ')}  ⇄  ${Object.keys(JSON.parse(products)).join(' + ')}`
  ).replace(/star/g, '*').replace(/gas/g, '(ℊ)');

const styles = () => ({
  tableFooter: {
    marginLeft: '-30px',
    div: {
      marginLeft: '-30px',
    },
  },

});

class MatchingReactions extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.fetchRow = this.fetchRow.bind(this);
    this.state = {
      order: 'asc',
      orderBy: 'energy',
      page: 0,
      rowsPerPage: 10,
      loading: false,
      pageInfo: {},
    };
  }

  fetchRow(reaction) {
    this.setState({
      loading: true,
    });
    let catappKeys;
    let catappIds;
    if (typeof reaction.aseIds !== 'undefined' && reaction.aseIds !== null) {
      catappIds = JSON.parse(reaction.aseIds);
      catappKeys = Object.keys(JSON.parse(reaction.aseIds));
    } else {
      catappIds = {};
      catappKeys = [];
      this.setState({
        loading: false,
      });
    }

    this.props.clearSystems();
    catappKeys.map((key) => {
      let aseId = catappIds[key];
      if (typeof aseId === 'object') {
        aseId = aseId[1];
      }
      const query = {
        query: `query{systems(uniqueId: "${aseId}") {
  edges {
    node {
    Formula
    energy
    Cifdata
    PublicationYear
    PublicationDoi
    PublicationAuthors
    PublicationTitle
    PublicationVolume
    PublicationUrl
    PublicationNumber
    PublicationJournal
    PublicationPages
    uniqueId
    volume
    mass
    Facet
    }
  }
}}`,
        ttl: 300,
      };
      return cachios.post(graphQLRoot, query).then((response) => {
        Scroll.animateScroll.scrollMore(900);
        const node = response.data.data.systems.edges[0].node;
        node.DFTCode = reaction.dftCode;
        node.DFTFunctional = reaction.dftFunctional;
        node.aseId = aseId;
        node.key = key
          .replace(/.*TSstar/g, '‡')
          .replace(/(.*)gas/g, (match, p1) => `${p1}(ℊ)`)
          .replace(/(.+)star/, (match, p1) => `${p1}/${reaction.surfaceComposition}`)
          .replace(/star/, reaction.surfaceComposition);

        node.full_key = node.key;
        if (typeof node.Facet !== 'undefined' && node.Facet !== '' && node.Facet !== null) {
          node.full_key = `${node.full_key} [${node.Facet}]`;
        }
        if (node.key.indexOf('(ℊ)') > -1) {
          node.full_key = `Molecule ${node.full_key}`;
        } else {
          node.full_key = `Surface ${node.full_key}`;
        }

        this.props.saveSystem(node);
        this.setState({
          loading: false,
        });
      }).catch(() => {
        this.setState({
          loading: false,
        });
      });
    });
  }
  handlePageChange = (event, page) => {
    this.setState({ page });
  };
  handleChangeRowsPerPage = (event) => {
    this.setState({ rowsPerPage: event.target.value });
  };

  render() {
    if (this.props.matchingReactions.length === 0) {
      if (this.props.searchSubmitted && (!_.isEmpty(this.props.searchParams) || !_.isEmpty(this.props.searchString))) {
        ReactGA.event({
          category: 'Search',
          action: 'Search',
          label: `No results: ${JSON.stringify(this.props.searchParams)} / ${this.props.searchString}`,
        });
        return (

Ooops!

            No reaction energies found. Please remove one or more filters.
            Or <Link to={`/catKitDemo/fcc/3.91/${this.props.searchParams.surfaceComposition}`}>construct</Link> your own.

        );
      }
      return null;
    }
    return (

Matching Reactions ({this.props.resultSize})

            <TableHead>
              <TableRow>
                <TableCell padding="none">Geometry</TableCell>
                <TableCell padding="none">Reaction</TableCell>
                <TableCell padding="none">Reaction Energy</TableCell>
                <Hidden smDown>
                  <TableCell>Activation Energy</TableCell>
                </Hidden>
                <TableCell padding="none">Surface</TableCell>
                <Hidden smDown>
                  <TableCell>Facet</TableCell>
                </Hidden>
              </TableRow>
            </TableHead>
            <TableBody>
              {
                /* eslint-disable arrow-body-style */
                this.props.matchingReactions
                  .slice(this.state.page * this.state.rowsPerPage, (this.state.page + 1) * this.state.rowsPerPage)
                  .map((result, i) => {
                    return (
                      <TableRow
                        hover
                        key={`row_${i}`}
                        onClick={() => {
                          this.props.selectReaction(result.node);
                          this.fetchRow(result.node);
                        }}
                      >
                        <TableCell padding="none">{result.node.aseIds !== null ? <FaCube /> : null}</TableCell>
                        <TableCell padding="dense">{prettyPrintReaction(result.node.reactants, result.node.products)}</TableCell>
                        <TableCell padding="none">{!result.node.reactionEnergy || `${result.node.reactionEnergy.toFixed(2)} eV` }</TableCell>
                        <Hidden smDown>
                          <TableCell>{!result.node.activationEnergy || `${result.node.activationEnergy.toFixed(2)} eV`}</TableCell>
                        </Hidden>
                        <TableCell padding="none">{result.node.surfaceComposition}</TableCell>
                        <Hidden smDown>
                          <TableCell>{result.node.facet}</TableCell>
                        </Hidden>
                      </TableRow>

                    );
                  })
                /* eslint-enable */
              }
            </TableBody>
            <TableFooter
              className={this.props.classes.tableFooter}
            >
              <TableRow>
                <TablePagination
                  count={this.props.resultSize}
                  rowsPerPage={this.state.rowsPerPage}
                  page={this.state.page}
                  onChangePage={this.handlePageChange}
                  onChangeRowsPerPage={this.handleChangeRowsPerPage}
                  rowsPerPageOptions={[10, 25, 100]}
                  className={this.props.classes.tableFooter}
                  labelRowsPerPage=""
                />
              </TableRow>
            </TableFooter>

        {this.state.loading ? <LinearProgress color="primary" /> : null }

    );
  }
}

MatchingReactions.propTypes = {
  selectReaction: PropTypes.func.isRequired,
  clearSystems: PropTypes.func.isRequired,
  saveSystem: PropTypes.func.isRequired,
  matchingReactions: PropTypes.array.isRequired,
  searchSubmitted: PropTypes.bool,
  searchParams: PropTypes.object,
  classes: PropTypes.object,
  resultSize: PropTypes.number,
  searchString: PropTypes.string,
};

MatchingReactions.defaultProps = {
  searchResults: [],
  searchString: '',
};

const mapStateToProps = (state) => ({
  filter: state.get('energiesPageReducer').filter,
  matchingReactions: state.get('energiesPageReducer').matchingReactions,
  searchSubmitted: state.get('energiesPageReducer').searchSubmitted,
  search: state.get('energiesPageReducer').search,
  resultSize: state.get('energiesPageReducer').resultSize,
  searchParams: state.get('energiesPageReducer').searchParams,

});

const mapDispatchToProps = (dispatch) => ({
  receiveReactions: (reactions) => {
    dispatch(actions.receiveReactions(reactions));
  },
  selectReaction: (reaction) => {
    dispatch(actions.selectReaction(reaction));
  },
  clearSystems: () => {
    dispatch(actions.clearSystems());
  },
  receiveSystems: (systems) => {
    dispatch(actions.receiveSystems(systems));
  },
  saveSystem: (system) => {
    dispatch(actions.saveSystem(system));
  },
});

export default withStyles(styles)(connect(mapStateToProps, mapDispatchToProps)(MatchingReactions));
<|endoftext|>