<commit_before>function resizeNarrative() {
    $('#map,#narrative,#story,#map,body,html,#loadingDiv').css({
        'height': $(window).height()-54
    });
}
resizeNarrative();

function resetLoadingLocation() {
    $("#loading").css("left", ($("#mapDiv").width() - $("#narrative").width()) / 2);
}
resetLoadingLocation();

var resizeTimeout = -1;

$(window).resize(function() {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(resizeNarrative, 500);
});

var map, layer, symbol, infoTemplate, query, featureLayer;
var visible = [];
var firstSet = true;
var oldLayer = 0;

require([
    "esri/Color",
    "esri/map",
    "esri/geometry/Extent",
    "esri/dijit/Scalebar",
    "esri/layers/FeatureLayer",
    "esri/layers/LayerDrawingOptions",
    "esri/layers/DynamicLayerInfo",
    "esri/layers/ArcGISDynamicMapServiceLayer",
    "esri/renderers/DotDensityRenderer",
    "esri/renderers/ScaleDependentRenderer",
    "esri/InfoTemplate",
    "esri/layers/ArcGISTiledMapServiceLayer",
    "esri/tasks/query",
    "esri/SpatialReference",
    "esri/tasks/QueryTask",
    "esri/graphic",
    "dojo/query",
    "dojo/domReady!"
], function(Color, Map, Extent, Scalebar, FeatureLayer, LayerDrawingOptions, DynamicLayerInfo, ArcGISDynamicMapServiceLayer, DotDensityRenderer, ScaleDependentRenderer, InfoTemplate, ArcGISTiledMapServiceLayer, Query, SpatialReference, QueryTask, Graphic, query) {
    console.log($("#loading").css('left'));
    map = new Map("mapDiv", {
                  basemap: "topo",
        //extent: new Extent({"xmin":1014757.1741241664,"ymin":-1461344.8489687443,"xmax":2970654.1258395016,"ymax":749169.9639166743,"spatialReference":{"wkid":102720}}),
                  center: [-100.78, 46.80],
                  zoom: 7,
        //maxScale: 1000000,
        //minScale: 5000000
        //basemap: "topo"
    });

    // add the basemap
    /*
    var streets = new ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer", {
        opacity: 0.0,
        showAttribution: false
    });
    map.addLayer(streets);
    */

        var layer = new ArcGISDynamicMapServiceLayer("http://undgeography.und.edu/geographyund/rest/services/ND125/WebMapND125/MapServer/33", {
            "id": 33,
        });

        var featureLayer = new FeatureLayer("http://undgeography.und.edu/geographyund/rest/services/ND125/WebMapND125/MapServer/35", {
                                            outFields: ["*"],
                                            });
        layer.show();
    // create our slider to show every 5 years after 1886
    layer.on("load", function(e) {
        values = [];
        for(i=1886; i<=2015; i++) {
             if (i == 1886) {
             values.push(i);
             }
             if (i % 5 == 0) {
                values.push(i);
             }
        }
        console.log(values);

        min = values[0];
        max = values[values.length-1];
        difference = (max - min);
        range = {
            'min': min,
            'max': max
        };

        $.each(values, function(index, value) {
            range['' + (100 - ((max - value) / difference * 100.0)) + '%'] = value;
        });
        console.log(range);

        $("#toggleSlider").noUiSlider({
            start: values[0],
            range: range,
            snap: true
        });

        $('#toggleSlider').noUiSlider_pips({
            mode: 'values',
            density: 10,
            values: values,
            stepped: true
        });

        // create a function for when the slider value is set
        $('#toggleSlider').on('set', function() {
            if (!firstSet) {
                map.graphics.clear();
            } else {
                firstSet = false;
            }
            map.infoWindow.hide();
            map.infoWindow.clearFeatures();
            showLoading();

            // find the index of this layer
            //currentLayers.push(getCurrentLayer());

            // show the visible layers
            //layer.setVisibleLayers(visible);

            // see if we should scroll to a new layer

            oldYear = $(this).val();

            // remove all styling from legendDiv
            $("#legendDiv").attr("style", "");

            // FILTER WITH
            var iYear = Math.floor($(this).val());
            var query = new Query();
                              //query.objectIds = [features[0].attributes.OBJECTID];
                              //query.outFields = ["*"];
            query.returnGeometry = true;
            query.where = "Built3 > " + iYear;

            console.log(iYear);
            console.log(query);

            featureLayer.queryFeatures(query, function(featureSet) {
                //remove all graphics on the maps graphics layer
                map.graphics.clear();
                console.log(featureSet);

                //QueryTask returns a featureSet.  Loop through features in the featureSet and add them to the map.
                dojo.forEach(featureSet.features, function(feature) {
                    // add the features
                    var graphic = feature;
                    graphic.setSymbol(symbol);

                    //Add graphic to the map graphics layer.
                    map.graphics.add(graphic);
                });

                map.graphics.redraw();
            });

            featureLayer.refresh();
    });

        // set as the current layer
        oldLayer = 0;
        $('#toggleSlider').val(min);
        layer.setVisibility(true);
    });
    // hide the loading icon when the dynamic layer finishes updating
    layer.on("update-end", hideLoading);

    // add the layer to the map
    map.addLayer(layer);
    map.addLayers([featureLayer]);

    // show the scalebar
    var scalebar = new Scalebar({
        map: map,
        scalebarUnit: "dual"
    });
});

function getCurrentLayer() {
    // find the index of this layer
    return 33;
}

function ToggleLayer(id) {
    map.graphics.clear();
    map.infoWindow.hide();
    map.infoWindow.clearFeatures();

    showLoading();
}

function hideLoading() {
    $("#loadingDiv").hide();
    $("#togglableLayers").removeAttr('disabled');
}

function showLoading() {
    $("#loadingDiv").show();
    $("#togglableLayers").attr('disabled', 'disabled');
}

$('#slider').click(function() {
    if ($(this).hasClass('expanded')) {
        $('#story').fadeOut(function() {
            $('#narrative').animate({width: 45});
            $('#mapWrapper').animate({right: 45}, function() {
                map.resize(true);
                map.reposition(true);
            });
            $('#slider').removeClass('expanded').find('i').removeClass('glyphicon-chevron-right').addClass('glyphicon-chevron-left');
            resetLoadingLocation();
        });
    }
    else {
        $('#narrative').animate({width: 460}, function() {
            $('#slider').addClass('expanded').find('i').addClass('glyphicon-chevron-right').removeClass('glyphicon-chevron-left');
            $('#story').fadeIn();
            $('#mapWrapper').animate({right: 460}, function() {
                map.resize(true);
                map.reposition(true);
            });
            resetLoadingLocation();
        });
    }
});

$(function() {
    $('[data-toggle="tooltip"]').tooltip();
});
<commit_msg>Changes to Railroads<commit_after>function resizeNarrative() {
    $('#map,#narrative,#story,#map,body,html,#loadingDiv').css({
        'height': $(window).height()-54
    });
}
resizeNarrative();

function resetLoadingLocation() {
    $("#loading").css("left", ($("#mapDiv").width() - $("#narrative").width()) / 2);
}
resetLoadingLocation();

var resizeTimeout = -1;

$(window).resize(function() {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(resizeNarrative, 500);
});

var map, layer, symbol, infoTemplate, query, featureLayer;
var visible = [];
var firstSet = true;
var oldLayer = 0;

require([
    "esri/Color",
    "esri/map",
    "esri/geometry/Extent",
    "esri/dijit/Scalebar",
    "esri/layers/FeatureLayer",
    "esri/layers/LayerDrawingOptions",
    "esri/layers/DynamicLayerInfo",
    "esri/layers/ArcGISDynamicMapServiceLayer",
    "esri/renderers/DotDensityRenderer",
    "esri/renderers/ScaleDependentRenderer",
    "esri/InfoTemplate",
    "esri/layers/ArcGISTiledMapServiceLayer",
    "esri/tasks/query",
    "esri/tasks/FeatureSet",
    "esri/SpatialReference",
    "esri/tasks/QueryTask",
    "esri/graphic",
    "dojo/query",
    "dojo/domReady!"
], function(Color, Map, Extent, Scalebar, FeatureLayer, LayerDrawingOptions, DynamicLayerInfo, ArcGISDynamicMapServiceLayer, DotDensityRenderer, ScaleDependentRenderer, InfoTemplate, ArcGISTiledMapServiceLayer, Query, FeatureSet, SpatialReference, QueryTask, Graphic, query) {
    console.log($("#loading").css('left'));
    map = new Map("mapDiv", {
                  basemap: "topo",
        //extent: new Extent({"xmin":1014757.1741241664,"ymin":-1461344.8489687443,"xmax":2970654.1258395016,"ymax":749169.9639166743,"spatialReference":{"wkid":102720}}),
                  center: [-100.78, 46.80],
                  zoom: 7,
        //maxScale: 1000000,
        //minScale: 5000000
        //basemap: "topo"
    });

    // add the basemap
    /*
    var streets = new ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer", {
        opacity: 0.0,
        showAttribution: false
    });
    map.addLayer(streets);
    */

        var layer = new ArcGISDynamicMapServiceLayer("http://undgeography.und.edu/geographyund/rest/services/ND125/WebMapND125/MapServer/41", {
            "id": 41,
        });

        var featureLayer = new FeatureLayer("http://undgeography.und.edu/geographyund/rest/services/ND125/WebMapND125/MapServer/35", {
                                            outFields: ["*"],
                                            });
        map.addLayer(layer);
    // create our slider to show every 5 years after 1886
    layer.on("load", function(e) {
        values = [];
        for(i=1886; i<=2015; i++) {
             if (i == 1886) {
             values.push(i);
             }
             if (i % 5 == 0) {
                values.push(i);
             }
        }
        console.log(values);

        min = values[0];
        max = values[values.length-1];
        difference = (max - min);
        range = {
            'min': min,
            'max': max
        };

        $.each(values, function(index, value) {
            range['' + (100 - ((max - value) / difference * 100.0)) + '%'] = value;
        });
        console.log(range);

        $("#toggleSlider").noUiSlider({
            start: values[0],
            range: range,
            snap: true
        });

        $('#toggleSlider').noUiSlider_pips({
            mode: 'values',
            density: 10,
            values: values,
            stepped: true
        });

        // create a function for when the slider value is set
        $('#toggleSlider').on('set', function() {
            if (!firstSet) {
                              console.log("Clearing map");
                map.graphics.clear();
            } else {
                              console.log("Not Clearing map");
                firstSet = false;
            }
            map.infoWindow.hide();
            map.infoWindow.clearFeatures();
            showLoading();

            // find the index of this layer
            //currentLayers.push(getCurrentLayer());

            // show the visible layers
            //layer.setVisibleLayers(visible);

            // see if we should scroll to a new layer

            oldYear = $(this).val();

            // remove all styling from legendDiv
            $("#legendDiv").attr("style", "");

            // FILTER WITH
            var iYear = Math.floor($(this).val());
            var query = new Query();
            //query.objectIds = [features[0].attr.OBJECTIDS];
            query.outFields =["*"];
            query.returnGeometry = true;
            query.where = "Built3 < " + iYear;
            query.spatialReference = {"wkid":102720};

            console.log(iYear);
            console.log(query);

            featureLayer.queryFeatures(query, function(FeatureSet) {
                //remove all graphics on the maps graphics layer
                map.graphics.clear();
                console.log(FeatureSet.features);
                                       var numFeatures = FeatureSet.features.length;
                                       for (var x=0; x<numFeatures; x++) {
                                        var graphic = FeatureSet.features[x];
                                        map.graphics.add(graphic);
                                        map.graphics.redraw();

                                       }

                /*/QueryTask returns a featureSet.  Loop through features in the featureSet and add them to the map.
                dojo.forEach(FeatureSet.features, function(feature) {
                    // add the features
                    var graphic = feature;
                    graphic.setSymbol(symbol);

                    //Add graphic to the map graphics layer.
                    map.graphics.draw(graphic);
                });

                map.graphics.redraw();
                 */
            });

            featureLayer.refresh();
    });

        // set as the current layer
        oldLayer = 0;
        $('#toggleSlider').val(min);
        layer.setVisibility(true);
    });
    // hide the loading icon when the dynamic layer finishes updating
    layer.on("update-end", hideLoading);

    // add the layer to the map
    map.addLayer(layer);
    map.addLayer(featureLayer);
    // show the scalebar
    var scalebar = new Scalebar({
        map: map,
        scalebarUnit: "dual"
    });
});

function getCurrentLayer() {
    // find the index of this layer
    return 33;
}

function ToggleLayer(id) {
    map.graphics.clear();
    map.infoWindow.hide();
    map.infoWindow.clearFeatures();

    showLoading();
}

function hideLoading() {
    $("#loadingDiv").hide();
    $("#togglableLayers").removeAttr('disabled');
}

function showLoading() {
    $("#loadingDiv").show();
    $("#togglableLayers").attr('disabled', 'disabled');
}

$('#slider').click(function() {
    if ($(this).hasClass('expanded')) {
        $('#story').fadeOut(function() {
            $('#narrative').animate({width: 45});
            $('#mapWrapper').animate({right: 45}, function() {
                map.resize(true);
                map.reposition(true);
            });
            $('#slider').removeClass('expanded').find('i').removeClass('glyphicon-chevron-right').addClass('glyphicon-chevron-left');
            resetLoadingLocation();
        });
    }
    else {
        $('#narrative').animate({width: 460}, function() {
            $('#slider').addClass('expanded').find('i').addClass('glyphicon-chevron-right').removeClass('glyphicon-chevron-left');
            $('#story').fadeIn();
            $('#mapWrapper').animate({right: 460}, function() {
                map.resize(true);
                map.reposition(true);
            });
            resetLoadingLocation();
        });
    }
});

$(function() {
    $('[data-toggle="tooltip"]').tooltip();
});
<|endoftext|>


<commit_before>/**
 * Retrieves all the rows in the active spreadsheet that contain data
 * When going through the rows if there no value in "invited by" then
 * sends the email field to the slack invite service.
 * For more information on using the Spreadsheet API, see
 * https://developers.google.com/apps-script/service_spreadsheet
 */
function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  // Sheet is a forms response sheet with 3 columns
  // "Timestamp" "What is your email address?" "Invited by"

  Logger.log("Looking for rows with email but no invited by...");
  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    if (row[2] == "" && row[1] != "") {
      var time = Math.ceil(new Date().getTime()/1000);
      Logger.log("Inviting email="+row[1]+ " t="+time);

      invite(row[1]);
      sheet.getRange(i+1, 3).setValue("scriptbot");

      SpreadsheetApp.flush();
    }
  }
};

/**
 * Sends the email to the slack invite endpoint.  You need to fill in your api token
 * and the channels you want the user to be added to.
 *
*/
function invite(email) {

  var time = Math.ceil(new Date().getTime()/1000);
  var url = "https://phillydev.slack.com/api/users.admin.invite?t=" + time;
  var payload =
      {
        "email" : email,
        "token" : "fill_in_your_api_token";
        "channels": "C03G04GL7,C03EC6Y8L",
        "set_active": "true",
        "_attempts": "1",
        "type" : "post",
      };

  if (payload["token"] == "fill_in_your_api_token") {
    Logger.log("You have to fill in your api token");
    return;
  }

  var options =
      {
        "method"  : "POST",
        "payload" : payload,
        "followRedirects" : true,
        "muteHttpExceptions": true
      };

  var result = UrlFetchApp.fetch(url, options);

  if (result.getResponseCode() == 200) {

    var params = JSON.parse(result.getContentText());
    Logger.log(params);

  } else {
    Logger.log("exception");
    Logger.log(result);
  }

};

function onOpen() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [{
    name : "Invite to Slack",
    functionName : "readRows"
  }];
  spreadsheet.addMenu("Script Center Menu", entries);
};
<commit_msg>fixing bad semi<commit_after>/**
 * Retrieves all the rows in the active spreadsheet that contain data
 * When going through the rows if there no value in "invited by" then
 * sends the email field to the slack invite service.
 * For more information on using the Spreadsheet API, see
 * https://developers.google.com/apps-script/service_spreadsheet
 */
function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  // Sheet is a forms response sheet with 3 columns
  // "Timestamp" "What is your email address?" "Invited by"

  Logger.log("Looking for rows with email but no invited by...");
  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    if (row[2] == "" && row[1] != "") {
      var time = Math.ceil(new Date().getTime()/1000);
      Logger.log("Inviting email="+row[1]+ " t="+time);

      invite(row[1]);
      sheet.getRange(i+1, 3).setValue("scriptbot");

      SpreadsheetApp.flush();
    }
  }
};

/**
 * Sends the email to the slack invite endpoint.  You need to fill in your api token
 * and the channels you want the user to be added to.
 *
*/
function invite(email) {

  var time = Math.ceil(new Date().getTime()/1000);
  var url = "https://phillydev.slack.com/api/users.admin.invite?t=" + time;
  var payload =
      {
        "email" : email,
        "token" : "fill_in_your_api_token",
        "channels": "C03G04GL7,C03EC6Y8L",
        "set_active": "true",
        "_attempts": "1",
        "type" : "post",
      };

  if (payload["token"] == "fill_in_your_api_token") {
    Logger.log("You have to fill in your api token");
    return;
  }

  var options =
      {
        "method"  : "POST",
        "payload" : payload,
        "followRedirects" : true,
        "muteHttpExceptions": true
      };

  var result = UrlFetchApp.fetch(url, options);

  if (result.getResponseCode() == 200) {

    var params = JSON.parse(result.getContentText());
    Logger.log(params);

  } else {
    Logger.log("exception");
    Logger.log(result);
  }

};

function onOpen() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [{
    name : "Invite to Slack",
    functionName : "readRows"
  }];
  spreadsheet.addMenu("Script Center Menu", entries);
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import css from './Checkbox.css';

const propTypes = {
  checkedIcon: PropTypes.element,
  uncheckedIcon: PropTypes.element,
  tertiaryIcon: PropTypes.element,
  input: PropTypes.object,
  meta: PropTypes.object,
  label: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.node,
  ]),
  labelClass: PropTypes.string,
  labelStyle: PropTypes.object,
  hover: PropTypes.bool,
  fullWidth: PropTypes.bool,
  marginBottom0: PropTypes.bool,
  inline: PropTypes.bool,
  meta: PropTypes.object,
  onChange: PropTypes.func,
  onFocus: PropTypes.func,
  name: PropTypes.string,
  id: PropTypes.string,
};

class Checkbox extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      inputChecked: false,
      inputIndeterminate: false,
      inputInFocus: false,
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  getLabelStyle() {
    return classNames(
      { [`${css.checkboxLabel}`]: !this.props.labelClass },
      { [`${css[this.props.labelStyle]}`]: !this.props.labelClass && this.props.labelStyle },
      this.props.labelClass,
    );
  }

  getRootStyle() {
    let rootStyle = this.props.hover ? css.root + ' ' + css.rootHover : css.root;
    let hovered = '';
    if (this.props.hover && this.state.inputInFocus) {
      hovered = ' ' + css.hovered;
    }
    rootStyle += hovered;
    rootStyle += this.props.fullWidth ? ' ' + css.rootFullWidth : ' ';
    rootStyle += this.props.marginBottom0 ? ' ' + css.marginBottom0 : ' ';
    rootStyle += this.props.inline ? ' ' + css.inline : '';
    if (this.props.meta) {
      rootStyle += this.props.meta.error || this.props.meta.warning ? ' ' + css.checkboxHasFeedback : '';
    }

    return rootStyle;
  }

  getContainerStyle() {
    let containerStyle = css.root;
    containerStyle += this.props.fullWidth ? ' ' + css.rootFullWidth : ' ';
    containerStyle += this.props.marginBottom0 ? ' ' + css.marginBottom0 : ' ';
    containerStyle += this.props.inline ? ' ' + css.inline : '';
    return containerStyle;
  }

  getInputStyle() {
    const base = css.checkboxInput;
    let hidden = '';
    if (this.props.checkedIcon || this.props.uncheckedIcon || this.props.tertiaryIcon) {
      hidden = css.hidden;
    }
    return `${base} ${hidden}`;
  }

  componentDidMount() {
    this.setState({
      inputChecked: this.input.checked,
      inputIndeterminate: this.input.indeterminate,
    });
  }

  handleChange(e) {
    this.setState({
      inputChecked: this.input.checked,
      inputIndeterminate: this.input.indeterminate,
    });

    this.props.input ? this.props.input.onChange(e) : this.props.onChange(e);
  }

  handleFocus(e) {
    this.setState({
      inputInFocus: true,
    });

    this.props.input ? this.props.input.onFocus(e) : null;
    this.props.onFocus ? this.props.onFocus(e) : null;
  }

  handleBlur(e) {
    this.setState({
      inputInFocus: false,
    });

    this.props.input ? this.props.input.onBlur(e) : null;
    this.props.onBlur ? this.props.onBlur(e) : null;
  }

  render() {
    let cleanedProps;
    let inputProps;
    let inputChecked;
    if (this.props.input) {
      var { input, meta: { error, warning, touched }, ...rest } = this.props;
      var { onChange, onFocus, onBlur, value, ...inputAttr } = input;
      inputProps = { ...inputAttr };
      cleanedProps = { ...rest };
      inputChecked = value;
    } else {
      cleanedProps = this.props;
      inputProps = null;
    }

    const { label, required, fullWidth, marginBottom0, hover, checkedIcon, uncheckedIcon, tertiaryIcon, labelStyle, ...inputCustom } = cleanedProps;

    let warningElement;
    if (this.props.meta) {
      warningElement = touched && warning ?
{warning}
 : null;
    }

    let iconElement = null;
    if (checkedIcon || uncheckedIcon || tertiaryIcon) {
      let icon = null;
      let ariaStatus = null;
      if (this.state.inputChecked) {
        icon = this.props.checkedIcon;
        ariaStatus = 'true';
      } else {
        icon = this.props.uncheckedIcon;
        ariaStatus = 'false';
      }
      if (this.state.inputIndeterminate) {
        icon = this.props.tertiaryIcon;
        ariaStatus = 'mixed';
      }
      iconElement = {icon};
    }

    let ariaProps = {};
    if (!this.props.name || !this.props.input) {
      ariaProps['aria-label'] = `checkbox ${this.props.label}`;
    }
    const { ...inputAriaProps } = ariaProps;

    return (

          <input type="checkbox" {...inputAriaProps} checked={inputChecked || inputCustom.checked}{...inputProps} {...inputCustom} className={this.getInputStyle()} onChange={this.handleChange} onFocus={this.handleFocus} onBlur={this.handleBlur} ref={(ref) => { this.input = ref; }} />
          {iconElement}

            {label}

        {warningElement}

    );
  }
}

Checkbox.propTypes = propTypes;

export default Checkbox;
<commit_msg>Lint: Checkbox. See STCOM-21.<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import css from './Checkbox.css';

const propTypes = {
  checkedIcon: PropTypes.element,
  uncheckedIcon: PropTypes.element,
  tertiaryIcon: PropTypes.element,
  input: PropTypes.object,
  meta: PropTypes.object,
  label: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.node,
  ]),
  labelClass: PropTypes.string,
  labelStyle: PropTypes.object,
  hover: PropTypes.bool,
  fullWidth: PropTypes.bool,
  marginBottom0: PropTypes.bool,
  inline: PropTypes.bool,
  onBlur: PropTypes.func,
  onChange: PropTypes.func,
  onFocus: PropTypes.func,
  name: PropTypes.string,
  id: PropTypes.string,
};

class Checkbox extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      inputChecked: false,
      inputIndeterminate: false,
      inputInFocus: false,
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  componentDidMount() {
    this.setState({
      inputChecked: this.input.checked,
      inputIndeterminate: this.input.indeterminate,
    });
  }

  getLabelStyle() {
    return classNames(
      { [`${css.checkboxLabel}`]: !this.props.labelClass },
      { [`${css[this.props.labelStyle]}`]: !this.props.labelClass && this.props.labelStyle },
      this.props.labelClass,
    );
  }

  getRootStyle() {
    return classNames(
      [`${css.root}`],
      { [`${css.rootHover}`]: this.props.hover },
      { [`${css.hovered}`]: (this.props.hover && this.state.inputInFocus) },
      { [`${css.rootFullWidth}`]: this.props.fullWidth },
      { [`${css.marginBottom0}`]: this.props.marginBottom0 },
      { [`${css.inline}`]: this.props.inline },
      { [`${css.checkboxHasFeedback}`]: (this.props.meta && (this.props.meta.error || this.props.meta.warning)) },
    );
  }

  getContainerStyle() {
    return classNames(
      [`${css.root}`],
      { [`${css.rootFullWidth}`]: this.props.fullWidth },
      { [`${css.marginBottom0}`]: this.props.marginBottom0 },
      { [`${css.inline}`]: this.props.inline },
    );
  }

  getInputStyle() {
    const base = css.checkboxInput;
    let hidden = '';
    if (this.props.checkedIcon || this.props.uncheckedIcon || this.props.tertiaryIcon) {
      hidden = css.hidden;
    }
    return `${base} ${hidden}`;
  }

  handleChange(e) {
    this.setState({
      inputChecked: this.input.checked,
      inputIndeterminate: this.input.indeterminate,
    });

    if (this.props.input) {
      this.props.input.onChange(e);
    } else {
      this.props.onChange(e);
    }
  }

  handleFocus(e) {
    this.setState({
      inputInFocus: true,
    });

    if (this.props.input) {
      this.props.input.onFocus(e);
    }

    if (this.props.onFocus) {
      this.props.onFocus(e);
    }
  }

  handleBlur(e) {
    this.setState({
      inputInFocus: false,
    });

    if (this.props.input) {
      this.props.input.onBlur(e);
    }

    if (this.props.onBlur) {
      this.props.onBlur(e);
    }
  }

  render() {
    let cleanedProps;
    let inputProps;
    let inputChecked;
    let metaTouched;
    let metaWarning;
    if (this.props.input) {
      const { input, meta: { error, warning, touched }, ...rest } = this.props;
      const { onChange, onFocus, onBlur, value, ...inputAttr } = input;
      metaTouched = touched;
      metaWarning = warning;
      inputProps = { ...inputAttr };
      cleanedProps = { ...rest };
      inputChecked = value;
    } else {
      cleanedProps = this.props;
      inputProps = null;
    }

    const { label, required, fullWidth, marginBottom0, hover, checkedIcon, uncheckedIcon, tertiaryIcon, labelStyle, ...inputCustom } = cleanedProps;

    let warningElement;
    if (this.props.meta) {
      warningElement = metaTouched && metaWarning ?
{metaWarning}
 : null;
    }

    let iconElement = null;
    if (checkedIcon || uncheckedIcon || tertiaryIcon) {
      let icon = null;
      if (this.state.inputChecked) {
        icon = this.props.checkedIcon;
      } else {
        icon = this.props.uncheckedIcon;
      }
      if (this.state.inputIndeterminate) {
        icon = this.props.tertiaryIcon;
      }
      iconElement = {icon};
    }

    const ariaProps = {};
    if (!this.props.name || !this.props.input) {
      ariaProps['aria-label'] = `checkbox ${this.props.label}`;
    }
    const { ...inputAriaProps } = ariaProps;

    return (

          <input
            type="checkbox"
            {...inputAriaProps}
            checked={inputChecked || inputCustom.checked}
            {...inputProps}
            {...inputCustom}
            className={this.getInputStyle()}
            onChange={this.handleChange}
            onFocus={this.handleFocus}
            onBlur={this.handleBlur}
            ref={(ref) => { this.input = ref; }}
          />
          {iconElement}

            {label}

        {warningElement}

    );
  }
}

Checkbox.propTypes = propTypes;

export default Checkbox;
<|endoftext|>


<commit_before>angular.module("vino.ui").directive("originPicker", function () {

    return {
        restrict: 'E',
        scope: {
            ngModel: '=',
            ngRequired: '='
        },
        template: '' +
            '<select id="domainOrigin" ng-required="ngRequired" ng-model="ngModel" ng-options="aoc.name group by aoc.region.name for aoc in aocs">' +
            '</select>',
        controller: function ($scope, Origin) {

            $scope.$watch("aocs.length", function () {
                if (!$scope.aocs) {
                    return;
                }
                $scope.$watch("ngModel", function () {
                    if (!$scope.ngModel) {
                        return;
                    }
                    var foundAOC = _.find($scope.aocs, {_id: $scope.ngModel._id});
                    if (foundAOC) {
                        $scope.ngModel = foundAOC;
                    }
                });
            });

            $scope.aocs = Origin.getAllAOCS();

        }
    }

});<commit_msg>Improve origin picker<commit_after>angular.module("vino.ui").directive("originPicker", function () {

    return {
        restrict: 'E',
        scope: {
            ngModel: '=',
            ngRequired: '='
        },
        template: '' +
            '<select id="domainOrigin" ng-required="ngRequired" ng-model="ngModel" ng-options="aoc.name group by aoc.region.name for aoc in aocs">' +
            '</select>',
        controller: function ($scope, Origin) {

            $scope.$watchCollection("aocs", function () {
                if (!$scope.aocs) {
                    return;
                }
                $scope.$watch("ngModel", function () {
                    if (!$scope.ngModel) {
                        return;
                    }
                    var foundAOC = _.find($scope.aocs, {_id: $scope.ngModel._id});
                    if (foundAOC) {
                        $scope.ngModel = foundAOC;
                    }
                });
            });

            $scope.aocs = Origin.getAllAOCS();

        }
    }

});<|endoftext|>


<commit_before>var express = require('express'),
    app = express(),
    http = require('http'),
    server = http.createServer(app),
    io = require('socket.io').listen(server);

    // request_lib = require('request'),
    // cheerio = require('cheerio'),

var clients = {};

io.sockets.on('connection', function(socket){
    io.set("transports", ["xhr-polling"]);
    io.set("polling duration", 20);
    socket.on('chat message', function(msg){
      io.sockets.in(socket.room).emit('chat message', msg);
    });
    socket.on('adduser', function(room_name){
      // store the room name in the socket session for this client
      socket.room = room_name;
      // send client to room 1
      socket.join(room_name);
      console.log("Room Name: " + room_name);
      // // echo to client they've connected
      // socket.emit('updatechat', 'SERVER', 'you have connected to room1');
      // echo to room 1 that a person has connected to their room
      // io.emit('chat message', 'New user has connected to room a');
      socket.broadcast.to(room_name).emit('chat message', 'New user has connected to this room.');
    });
});

app.set('port', (process.env.PORT || 5000));

app.get('/b', function(request, response) {
  response.sendFile(__dirname + '/html/textpad.html');
});

// for now if i type localhost:5000/a it should open a new
app.get('/a', function(request, response) {
  response.sendFile(__dirname + '/html/a.html');
});

server.listen(app.get('port'), function() {
    console.log("Node app is running at port: " + app.get('port'));
});

  // response.writeHead(200, {"Content-Type": "text/html"});
  // response.write("<!DOCTYPE \"html\">");
  // response.write("");
  // response.write("");
  // response.write("<title>Hello World Page</title>");
  // response.write("");
  // response.write("");
  // response.write("Hello World! 5000");
  // response.write("");
  // response.write("");
  // response.end();<commit_msg>remove xlhr polling option for socket and heroku<commit_after>var express = require('express'),
    app = express(),
    http = require('http'),
    server = http.createServer(app),
    io = require('socket.io').listen(server);

    // request_lib = require('request'),
    // cheerio = require('cheerio'),

var clients = {};

io.sockets.on('connection', function(socket){

    socket.on('chat message', function(msg){
      io.sockets.in(socket.room).emit('chat message', msg);
    });
    socket.on('adduser', function(room_name){
      // store the room name in the socket session for this client
      socket.room = room_name;
      // send client to room 1
      socket.join(room_name);
      console.log("Room Name: " + room_name);
      // // echo to client they've connected
      // socket.emit('updatechat', 'SERVER', 'you have connected to room1');
      // echo to room 1 that a person has connected to their room
      // io.emit('chat message', 'New user has connected to room a');
      socket.broadcast.to(room_name).emit('chat message', 'New user has connected to this room.');
    });
});

app.set('port', (process.env.PORT || 5000));

app.get('/b', function(request, response) {
  response.sendFile(__dirname + '/html/textpad.html');
});

// for now if i type localhost:5000/a it should open a new
app.get('/a', function(request, response) {
  response.sendFile(__dirname + '/html/a.html');
});

server.listen(app.get('port'), function() {
    console.log("Node app is running at port: " + app.get('port'));
});

  // response.writeHead(200, {"Content-Type": "text/html"});
  // response.write("<!DOCTYPE \"html\">");
  // response.write("");
  // response.write("");
  // response.write("<title>Hello World Page</title>");
  // response.write("");
  // response.write("");
  // response.write("Hello World! 5000");
  // response.write("");
  // response.write("");
  // response.end();<|endoftext|>


<commit_before>(function() {

	// want to hide these initially
	$('#password-change, #search-div, #order-div, #color-div, #recent-ips-div, #theme-div, #maps-div').hide();
	var passwordDown = false, colorDown = false, orderDown = false, searchDown = false, ipsDown = false, themeDown = false, mapsDown = false;

	// cache the DOM
	var $passwordDropdown = $('.password_span'), $orderDropdown = $('.order_dropdown_span'), $searchDropdown = $('.search_dropdown_span'),
		$colorDropdown = $('.color_dropdown_span'), $recentIps = $('#recent-ips-div'), $ipsDropdown = $('.recent_ips_span'),
		$themeDropdown = $('.theme_dropdown_span'), $mapsDropdown = $('.maps_dropdown_span');

	/**
	* @function localStorageTest
	*
	* Checks that the localStorage is enabled on the users browser.
	**/
	function localStorageTest() {
		var test = 'test';
		try {
			localStorage.setItem(test, test);
			localStorage.removeItem(test);
			return true;
		} catch(e) {
			return false;
		}
	}

	/**
	* @function String format
	*
	* Add functionality to String object, for C# style string formatting.
	* Usage: "{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
	* From; http://stackoverflow.com/a/4673436
	**/
	if (!String.prototype.format) {
		String.prototype.format = function() {
			var args = arguments;
			return this.replace(/{(\d+)}/g, function(match, number) {
				return typeof args[number] != 'undefined' ? args[number] : match;
			});
		};
	}

	if(localStorage.getItem('theme') === 'light') {
		$('html').removeClass('dark-theme');
		$('.container-fluid.account-dark').removeClass('account-dark');
	} else if(localStorage.getItem('theme') === 'dark') {
		$('html').addClass('dark-theme');
		$('.container-fluid.account-dark').addClass('account-dark');
	}

	getSettings();
	/**
	* @function
	*
	* Will get the users chosen tag color from the database.
	**/
	function getSettings() {
		$.ajax({
			method: 'POST',
			url: 'includes/user-settings.php',
			data: {
				id: userId,
				action: 'get-settings'
			}
		})
		.done(function(data, result) {

			data = JSON.parse(data);
			var color = data[0];
			var order = data[1];

			var $selectColor = $('#select-tag-color');
			var $item = $selectColor.find('option[value={0}]'.format(color));
			$item.remove();
			$selectColor.find('option:eq(0)').before($item);
			$('#select-tag-color > option:eq(0)').attr('selected', true);

			$noteOrder = $('#options-note-order');
			$item = $noteOrder.find('option[value={0}]'.format(order));
			$item.remove();
			$noteOrder.find('option:eq(0)').before($item);
			$('#options-note-order > option:eq(0)').attr('selected', true);

			if(data[2] === "true") {
				$('#search_title').prop('checked', true);
			}

			if(data[3] === "true") {
				$('#search_text').prop('checked', true);
			}

			if(data[4] === "true") {
				$('#search_mark_done').prop('checked', true);
			}

			$('#total_notes').append(data[5]);

			data[6].reverse();
			$recentIps.append('Most Recent');
			$.each(data[6], function(i, v) {
				$recentIps.append('
{0}
'.format(v));
			});

			if(data[7] === 'dark') {
				$('#theme_checkbox').prop('checked', true);
			}

			localStorage.setItem('theme', data[7]);
		})
		.fail(function(error) {
			console.log('An error occurred', error);
		});
	}

	/**
	*@function
	*
	* Will update the users chosen color in the database
	**/
	$('#tag-color-button').on('click', function() {
		var color = $('#select-tag-color').val();

		$.ajax({
			method: 'POST',
			url: 'includes/user-settings.php',
			data: {
				color: color,
				id: userId,
				action: 'set-tag-color'
			}
		})
		.done(function(data, status) {
			toastr.success('Tag color updated!');
		})
		.fail(function(error) {
			console.log('An error occurred', error);
		});
	});

	/**
	*@function
	*
	* Will update the users chosen order to sidplay the notes in.
	* Order is taken from a select list.
	**/
	$('#options-order-button').on('click', function() {
		var order = $('#options-note-order').val();

		$.ajax({
			method: 'POST',
			url: 'includes/user-settings.php',
			data: {
				id: userId,
				action: 'set-note-order',
				order: order
			}
		})
		.done(function(data, status) {
			toastr.success('Note order has been successfully updated!');
		})
		.fail(function(error) {
			console.log('An error occurred', error);
		});
	});

	/**
	*@function
	*
	* Will update the users choice of what to search the database for
	* when the search function is used.
	**/
	$('#options-search-button').on('click', function() {
		var title = $('#search_title').is(':checked');
		var text = $('#search_text').is(':checked');
		var searchComplete = $('#search_mark_done').is(':checked');

		if(title === false && text === false) {
			alert('You must chose to search by either one or both of title and text!');
			return;
		}

		$.ajax({
			method: 'POST',
			url: 'includes/user-settings.php',
			data: {
				id: userId,
				action: 'set-search-parameters',
				text: text,
				title: title,
				complete: searchComplete
			}
		})
		.done(function(data, status) {
			toastr.success('Search settings updated!');
		})
		.fail(function(error) {
			console.log('An error occurred', error);
		});
	});

	/**
	* @function
	*
	* Change the users password.
	* Will validate that the user wishes to change their password
	* the old password has something entered into it's field,
	* and that the new password being entered has been confirmed.
	* @param {object} e
	**/
	$('#change-password-form').on('submit', function(e) {
		$('.validation-error').remove();
		var newPassword = $('#new-password').val();
		var confirmPassword = $('#confirm-password').val();
		var old = $('#old-password').val();

		if(!confirm('Please confirm you wish to change your password.')) {
			e.preventDefault();
			return;
		}

		if(old === '') {
			$('#old-password').after('Please enter your old password!');
			e.preventDefault();
			return;
		}

		if(newPassword.trim() === '' || confirmPassword.trim() === '') {
			$('#new-password').after('The new or confirmation input is empty!');
			e.preventDefault();
			return;
		}

		if(newPassword !== confirmPassword) {
			$('#confirm-password').after('The confirmation password is different!');
			e.preventDefault();
			return;
		}
	});

	/**
	* @function
	*
	* Changes the front-end theme.
	**/
	$('#theme-button').on('click', function() {
		var theme = $('#theme_checkbox').is(':checked');
		var color = 'light';

		if(theme) {
			color = 'dark';
		}

		$.ajax({
			method: 'POST',
			url: 'includes/user-settings.php',
			data: {
				action: 'set-theme',
				theme: color,
				id: userId
			}
		})
		.done(function(data, status) {
			data = JSON.parse(data);
			if(data === 'success') {
				if(localStorageTest) {
					localStorage.setItem('theme', color);
					toastr.info('Updated theme settings! Please refresh your page.');
				} else {
					toastr.info('Please log out and back in for changes to take place');
				}

				//if(color === 'light') {
				//	$('html').removeClass('dark-theme');
				//	$('.container-fluid.account-dark').removeClass('account-dark');
				//} else if(color === 'dark') {
				//	$('html').addClass('dark-theme');
				//	$('.container-fluid.account-dark').addClass('account-dark');
				//}
			}
		})
		.fail(function(error) {
			console.log(error);
		});
	});

	/**
	* @function
	* Toggle to show the form to change the users password
	*
	**/
	$('#password-header').on('click', function() {
		$('#password-change').toggle();

		if(passwordDown) {
			$passwordDropdown.addClass('glyphicon-chevron-up');
			$passwordDropdown.removeClass('glyphicon-chevron-down');
			passwordDown = false;
		} else {
			$passwordDropdown.addClass('glyphicon-chevron-down');
			$passwordDropdown.removeClass('glyphicon-chevron-up');
			passwordDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the form for the user to choose their notes color
	*
	**/
	$('#color-header').on('click', function() {
		$('#color-div').toggle();

		if(colorDown) {
			$colorDropdown.addClass('glyphicon-chevron-up');
			$colorDropdown.removeClass('glyphicon-chevron-down');
			colorDown = false;
		} else {
			$colorDropdown.addClass('glyphicon-chevron-down');
			$colorDropdown.removeClass('glyphicon-chevron-up');
			colorDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the form for the user to choose what order to display the notes
	*
	**/
	$('#order-header').on('click', function() {
		$('#order-div').toggle();

		if(orderDown) {
			$orderDropdown.addClass('glyphicon-chevron-up');
			$orderDropdown.removeClass('glyphicon-chevron-down');
			orderDown = false;
		} else {
			$orderDropdown.addClass('glyphicon-chevron-down');
			$orderDropdown.removeClass('glyphicon-chevron-up');
			orderDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the form for the user to customise the search option
	*
	**/
	$('#search-header').on('click', function() {
		$('#search-div').toggle();

		if(searchDown) {
			$searchDropdown.addClass('glyphicon-chevron-up');
			$searchDropdown.removeClass('glyphicon-chevron-down');
			searchDown = false;
		} else {
			$searchDropdown.addClass('glyphicon-chevron-down');
			$searchDropdown.removeClass('glyphicon-chevron-up');
			searchDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the list of recently used IPs
	*
	**/
	$('#recent-ips-header').on('click', function() {
		$('#recent-ips-div').toggle();

		if(ipsDown) {
			$ipsDropdown.addClass('glyphicon-chevron-up');
			$ipsDropdown.removeClass('glyphicon-chevron-down');
			ipsDown = false;
		} else {
			$ipsDropdown.addClass('glyphicon-chevron-down');
			$ipsDropdown.removeClass('glyphicon-chevron-up');
			ipsDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the form for the user to choose what theme to use - currently dark or light theme.
	*
	**/
	$('#theme-header').on('click', function() {
		$('#theme-div').toggle();

		if(themeDown) {
			$themeDropdown.addClass('glyphicon-chevron-up');
			$themeDropdown.removeClass('glyphicon-chevron-down');
			themeDown = false;
		} else {
			$themeDropdown.addClass('glyphicon-chevron-down');
			$themeDropdown.removeClass('glyphicon-chevron-up');
			themeDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the form for the user to choose what theme to use - currently dark or light theme.
	*
	**/
	$('#maps-header').on('click', function() {
		$('#maps-div').toggle();

		if(mapsDown) {
			$mapsDropdown.addClass('glyphicon-chevron-up');
			$mapsDropdown.removeClass('glyphicon-chevron-down');
			mapsDown = false;
		} else {
			$mapsDropdown.addClass('glyphicon-chevron-down');
			$mapsDropdown.removeClass('glyphicon-chevron-up');
			mapsDown = true;
		}
	});

	/**
	* @function Anonymous Geolocation function
	*
	* Checks that Geolocation API can be used, and then gets the users latitude and longitude from this.
	* Uses Google Maps API to then get a map of the users coordinates, which is then displayed in an image.
	* Posts the users coordinates into the database for future use.
	**/
	if("geolocation" in navigator) {
		navigator.geolocation.getCurrentPosition(function(position) {
			console.log(position.coords.latitude, position.coords.longitude);
			var longitude = position.coords.longitude;
			var latitude = position.coords.latitude;

			var img = new Image();
			// need an access key for google
			img.src = 'https://maps.googleapis.com/maps/api/staticmap?center=' + latitude + ',' + longitude + '&zoom=13&size=300x300&sensor=false';

			// place the image on the page.
			$('#map_location').append(img);

			$.ajax({
				url: 'includes/user-settings.php',
				method: 'POST',
				data: {
					action: 'location',
					latitude: latitude,
					longitude: longitude,
					id: userId
				}
			})
			.done(function(data) {
				data = JSON.parse(data);
				if(data === 'success') {
					console.log('Saved');
				}
			})
			.error(function(data) {
				console.warn('Could not save location');
			});
		});
	} else {
		console.warn('Geolocation is not available');
	}

})();<commit_msg>Move loading into separate function<commit_after>(function() {

	// want to hide these initially
	$('#password-change, #search-div, #order-div, #color-div, #recent-ips-div, #theme-div, #maps-div').hide();
	var passwordDown = false, colorDown = false, orderDown = false, searchDown = false, ipsDown = false, themeDown = false, mapsDown = false;

	// cache the DOM
	var $passwordDropdown = $('.password_span'), $orderDropdown = $('.order_dropdown_span'), $searchDropdown = $('.search_dropdown_span'),
		$colorDropdown = $('.color_dropdown_span'), $recentIps = $('#recent-ips-div'), $ipsDropdown = $('.recent_ips_span'),
		$themeDropdown = $('.theme_dropdown_span'), $mapsDropdown = $('.maps_dropdown_span');

	/**
	* @function localStorageTest
	*
	* Checks that the localStorage is enabled on the users browser.
	**/
	function localStorageTest() {
		var test = 'test';
		try {
			localStorage.setItem(test, test);
			localStorage.removeItem(test);
			return true;
		} catch(e) {
			return false;
		}
	}

	/**
	* @function String format
	*
	* Add functionality to String object, for C# style string formatting.
	* Usage: "{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
	* From; http://stackoverflow.com/a/4673436
	**/
	if (!String.prototype.format) {
		String.prototype.format = function() {
			var args = arguments;
			return this.replace(/{(\d+)}/g, function(match, number) {
				return typeof args[number] != 'undefined' ? args[number] : match;
			});
		};
	}

	if(localStorage.getItem('theme') === 'light') {
		$('html').removeClass('dark-theme');
		$('.container-fluid.account-dark').removeClass('account-dark');
	} else if(localStorage.getItem('theme') === 'dark') {
		$('html').addClass('dark-theme');
		$('.container-fluid.account-dark').addClass('account-dark');
	}

	getSettings();
	/**
	* @function
	*
	* Will get the users chosen tag color from the database.
	**/
	function getSettings() {
		$.ajax({
			method: 'POST',
			url: 'includes/user-settings.php',
			data: {
				id: userId,
				action: 'get-settings'
			}
		})
		.done(function(data, result) {
			data = JSON.parse(data);
			populateOptions(data);

		})
		.fail(function(error) {
			console.log('An error occurred', error);
		});
	}

	function populateOptions(data) {
		var color = data[0];
		var order = data[1];

		var $selectColor = $('#select-tag-color');
		var $item = $selectColor.find('option[value={0}]'.format(color));
		$item.remove();
		$selectColor.find('option:eq(0)').before($item);
		$('#select-tag-color > option:eq(0)').attr('selected', true);

		$noteOrder = $('#options-note-order');
		$item = $noteOrder.find('option[value={0}]'.format(order));
		$item.remove();
		$noteOrder.find('option:eq(0)').before($item);
		$('#options-note-order > option:eq(0)').attr('selected', true);

		if(data[2] === "true") {
			$('#search_title').prop('checked', true);
		}

		if(data[3] === "true") {
			$('#search_text').prop('checked', true);
		}

		if(data[4] === "true") {
			$('#search_mark_done').prop('checked', true);
		}

		$('#total_notes').append(data[5]);

		data[6].reverse();
		$recentIps.append('Most Recent');
		$.each(data[6], function(i, v) {
			$recentIps.append('
{0}
'.format(v));
		});

		if(data[7] === 'dark') {
			$('#theme_checkbox').prop('checked', true);
		}

		localStorage.setItem('theme', data[7]);
	}

	/**
	*@function
	*
	* Will update the users chosen color in the database
	**/
	$('#tag-color-button').on('click', function() {
		var color = $('#select-tag-color').val();

		$.ajax({
			method: 'POST',
			url: 'includes/user-settings.php',
			data: {
				color: color,
				id: userId,
				action: 'set-tag-color'
			}
		})
		.done(function(data, status) {
			toastr.success('Tag color updated!');
		})
		.fail(function(error) {
			console.log('An error occurred', error);
		});
	});

	/**
	*@function
	*
	* Will update the users chosen order to sidplay the notes in.
	* Order is taken from a select list.
	**/
	$('#options-order-button').on('click', function() {
		var order = $('#options-note-order').val();

		$.ajax({
			method: 'POST',
			url: 'includes/user-settings.php',
			data: {
				id: userId,
				action: 'set-note-order',
				order: order
			}
		})
		.done(function(data, status) {
			toastr.success('Note order has been successfully updated!');
		})
		.fail(function(error) {
			console.log('An error occurred', error);
		});
	});

	/**
	*@function
	*
	* Will update the users choice of what to search the database for
	* when the search function is used.
	**/
	$('#options-search-button').on('click', function() {
		var title = $('#search_title').is(':checked');
		var text = $('#search_text').is(':checked');
		var searchComplete = $('#search_mark_done').is(':checked');

		if(title === false && text === false) {
			alert('You must chose to search by either one or both of title and text!');
			return;
		}

		$.ajax({
			method: 'POST',
			url: 'includes/user-settings.php',
			data: {
				id: userId,
				action: 'set-search-parameters',
				text: text,
				title: title,
				complete: searchComplete
			}
		})
		.done(function(data, status) {
			toastr.success('Search settings updated!');
		})
		.fail(function(error) {
			console.log('An error occurred', error);
		});
	});

	/**
	* @function
	*
	* Change the users password.
	* Will validate that the user wishes to change their password
	* the old password has something entered into it's field,
	* and that the new password being entered has been confirmed.
	* @param {object} e
	**/
	$('#change-password-form').on('submit', function(e) {
		$('.validation-error').remove();
		var newPassword = $('#new-password').val();
		var confirmPassword = $('#confirm-password').val();
		var old = $('#old-password').val();

		if(!confirm('Please confirm you wish to change your password.')) {
			e.preventDefault();
			return;
		}

		if(old === '') {
			$('#old-password').after('Please enter your old password!');
			e.preventDefault();
			return;
		}

		if(newPassword.trim() === '' || confirmPassword.trim() === '') {
			$('#new-password').after('The new or confirmation input is empty!');
			e.preventDefault();
			return;
		}

		if(newPassword !== confirmPassword) {
			$('#confirm-password').after('The confirmation password is different!');
			e.preventDefault();
			return;
		}
	});

	/**
	* @function
	*
	* Changes the front-end theme.
	**/
	$('#theme-button').on('click', function() {
		var theme = $('#theme_checkbox').is(':checked');
		var color = 'light';

		if(theme) {
			color = 'dark';
		}

		$.ajax({
			method: 'POST',
			url: 'includes/user-settings.php',
			data: {
				action: 'set-theme',
				theme: color,
				id: userId
			}
		})
		.done(function(data, status) {
			data = JSON.parse(data);
			if(data === 'success') {
				if(localStorageTest) {
					localStorage.setItem('theme', color);
					toastr.info('Updated theme settings! Please refresh your page.');
				} else {
					toastr.info('Please log out and back in for changes to take place');
				}

				//if(color === 'light') {
				//	$('html').removeClass('dark-theme');
				//	$('.container-fluid.account-dark').removeClass('account-dark');
				//} else if(color === 'dark') {
				//	$('html').addClass('dark-theme');
				//	$('.container-fluid.account-dark').addClass('account-dark');
				//}
			}
		})
		.fail(function(error) {
			console.log(error);
		});
	});

	/**
	* @function
	* Toggle to show the form to change the users password
	*
	**/
	$('#password-header').on('click', function() {
		$('#password-change').toggle();

		if(passwordDown) {
			$passwordDropdown.addClass('glyphicon-chevron-up');
			$passwordDropdown.removeClass('glyphicon-chevron-down');
			passwordDown = false;
		} else {
			$passwordDropdown.addClass('glyphicon-chevron-down');
			$passwordDropdown.removeClass('glyphicon-chevron-up');
			passwordDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the form for the user to choose their notes color
	*
	**/
	$('#color-header').on('click', function() {
		$('#color-div').toggle();

		if(colorDown) {
			$colorDropdown.addClass('glyphicon-chevron-up');
			$colorDropdown.removeClass('glyphicon-chevron-down');
			colorDown = false;
		} else {
			$colorDropdown.addClass('glyphicon-chevron-down');
			$colorDropdown.removeClass('glyphicon-chevron-up');
			colorDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the form for the user to choose what order to display the notes
	*
	**/
	$('#order-header').on('click', function() {
		$('#order-div').toggle();

		if(orderDown) {
			$orderDropdown.addClass('glyphicon-chevron-up');
			$orderDropdown.removeClass('glyphicon-chevron-down');
			orderDown = false;
		} else {
			$orderDropdown.addClass('glyphicon-chevron-down');
			$orderDropdown.removeClass('glyphicon-chevron-up');
			orderDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the form for the user to customise the search option
	*
	**/
	$('#search-header').on('click', function() {
		$('#search-div').toggle();

		if(searchDown) {
			$searchDropdown.addClass('glyphicon-chevron-up');
			$searchDropdown.removeClass('glyphicon-chevron-down');
			searchDown = false;
		} else {
			$searchDropdown.addClass('glyphicon-chevron-down');
			$searchDropdown.removeClass('glyphicon-chevron-up');
			searchDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the list of recently used IPs
	*
	**/
	$('#recent-ips-header').on('click', function() {
		$('#recent-ips-div').toggle();

		if(ipsDown) {
			$ipsDropdown.addClass('glyphicon-chevron-up');
			$ipsDropdown.removeClass('glyphicon-chevron-down');
			ipsDown = false;
		} else {
			$ipsDropdown.addClass('glyphicon-chevron-down');
			$ipsDropdown.removeClass('glyphicon-chevron-up');
			ipsDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the form for the user to choose what theme to use - currently dark or light theme.
	*
	**/
	$('#theme-header').on('click', function() {
		$('#theme-div').toggle();

		if(themeDown) {
			$themeDropdown.addClass('glyphicon-chevron-up');
			$themeDropdown.removeClass('glyphicon-chevron-down');
			themeDown = false;
		} else {
			$themeDropdown.addClass('glyphicon-chevron-down');
			$themeDropdown.removeClass('glyphicon-chevron-up');
			themeDown = true;
		}
	});

	/**
	* @function
	* Toggle to show the form for the user to choose what theme to use - currently dark or light theme.
	*
	**/
	$('#maps-header').on('click', function() {
		$('#maps-div').toggle();

		if(mapsDown) {
			$mapsDropdown.addClass('glyphicon-chevron-up');
			$mapsDropdown.removeClass('glyphicon-chevron-down');
			mapsDown = false;
		} else {
			$mapsDropdown.addClass('glyphicon-chevron-down');
			$mapsDropdown.removeClass('glyphicon-chevron-up');
			mapsDown = true;
		}
	});

	/**
	* @function Anonymous Geolocation function
	*
	* Checks that Geolocation API can be used, and then gets the users latitude and longitude from this.
	* Uses Google Maps API to then get a map of the users coordinates, which is then displayed in an image.
	* Posts the users coordinates into the database for future use.
	**/
	if("geolocation" in navigator) {
		navigator.geolocation.getCurrentPosition(function(position) {
			console.log(position.coords.latitude, position.coords.longitude);
			var longitude = position.coords.longitude;
			var latitude = position.coords.latitude;

			var img = new Image();
			// need an access key for google
			img.src = 'https://maps.googleapis.com/maps/api/staticmap?center=' + latitude + ',' + longitude + '&zoom=13&size=300x300&sensor=false';

			// place the image on the page.
			$('#map_location').append(img);

			$.ajax({
				url: 'includes/user-settings.php',
				method: 'POST',
				data: {
					action: 'location',
					latitude: latitude,
					longitude: longitude,
					id: userId
				}
			})
			.done(function(data) {
				data = JSON.parse(data);
				if(data === 'success') {
					console.log('Saved');
				}
			})
			.error(function(data) {
				console.warn('Could not save location');
			});
		});
	} else {
		console.warn('Geolocation is not available');
	}

})();<|endoftext|>


<commit_before>'use strict'
/*
**
**Blobber Server
**Written by Sandeep Vattapparambil
**sandeepv68@gmail.com
**
*/

var express = require('express')/*Import the express module*/
var app = express()/*Instantiate express module*/

/*Routing*/
app.get('/', function (req, res) {
  res.send('Hello World!')
})

/*express server*/
app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})
<commit_msg>ejs updates<commit_after>/*
**
**Blobber Server
**Written by Sandeep Vattapparambil
**sandeepv68@gmail.com
**
*/
'use strict'
var express = require('express')/*Import the express module*/
var app = express()/*Instantiate express module*/
var ejs = require('ejs')/*Import Embedded JavaScript Templating*/

/*Routing*/
app.get('/', function (req, res) {
  res.send('Hello World!')
})

/*express server*/
app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})
<|endoftext|>


<commit_before>'use strict';

angular.module('ddsCommon').constant('droitsDescription', [
    {
        'id':'cmu_c',
        'hasMontant':false,
        'label':'Couverture Maladie Universelle Complémentaire',
        'shortLabel':'CMU-C',
        'description':'La CMU-C est une protection complémentaire santé gratuite accordée aux personnes remplissant certaines conditions de résidence et de ressources.',
        'imgSrc':'logo_cmu.png',
        'link':'http://www.cmu.fr/cmu-complementaire.php'
    },
    {
        'id':'acs',
        'isMontantAnnuel':true,
        'label':'Aide pour une Complémentaire Santé',
        'shortLabel':'ACS',
        'description':'L’aide pour l’acquisition d’une assurance complémentaire santé, dite ACS, est une aide financière pour payer une complémentaire santé (exemple : une mutuelle).',
        'imgSrc':'logo_cmu.png',
        'link':'http://www.cmu.fr/acs.php'
    },
    {
        'id':'aspa',
        'label':'Allocation de Solidarité aux Personnes Âgées',
        'shortLabel':'ASPA',
        'description':'L’allocation de solidarité aux personnes âgées (Aspa) est une allocation destinée aux personnes âgées disposant de faibles revenus en vue de leur assurer un niveau minimum de ressources. Elle remplace le minimum vieillesse depuis 2006.',
        'imgSrc':'logo_aspa.png',
        'link':'http://vosdroits.service-public.fr/particuliers/F16871.xhtml'
    },
    {
        'id':'asi',
        'label':'Allocation Supplémentaire d’Invalidité',
        'shortLabel':'ASI',
        'description':'L’allocation supplémentaire d’invalidité (Asi) est une prestation versée sous certaines conditions aux personnes invalides titulaires d’une pension de retraite ou d’invalidité qui n’ont pas atteint l’âge légal de départ à la retraite pour bénéficier de l’allocation de solidarité aux personnes âgées (Aspa)',
        'imgSrc':'logo_aspa.png',
        'link':'http://vosdroits.service-public.fr/particuliers/F16940.xhtml'
    },
    {
        'id':'af',
        'label':'Allocations Familiales',
        'shortLabel':'AF',
        'description':'Les allocations familiales sont versées, sans condition de ressources, aux personnes ayant au moins 2 enfants de moins de 20 ans à charge. Le montant des prestations dépend du nombre d’enfants à charge et de leur âge.',
        'imgSrc':'logo_caf.png',
        'link':'http://www.caf.fr/aides-et-services/s-informer-sur-les-aides/petite-enfance/les-allocations-familiales-af-0'
    },
    {
        'id':'cf',
        'label':'Complément Familial',
        'shortLabel':'CF',
        'description':'Le complément familial est versé, sous certaines conditions, aux personnes ayant au moins 3 enfants à charge.',
        'imgSrc':'logo_caf.png',
        'link':'http://www.caf.fr/aides-et-services/s-informer-sur-les-aides/enfance-et-jeunesse/le-complement-familialcf',
        'isBaseRessourcesYearMoins2':true
    },
    {
        'id':'asf',
        'label':'Allocation de Soutien Familial',
        'shortLabel':'ASF',
        'description':'L’ASF est versée par la CAF ou la MSA au parent qui élève seul son enfant ou à la personne qui a recueilli un enfant, qu’elle vive seule ou en couple.',
        'imgSrc':'logo_caf.png',
        'link':'http://vosdroits.service-public.fr/particuliers/F815.xhtml'
    },
    {
        'id':'paje_base',
        'label':'Prestation d’Accueil du Jeune Enfant - Allocation de base',
        'shortLabel':'PAJE-BASE',
        'description': 'L’allocation de base vous aide à assurer les dépenses liées à l’entretien et à l’éducation de votre enfant.',
        'imgSrc':'logo_caf.png',
        'link':'https://www.caf.fr/aides-et-services/s-informer-sur-les-aides/petite-enfance/l-allocation-de-base',
        'isBaseRessourcesYearMoins2':true
    },
    {
        'id':'rsa',
        'label':'Revenu de Solidarité Active',
        'shortLabel':'RSA',
        'description':'Le RSA est destiné à assurer aux personnes disposant de faibles ressources un niveau minimum de revenu variable selon la composition de leur foyer.',
        'imgSrc':'logo_rsa.png',
        'link':'http://vosdroits.service-public.fr/particuliers/N19775.xhtml'
    },
    {
        'id':'aide_logement',
        'label':'Aide au Logement',
        'shortLabel':'AL',
        'description':'L\'aide au logement est une aide financière destinée à réduire le montant de votre loyer ou votre mensualité d’emprunt immobilier. Elle est attribuée selon la nature de votre logement et la composition de votre famille.',
        'imgSrc':'logo_caf.png',
        'link':'https://www.caf.fr/aides-et-services/s-informer-sur-les-aides/logement-et-cadre-de-vie/les-aides-au-logement-0',
        'isBaseRessourcesYearMoins2':true,
        'montantInconnuDisclaimer': 'Votre situation ne nous permet pas de calculer le montant de l\'aide au logement.
Le simulateur de la caf pourra mieux vous renseigner.'
    },
    {
        'id':'apl',
        'shortLabel':'APL',
        'isSimulated': false
    },
    {
        'id':'alf',
        'shortLabel':'ALF',
        'isSimulated': false
    },
    {
        'id':'als',
        'shortLabel':'ALS',
        'isSimulated': false
    },
    {
        'id':'ass',
        'label':'Allocation de Solidarité Spécifique',
        'shortLabel':'ASS',
        'description':'L’allocation de solidarité spécifique (ASS) est une aide financière destinée aux personnes ayant épuisé leurs droits aux allocations chômage.',
        'imgSrc':'logo_ass.png',
        'link':'http://vosdroits.service-public.fr/particuliers/F12484.xhtml'
    },
    {
        'id':'bourse_college',
        'isMontantAnnuel':true,
        'label':'Bourse de collège',
        'shortLabel':'Bourse collège',
        'description':'La bourse des collèges est une aide destinée à favoriser la scolarité des collégiens. Elle est versée sous conditions de ressources.',
        'imgSrc':'logo_education_nationale.png',
        'link':'http://www.education.gouv.fr/cid88/les-aides-financieres-au-college.html#Les%20bourses%20de%20coll%C3%A8ge',
        'isBaseRessourcesYearMoins2':true
    },
    {
        'id':'bourse_lycee',
        'isMontantAnnuel':true,
        'label':'Bourse de lycée',
        'shortLabel':'Bourse lycée',
        'description':'La bourse des lycées est accordée, sous condition de ressources, à la famille d’un lycéen. Son montant dépend des ressources et des charges de la famille.',
        'imgSrc':'logo_education_nationale.png',
        'link':'http://www.education.gouv.fr/cid151/aides-financieres-au-lycee.html#Les%20bourses%20de%20lycée',
        'isBaseRessourcesYearMoins2':true,
        'isSimulated': false
    }
]);
<commit_msg>complète texte de présentation de la bourse de lycée<commit_after>'use strict';

angular.module('ddsCommon').constant('droitsDescription', [
    {
        'id':'cmu_c',
        'hasMontant':false,
        'label':'Couverture Maladie Universelle Complémentaire',
        'shortLabel':'CMU-C',
        'description':'La CMU-C est une protection complémentaire santé gratuite accordée aux personnes remplissant certaines conditions de résidence et de ressources.',
        'imgSrc':'logo_cmu.png',
        'link':'http://www.cmu.fr/cmu-complementaire.php'
    },
    {
        'id':'acs',
        'isMontantAnnuel':true,
        'label':'Aide pour une Complémentaire Santé',
        'shortLabel':'ACS',
        'description':'L’aide pour l’acquisition d’une assurance complémentaire santé, dite ACS, est une aide financière pour payer une complémentaire santé (exemple : une mutuelle).',
        'imgSrc':'logo_cmu.png',
        'link':'http://www.cmu.fr/acs.php'
    },
    {
        'id':'aspa',
        'label':'Allocation de Solidarité aux Personnes Âgées',
        'shortLabel':'ASPA',
        'description':'L’allocation de solidarité aux personnes âgées (Aspa) est une allocation destinée aux personnes âgées disposant de faibles revenus en vue de leur assurer un niveau minimum de ressources. Elle remplace le minimum vieillesse depuis 2006.',
        'imgSrc':'logo_aspa.png',
        'link':'http://vosdroits.service-public.fr/particuliers/F16871.xhtml'
    },
    {
        'id':'asi',
        'label':'Allocation Supplémentaire d’Invalidité',
        'shortLabel':'ASI',
        'description':'L’allocation supplémentaire d’invalidité (Asi) est une prestation versée sous certaines conditions aux personnes invalides titulaires d’une pension de retraite ou d’invalidité qui n’ont pas atteint l’âge légal de départ à la retraite pour bénéficier de l’allocation de solidarité aux personnes âgées (Aspa)',
        'imgSrc':'logo_aspa.png',
        'link':'http://vosdroits.service-public.fr/particuliers/F16940.xhtml'
    },
    {
        'id':'af',
        'label':'Allocations Familiales',
        'shortLabel':'AF',
        'description':'Les allocations familiales sont versées, sans condition de ressources, aux personnes ayant au moins 2 enfants de moins de 20 ans à charge. Le montant des prestations dépend du nombre d’enfants à charge et de leur âge.',
        'imgSrc':'logo_caf.png',
        'link':'http://www.caf.fr/aides-et-services/s-informer-sur-les-aides/petite-enfance/les-allocations-familiales-af-0'
    },
    {
        'id':'cf',
        'label':'Complément Familial',
        'shortLabel':'CF',
        'description':'Le complément familial est versé, sous certaines conditions, aux personnes ayant au moins 3 enfants à charge.',
        'imgSrc':'logo_caf.png',
        'link':'http://www.caf.fr/aides-et-services/s-informer-sur-les-aides/enfance-et-jeunesse/le-complement-familialcf',
        'isBaseRessourcesYearMoins2':true
    },
    {
        'id':'asf',
        'label':'Allocation de Soutien Familial',
        'shortLabel':'ASF',
        'description':'L’ASF est versée par la CAF ou la MSA au parent qui élève seul son enfant ou à la personne qui a recueilli un enfant, qu’elle vive seule ou en couple.',
        'imgSrc':'logo_caf.png',
        'link':'http://vosdroits.service-public.fr/particuliers/F815.xhtml'
    },
    {
        'id':'paje_base',
        'label':'Prestation d’Accueil du Jeune Enfant - Allocation de base',
        'shortLabel':'PAJE-BASE',
        'description': 'L’allocation de base vous aide à assurer les dépenses liées à l’entretien et à l’éducation de votre enfant.',
        'imgSrc':'logo_caf.png',
        'link':'https://www.caf.fr/aides-et-services/s-informer-sur-les-aides/petite-enfance/l-allocation-de-base',
        'isBaseRessourcesYearMoins2':true
    },
    {
        'id':'rsa',
        'label':'Revenu de Solidarité Active',
        'shortLabel':'RSA',
        'description':'Le RSA est destiné à assurer aux personnes disposant de faibles ressources un niveau minimum de revenu variable selon la composition de leur foyer.',
        'imgSrc':'logo_rsa.png',
        'link':'http://vosdroits.service-public.fr/particuliers/N19775.xhtml'
    },
    {
        'id':'aide_logement',
        'label':'Aide au Logement',
        'shortLabel':'AL',
        'description':'L\'aide au logement est une aide financière destinée à réduire le montant de votre loyer ou votre mensualité d’emprunt immobilier. Elle est attribuée selon la nature de votre logement et la composition de votre famille.',
        'imgSrc':'logo_caf.png',
        'link':'https://www.caf.fr/aides-et-services/s-informer-sur-les-aides/logement-et-cadre-de-vie/les-aides-au-logement-0',
        'isBaseRessourcesYearMoins2':true,
        'montantInconnuDisclaimer': 'Votre situation ne nous permet pas de calculer le montant de l\'aide au logement.
Le simulateur de la caf pourra mieux vous renseigner.'
    },
    {
        'id':'apl',
        'shortLabel':'APL',
        'isSimulated': false
    },
    {
        'id':'alf',
        'shortLabel':'ALF',
        'isSimulated': false
    },
    {
        'id':'als',
        'shortLabel':'ALS',
        'isSimulated': false
    },
    {
        'id':'ass',
        'label':'Allocation de Solidarité Spécifique',
        'shortLabel':'ASS',
        'description':'L’allocation de solidarité spécifique (ASS) est une aide financière destinée aux personnes ayant épuisé leurs droits aux allocations chômage.',
        'imgSrc':'logo_ass.png',
        'link':'http://vosdroits.service-public.fr/particuliers/F12484.xhtml'
    },
    {
        'id':'bourse_college',
        'isMontantAnnuel':true,
        'label':'Bourse de collège',
        'shortLabel':'Bourse collège',
        'description':'La bourse des collèges est une aide destinée à favoriser la scolarité des collégiens. Elle est versée sous conditions de ressources.',
        'imgSrc':'logo_education_nationale.png',
        'link':'http://www.education.gouv.fr/cid88/les-aides-financieres-au-college.html#Les%20bourses%20de%20coll%C3%A8ge',
        'isBaseRessourcesYearMoins2':true
    },
    {
        'id':'bourse_lycee',
        'isMontantAnnuel':true,
        'label':'Bourse de lycée',
        'shortLabel':'Bourse lycée',
        'description':'La bourse des lycées est accordée, sous condition de ressources, à la famille d’un lycéen. Son montant dépend des ressources et des charges de la famille. A noter que cette bourse peut être accompagnée de diverses primes (prime d’équipement, prime à la qualification, bourse au mérite au lycée, prime à l’internat...) dont le montant n’est pas inclus ici.',
        'imgSrc':'logo_education_nationale.png',
        'link':'http://www.education.gouv.fr/cid151/aides-financieres-au-lycee.html#Les%20bourses%20de%20lycée',
        'isBaseRessourcesYearMoins2':true,
        'isSimulated': false
    }
]);
<|endoftext|>


<commit_before>

document.addEventListener('DOMContentLoaded', function() {
  //run the code
//call all the elements I think I need
  var racerTable = document.querySelector('.racer_table');
//these vars below are redundent I think
  var player1 = player1Track.querySelectorAll('td');
  var player2 = player2Track.querySelectorAll('td');
  var player1Track = document.querySelector('#player1_strip');
  var player2Track = document.querySelector('#player2_strip');
//  var playerPosition = document.querySelectorAll('.active');
 // var tablePosition = document.querySelectorAll("td");
  var tracks = document.querySelectorAll("tr");
  var start1 = 1;
  var start2 =1;
  var race = document.addEventListener('keyup', updatePlayerPosition);
  var lengthOfTrack = 7;
  var restart = false;

  lengthOfTrack = prompt("How far do you want to race? 1-20 parsecs?");

//create how long the track is
//loops for 'number' of player tracks, how many 'tr's there are -no of players?
                for (var i = 0; i < tracks.length; i++) {
                    //loop for 'length' of tracks
                    for (var j = 0; j < lengthOfTrack.length; j++) {
                        var parsec = document.createElement('td');
                        tracks[i].appendChild(parsec);
                    }
                    //set last cell in array as finish line
                    parsec.className = "finish"
                };

restartGame()
//enacted everytime a key is released
  function updatePlayerPosition(event) {
    //if 'a' is pressed player 1
    if (event.which === 13) {
//change position function is called on player 1, start position is incremented
        changePosition(player1);
        if (player1Track[start1].className === "active") {
            player1Track[start1].className = "active";
            player1Track[start1-1].className = "";
            start1 +=1;
        }
        else if (player1Track[start1].className === "finish") {
                player1Track[start1-1].className = "";
                alert("Congratulations Star Racer, you've won!");
                restart = confirm("Play again?");
                //laura code: when player reaches end, cel is not incremented
                if (restart) {
                    restartGame()
                } else {
                    race = document.removeEventlistener('keyup', updatePlayerPosition);
                }
        }
        }
    //if enter is pressed, update changes on player 2
        else if (event.which === 97) {
            changePosition(player2);
            if (player2Track[start2].className === "active") {
                player2Track[start2].className = "active";
                player2Track[start2-1].className = "";
                start2 +=1;
        }
            else if (player1Track[start1].className === "finish") {
                player1Track[start1-1].className = "";
                alert("Congratulations Star Racer, you've won!");
                restart = confirm("Play again?");
                 if (restart) {
                    restartGame()
                } else {
                    play = document.removeEventlistener('keyup', updatePlayerPosition);
                }
            }
    };

function restartGame() {
    player1Track = document.querySelectorAll('#player1_strip td');
    player2Track = document.querySelectorAll('#player2_strip td');
//back to number 1's
    start1 = 1;
    start2 = 1;
//   remove class names from all cells and sets first cell as start
    for (var i = 0; i < player1Track.length-1; i++) {
        player1Track[i].className = "";
        player2Track[i].className = "";
        player1Track[0].className = "active";
        player2Track[0].className = "active";

        restart = false;
    };
  };
})<commit_msg>when applied, this commit will check<commit_after>

document.addEventListener('DOMContentLoaded', function() {
  //run the code
//call all the elements I think I need
  var racerTable = document.querySelector('.racer_table');
//these vars below are redundent I think
  var player1 = player1Track.querySelectorAll('td');
  var player2 = player2Track.querySelectorAll('td');
  var playerTrack
  var player1Track = document.querySelector('#player1_strip');
  var player2Track = document.querySelector('#player2_strip');
//  var playerPosition = document.querySelectorAll('.active');
 // var tablePosition = document.querySelectorAll("td");
  var tracks = document.querySelectorAll("tr");
  var start1 = 1;
  var start2 =1;
  var race = document.addEventListener('keyup', selectPlayer, false);
  var lengthOfTrack = 7;
  var restart = false;

  lengthOfTrack = prompt("How far do you want to race? 1-20 parsecs?");

//create how long the track is
//loops for 'number' of player tracks, how many 'tr's there are -no of players?
                for (var i = 0; i < tracks.length; i++) {
                    //loop for 'length' of tracks
                    for (var j = 0; j < lengthOfTrack.length; j++) {
                        var parsec = document.createElement('td');
                        tracks[i].appendChild(parsec);
                    }
                    //set last cell in array as finish line
                    parsec.className = "finish"
                };

}

restartGame()

  function selectPlayer() {
    var player
    if (event.which === 13) {
        playerTrack = player1Track;
        start = start1;
    } else if (event.which === 97) {
        playerTrack = player2Track;
        start = start2;
    }
    updatePlayerPosition(playerTrack, start)

//enacted everytime a key is released
  function updatePlayerPosition(playerTrack, start) {
    //if 'a' is pressed player 1
    if (event.which === 13) {
//change position function is called on player 1, start position is incremented
        if (player1Track[start1].className === "active") {
            player1Track[start1].className = "active";
            player1Track[start1-1].className = "";
            start1 +=1;
        }
        else if (player1Track[start1].className === "finish") {
                player1Track[start1-1].className = "";
                alert("Congratulations Star Racer, you've won!");
                restart = confirm("Play again?");
                //laura code: when player reaches end, cel is not incremented
                if (restart) {
                    restartGame()
                } else {
                    race = document.removeEventlistener('keyup', updatePlayerPosition);
                }
        }
        }
    //if enter is pressed, update changes on player 2
        else if (event.which === 97) {
            changePosition(player2);
            if (player2Track[start2].className === "active") {
                player2Track[start2].className = "active";
                player2Track[start2-1].className = "";
                start2 +=1;
        }
            else if (player1Track[start1].className === "finish") {
                player1Track[start1-1].className = "";
                alert("Congratulations Star Racer, you've won!");
                restart = confirm("Play again?");
                 if (restart) {
                    restartGame()
                } else {
                    play = document.removeEventlistener('keyup', updatePlayerPosition);
                }
            }
    };

function restartGame() {
    player1Track = document.querySelectorAll('#player1_strip td');
    player2Track = document.querySelectorAll('#player2_strip td');
//back to number 1's
    start1 = 1;
    start2 = 1;
//   remove class names from all cells and sets first cell as start
    for (var i = 0; i < player1Track.length-1; i++) {
        player1Track[i].className = "";
        player2Track[i].className = "";
        player1Track[0].className = "active";
        player2Track[0].className = "active";

        restart = false;
    };
  };
})<|endoftext|>