<commit_before>// dependencies
//
import React from 'react';
import update from 'react-addons-update';
import uniqueId from 'lodash/uniqueId';
import isArray from 'lodash/isArray';
import classnames from 'classnames';

/**
 * The CheckboxGroup component
 */
class CheckboxGroup extends React.Component {
    /**
     * Construct the component instance
     * @param  {Object} props The component properties
     */
    constructor(props) {
        super(props);

        // declare a variable for the component value
        //
        let value = [];

        // do we have a value prop? if so, make sure it's either an array, or
        // convert it to an array
        //
        if (this.props.value) {
            value = isArray(this.props.value) ? this.props.value : [this.props.value];
        }

        // calculate a unique ID for the component if one is not provided
        //
        this.id = this.props.id || uniqueId('form-checkboxgroup-');

        // intialize the validation message for the component
        //
        this.validationMessage = this.props.validationMessage
            || `At least one item in ${this.props.description} must be selected`;

        // initialize the component state
        //
        this.state = {
            value,
            hasBeenClicked: false,
        };

        // bind `this` to the onClick handler
        //
        this.onClick = this.onClick.bind(this);
    }

    /**
     * Handle the "component is mounting" event
     */
    componentWillMount() {
        // determine if it's valid
        //
        const isValid = !this.props.required || this.state.value.length;

        // call the `onChildValidationEvent` handler once with
        // `hasValidated`=false, just to ensure that the parent knows about this
        // child
        //
        if (this.context.onChildValidationEvent) {
            this.context.onChildValidationEvent(
                this.id,
                false,
                isValid ? null : this.validationMessage
            );
        }
    }

    /**
     * Handle a click or change event for one of the input elements
     * @param  {String} value The value for the input element that was clicked
     */
    onClick(value) {
        // determine if the item clicked is currently in the list of checked
        // items
        //
        const idx = this.state.value.findIndex((val) => val === value);

        // declare a variable to hold the update details
        //
        let delta = null;

        // do we have this item in the list of checked items already?
        //
        if (idx === -1) {
            // no. add the item to the array
            //
            delta = { hasBeenClicked: { $set: true }, value: { $push: [value] } };
        } else {
            // yes. remove the item from the array
            //
            delta = { hasBeenClicked: { $set: true }, value: { $splice: [[idx, 1]] } };
        }

        // update the state...
        //
        this.setState((state) => update(state, delta), () => {
            // then call the `onChange` handler (if any)
            //
            if (this.props.onChange) {
                this.props.onChange(this.state.value);
            }

            // determine if the value is valid
            //
            const isValid = !this.props.required || this.state.value.length;

            // call the "child has validated" handler
            //
            if (this.context.onChildValidationEvent) {
                this.context.onChildValidationEvent(
                    this.id,
                    true,
                    isValid ? null : this.validationMessage
                );
            }
        });
    }

    /**
     * Render the component
     * @return {React.Element} The React element describing the component
     */
    render() {
        // build the list of classes for the outermost div
        //
        const classes = classnames('form-group', {
            'has-error': this.props.required
                && this.state.hasBeenClicked
                && !this.state.value.length,
        });

        // render a label for the component, if a label has been provided
        //
        const label = this.props.label
            ? (
            <label
                className={classnames('control-label', 'pull-left', {
                    [`col-xs-${this.context.labelColumns}`]: this.context.labelColumns,
                })}
            >
                {this.props.label}

            )
            : null;

        // render the help block if the component has failed validation
        //
        const helpBlock =
            this.props.required && this.state.hasBeenClicked && !this.state.value.length
            ? {this.validationMessage}
            : '';

        // render the input elements for the component
        //
        const inputs = (
            <div
                className={classnames('form-checkboxgroup-inputs', {
                    [`col-xs-${12 - this.context.labelColumns}`]: this.context.labelColumns,
                })}
            >
                {this.props.options.map((opt) =>

                            <input
                                type="checkbox"
                                value={opt.value}
                                checked={
                                    this.state.value.findIndex((val) =>
                                        val === opt.value
                                    ) !== -1
                                }
                                onChange={() => this.onClick(opt.value)}
                                onClick={() => this.onClick(opt.value)}
                            />
                            {opt.name}

                )}

                {helpBlock}

        );

        // render the whole component and return it
        //
        return (

                {label}

                {inputs}

        );
    }
}

/**
 * The property types for the component
 * @type {Object}
 */
CheckboxGroup.propTypes = {
    required:          React.PropTypes.bool,
    id:                React.PropTypes.string,
    label:             React.PropTypes.string,
    description:       React.PropTypes.string,
    validationMessage: React.PropTypes.string,
    onChange:          React.PropTypes.func,
    value:             React.PropTypes.oneOfType([
        React.PropTypes.arrayOf(React.PropTypes.string),
        React.PropTypes.arrayOf(React.PropTypes.number),
        React.PropTypes.string,
        React.PropTypes.number,
    ]),
    options:           React.PropTypes.arrayOf(React.PropTypes.object),
};

/**
 * The context types for the component
 * @type {Object}
 */
CheckboxGroup.contextTypes = {
    onChildValidationEvent: React.PropTypes.func,
    labelColumns:           React.PropTypes.number,
};

// export the component
//
export default CheckboxGroup;
<commit_msg>removed onClick handler<commit_after>// dependencies
//
import React from 'react';
import update from 'react-addons-update';
import uniqueId from 'lodash/uniqueId';
import isArray from 'lodash/isArray';
import classnames from 'classnames';

/**
 * The CheckboxGroup component
 */
class CheckboxGroup extends React.Component {
    /**
     * Construct the component instance
     * @param  {Object} props The component properties
     */
    constructor(props) {
        super(props);

        // declare a variable for the component value
        //
        let value = [];

        // do we have a value prop? if so, make sure it's either an array, or
        // convert it to an array
        //
        if (this.props.value) {
            value = isArray(this.props.value) ? this.props.value : [this.props.value];
        }

        // calculate a unique ID for the component if one is not provided
        //
        this.id = this.props.id || uniqueId('form-checkboxgroup-');

        // intialize the validation message for the component
        //
        this.validationMessage = this.props.validationMessage
            || `At least one item in ${this.props.description} must be selected`;

        // initialize the component state
        //
        this.state = {
            value,
            hasBeenClicked: false,
        };

        // bind `this` to the onClick handler
        //
        this.onClick = this.onClick.bind(this);
    }

    /**
     * Handle the "component is mounting" event
     */
    componentWillMount() {
        // determine if it's valid
        //
        const isValid = !this.props.required || this.state.value.length;

        // call the `onChildValidationEvent` handler once with
        // `hasValidated`=false, just to ensure that the parent knows about this
        // child
        //
        if (this.context.onChildValidationEvent) {
            this.context.onChildValidationEvent(
                this.id,
                false,
                isValid ? null : this.validationMessage
            );
        }
    }

    /**
     * Handle a click or change event for one of the input elements
     * @param  {String} value The value for the input element that was clicked
     */
    onClick(value) {
        // determine if the item clicked is currently in the list of checked
        // items
        //
        const idx = this.state.value.findIndex((val) => val === value);

        // declare a variable to hold the update details
        //
        let delta = null;

        // do we have this item in the list of checked items already?
        //
        if (idx === -1) {
            // no. add the item to the array
            //
            delta = { hasBeenClicked: { $set: true }, value: { $push: [value] } };
        } else {
            // yes. remove the item from the array
            //
            delta = { hasBeenClicked: { $set: true }, value: { $splice: [[idx, 1]] } };
        }

        // update the state...
        //
        this.setState((state) => update(state, delta), () => {
            // then call the `onChange` handler (if any)
            //
            if (this.props.onChange) {
                this.props.onChange(this.state.value);
            }

            // determine if the value is valid
            //
            const isValid = !this.props.required || this.state.value.length;

            // call the "child has validated" handler
            //
            if (this.context.onChildValidationEvent) {
                this.context.onChildValidationEvent(
                    this.id,
                    true,
                    isValid ? null : this.validationMessage
                );
            }
        });
    }

    /**
     * Render the component
     * @return {React.Element} The React element describing the component
     */
    render() {
        // build the list of classes for the outermost div
        //
        const classes = classnames('form-group', {
            'has-error': this.props.required
                && this.state.hasBeenClicked
                && !this.state.value.length,
        });

        // render a label for the component, if a label has been provided
        //
        const label = this.props.label
            ? (
            <label
                className={classnames('control-label', 'pull-left', {
                    [`col-xs-${this.context.labelColumns}`]: this.context.labelColumns,
                })}
            >
                {this.props.label}

            )
            : null;

        // render the help block if the component has failed validation
        //
        const helpBlock =
            this.props.required && this.state.hasBeenClicked && !this.state.value.length
            ? {this.validationMessage}
            : '';

        // render the input elements for the component
        //
        const inputs = (
            <div
                className={classnames('form-checkboxgroup-inputs', {
                    [`col-xs-${12 - this.context.labelColumns}`]: this.context.labelColumns,
                })}
            >
                {this.props.options.map((opt) =>

                            <input
                                type="checkbox"
                                value={opt.value}
                                checked={
                                    this.state.value.findIndex((val) =>
                                        val === opt.value
                                    ) !== -1
                                }
                                onChange={() => this.onClick(opt.value)}
                            />
                            {opt.name}

                )}

                {helpBlock}

        );

        // render the whole component and return it
        //
        return (

                {label}

                {inputs}

        );
    }
}

/**
 * The property types for the component
 * @type {Object}
 */
CheckboxGroup.propTypes = {
    required:          React.PropTypes.bool,
    id:                React.PropTypes.string,
    label:             React.PropTypes.string,
    description:       React.PropTypes.string,
    validationMessage: React.PropTypes.string,
    onChange:          React.PropTypes.func,
    value:             React.PropTypes.oneOfType([
        React.PropTypes.arrayOf(React.PropTypes.string),
        React.PropTypes.arrayOf(React.PropTypes.number),
        React.PropTypes.string,
        React.PropTypes.number,
    ]),
    options:           React.PropTypes.arrayOf(React.PropTypes.object),
};

/**
 * The context types for the component
 * @type {Object}
 */
CheckboxGroup.contextTypes = {
    onChildValidationEvent: React.PropTypes.func,
    labelColumns:           React.PropTypes.number,
};

// export the component
//
export default CheckboxGroup;
<|endoftext|>


<commit_before>
(function(window, angular, wb, $) {'use strict';
    var app = angular.module('reportGenerator', ['dataset-types', 'advanced-search', 'display-fields', 'services.config']),
        $resultsTable = $('#results'),
        maxFieldItems = 100,
        queryDefaults = {
            wt: 'json'
        },
        datatableDefaults = {
            columnDefs: [
                {
                    className: 'nowrap right',
                    targets: [0]
                }
            ],
            pageLength: 100,
            lengthMenu: [[50, 100, 200, 500, -1], [50, 100, 200, 500, 'All']]
        };

    app.run(['$http', '$rootScope', 'configuration', function($http, $rootScope, configuration) {

        function createQuery(keywords) {
            var regexp = /(.*?)((?: (?:OR|AND) )|$)/g;

            if (keywords.length === 0) {
                return '*';
            }

            keywords = keywords.replace(regexp, function(match, key, sep) {
                if (key.length !== 0 && !key.match(/:[\(\[].*?[\)\]]/)) {
                    key = 'text:(*' + key + '*)';
                }
                return key + sep;
            });
            return keywords;
        }

        function sanitizeData(rows, fields) {
            var row, r, field, f, cell;

            for (r = 0; r < rows.length; r += 1) {
                row = rows[r];

                for (f = 0; f < fields.length; f += 1) {
                    field = fields[f];
                    cell = row[field];

                    row[field] = cell || '';

                    if (typeof cell === 'object') {
                        row[field] = cell.splice(0, maxFieldItems).join(',');
                    }
                }
            }

            return rows;
        }

        function createFieldsMapping(fields) {
            var fieldsMapping = [],
                f;

            for (f = 0; f < fields.length; f += 1) {
                fieldsMapping.push({
                    data: fields[f],
                    title: fields[f],
                });
            }

            return fieldsMapping;
        }

        function maxResultsFromUrl() {
            var maxResults = wb.pageUrlParts.params.rows;

            if ($rootScope.maxResultsOptions[maxResults]) {
                return maxResults;
            }
        }

        $rootScope.query = wb.pageUrlParts.params.q ? decodeURI(wb.pageUrlParts.params.q) : '';
        $rootScope.maxResultsOptions = {
            20: 20,
            50: 50,
            100: 100,
            1000: '1000 (default)',
            2000: 2000
        };
        $rootScope.maxResults = maxResultsFromUrl() || '1000';

        $rootScope.clearKeywords = function() {
            $rootScope.query = '';
        };

        $rootScope.saveUrl = function() {
            var urlParts = wb.pageUrlParts,
                url = urlParts.absolute.replace(urlParts.search, '').replace(urlParts.hash, '');

            $rootScope.savedUrl = url +
                '?fq=' + $rootScope.dataTypeCtrl.selectedDatasetTypes.join(',') +
                '&q=' + $rootScope.query +
                '&fl=' + $rootScope.dspFieldCtrl.fields.join(',') +
                '&rows=' + $rootScope.maxResults;
        };

        $rootScope.sendQuery = function() {
            var url = configuration.solrCore + '/select',
                params = $.extend(queryDefaults, {
                    fq: 'site_id:' + configuration.siteID + ' AND state:active AND dataset_type:(' + $rootScope.dataTypeCtrl.selectedDatasetTypes.join(' OR ') + ')',
                    q: createQuery($rootScope.query),
                    fl: $rootScope.dspFieldCtrl.fields.join(','),
                    rows: parseInt($rootScope.maxResults, 10)
                }),
                httpMethod = $http.get;

            if (configuration.solrCore.indexOf(configuration.ckanInstance) === -1) {
                httpMethod = $http.jsonp;
                params['json.wrf'] = 'JSON_CALLBACK';
            }

            httpMethod(url, {params: params})
                .then(function(data) {
                    $rootScope.queryError = false;
                    $rootScope.queryResultsCount = data.data.response.numFound;
                    $rootScope.queryResults = data.data.response;
                    $rootScope.downloadLink = data.config.url + '?' + $.param($.extend({}, data.config.params, {wt: 'csv', 'csv.mv.separator': '·', rows: 999999999}));

                    var fields = data.data.responseHeader.params.fl.split(','),
                        datatable = $.extend(datatableDefaults, {
                            data: sanitizeData($rootScope.queryResults.docs, fields),
                            columns: createFieldsMapping(fields),
                            fnRowCallback: function(row, data) {
                                var name = data.name,
                                    $firstCell = $(row.firstChild);

                                if ($firstCell.find('a').length === 0) {
                                    $firstCell.append(
                                        '' +
                                            'View ' + name + '' +
                                        '' +
                                            'Edit ' + name + ''
                                    );
                                }
                            }
                        });

                    $resultsTable.DataTable().destroy();
                    $resultsTable.empty();

                    $resultsTable.dataTable(datatable);
                }, function(response) {
                    delete $rootScope.queryResults;
                    $rootScope.queryError = true;

                    if (response && response.data && response.data.error && response.data.error.msg) {
                        $rootScope.queryErrorMessage = response.data.error.msg;
                    }
                });
        };
    }]);

})(window, angular, wb, jQuery);
<commit_msg>Fixed the columns definition not being changeable after the first search<commit_after>
(function(window, angular, wb, $) {'use strict';
    var app = angular.module('reportGenerator', ['dataset-types', 'advanced-search', 'display-fields', 'services.config']),
        $resultsTable = $('#results'),
        maxFieldItems = 100,
        queryDefaults = {
            wt: 'json'
        },
        datatableDefaults = {
            columnDefs: [
                {
                    className: 'nowrap right',
                    targets: [0]
                }
            ],
            pageLength: 100,
            lengthMenu: [[50, 100, 200, 500, -1], [50, 100, 200, 500, 'All']]
        };

    app.run(['$http', '$rootScope', 'configuration', function($http, $rootScope, configuration) {

        function createQuery(keywords) {
            var regexp = /(.*?)((?: (?:OR|AND) )|$)/g;

            if (keywords.length === 0) {
                return '*';
            }

            keywords = keywords.replace(regexp, function(match, key, sep) {
                if (key.length !== 0 && !key.match(/:[\(\[].*?[\)\]]/)) {
                    key = 'text:(*' + key + '*)';
                }
                return key + sep;
            });
            return keywords;
        }

        function sanitizeData(rows, fields) {
            var row, r, field, f, cell;

            for (r = 0; r < rows.length; r += 1) {
                row = rows[r];

                for (f = 0; f < fields.length; f += 1) {
                    field = fields[f];
                    cell = row[field];

                    row[field] = cell || '';

                    if (typeof cell === 'object') {
                        row[field] = cell.splice(0, maxFieldItems).join(',');
                    }
                }
            }

            return rows;
        }

        function createFieldsMapping(fields) {
            var fieldsMapping = [],
                f;

            for (f = 0; f < fields.length; f += 1) {
                fieldsMapping.push({
                    data: fields[f],
                    title: fields[f],
                });
            }

            return fieldsMapping;
        }

        function maxResultsFromUrl() {
            var maxResults = wb.pageUrlParts.params.rows;

            if ($rootScope.maxResultsOptions[maxResults]) {
                return maxResults;
            }
        }

        $rootScope.query = wb.pageUrlParts.params.q ? decodeURI(wb.pageUrlParts.params.q) : '';
        $rootScope.maxResultsOptions = {
            20: 20,
            50: 50,
            100: 100,
            1000: '1000 (default)',
            2000: 2000
        };
        $rootScope.maxResults = maxResultsFromUrl() || '1000';

        $rootScope.clearKeywords = function() {
            $rootScope.query = '';
        };

        $rootScope.saveUrl = function() {
            var urlParts = wb.pageUrlParts,
                url = urlParts.absolute.replace(urlParts.search, '').replace(urlParts.hash, '');

            $rootScope.savedUrl = url +
                '?fq=' + $rootScope.dataTypeCtrl.selectedDatasetTypes.join(',') +
                '&q=' + $rootScope.query +
                '&fl=' + $rootScope.dspFieldCtrl.fields.join(',') +
                '&rows=' + $rootScope.maxResults;
        };

        $rootScope.sendQuery = function() {
            var url = configuration.solrCore + '/select',
                params = $.extend(queryDefaults, {
                    fq: 'site_id:' + configuration.siteID + ' AND state:active AND dataset_type:(' + $rootScope.dataTypeCtrl.selectedDatasetTypes.join(' OR ') + ')',
                    q: createQuery($rootScope.query),
                    fl: $rootScope.dspFieldCtrl.fields.join(','),
                    rows: parseInt($rootScope.maxResults, 10)
                }),
                httpMethod = $http.get;

            if (configuration.solrCore.indexOf(configuration.ckanInstance) === -1) {
                httpMethod = $http.jsonp;
                params['json.wrf'] = 'JSON_CALLBACK';
            }

            httpMethod(url, {params: params})
                .then(function(data) {
                    $rootScope.queryError = false;
                    $rootScope.queryResultsCount = data.data.response.numFound;
                    $rootScope.queryResults = data.data.response;
                    $rootScope.downloadLink = data.config.url + '?' + $.param($.extend({}, data.config.params, {wt: 'csv', 'csv.mv.separator': '·', rows: 999999999}));

                    var fields = data.data.responseHeader.params.fl.split(','),
                        datatable = $.extend({}, datatableDefaults, {
                            data: sanitizeData($rootScope.queryResults.docs, fields),
                            columns: createFieldsMapping(fields),
                            fnRowCallback: function(row, data) {
                                var name = data.name,
                                    $firstCell = $(row.firstChild);

                                if ($firstCell.find('a').length === 0) {
                                    $firstCell.append(
                                        '' +
                                            'View ' + name + '' +
                                        '' +
                                            'Edit ' + name + ''
                                    );
                                }
                            }
                        });

                    $resultsTable.DataTable().destroy();
                    $resultsTable.empty();

                    $resultsTable.dataTable(datatable);
                }, function(response) {
                    delete $rootScope.queryResults;
                    $rootScope.queryError = true;

                    if (response && response.data && response.data.error && response.data.error.msg) {
                        $rootScope.queryErrorMessage = response.data.error.msg;
                    }
                });
        };
    }]);

})(window, angular, wb, jQuery);
<|endoftext|>


<commit_before>'use strict';
// function newElement(elType, elAttribute, elAttributeName, elText, elParentId){
  // var element = document.createElement(elType);
  // element.setAttribute(elAttribute, elAttributeName);
  // element.textContent(elText);
  // var parentEl = getElementById(elParentId);
  // parentEl.appendChild(element);
// }
//var hourlyCookies = [];

function randomCust(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

var pike = {
  name: '1st and Pike',
  minCust: 23,
  maxCust: 65,
  avgCookies: 6.3,
  cookPerHrArray: [],
  CookPerHr: function(){
    for (var i = 0; i < 15; i++){
      var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
      //console.log(cookies);
      this.cookPerHrArray.push(cookies);
    }
  }
};

var seaTac = {
  name: 'SeaTac Airport',
  minCust: 3,
  maxCust: 24,
  avgCookies: 1.2,
  cookPerHrArray: [],
  CookPerHr: function(){
    for (var i = 0; i < 15; i++){
      var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
      //console.log(cookies);
      this.cookPerHrArray.push(cookies);
    }
  }
};

var seaCenter = {
  name: 'Seattle Center',
  minCust: 11,
  maxCust: 38,
  avgCookies: 3.7,
  cookPerHrArray: [],
  CookPerHr: function(){
    for (var i = 0; i < 15; i++){
      var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
      //console.log(cookies);
      this.cookPerHrArray.push(cookies);
    }
  }
};

var capHill = {
  name: 'Capitol Hill',
  minCust: 20,
  maxCust: 38,
  avgCookies: 2.3,
  cookPerHrArray: [],
  CookPerHr: function(){
    for (var i = 0; i < 15; i++){
      var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
      //console.log(cookies);
      this.cookPerHrArray.push(cookies);
    }
  }
};

var alki = {
  name: 'Alki',
  minCust: 2,
  maxCust: 16,
  avgCookies: 4.6,
  cookPerHrArray: [],
  CookPerHr: function(){
    for (var i = 0; i < 15; i++){
      var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
      //console.log(cookies);
      this.cookPerHrArray.push(cookies);
    }
  }
};

// console.log('Pike');
// pike.CookPerHr();

//console.log(pike.cookPerHrArray);
// console.log(pike);

function hrlist(store){
  var total = 0;
  var hrSalesList = [];
  var locEl = document.createElement('ul');
  for (var i = 6; i < 21; i++){
    if (i < 13){
      hrSalesList.push(i + 'am: ' + store.cookPerHrArray[i - 6] + ' cookies');
      //console.log(i + 'am: ' + store.cookPerHrArray[i - 6] + ' cookies');
    } else {
      var time = i - 12;
      hrSalesList.push(time + 'am: ' + store.cookPerHrArray[i - 6] + ' cookies');
      //console.log(time + 'pm: ' + store.cookPerHrArray[i - 6] + ' cookies');
    }
    total += store.cookPerHrArray[i - 6];
    //var
  }
  //var locEl = document.createElement('li');
  locEl.setAttribute('class', '');
  console.log(hrSalesList);
  console.log('Total: ' + total + ' cookies');
  return hrSalesList;
};
hrlist(pike);
var stores = [pike, seaTac, seaCenter, capHill, alki];
var storeStrings = ['pike', 'seaTac', 'seaCenter', 'capHill', 'alki'];
for (var i = 0; i < stores.length; i++){
  var loc = stores[i];
  loc.CookPerHr();
  var locEl = document.createElement('div');
  locEl.setAttribute('id', storeStrings[i]);
  var holderEl = document.getElementById('store-stats');
  holderEl.appendChild(locEl);

  var storeEl = document.createElement('h1');
  storeEl.setAttribute('id', storeStrings[i] + 'H1');
  storeEl.textContent = loc.name;
  var divEl = document.getElementById(storeStrings[i]);
  divEl.appendChild(storeEl);
  console.log(loc.name);
  newListEl(storeStrings[i], hrlist(loc));
  hrlist(loc);
}

function newListEl(store, list){
  var locUnorderedEl = document.createElement('ul');
  locUnorderedEl.setAttribute('id', store + 'Ul');
  var divEl = document.getElementById(store);
  divEl.appendChild(locUnorderedEl);
  for (var i = 0; i < list.length; i++){
    var locListEl = document.createElement('li');
    locListEl.setAttribute('class', store + 'Li');
    locListEl.textContent = list[i];
    var UnorderedEl = document.getElementById(store + 'Ul');
    UnorderedEl.appendChild(locListEl);
  }
};
//display(pike);
//display(alki);
//----------------Demo area------------------------V

// function CookieStore(name, minCust, maxCust, avg){
//   this.name = name,
//   this.minCust = minCust,
//   this.maxCust = maxCust,
//   this.avgCookies = avgCookies,
//   this.cookPerHrArray = [];
// }
//
// CookieStore.prototype.cookPerHr = function(){
//   for (var i = 0; i < 15; i++){
//     var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
//     //console.log(cookies);
//     this.cookPerHrArray.push(cookies);
//   }
// };
//
// var pike = new CookieStore('1st and Pike', 23, 65, 6.3);
<commit_msg>more demo<commit_after>'use strict';
// function newElement(elType, elAttribute, elAttributeName, elText, elParentId){
  // var element = document.createElement(elType);
  // element.setAttribute(elAttribute, elAttributeName);
  // element.textContent(elText);
  // var parentEl = getElementById(elParentId);
  // parentEl.appendChild(element);
// }
//var hourlyCookies = [];

var stores = [pike, seaTac, seaCenter, capHill, alki];
var storeStrings = ['pike', 'seaTac', 'seaCenter', 'capHill', 'alki'];

function randomCust(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

var pike = {
  name: '1st and Pike',
  minCust: 23,
  maxCust: 65,
  avgCookies: 6.3,
  cookPerHrArray: [],
  CookPerHr: function(){
    for (var i = 0; i < 15; i++){
      var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
      //console.log(cookies);
      this.cookPerHrArray.push(cookies);
    }
  }
};

var seaTac = {
  name: 'SeaTac Airport',
  minCust: 3,
  maxCust: 24,
  avgCookies: 1.2,
  cookPerHrArray: [],
  CookPerHr: function(){
    for (var i = 0; i < 15; i++){
      var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
      //console.log(cookies);
      this.cookPerHrArray.push(cookies);
    }
  }
};

var seaCenter = {
  name: 'Seattle Center',
  minCust: 11,
  maxCust: 38,
  avgCookies: 3.7,
  cookPerHrArray: [],
  CookPerHr: function(){
    for (var i = 0; i < 15; i++){
      var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
      //console.log(cookies);
      this.cookPerHrArray.push(cookies);
    }
  }
};

var capHill = {
  name: 'Capitol Hill',
  minCust: 20,
  maxCust: 38,
  avgCookies: 2.3,
  cookPerHrArray: [],
  CookPerHr: function(){
    for (var i = 0; i < 15; i++){
      var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
      //console.log(cookies);
      this.cookPerHrArray.push(cookies);
    }
  }
};

var alki = {
  name: 'Alki',
  minCust: 2,
  maxCust: 16,
  avgCookies: 4.6,
  cookPerHrArray: [],
  CookPerHr: function(){
    for (var i = 0; i < 15; i++){
      var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
      //console.log(cookies);
      this.cookPerHrArray.push(cookies);
    }
  }
};

// console.log('Pike');
// pike.CookPerHr();

//console.log(pike.cookPerHrArray);
// console.log(pike);

function hrlist(store){
  var total = 0;
  var hrSalesList = [];
  var locEl = document.createElement('ul');
  for (var i = 6; i < 21; i++){
    if (i < 13){
      hrSalesList.push(i + 'am: ' + store.cookPerHrArray[i - 6] + ' cookies');
      //console.log(i + 'am: ' + store.cookPerHrArray[i - 6] + ' cookies');
    } else {
      var time = i - 12;
      hrSalesList.push(time + 'am: ' + store.cookPerHrArray[i - 6] + ' cookies');
      //console.log(time + 'pm: ' + store.cookPerHrArray[i - 6] + ' cookies');
    }
    total += store.cookPerHrArray[i - 6];
    //var
  }
  //var locEl = document.createElement('li');
  locEl.setAttribute('class', '');
  console.log(hrSalesList);
  console.log('Total: ' + total + ' cookies');
  return hrSalesList;
};
hrlist(pike);

for (var i = 0; i < stores.length; i++){
  var loc = stores[i];
  loc.CookPerHr();
  var locEl = document.createElement('div');
  locEl.setAttribute('id', storeStrings[i]);
  var holderEl = document.getElementById('store-stats');
  holderEl.appendChild(locEl);

  var storeEl = document.createElement('h1');
  storeEl.setAttribute('id', storeStrings[i] + 'H1');
  storeEl.textContent = loc.name;
  var divEl = document.getElementById(storeStrings[i]);
  divEl.appendChild(storeEl);
  console.log(loc.name);
  newListEl(storeStrings[i], hrlist(loc));
  hrlist(loc);
}

function newListEl(store, list){
  var locUnorderedEl = document.createElement('ul');
  locUnorderedEl.setAttribute('id', store + 'Ul');
  var divEl = document.getElementById(store);
  divEl.appendChild(locUnorderedEl);
  for (var i = 0; i < list.length; i++){
    var locListEl = document.createElement('li');
    locListEl.setAttribute('class', store + 'Li');
    locListEl.textContent = list[i];
    var UnorderedEl = document.getElementById(store + 'Ul');
    UnorderedEl.appendChild(locListEl);
  }
};
//display(pike);
//display(alki);
//----------------Demo area------------------------V

// function CookieStore(name, minCust, maxCust, avg){
//   this.name = name,
//   this.minCust = minCust,
//   this.maxCust = maxCust,
//   this.avgCookies = avgCookies,
//   this.cookPerHrArray = [];
// }
//
// CookieStore.prototype.cookPerHr = function(){
//   for (var i = 0; i < 15; i++){
//     var cookies = Math.ceil(this.avgCookies * randomCust(this.minCust, this.maxCust));
//     //console.log(cookies);
//     this.cookPerHrArray.push(cookies);
//   }
// };
//
// var pike = new CookieStore('1st and Pike', 23, 65, 6.3);

// var tableEl = document.createElement('table');
//
// for(var i = 0; i < stores.length; i++){
//   var currentStore = stores[i];
//
//   var rowEl = document.createElement('tr');
//
//   var nameEl = document.createElement('th');
//   nameEl.textContent = currentStore.name;
//   rowEl.appendChild(nameEl);
//
//   var minCustEl = document.createElement('td');
//   minCustEl.textContent = currentStore.nimCust;
//   rowEl.appendChild(minCustEl);
//
//   var maxCustEl = document.createElement('td');
//   maxCustEl.textContent = currentStore.maxCust;;
//   rowEl.appendChild(maxCustEl);
//
//   var avgCookiesEL = document,createElement('td');
//   avgCookiesEL.textContent = currentStore.avgCookies
//   rowEl.appendChild(avgCookiesEL);
//
//   tableEl.appendChild(rowEl);
// }

//document.body.appendChild(tableEl);
<|endoftext|>


<commit_before>//dependencies
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
import ComponentBaseBehaviour from '../../../behaviours/component-base';
import {isUndefined, isNull, isNumber} from 'lodash/lang';
import {union} from 'lodash/array';
const UNSELECTED_KEY = 'UNSELECTED_KEY';
/**
 * Parse the value.
 * @param  {string | number} propsValue - The value given as props to read the type.
 * @param  {string} rawValue   - The raw string value.
 * @return {strint | number}  - The parsed value.
 */
function _valueParser(propsValue, rawValue) {
    return isNumber(propsValue) ? +rawValue : rawValue;
}
const propTypes = {
    disabled: PropTypes.bool,
    error: PropTypes.string,
    hasUndefined: PropTypes.bool,
    isRequired: PropTypes.bool,
    labelKey: PropTypes.string,
    mubtiple: PropTypes.bool,
    name: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    placeHolder: PropTypes.string,
    value: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number
    ]),
    valueKey: PropTypes.string,
    values: PropTypes.array.isRequired
};

const defaultProps = {
    disabled: false,
    hasUndefined: true,
    isRequired: false,
    labelKey: 'label',
    multiple: false,
    values: [],
    valueKey: 'code',
    valueParser: _valueParser
};

/**
 * Component standing for an HTML input.
 */
@ComponentBaseBehaviour
class Select extends Component {

    /**
     * Get the dom value of the component.
     * @return {object} - The unformated dom value.
     */
    getValue = () => {
        const {value} = this.props;
        return isUndefined(value) || UNSELECTED_KEY === value ? null : value;
    }
    /**
     * Handle the change on the select, it only propagates the value.
     * @param  {object} evt - The react DOM event.
     * @return {object} - The function onChange from the props, called.
     */
    _handleSelectChange = (evt) =>{
        const {onChange, valueParser, value: propsValue} = this.props;
        const {value} = evt.target;
        return onChange(valueParser(propsValue, value));
    }
    /** inheritdoc */
    _renderOptions({hasUndefined, labelKey, isRequired, value, values = [], valueKey}){
        const isRequiredAndNoValue = isRequired && (isUndefined(value) || isNull(value));
        if(hasUndefined || isRequiredAndNoValue){
            values = union(
                [{[labelKey]: this.i18n('select.unSelected'), [valueKey]: UNSELECTED_KEY}],
                values
            );
        }
        return values.map((val, idx) => {
            const optVal = `${val[valueKey]}`;
            const elementValue = val[labelKey];
            const optLabel = isUndefined(elementValue) || isNull(elementValue) ? this.i18n('select.noLabel') : elementValue;
            return <option key={idx} value={optVal}>{optLabel}</option>;
        });
    }
    /**
     * @inheritdoc
     * @override
    */
    render() {
        const {error, name, placeholder, style, value, values, disabled, onChange, ...otherProps} = this.props;
        //const pattern = error ? 'hasError' : null; //add pattern to overide mdl error style when displaying an focus error.
        const selectOtherProps = disabled ? {disabled: 'disabled', ...otherProps} : otherProps;
        return (

                <select name={name} onChange={this._handleSelectChange} ref='htmlSelect' value={value} {...selectOtherProps}>
                    {this._renderOptions(this.props)}
                </select>
                {error &&
{error}
}

        );
    }
}

//Static props.
Select.displayName = 'Select';
Select.defaultProps = defaultProps;
Select.propTypes = propTypes;

export default Select;
<commit_msg>[select] Return undefined is unselected<commit_after>//dependencies
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
import ComponentBaseBehaviour from '../../../behaviours/component-base';
import {isUndefined, isNull, isNumber} from 'lodash/lang';
import {union} from 'lodash/array';
const UNSELECTED_KEY = 'UNSELECTED_KEY';
/**
* Parse the value.
* @param  {string | number} propsValue - The value given as props to read the type.
* @param  {string} rawValue   - The raw string value.
* @return {strint | number}  - The parsed value.
*/
function _valueParser(propsValue, rawValue) {
    if(UNSELECTED_KEY === rawValue) {
        return undefined;
    }
    return isNumber(propsValue) ? +rawValue : rawValue;
}
const propTypes = {
    disabled: PropTypes.bool,
    error: PropTypes.string,
    hasUndefined: PropTypes.bool,
    isRequired: PropTypes.bool,
    labelKey: PropTypes.string,
    mubtiple: PropTypes.bool,
    name: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    placeHolder: PropTypes.string,
    value: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number
    ]),
    valueKey: PropTypes.string,
    values: PropTypes.array.isRequired
};

const defaultProps = {
    disabled: false,
    hasUndefined: true,
    isRequired: false,
    labelKey: 'label',
    multiple: false,
    values: [],
    valueKey: 'code',
    valueParser: _valueParser
};

/**
* Component standing for an HTML input.
*/
@ComponentBaseBehaviour
class Select extends Component {

    /**
    * Get the dom value of the component.
    * @return {object} - The unformated dom value.
    */
    getValue = () => {
        const {value} = this.props;
        return isUndefined(value) || UNSELECTED_KEY === value ? null : value;
    }
    /**
    * Handle the change on the select, it only propagates the value.
    * @param  {object} evt - The react DOM event.
    * @return {object} - The function onChange from the props, called.
    */
    _handleSelectChange = (evt) =>{
        const {onChange, valueParser, value: propsValue} = this.props;
        const {value} = evt.target;
        return onChange(valueParser(propsValue, value));
    }
    /** inheritdoc */
    _renderOptions({hasUndefined, labelKey, isRequired, value, values = [], valueKey}){
        const isRequiredAndNoValue = isRequired && (isUndefined(value) || isNull(value));
        if(hasUndefined || isRequiredAndNoValue){
            values = union(
                [{[labelKey]: this.i18n('select.unSelected'), [valueKey]: UNSELECTED_KEY}],
                values
            );
        }
        return values.map((val, idx) => {
            const optVal = `${val[valueKey]}`;
            const elementValue = val[labelKey];
            const optLabel = isUndefined(elementValue) || isNull(elementValue) ? this.i18n('select.noLabel') : elementValue;
            return <option key={idx} value={optVal}>{optLabel}</option>;
            });
        }
        /**
        * @inheritdoc
        * @override
        */
        render() {
            const {error, name, placeholder, style, value, values, disabled, onChange, ...otherProps} = this.props;
            //const pattern = error ? 'hasError' : null; //add pattern to overide mdl error style when displaying an focus error.
            const selectOtherProps = disabled ? {disabled: 'disabled', ...otherProps} : otherProps;
            return (

                    <select name={name} onChange={this._handleSelectChange} ref='htmlSelect' value={value} {...selectOtherProps}>
                        {this._renderOptions(this.props)}
                    </select>
                    {error &&
{error}
}

            );
        }
    }

    //Static props.
    Select.displayName = 'Select';
    Select.defaultProps = defaultProps;
    Select.propTypes = propTypes;

    export default Select;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import cx from 'classnames'

import '../../css/browser/browser-tab-webentity-name-field'

class BrowserTabWebentityNameField extends React.Component {

  onKeyPress (e) {
    if (e.charCode === 13) {
      e.stopPropagation()
      this.props.onChange(e.target.value);
    }
  }

  render () {
    return <input className={ cx('browser-tab-webentity-name over-overlay', { loading: !this.props.initialValue }) }
      disabled={ this.props.disabled } // PAGE_HYPHE_HOME
      defaultValue={ this.props.initialValue }
      readOnly={ !this.props.editable || !this.props.initialValue }
      onKeyPress={ e => this.onKeyPress(e) } />
  }
}

BrowserTabWebentityNameField.propTypes = {
  initialValue: PropTypes.string,
  disabled: PropTypes.bool.isRequired,
  editable: PropTypes.bool.isRequired,
  onChange: PropTypes.func.isRequired
}

BrowserTabWebentityNameField.defaultProps = {
  initialValue: ''
}

export default BrowserTabWebentityNameField
<commit_msg>fix(name): update input's value on prop received<commit_after>import React, { PropTypes } from 'react'
import { findDOMNode } from 'react-dom'
import cx from 'classnames'

import '../../css/browser/browser-tab-webentity-name-field'

class BrowserTabWebentityNameField extends React.Component {

  onKeyPress (e) {
    if (e.charCode === 13) {
      e.stopPropagation()
      this.props.onChange(e.target.value);
    }
  }

  // React told me:
  // "Well dude, you chose to make an uncontrolled input, now YOU control it yourself"
  // Had to agree
  componentWillReceiveProps ({ initialValue }) {
    findDOMNode(this).value = initialValue
  }

  render () {
    return <input className={ cx('browser-tab-webentity-name over-overlay', { loading: !this.props.initialValue }) }
      disabled={ this.props.disabled } // PAGE_HYPHE_HOME
      defaultValue={ this.props.initialValue }
      readOnly={ !this.props.editable || !this.props.initialValue }
      onKeyPress={ e => this.onKeyPress(e) } />
  }
}

BrowserTabWebentityNameField.propTypes = {
  initialValue: PropTypes.string,
  disabled: PropTypes.bool.isRequired,
  editable: PropTypes.bool.isRequired,
  onChange: PropTypes.func.isRequired
}

BrowserTabWebentityNameField.defaultProps = {
  initialValue: ''
}

export default BrowserTabWebentityNameField
<|endoftext|>


<commit_before>var JSHint = require('jshint').JSHINT;
var CSSLint = require('csslint').CSSLint;
var cssparse = require('css');
var acorn = require('acorn');
var domify = require('domify');
var JscsStringChecker = require('jscs/lib/string-checker.js');
var _ = require('lodash');

var ResponseTypes = {
	LINT : 'lint',
	STYLE : 'style',
	ERROR : 'error',
	FAILURE : 'failure',
	SUCCESS : 'success'
};

var extend = function(a, b){
	var surrogate = function(){};
	surrogate.prototype = a.prototype;
	b.prototype = new surrogate();
};

var Response = function(type, message, errors){
	this.type = type;
	this.message = message || '';
	this.errors = errors;
};

var RinzaiError = function(message, line, char){
	this.message = message;
	this.line = line;
	this.char = char;
};

var Question = function(config, options){
	this.options = options;
	this.test = config.test;
	this.envUrl = config.envUrl;
	this.messages = config.messages || {};
	this.type = config.type;
};

Question.prototype.createEnvironment = function(cb){
	var self = this;
	this.envFrame = document.createElement('iframe');
	this.envFrame.style.position = 'absolute';
	this.envFrame.style.top = '-1000px';
	this.envFrame.style.left = '-1000px';
	document.body.appendChild(this.envFrame);
	var env = this.envFrame.contentWindow;
	if(this.envUrl){
		this.envFrame.src = this.envUrl;
		var onLoad = function(){
			self.envFrame.removeEventListener('load', onLoad);
			cb(env);
		};
		this.envFrame.addEventListener('load', onLoad);
	} else {
		cb(env);
	}
};

Question.prototype.destroyEnvironment = function(){
	if(this.envFrame){
		this.envFrame.parentNode.removeChild(this.envFrame);
	 	delete this.envFrame;
	}
};

Question.prototype.runTest = function(content, parsed, cb){
	var self = this;
	var env = this.createEnvironment(function(env){
		try {
			self.test(content, parsed, env);
		} catch(e) {
			self.destroyEnvironment();
			return cb(e);
		}
		self.destroyEnvironment();
		return cb();
	});
};

var HTMLQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, HTMLQuestion);

HTMLQuestion.prototype.answer = function(content, cb){
	var self = this;
	var nodes;
	try {
		nodes = domify(content);
	} catch(e) {
		return cb(new Response(
			ResponseTypes.ERROR,
			this.messages[ResponseTypes.ERROR],
			[
				new RinzaiError('HTML Parse Error', null, null)
			]
		));
	}

	this.runTest(content, nodes, function(testErr){
		if(testErr) {
			return cb(new Response(
				ResponseTypes.FAILURE,
				self.messages[ResponseTypes.FAILURE],
				[
					new RinzaiError(testErr.message, null, null)
				]
			));
		}

		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var JSQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, JSQuestion);

JSQuestion.prototype.answer = function(content, cb){
	var self = this;

	JSHint(content, this.options.jshint);
	if(JSHint.errors.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(JSHint.errors, function(err){
				return new RinzaiError(err.reason, err.line);
			})
		));
	}

	var checker = new JscsStringChecker();
	checker.registerDefaultRules();
	checker.configure(this.options.jscs || {});
	var styleErrors = checker.checkString(content);
	if(styleErrors.getErrorList().length){
		return cb(new Response(
			ResponseTypes.STYLE,
			this.messages[ResponseTypes.STYLE],
			_.map(styleErrors.getErrorList(), function(err){
				return new RinzaiError(err.message, err.line, err.column);
			})
		));
	}

	var ast = acorn.parse(content);
	this.runTest(content, ast, function(testErr){
		if(testErr){
			var firstStack = testErr.stack.split('\n')[1];
			if(firstStack && firstStack.indexOf('eval') > -1){
				var position = firstStack.match(/(\d+)\:(\d+)\)$/);
				return cb(new Response(
					ResponseTypes.ERROR,
					self.messages[ResponseTypes.ERROR],
					[
						new RinzaiError(testErr.message, parseInt(position[1], 10), parseInt(position[2], 10))
					]
				));
			} else {
				return cb(new Response(
					ResponseTypes.FAILURE,
					self.messages[ResponseTypes.FAILURE],
					[
						new RinzaiError(testErr.message, null, null)
					]
				));
			}
		}
		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var CSSQuestion = function(config){
	this.test = config.test;
};

extend(Question, CSSQuestion);

CSSQuestion.prototype.answer = function(content){
	var results = CSSLint.verify(content);
	if(results.messages.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(results.messages, function(err){
				return new RinzaiError(err.message, err.line, err.col);
			})
		));
	}
	return cb(new Response(
		ResponseTypes.SUCCESS,
		self.messages[ResponseTypes.SUCCESS]
	));
};

var Rinzai = function(config, options){
	this.options = options || {};
	this.questions = [];
	this.questionsById = {};
	_.forEach(config.questions, this.addQuestion, this);
};

Rinzai.prototype.addQuestion = function(q){
	var question;
	switch(q.type){
		case 'html':
			question = new HTMLQuestion(q, this.options);
			break;
		case 'javascript':
			question = new JSQuestion(q, this.options);
			break;
		case 'css':
			question = new CSSQuestion(q, this.options);
			break;
		default:
			throw new Error('Question type is unknown or undefined');
	}
	this.questions.push(question);
	this.questionsById[q.id] = question;
	return question;
};

module.exports = Rinzai;
<commit_msg>Added callback to css question<commit_after>var JSHint = require('jshint').JSHINT;
var CSSLint = require('csslint').CSSLint;
var cssparse = require('css');
var acorn = require('acorn');
var domify = require('domify');
var JscsStringChecker = require('jscs/lib/string-checker.js');
var _ = require('lodash');

var ResponseTypes = {
	LINT : 'lint',
	STYLE : 'style',
	ERROR : 'error',
	FAILURE : 'failure',
	SUCCESS : 'success'
};

var extend = function(a, b){
	var surrogate = function(){};
	surrogate.prototype = a.prototype;
	b.prototype = new surrogate();
};

var Response = function(type, message, errors){
	this.type = type;
	this.message = message || '';
	this.errors = errors;
};

var RinzaiError = function(message, line, char){
	this.message = message;
	this.line = line;
	this.char = char;
};

var Question = function(config, options){
	this.options = options;
	this.test = config.test;
	this.envUrl = config.envUrl;
	this.messages = config.messages || {};
	this.type = config.type;
};

Question.prototype.createEnvironment = function(cb){
	var self = this;
	this.envFrame = document.createElement('iframe');
	this.envFrame.style.position = 'absolute';
	this.envFrame.style.top = '-1000px';
	this.envFrame.style.left = '-1000px';
	document.body.appendChild(this.envFrame);
	var env = this.envFrame.contentWindow;
	if(this.envUrl){
		this.envFrame.src = this.envUrl;
		var onLoad = function(){
			self.envFrame.removeEventListener('load', onLoad);
			cb(env);
		};
		this.envFrame.addEventListener('load', onLoad);
	} else {
		cb(env);
	}
};

Question.prototype.destroyEnvironment = function(){
	if(this.envFrame){
		this.envFrame.parentNode.removeChild(this.envFrame);
	 	delete this.envFrame;
	}
};

Question.prototype.runTest = function(content, parsed, cb){
	var self = this;
	var env = this.createEnvironment(function(env){
		try {
			self.test(content, parsed, env);
		} catch(e) {
			self.destroyEnvironment();
			return cb(e);
		}
		self.destroyEnvironment();
		return cb();
	});
};

var HTMLQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, HTMLQuestion);

HTMLQuestion.prototype.answer = function(content, cb){
	var self = this;
	var nodes;
	try {
		nodes = domify(content);
	} catch(e) {
		return cb(new Response(
			ResponseTypes.ERROR,
			this.messages[ResponseTypes.ERROR],
			[
				new RinzaiError('HTML Parse Error', null, null)
			]
		));
	}

	this.runTest(content, nodes, function(testErr){
		if(testErr) {
			return cb(new Response(
				ResponseTypes.FAILURE,
				self.messages[ResponseTypes.FAILURE],
				[
					new RinzaiError(testErr.message, null, null)
				]
			));
		}

		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var JSQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, JSQuestion);

JSQuestion.prototype.answer = function(content, cb){
	var self = this;

	JSHint(content, this.options.jshint);
	if(JSHint.errors.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(JSHint.errors, function(err){
				return new RinzaiError(err.reason, err.line);
			})
		));
	}

	var checker = new JscsStringChecker();
	checker.registerDefaultRules();
	checker.configure(this.options.jscs || {});
	var styleErrors = checker.checkString(content);
	if(styleErrors.getErrorList().length){
		return cb(new Response(
			ResponseTypes.STYLE,
			this.messages[ResponseTypes.STYLE],
			_.map(styleErrors.getErrorList(), function(err){
				return new RinzaiError(err.message, err.line, err.column);
			})
		));
	}

	var ast = acorn.parse(content);
	this.runTest(content, ast, function(testErr){
		if(testErr){
			var firstStack = testErr.stack.split('\n')[1];
			if(firstStack && firstStack.indexOf('eval') > -1){
				var position = firstStack.match(/(\d+)\:(\d+)\)$/);
				return cb(new Response(
					ResponseTypes.ERROR,
					self.messages[ResponseTypes.ERROR],
					[
						new RinzaiError(testErr.message, parseInt(position[1], 10), parseInt(position[2], 10))
					]
				));
			} else {
				return cb(new Response(
					ResponseTypes.FAILURE,
					self.messages[ResponseTypes.FAILURE],
					[
						new RinzaiError(testErr.message, null, null)
					]
				));
			}
		}
		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var CSSQuestion = function(config){
	this.test = config.test;
};

extend(Question, CSSQuestion);

CSSQuestion.prototype.answer = function(content, cb){
	var results = CSSLint.verify(content);
	if(results.messages.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(results.messages, function(err){
				return new RinzaiError(err.message, err.line, err.col);
			})
		));
	}
	return cb(new Response(
		ResponseTypes.SUCCESS,
		self.messages[ResponseTypes.SUCCESS]
	));
};

var Rinzai = function(config, options){
	this.options = options || {};
	this.questions = [];
	this.questionsById = {};
	_.forEach(config.questions, this.addQuestion, this);
};

Rinzai.prototype.addQuestion = function(q){
	var question;
	switch(q.type){
		case 'html':
			question = new HTMLQuestion(q, this.options);
			break;
		case 'javascript':
			question = new JSQuestion(q, this.options);
			break;
		case 'css':
			question = new CSSQuestion(q, this.options);
			break;
		default:
			throw new Error('Question type is unknown or undefined');
	}
	this.questions.push(question);
	this.questionsById[q.id] = question;
	return question;
};

module.exports = Rinzai;
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import ReactDOM from 'react-dom'
import JSONTree from 'react-json-tree'

import { connect } from 'react-redux';
import { removeMetric, changeMetric } from 'gModules/metrics/actions.js'
import { changeGuesstimate } from 'gModules/guesstimates/actions.js'
import { changeGuesstimateForm } from 'gModules/guesstimate_form/actions.js'

import Histogram from 'gComponents/simulations/histogram'
import MetricModal from '../modal/index.js'
import StatTable from 'gComponents/simulations/stat_table'
import DistributionEditor from 'gComponents/distributions/editor/index.js'
import DistributionSummary from 'gComponents/distributions/summary/index.js'
import MetricToolTip from './tooltip.js'
import MetricName from './name'
import Icon from 'react-fa'
import $ from 'jquery'
import MetricToken from './token/index.js'
import './style.css'
import * as canvasStateProps from 'gModules/canvas_state/prop_type.js'

const INTERMEDIATE = 'INTERMEDIATE'
const OUTPUT = 'OUTPUT'
const INPUT = 'INPUT'
const NOEDGE = 'NOEDGE'

const relationshipClasses = {}
relationshipClasses[INTERMEDIATE] = 'intermediate'
relationshipClasses[OUTPUT] = 'output'
relationshipClasses[INPUT] = 'input'
relationshipClasses[NOEDGE] = 'noedge'

const relationshipType = (edges) => {
  if (edges.inputs.length && edges.outputs.length) { return INTERMEDIATE }
  if (edges.inputs.length) { return OUTPUT }
  if (edges.outputs.length) { return INPUT }
  return NOEDGE
}

const PT = PropTypes
class MetricCard extends Component {
  displayName: 'MetricCard'

  static propTypes = {
    canvasState: canvasStateProps.canvasState,
    dispatch: PT.func.isRequired,
    gridKeyPress: PT.func.isRequired,
    guesstimateForm: PT.object.isRequired,
    handleSelect: PT.func.isRequired,
    isSelected: PT.bool.isRequired,
    location: PT.shape({
      row: PT.number,
      column: PT.number
    }),
    metric: PT.object.isRequired
  }

  state = {modalIsOpen: false};

  componentDidUpdate() {
    const hasContent = _.has(this, 'refs.name') && this.refs.name.hasContent()
    if (!this.props.isSelected && this._isEmpty() && !hasContent){
      this.handleRemoveMetric()
    }
  }

  openModal() {
     this.setState({modalIsOpen: true});
  }

  closeModal() {
     this.setState({modalIsOpen: false});
  }

  _handleClick(event) {
    const selectableEl = (event.target.parentElement.getAttribute('data-select') !== 'false')
    const notYetSelected = !this.props.isSelected
    if (selectableEl && notYetSelected){
      if (this.props.canvasState.metricClickMode === 'FUNCTION_INPUT_SELECT') {
        event.preventDefault()
        $(window).trigger('functionMetricClicked', this.props.metric)
      } else {
        this.props.handleSelect(this.props.location)
      }
    }
  }

  _handlePress(e) {
    if (e.target === ReactDOM.findDOMNode(this)) {
      if (e.keyCode == '13') {
        e.preventDefault()
        this.openModal()
      }
      if (e.keyCode == '8') {
        e.preventDefault()
        this.handleRemoveMetric()
      }
      this.props.gridKeyPress(e)
    }
    e.stopPropagation()
  }

  _isEmpty(){
    return (!this._hasGuesstimate() && !this._hasName())
  }

  _hasName(){
    return !!this.props.metric.name
  }

  _hasGuesstimate(){
    const {metric} = this.props
    const hasInput = !_.isEmpty(_.get(metric, 'guesstimate.input'))
    const hasData = !_.isEmpty(_.get(metric, 'guesstimate.data'))
    return (hasInput || hasData)
  }

  _isTitle(){
    return (this._hasName() && !this._hasGuesstimate())
  }

  handleChangeMetric(values) {
    values.id = this._id()
    this.props.dispatch(changeMetric(values))
  }

  handleChangeGuesstimate(values) {
    let guesstimate = values
    guesstimate.metric = this.props.metric.id
    this.props.dispatch(changeGuesstimate(this._id(), guesstimate))
    this.props.dispatch(changeGuesstimateForm(guesstimate, true))
  }

  handleRemoveMetric () {
    this.props.dispatch(removeMetric(this._id()))
  }

  _id(){
    return this.props.metric.id
  }

  focus() {
    $(this.refs.dom).focus();
  }

  showSimulation() {
    const stats = _.get(this.props, 'metric.simulation.stats')
    if (stats && _.isFinite(stats.mean) && _.isFinite(stats.stdev) && _.isFinite(stats.length)) {
      return (stats.stdev === 0 || (stats.length > 5))
    } else {
      return false
    }
  }

  _shouldShowStatistics() {
    const isScientific = (this.props.canvasState.metricCardView === 'scientific')
    const isAvailable = this.showSimulation() && (_.get(this.props, 'metric.simulation.stats').length > 1)
    return isScientific && isAvailable
  }

  _focusForm() {
    const editorRef = _.get(this.refs, 'DistributionEditor.refs.wrappedInstance')
    editorRef && editorRef.focus()
  }

  render() {
    const {isSelected, metric, guesstimateForm} = this.props
    const {canvasState: {metricCardView, metricClickMode}} = this.props
    const {guesstimate} = metric

    const anotherFunctionSelected = ((metricClickMode === 'FUNCTION_INPUT_SELECT') && !isSelected)

    const showSimulation = this.showSimulation()
    const shouldShowStatistics = this._shouldShowStatistics()
    const shouldShowJsonTree = (metricCardView === 'debugging')
    const hasGuesstimateDescription = !_.isEmpty(guesstimate.description)

    const titleView = !this.props.hovered && !isSelected && this._isTitle()
    const relationshipClass = relationshipClasses[relationshipType(metric.edges)]

    let className = isSelected ? 'metricCard grid-item-focus' : 'metricCard'
    className += ` ${metricCardView}`
    className += titleView ? ' titleView' : ''
    className += ' ' + relationshipClass

    return (

        {this.props.hovered && !isSelected &&
          <MetricToolTip guesstimate={guesstimate}/>
        }

        <MetricModal
            metric={metric}
            guesstimateForm={guesstimateForm}
            isOpen={this.state.modalIsOpen}
            closeModal={this.closeModal.bind(this)}
            onChange={this.handleChangeGuesstimate.bind(this)}
        />

        <div className={`section ${metricCardView}`}>

          {(metricCardView !== 'basic') && showSimulation &&
            <Histogram height={(metricCardView === 'scientific') ? 110 : 30}
                simulation={metric.simulation}
                cutOffRatio={0.995}
            />
          }

                {(!_.isEmpty(metric.name) || isSelected) &&

                    <MetricName
                      isSelected={isSelected}
                      name={metric.name}
                      onChange={this.handleChangeMetric.bind(this)}
                      jumpSection={this._focusForm.bind(this)}
                      ref='name'
                    />

                }

                  {showSimulation &&
                    <DistributionSummary
                        guesstimateForm={guesstimateForm}
                        simulation={metric.simulation}
                    />
                  }

              <MetricToken
                 readableId={metric.readableId}
                 anotherFunctionSelected={anotherFunctionSelected}
                 onOpenModal={this.openModal.bind(this)}
                 hasGuesstimateDescription={hasGuesstimateDescription}
              />

          {shouldShowJsonTree &&

 <JSONTree data={this.props}/>

          }

          {shouldShowStatistics &&

 <StatTable stats={metric.simulation.stats}/>

          }

        {isSelected && !this.state.modalIsOpen &&

            <DistributionEditor
                metricId={metric.id}
                metricFocus={this.focus.bind(this)}
                onOpen={this.openModal.bind(this)}
                ref='DistributionEditor'
                size='small'
            />

        }

    );
  }
}

function select(state) {
  return {
    guesstimateForm: state.guesstimateForm
  }
}

module.exports = connect(select)(MetricCard);
<commit_msg>WIP; switching branches.<commit_after>import React, {Component, PropTypes} from 'react'
import ReactDOM from 'react-dom'
import JSONTree from 'react-json-tree'
import PureRenderMixin from 'react-addons-pure-render-mixin'

import { connect } from 'react-redux';
import { removeMetric, changeMetric } from 'gModules/metrics/actions.js'
import { changeGuesstimate } from 'gModules/guesstimates/actions.js'
import { changeGuesstimateForm } from 'gModules/guesstimate_form/actions.js'

import Histogram from 'gComponents/simulations/histogram'
import MetricModal from '../modal/index.js'
import StatTable from 'gComponents/simulations/stat_table'
import DistributionEditor from 'gComponents/distributions/editor/index.js'
import DistributionSummary from 'gComponents/distributions/summary/index.js'
import MetricToolTip from './tooltip.js'
import MetricName from './name'
import Icon from 'react-fa'
import $ from 'jquery'
import MetricToken from './token/index.js'
import './style.css'
import * as canvasStateProps from 'gModules/canvas_state/prop_type.js'

const INTERMEDIATE = 'INTERMEDIATE'
const OUTPUT = 'OUTPUT'
const INPUT = 'INPUT'
const NOEDGE = 'NOEDGE'

const relationshipClasses = {}
relationshipClasses[INTERMEDIATE] = 'intermediate'
relationshipClasses[OUTPUT] = 'output'
relationshipClasses[INPUT] = 'input'
relationshipClasses[NOEDGE] = 'noedge'

const relationshipType = (edges) => {
  if (edges.inputs.length && edges.outputs.length) { return INTERMEDIATE }
  if (edges.inputs.length) { return OUTPUT }
  if (edges.outputs.length) { return INPUT }
  return NOEDGE
}

const PT = PropTypes
class MetricCard extends Component {
  constructor(props) {
    super(props)
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this)
  }

  displayName: 'MetricCard'

  static propTypes = {
    canvasState: canvasStateProps.canvasState,
    dispatch: PT.func.isRequired,
    gridKeyPress: PT.func.isRequired,
    guesstimateForm: PT.object.isRequired,
    handleSelect: PT.func.isRequired,
    isSelected: PT.bool.isRequired,
    location: PT.shape({
      row: PT.number,
      column: PT.number
    }),
    metric: PT.object.isRequired
  }

  state = {modalIsOpen: false};

  componentDidUpdate() {
    const hasContent = _.has(this, 'refs.name') && this.refs.name.hasContent()
    if (!this.props.isSelected && this._isEmpty() && !hasContent){
      this.handleRemoveMetric()
    }
  }

  openModal() {
     this.setState({modalIsOpen: true});
  }

  closeModal() {
     this.setState({modalIsOpen: false});
  }

  _handleClick(event) {
    const selectableEl = (event.target.parentElement.getAttribute('data-select') !== 'false')
    const notYetSelected = !this.props.isSelected
    if (selectableEl && notYetSelected){
      if (this.props.canvasState.metricClickMode === 'FUNCTION_INPUT_SELECT') {
        event.preventDefault()
        $(window).trigger('functionMetricClicked', this.props.metric)
      } else {
        this.props.handleSelect(this.props.location)
      }
    }
  }

  _handlePress(e) {
    if (e.target === ReactDOM.findDOMNode(this)) {
      if (e.keyCode == '13') {
        e.preventDefault()
        this.openModal()
      }
      if (e.keyCode == '8') {
        e.preventDefault()
        this.handleRemoveMetric()
      }
      this.props.gridKeyPress(e)
    }
    e.stopPropagation()
  }

  _isEmpty(){
    return (!this._hasGuesstimate() && !this._hasName())
  }

  _hasName(){
    return !!this.props.metric.name
  }

  _hasGuesstimate(){
    const {metric} = this.props
    const hasInput = !_.isEmpty(_.get(metric, 'guesstimate.input'))
    const hasData = !_.isEmpty(_.get(metric, 'guesstimate.data'))
    return (hasInput || hasData)
  }

  _isTitle(){
    return (this._hasName() && !this._hasGuesstimate())
  }

  handleChangeMetric(values) {
    values.id = this._id()
    this.props.dispatch(changeMetric(values))
  }

  handleChangeGuesstimate(values) {
    let guesstimate = values
    guesstimate.metric = this.props.metric.id
    this.props.dispatch(changeGuesstimate(this._id(), guesstimate))
    this.props.dispatch(changeGuesstimateForm(guesstimate, true))
  }

  handleRemoveMetric () {
    this.props.dispatch(removeMetric(this._id()))
  }

  _id(){
    return this.props.metric.id
  }

  focus() {
    $(this.refs.dom).focus();
  }

  showSimulation() {
    const stats = _.get(this.props, 'metric.simulation.stats')
    if (stats && _.isFinite(stats.mean) && _.isFinite(stats.stdev) && _.isFinite(stats.length)) {
      return (stats.stdev === 0 || (stats.length > 5))
    } else {
      return false
    }
  }

  _shouldShowStatistics() {
    const isScientific = (this.props.canvasState.metricCardView === 'scientific')
    const isAvailable = this.showSimulation() && (_.get(this.props, 'metric.simulation.stats').length > 1)
    return isScientific && isAvailable
  }

  _focusForm() {
    const editorRef = _.get(this.refs, 'DistributionEditor.refs.wrappedInstance')
    editorRef && editorRef.focus()
  }

  render() {
    const {isSelected, metric, guesstimateForm} = this.props
    const {canvasState: {metricCardView, metricClickMode}} = this.props
    const {guesstimate} = metric

    const anotherFunctionSelected = ((metricClickMode === 'FUNCTION_INPUT_SELECT') && !isSelected)

    const showSimulation = this.showSimulation()
    const shouldShowStatistics = this._shouldShowStatistics()
    const shouldShowJsonTree = (metricCardView === 'debugging')
    const hasGuesstimateDescription = !_.isEmpty(guesstimate.description)

    const titleView = !this.props.hovered && !isSelected && this._isTitle()
    const relationshipClass = relationshipClasses[relationshipType(metric.edges)]

    let className = isSelected ? 'metricCard grid-item-focus' : 'metricCard'
    className += ` ${metricCardView}`
    className += titleView ? ' titleView' : ''
    className += ' ' + relationshipClass

    return (

        {this.props.hovered && !isSelected &&
          <MetricToolTip guesstimate={guesstimate}/>
        }

        <MetricModal
            metric={metric}
            guesstimateForm={guesstimateForm}
            isOpen={this.state.modalIsOpen}
            closeModal={this.closeModal.bind(this)}
            onChange={this.handleChangeGuesstimate.bind(this)}
        />

        <div className={`section ${metricCardView}`}>

          {(metricCardView !== 'basic') && showSimulation &&
            <Histogram height={(metricCardView === 'scientific') ? 110 : 30}
                simulation={metric.simulation}
                cutOffRatio={0.995}
            />
          }

                {(!_.isEmpty(metric.name) || isSelected) &&

                    <MetricName
                      isSelected={isSelected}
                      name={metric.name}
                      onChange={this.handleChangeMetric.bind(this)}
                      jumpSection={this._focusForm.bind(this)}
                      ref='name'
                    />

                }

                  {showSimulation &&
                    <DistributionSummary
                        guesstimateForm={guesstimateForm}
                        simulation={metric.simulation}
                    />
                  }

              <MetricToken
                 readableId={metric.readableId}
                 anotherFunctionSelected={anotherFunctionSelected}
                 onOpenModal={this.openModal.bind(this)}
                 hasGuesstimateDescription={hasGuesstimateDescription}
              />

          {shouldShowJsonTree &&

 <JSONTree data={this.props}/>

          }

          {shouldShowStatistics &&

 <StatTable stats={metric.simulation.stats}/>

          }

        {isSelected && !this.state.modalIsOpen &&

            <DistributionEditor
                metricId={metric.id}
                metricFocus={this.focus.bind(this)}
                onOpen={this.openModal.bind(this)}
                ref='DistributionEditor'
                size='small'
            />

        }

    );
  }
}

function select(state) {
  return {
    guesstimateForm: state.guesstimateForm
  }
}

module.exports = connect(select)(MetricCard);
<|endoftext|>


<commit_before>App.addChild('Explore', _.extend({
  el: '.content[data-action="index"][data-controller-name="explore"]',

  events: {
    'click .explore-toggle':'toggleCategoryList'
  },

  routeFilters: {
    recent: { recent: true },
    in_funding: { in_funding: true },
    expiring: { expiring: true },
    recommended: { recommended: true },
    successful: { successful: true }
  },

  activate: function(){
    this.$loader = this.$("#loading img");
    this.$loaderDiv = this.$("#loading");
    this.$results = this.$(".results");
    this.path = this.$("#explore_results").data('projects-path');

    this.route('recommended');
    this.route('expiring');
    this.route('recent');
    this.route('in_funding');
    this.route('successful');
    this.route('by_category_id/:id');
    this.route('near_of/:state');

    this.setInitialFilter();
    this.setupScroll();

    if(window.location.hash == ''){
      this.fetchPage();
    }
  },

  toggleCategoryList: function(event) {
    this.fetchPage();
    this.$('#categories-wrapper').slideToggle();
  },

  selectLink: function(){
    this.$('.follow-category').hide();
    this.toggleCategoryList();

    var link = this.$('a[href="' + window.location.hash + '"]')
    this.$('a.selected').removeClass('selected');

    link.addClass('selected');

    if(link.data('categoryid') || link.data('name')) {
      this.followCategory.setupFollowHeader(link);
    }
  },

  followRoute: function(route, name, params){
    this.filter = {};
    if(params.length > 0){
      this.filter[name] = params[0];
    }
    else{
      this.filter[name] = true;
    }
    this.firstPage();
    this.fetchPage();
    if(this.parent && this.parent.$search.length > 0){
      this.parent.$search.val('');
    }
    this.selectLink();
  },

  setInitialFilter: function(){
    var search = null;;
    if(this.parent && (search = this.parent.$search.val())){
      this.filter = { pg_search: search };
    }
    else{
      this.filter = {
        recommended: true,
        not_expired: true
      };
    }
  },

}, Skull.InfiniteScroll));

App.views.Explore.addChild('FollowCategory', {
  el: '.follow-category',

  setupFollowHeader: function(selectedItem) {
    var unfollow_btn = this.$('.unfollow-btn');
    var follow_btn = this.$('.follow-btn');

    this.$('.btn.btn-medium').hide();
    this.$('.category-info').html(selectedItem.data('name'));
    this.$('.following').hide();

    if(selectedItem.data('categoryid') > 0) {
      this.$('.category-follow span.count').html(selectedItem.data('totalfollowers'));

      if(selectedItem.data('totalfollowers') > 0) {
        this.$('.following').show();
      }

      if(selectedItem.data('isfollowing')) {
        unfollow_btn.prop('href', selectedItem.data('unfollowpath'))
        unfollow_btn.show();
      } else {
        follow_btn.prop('href', selectedItem.data('followpath'))
        follow_btn.show();
      }
    }

    this.$el.show();
  }

});

<commit_msg>hide category list on project search<commit_after>App.addChild('Explore', _.extend({
  el: '.content[data-action="index"][data-controller-name="explore"]',

  events: {
    'click .explore-toggle':'toggleCategoryList'
  },

  routeFilters: {
    recent: { recent: true },
    in_funding: { in_funding: true },
    expiring: { expiring: true },
    recommended: { recommended: true },
    successful: { successful: true }
  },

  activate: function(){
    this.$loader = this.$("#loading img");
    this.$loaderDiv = this.$("#loading");
    this.$results = this.$(".results");
    this.path = this.$("#explore_results").data('projects-path');

    this.route('recommended');
    this.route('expiring');
    this.route('recent');
    this.route('in_funding');
    this.route('successful');
    this.route('by_category_id/:id');
    this.route('near_of/:state');

    this.setInitialFilter();
    this.setupScroll();

    if(window.location.hash == ''){
      this.fetchPage();
    }
    if(window.location.search.indexOf("pg_search") >= 0){
      this.toggleCategoryList();
    }
  },

  toggleCategoryList: function(event) {
    this.fetchPage();
    this.$('#categories-wrapper').slideToggle();
  },

  selectLink: function(){
    this.$('.follow-category').hide();
    this.toggleCategoryList();

    var link = this.$('a[href="' + window.location.hash + '"]')
    this.$('a.selected').removeClass('selected');

    link.addClass('selected');

    if(link.data('categoryid') || link.data('name')) {
      this.followCategory.setupFollowHeader(link);
    }
  },

  followRoute: function(route, name, params){
    this.filter = {};
    if(params.length > 0){
      this.filter[name] = params[0];
    }
    else{
      this.filter[name] = true;
    }
    this.firstPage();
    this.fetchPage();
    if(this.parent && this.parent.$search.length > 0){
      this.parent.$search.val('');
    }
    this.selectLink();
  },

  setInitialFilter: function(){
    var search = null;;
    if(this.parent && (search = this.parent.$search.val())){
      this.filter = { pg_search: search };
    }
    else{
      this.filter = {
        recommended: true,
        not_expired: true
      };
    }
  },

}, Skull.InfiniteScroll));

App.views.Explore.addChild('FollowCategory', {
  el: '.follow-category',

  setupFollowHeader: function(selectedItem) {
    var unfollow_btn = this.$('.unfollow-btn');
    var follow_btn = this.$('.follow-btn');

    this.$('.btn.btn-medium').hide();
    this.$('.category-info').html(selectedItem.data('name'));
    this.$('.following').hide();

    if(selectedItem.data('categoryid') > 0) {
      this.$('.category-follow span.count').html(selectedItem.data('totalfollowers'));

      if(selectedItem.data('totalfollowers') > 0) {
        this.$('.following').show();
      }

      if(selectedItem.data('isfollowing')) {
        unfollow_btn.prop('href', selectedItem.data('unfollowpath'))
        unfollow_btn.show();
      } else {
        follow_btn.prop('href', selectedItem.data('followpath'))
        follow_btn.show();
      }
    }

    this.$el.show();
  }

});

<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require toastr
//= require_tree .

$(function(){ $(document).foundation(); });

toastr.options = {
  "closeButton": true,
  "debug": false,
  "newestOnTop": false,
  "progressBar": false,
  "positionClass": "toast-top-full-width",
  "preventDuplicates": false,
  "onclick": null,
  "showDuration": "300",
  "hideDuration": "1000",
  "timeOut": "5000",
  "extendedTimeOut": "1000",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
}<commit_msg>Damn you toastr<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require toastr
//= require_tree .

$(function(){
  $(document).foundation();
  toastr.options = {
    "closeButton": true,
    "debug": false,
    "newestOnTop": false,
    "progressBar": false,
    "positionClass": "toast-top-full-width",
    "preventDuplicates": false,
    "onclick": null,
    "showDuration": "300",
    "hideDuration": "1000",
    "timeOut": "5000",
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
  }
});

<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks

HTMLElement.prototype.defaultblur = HTMLElement.prototype.blur;
HTMLElement.prototype.blur = function() {
    this.defaultblur();
    window.Keyboard.hide();
};

$(function() {
    $(document).on('touchstart click', '.alert', function(e) {
        e.stopPropagation();
        $(".alert").slideUp();

    });
    $(document).on('touchstart click', '.notice', function(e) {
        e.stopPropagation();
        $(".notice").slideUp();

    });
});

$(document).ready(function() {
    if ($('#notice\\ error').length) {
        $("#audio-error").trigger('play')
        navigator.vibrate([500]);
        $('#notice\\ error').animate({
            height: '300'
        })
        $('html,body').animate({
            scrollTop: $('#notice\\ error').offset().top
        }, 500);
        document.activeElement.blur();
    }

});<commit_msg>More experimentation<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks

HTMLElement.prototype.defaultblur = HTMLElement.prototype.blur;
HTMLElement.prototype.blur = function() {
    this.defaultblur();
    window.Keyboard.hide();
};

$(function() {
    $(document).on('touchstart click', '.alert', function(e) {
        e.stopPropagation();
        $(".alert").slideUp();

    });
    $(document).on('touchstart click', '.notice', function(e) {
        e.stopPropagation();
        $(".notice").slideUp();

    });
});

$(document).ready(function() {
    if ($('#notice\\ error').length) {
        $("#audio-error").trigger('play')
        navigator.vibrate([500]);
        $('#notice\\ error').animate({
            height: '300'
        })
        $('html,body').animate({
            scrollTop: $('#notice\\ error').offset().top
        }, 500);
        document.activeElement.blur();
        window.Keyboard.hide();
        $("input").blur();
    }

});<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
<commit_msg>Jquery was a lie, thanks a LOT heroku<commit_after><|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require fitvids.js
//= require posts.js
//= require_tree ./admin<commit_msg>require showdown<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require fitvids.js
//= require posts.js
//= require showdown.js
//= require_tree ./admin
<|endoftext|>