<commit_before>'use strict';

$(function() {

    //
    // Period for simple moving average.
    //
    var smaPeriod = 30;

    //
    // Data loaded for the current graph.
    //
    var curDataFrame = null;

    //
    // Default company code.
    //
    var defaultCompanyCode = 'ABC.AX';

    //
    // Used to suppress chart reload while resizing the chart.
    //
    var resizingChart = false;

	/*
	 * Generate a simple moving average from the series.
	 */
    var computeSmaSeries = function (series, period) {

    	assert.isNumber(period, "Expected 'period' parameter to 'sma' to be a number that specifies the time period of the moving average.");

        return series.rollingWindow(period)
            .asPairs()
            .select(function (pair) {
                var window = pair[1];
                return [window.getIndex().last(), window.average()];
            })
            .asValues()
            ;
    };

    //
    // Load data in format required by highstock.
    //
    var loadHighstockData = function (code, options) {

        var extendedOptions = $.extend({}, options, {
            baseUrl: location.protocol + '//' + location.hostname + ':' + location.port + '/yahoo',
        });

        return dataForge.fromYahoo(code, extendedOptions)
            .then(function (dataFrame) {
                curDataFrame = dataFrame.reverse()
                    .setIndex("Date")
                    .bake();
                return curDataFrame;
            });
    };

    //
    // Destroy the existing chart.
    //
    var destroyChart = function () {
        var chart = $('#container').highcharts();
        if (chart) {
            chart.destroy();
        }
    };

    //
    // Destroy and reload the chart.
    //
    var reloadChart = function () {
        destroyChart();
        loadChart();
    };

    $("#company").change(function() {
        reloadChart();
    });

    $('#loadChart').click(function () {
        reloadChart();
    });

    $('#SMA-period').change(function () {
        smaPeriod = $('#SMA-period').val();
        var chart = $('#container').highcharts();
        if (chart && curDataFrame) {
            computeSMA(chart, curDataFrame);
        }
    });

    $('#recalcSMA').click(function () {
        smaPeriod = parseInt($('#SMA-period').val());
        var chart = $('#container').highcharts();
        if (chart && curDataFrame) {
            computeSMA(chart, curDataFrame);
        }
    });

    //
    // Load new data depending on the selected date range.
    //
    var afterSetExtremes = function(e) {

        if (resizingChart) {
            // Don't need to reload data when resizing the chart.
            return;
        }

        var chart = $('#container').highcharts();

        chart.showLoading('Loading data...');

        var fromDate = new Date(e.min);
        var toDate = new Date(e.max);
        var elapsedMonths = moment(toDate).diff(fromDate, 'months');
        var interval = 'daily';
        if (elapsedMonths > 50) {
            interval = 'monthly';
        }
        else if (elapsedMonths > 18) {
            interval = 'weekly';
        }

        loadHighstockData(defaultCompanyCode, {
                fromDate: fromDate,
                toDate: toDate,
                interval: interval,
            })
            .then(function (dataFrame) {
                var price = dataFrame.subset(["Date", "Open", "High", "Low", "Close"]).toHighstockOHLC();
                var volume = dataFrame.subset(["Date", "Volume"]).toHighstock();

                chart.series[0].setData(price);
                chart.series[2].setData(volume);

                computeSMA(chart, dataFrame);
                chart.hideLoading();
            })
            .catch(function (err) {
                chart.hideLoading();
                console.error(err);
            });
    };

    //
    // Compute simple moving average of the price.
    //
    var computeSMA = function (chart, dataFrame) {
        var sma = computeSmaSeries(dataFrame.getSeries("Close"), smaPeriod)
            .toHighstock();
        chart.series[1].setData(sma);
    };

    //
    // Resize the chart to fit the page.
    //
    var resizeChart = function () {
        try {
            resizingChart = true;
            var chart = $('#container').highcharts();
            chart.setSize($(window).width(), $(window).height()-50);
        }
        finally {
            resizingChart = false;
        }
    };

    //
    // Load the chart.
    //
    var loadChart = function () {

        var code = $("#company").val();
        console.log('Loading ' + code);

        loadHighstockData(code, {
                interval: 'monthly'
            })
            .then(function (dataFrame) {
                var price = dataFrame.toHighstockOHLC();
                var volume = dataFrame.getSeries("Volume").toHighstock();
                var sma = computeSmaSeries(dataFrame.getSeries("Close"), smaPeriod)
                    .toHighstock();

                var groupingUnits = [
                    [
                        'day',
                        [1]
                    ],
                    [
                        'week',                         // unit name
                        [1]                             // allowed multiples
                    ],
                    [
                        'month',
                        [1, 2, 3, 4, 6]
                    ]
                ];

                var chartOptions =
                {
                    chart: {
                        width: $(window).width(),
                        height: $(window).height()-50
                    },

                    navigator: {
                        adaptToUpdatedData: false,
                        series: [
                            {
                                data: price
                            },
                        ]
                    },

                    scrollbar: {
                        liveRedraw: false
                    },

                    title: {
                        text: code.toUpperCase() + ' price history'
                    },

                    subtitle: {
                        text: 'A demo of Highstock using Data-Forge with data loaded from Yahoo.'
                    },

                    rangeSelector: {
                        buttons: [
                            {
                                type: 'hour',
                                count: 1,
                                text: '1h'
                            },
                            {
                                type: 'day',
                                count: 1,
                                text: '1d'
                            },
                            {
                                type: 'month',
                                count: 1,
                                text: '1m'
                            },
                            {
                                type: 'year',
                                count: 1,
                                text: '1y'
                                }, {
                                type: 'all',
                                text: 'All'
                            }
                        ],
                        inputEnabled: true,
                        selected: 4 // all
                    },

                    xAxis: {
                        events: {
                            afterSetExtremes: afterSetExtremes
                        },
                        minRange: 3600 * 1000 * 24 * 5 // 1 week
                    },

                    yAxis: [
                        {
                            labels: {
                                align: 'right',
                                x: -3
                            },
                            title: {
                                text: 'Price'
                            },
                            height: '60%',
                            lineWidth: 2
                        },
                        {
                            labels: {
                                align: 'right',
                                x: -3
                            },
                            title: {
                                text: 'Volume'
                            },
                            top: '65%',
                            height: '35%',
                            offset: 0,
                            lineWidth: 2
                        }
                    ],

                    series: [
                        {
                            type: 'candlestick',
                            name: 'Price',
                            data: price,
                            dataGrouping: {
                                units: groupingUnits
                            }
                        },
                        {
                            type: 'line',
                            name: 'SMA',
                            color: 'red',
                            data: sma,
                            dataGrouping: {
                                units: groupingUnits
                            },
                            tooltip: {
                                valueDecimals: 5
                            }
                        },
                        {
                            type: 'column',
                            name: 'Volume',
                            data: volume,
                            yAxis: 1,
                            dataGrouping: {
                                units: groupingUnits
                            }
                        }
                    ]
                };

                // create the chart
                $('#container').highcharts('StockChart', chartOptions);
            })
            .catch(function (err) {
                console.error(err.stack || err);
            });
    };

    loadChart();

    //
    // Resize chart when window size changes.
    //
    $(window).resize(function() {
        resizeChart();
    });
});
<commit_msg> Removed use of assert fn.<commit_after>'use strict';

$(function() {

    //
    // Period for simple moving average.
    //
    var smaPeriod = 30;

    //
    // Data loaded for the current graph.
    //
    var curDataFrame = null;

    //
    // Default company code.
    //
    var defaultCompanyCode = 'ABC.AX';

    //
    // Used to suppress chart reload while resizing the chart.
    //
    var resizingChart = false;

	/*
	 * Generate a simple moving average from the series.
	 */
    var computeSmaSeries = function (series, period) {

        return series.rollingWindow(period)
            .asPairs()
            .select(function (pair) {
                var window = pair[1];
                return [window.getIndex().last(), window.average()];
            })
            .asValues()
            ;
    };

    //
    // Load data in format required by highstock.
    //
    var loadHighstockData = function (code, options) {

        var extendedOptions = $.extend({}, options, {
            baseUrl: location.protocol + '//' + location.hostname + ':' + location.port + '/yahoo',
        });

        return dataForge.fromYahoo(code, extendedOptions)
            .then(function (dataFrame) {
                curDataFrame = dataFrame.reverse()
                    .setIndex("Date")
                    .bake();
                return curDataFrame;
            });
    };

    //
    // Destroy the existing chart.
    //
    var destroyChart = function () {
        var chart = $('#container').highcharts();
        if (chart) {
            chart.destroy();
        }
    };

    //
    // Destroy and reload the chart.
    //
    var reloadChart = function () {
        destroyChart();
        loadChart();
    };

    $("#company").change(function() {
        reloadChart();
    });

    $('#loadChart').click(function () {
        reloadChart();
    });

    $('#SMA-period').change(function () {
        smaPeriod = $('#SMA-period').val();
        var chart = $('#container').highcharts();
        if (chart && curDataFrame) {
            computeSMA(chart, curDataFrame);
        }
    });

    $('#recalcSMA').click(function () {
        smaPeriod = parseInt($('#SMA-period').val());
        var chart = $('#container').highcharts();
        if (chart && curDataFrame) {
            computeSMA(chart, curDataFrame);
        }
    });

    //
    // Load new data depending on the selected date range.
    //
    var afterSetExtremes = function(e) {

        if (resizingChart) {
            // Don't need to reload data when resizing the chart.
            return;
        }

        var chart = $('#container').highcharts();

        chart.showLoading('Loading data...');

        var fromDate = new Date(e.min);
        var toDate = new Date(e.max);
        var elapsedMonths = moment(toDate).diff(fromDate, 'months');
        var interval = 'daily';
        if (elapsedMonths > 50) {
            interval = 'monthly';
        }
        else if (elapsedMonths > 18) {
            interval = 'weekly';
        }

        loadHighstockData(defaultCompanyCode, {
                fromDate: fromDate,
                toDate: toDate,
                interval: interval,
            })
            .then(function (dataFrame) {
                var price = dataFrame.subset(["Date", "Open", "High", "Low", "Close"]).toHighstockOHLC();
                var volume = dataFrame.subset(["Date", "Volume"]).toHighstock();

                chart.series[0].setData(price);
                chart.series[2].setData(volume);

                computeSMA(chart, dataFrame);
                chart.hideLoading();
            })
            .catch(function (err) {
                chart.hideLoading();
                console.error(err);
            });
    };

    //
    // Compute simple moving average of the price.
    //
    var computeSMA = function (chart, dataFrame) {
        var sma = computeSmaSeries(dataFrame.getSeries("Close"), smaPeriod)
            .toHighstock();
        chart.series[1].setData(sma);
    };

    //
    // Resize the chart to fit the page.
    //
    var resizeChart = function () {
        try {
            resizingChart = true;
            var chart = $('#container').highcharts();
            chart.setSize($(window).width(), $(window).height()-50);
        }
        finally {
            resizingChart = false;
        }
    };

    //
    // Load the chart.
    //
    var loadChart = function () {

        var code = $("#company").val();
        console.log('Loading ' + code);

        loadHighstockData(code, {
                interval: 'monthly'
            })
            .then(function (dataFrame) {
                var price = dataFrame.toHighstockOHLC();
                var volume = dataFrame.getSeries("Volume").toHighstock();
                var sma = computeSmaSeries(dataFrame.getSeries("Close"), smaPeriod)
                    .toHighstock();

                var groupingUnits = [
                    [
                        'day',
                        [1]
                    ],
                    [
                        'week',                         // unit name
                        [1]                             // allowed multiples
                    ],
                    [
                        'month',
                        [1, 2, 3, 4, 6]
                    ]
                ];

                var chartOptions =
                {
                    chart: {
                        width: $(window).width(),
                        height: $(window).height()-50
                    },

                    navigator: {
                        adaptToUpdatedData: false,
                        series: [
                            {
                                data: price
                            },
                        ]
                    },

                    scrollbar: {
                        liveRedraw: false
                    },

                    title: {
                        text: code.toUpperCase() + ' price history'
                    },

                    subtitle: {
                        text: 'A demo of Highstock using Data-Forge with data loaded from Yahoo.'
                    },

                    rangeSelector: {
                        buttons: [
                            {
                                type: 'hour',
                                count: 1,
                                text: '1h'
                            },
                            {
                                type: 'day',
                                count: 1,
                                text: '1d'
                            },
                            {
                                type: 'month',
                                count: 1,
                                text: '1m'
                            },
                            {
                                type: 'year',
                                count: 1,
                                text: '1y'
                                }, {
                                type: 'all',
                                text: 'All'
                            }
                        ],
                        inputEnabled: true,
                        selected: 4 // all
                    },

                    xAxis: {
                        events: {
                            afterSetExtremes: afterSetExtremes
                        },
                        minRange: 3600 * 1000 * 24 * 5 // 1 week
                    },

                    yAxis: [
                        {
                            labels: {
                                align: 'right',
                                x: -3
                            },
                            title: {
                                text: 'Price'
                            },
                            height: '60%',
                            lineWidth: 2
                        },
                        {
                            labels: {
                                align: 'right',
                                x: -3
                            },
                            title: {
                                text: 'Volume'
                            },
                            top: '65%',
                            height: '35%',
                            offset: 0,
                            lineWidth: 2
                        }
                    ],

                    series: [
                        {
                            type: 'candlestick',
                            name: 'Price',
                            data: price,
                            dataGrouping: {
                                units: groupingUnits
                            }
                        },
                        {
                            type: 'line',
                            name: 'SMA',
                            color: 'red',
                            data: sma,
                            dataGrouping: {
                                units: groupingUnits
                            },
                            tooltip: {
                                valueDecimals: 5
                            }
                        },
                        {
                            type: 'column',
                            name: 'Volume',
                            data: volume,
                            yAxis: 1,
                            dataGrouping: {
                                units: groupingUnits
                            }
                        }
                    ]
                };

                // create the chart
                $('#container').highcharts('StockChart', chartOptions);
            })
            .catch(function (err) {
                console.error(err.stack || err);
            });
    };

    loadChart();

    //
    // Resize chart when window size changes.
    //
    $(window).resize(function() {
        resizeChart();
    });
});
<|endoftext|>


<commit_before>import coreUtils from '@opentripplanner/core-utils'
import React, { Component, createRef } from 'react'
import { connect } from 'react-redux'
import styled from 'styled-components'

import { isBlank } from '../../util/ui'
import {
  excludeLastStop,
  getSecondsUntilDeparture,
  getStopTimesByPattern,
  stopTimeComparator
} from '../../util/viewer'
import StopTimeCell from './stop-time-cell'

const { getTimeFormat } = coreUtils.time

// Styles for the schedule table and its contents.
const StyledTable = styled.table`
  border-spacing: collapse;
  margin-top: 20px;
  width: 100%;
  th {
    font-size: 75%;
  }
  tr > * {
    border-bottom: 1px solid #ccc;
    padding: 2px 0 2px 10px;
    vertical-align: top;
  }
  td:first-child, th:first-child {
    padding-left: 0;
  }
`

const RouteCell = styled.td`
  font-weight: bold;
`
const TimeCell = styled.td`
  font-weight: bold;
  text-align: right;
  white-space: nowrap;
`

class StopScheduleTable extends Component {
  firstDepartureRef = createRef()

  /*
   * Scroll to the first stop time that is departing from now.
   */
  _scrollToFirstDeparture = () => {
    const { current } = this.firstDepartureRef
    if (current) {
      current.scrollIntoView()
    }
  }

  componentDidMount () {
    this._scrollToFirstDeparture()
  }

  componentDidUpdate () {
    this._scrollToFirstDeparture()
  }

  render () {
    const { homeTimezone, stopData, stopViewerArriving, timeFormat } = this.props
    const hasStopTimesAndRoutes = !!(stopData && stopData.stopTimes && stopData.stopTimes.length > 0 && stopData.routes)

    if (!hasStopTimesAndRoutes) {
      return
No stop times found for date.

    }

    const stopTimesByPattern = getStopTimesByPattern(stopData)

    // Merge stop times, so that we can sort them across all route patterns.
    let mergedStopTimes = []
    Object.values(stopTimesByPattern).forEach(({ pattern, route, times }) => {
      const filteredTimes = times
        .filter(excludeLastStop)
        .map(stopTime => {
          // Add the route attribute and headsign to each stop time for rendering route info.
          const headsign = isBlank(stopTime.headsign) ? pattern.headsign : stopTime.headsign
          return {
            ...stopTime,
            route,
            headsign
          }
        })
      mergedStopTimes = mergedStopTimes.concat(filteredTimes)
    })

    mergedStopTimes = mergedStopTimes.sort(stopTimeComparator)

    // Find the next stop time that is departing. We will scroll to that stop time entry.
    let firstDepartureFromNow
    if (mergedStopTimes.length) {
      // Search starting from the last stop time (largest seconds until departure) for this pattern.
      const lastStopTime = mergedStopTimes[mergedStopTimes.length - 1]

      firstDepartureFromNow = mergedStopTimes.reduce((firstStopTime, stopTime) => {
        const firstStopTimeSeconds = getSecondsUntilDeparture(firstStopTime, true)
        const stopTimeSeconds = getSecondsUntilDeparture(stopTime, true)

        return stopTimeSeconds < firstStopTimeSeconds && stopTimeSeconds >= 0
          ? stopTime
          : firstStopTime
      }, lastStopTime)
    }

    return (

    )
  }
}

// connect to redux store

const mapStateToProps = (state, ownProps) => {
  const { config, transitIndex, ui } = state.otp
  return {
    homeTimezone: config.homeTimezone,
    stopData: transitIndex.stops[ui.viewedStop.stopId],
    stopViewerArriving: config.language.stopViewerArriving,
    timeFormat: getTimeFormat(config)
  }
}

const mapDispatchToProps = {
}

export default connect(mapStateToProps, mapDispatchToProps)(StopScheduleTable)
<commit_msg>refactor(StopScheduleTable): Do not render times for pattern without route object.<commit_after>import coreUtils from '@opentripplanner/core-utils'
import React, { Component, createRef } from 'react'
import { connect } from 'react-redux'
import styled from 'styled-components'

import { isBlank } from '../../util/ui'
import {
  excludeLastStop,
  getRouteIdForPattern,
  getSecondsUntilDeparture,
  getStopTimesByPattern,
  stopTimeComparator
} from '../../util/viewer'
import StopTimeCell from './stop-time-cell'

const { getTimeFormat } = coreUtils.time

// Styles for the schedule table and its contents.
const StyledTable = styled.table`
  border-spacing: collapse;
  margin-top: 20px;
  width: 100%;
  th {
    font-size: 75%;
  }
  tr > * {
    border-bottom: 1px solid #ccc;
    padding: 2px 0 2px 10px;
    vertical-align: top;
  }
  td:first-child, th:first-child {
    padding-left: 0;
  }
`

const RouteCell = styled.td`
  font-weight: bold;
`
const TimeCell = styled.td`
  font-weight: bold;
  text-align: right;
  white-space: nowrap;
`

class StopScheduleTable extends Component {
  firstDepartureRef = createRef()

  /*
   * Scroll to the first stop time that is departing from now.
   */
  _scrollToFirstDeparture = () => {
    const { current } = this.firstDepartureRef
    if (current) {
      current.scrollIntoView()
    }
  }

  componentDidMount () {
    this._scrollToFirstDeparture()
  }

  componentDidUpdate () {
    this._scrollToFirstDeparture()
  }

  render () {
    const { homeTimezone, stopData, stopViewerArriving, timeFormat } = this.props
    const hasStopTimesAndRoutes = !!(stopData && stopData.stopTimes && stopData.stopTimes.length > 0 && stopData.routes)

    if (!hasStopTimesAndRoutes) {
      return
No stop times found for date.

    }

    const stopTimesByPattern = getStopTimesByPattern(stopData)

    // Merge stop times, so that we can sort them across all route patterns.
    let mergedStopTimes = []
    Object.values(stopTimesByPattern).forEach(({ pattern, route, times }) => {
      // TODO: refactor the IF block below (copied fromn StopViewer).
      // Only add pattern if route is found.
      // FIXME: there is currently a bug with the alernative transit index
      // where routes are not associated with the stop if the only stoptimes
      // for the stop are drop off only. See https://github.com/ibi-group/trimet-mod-otp/issues/217
      if (!route) {
        console.warn(`Cannot render stop times for missing route ID: ${getRouteIdForPattern(pattern)}`)
        return
      }

      const filteredTimes = times
        .filter(excludeLastStop)
        .map(stopTime => {
          // Add the route attribute and headsign to each stop time for rendering route info.
          const headsign = isBlank(stopTime.headsign) ? pattern.headsign : stopTime.headsign
          return {
            ...stopTime,
            route,
            headsign
          }
        })
      mergedStopTimes = mergedStopTimes.concat(filteredTimes)
    })

    mergedStopTimes = mergedStopTimes.sort(stopTimeComparator)

    // Find the next stop time that is departing. We will scroll to that stop time entry.
    let firstDepartureFromNow
    if (mergedStopTimes.length) {
      // Search starting from the last stop time (largest seconds until departure) for this pattern.
      const lastStopTime = mergedStopTimes[mergedStopTimes.length - 1]

      firstDepartureFromNow = mergedStopTimes.reduce((firstStopTime, stopTime) => {
        const firstStopTimeSeconds = getSecondsUntilDeparture(firstStopTime, true)
        const stopTimeSeconds = getSecondsUntilDeparture(stopTime, true)

        return stopTimeSeconds < firstStopTimeSeconds && stopTimeSeconds >= 0
          ? stopTime
          : firstStopTime
      }, lastStopTime)
    }

    return (

    )
  }
}

// connect to redux store

const mapStateToProps = (state, ownProps) => {
  const { config, transitIndex, ui } = state.otp
  return {
    homeTimezone: config.homeTimezone,
    stopData: transitIndex.stops[ui.viewedStop.stopId],
    stopViewerArriving: config.language.stopViewerArriving,
    timeFormat: getTimeFormat(config)
  }
}

const mapDispatchToProps = {
}

export default connect(mapStateToProps, mapDispatchToProps)(StopScheduleTable)
<|endoftext|>


<commit_before>
/**
 * UI Layout Class
 * @class UI.Layout
 * @implements {Events, Options}
 */
define([
	"UI/Container/Container",
	"UI/Layout/Component",
	"UI/Layout/Resize"
], function(
	Container,
	Component,
	Resize
) {

	var _log = __debug('ui:layout');

	var exports = new Class({

		Implements: [Events, Options, Component, Resize],

		/**
		 * Layout options
		 * @type {Object}
		 * @param {name} [name] layout
		 * @param {Object} [clss] Default component class
		 */
		options: {
			name: 'layout',
			clss: Container,
			settings: {}
		},

		/**
		 * [initialize description]
		 * @param  {[type]} options [description]
		 * @return {[type]}         [description]
		 */
		initialize: function(options){
			this.setOptions(options);

			this._initLayout(this.options);

			return this;
		},

		/**
		 * [_initLayout description]
		 * @return {[type]} [description]
		 */
		_initLayout: function(opts) {
			//_log.debug('initialize', opts);
			var node = opts.node;
			this.settings = opts.settings || {};
			this.component = {};
			this.components = [];
			this.resizer = {};

			this._initContainer(opts);
			this._processComponents(node);
			this._initEvents();
		},

		/**
		 * [_initEvents description]
		 * @param  {[type]} opts [description]
		 * @return {[type]}      [description]
		 */
		_initEvents: function(opts) {
			var self = this;

			window.addEvent('resize', function() {
				//_log.debug('layout resize', this.container.getCoordinates());
				var coord = self.container.getCoordinates();
				if (coord.width < 720 && self.navi) {
					self.navi.minimize();
					//self.resizer.navi.hide();
				}
				self.fireEvent('drag');
			});

			(function() {
				self.fireEvent('drag');
			}).delay(1000);
		},

		/**
		 * [_initContainer description]
		 * @return {[type]} [description]
		 */
		_initContainer: function(opts) {

			this.container = new Container({
				resizable: false,
				'class': 'ui-layout layout-' + opts.node._name
			}).inject(opts.container);

			this.mask = new Element('div', {
				'class': 'layout-mask',
			}).inject(this.container);

			//_log.debug('Layout container', this.container);

			this.container.addClass('ui-layout');
			this.container.addClass('layout-' + opts.node._name);

			if (this.options.theme)
				this.container.addClass('theme-' + this.options.theme);

			opts.node.container = this.container;
		},

		/**
		 * [_process description]
		 * @param  {[type]} mnml [description]
		 * @return {[type]}      [description]
		 */
		_processComponents: function(node, type, level) {
			//_log.debug('_processComponents', node, type, level || 1);
			var list = node._list || [];
				level = level++ || 1;

			//_log.debug('---!!! axis', node._axis);

			if (type !== 'tab') {
				this._initFlexDirection(node.container, node._axis);
			}

			for (var i = 0, len = list.length; i < list.length; i++) {
				//_log.debug('--', list[i]);
				var name = list[i],
					comp = node[name] || {};

				comp.clss = comp.clss || this.options.clss;
				comp.opts = comp.opts || {};
				comp.opts.name = name;
				comp.opts.position = i + 1;
				comp.opts.nComp = list.length;

				if (name === "navi")
					comp.opts.useUnderlay = true;

				if (i === list.length - 1) {
					//_log.debug('last--', name);
					comp.opts.last = true;
				}

				if (type !== 'tab') {
					comp.opts.container = node.container;
				}

				var component = this._initComponent(comp);

				if (type === 'tab') {
					//_log.debug('tab', component);
					component.options.noResizer = true;
					node.container.addTab(component);
				}

				component.element.addClass('container-'+name);

				if (comp.node) {
					comp.node.container = component;

					if (component.options.clss === 'tab') {
						var c = this._processComponents(comp.node, 'tab', level);
					} else {
						this._processComponents(comp.node, null, level);
					}
				}
			}
		},

		/**
		 * [_initFlexDirection description]
		 * @param  {[type]} container [description]
		 * @param  {[type]} axis      [description]
		 * @return {[type]}           [description]
		 */
		_initFlexDirection: function(container, axis) {
			//_log.debug('_initFlexDirection', container, axis);

			if (!container) return;

			axis = axis || 'x';

			if (axis === 'x') {
				container.addClass('flex-horizontal');
			} else if (axis === 'y') {
				container.addClass('flex-vertical');
			}
		},

		/**
		 * [setDevice description]
		 * @param {[type]} device [description]
		 */
		setDevice: function(device) {
			//_log.debug('setDevice');

			this.device = device;

			this.fireEvent('device', device);
		}
	});

	return exports;
});
<commit_msg>add destroy method<commit_after>
/**
 * UI Layout Class
 * @class UI.Layout
 * @implements {Events, Options}
 */
define([
	"UI/Container/Container",
	"UI/Layout/Component",
	"UI/Layout/Resize"
], function(
	Container,
	Component,
	Resize
) {

	var _log = __debug('ui:layout');

	var exports = new Class({

		Implements: [Events, Options, Component, Resize],

		/**
		 * Layout options
		 * @type {Object}
		 * @param {name} [name] layout
		 * @param {Object} [clss] Default component class
		 */
		options: {
			name: 'layout',
			clss: Container,
			settings: {}
		},

		/**
		 * [initialize description]
		 * @param  {[type]} options [description]
		 * @return {[type]}         [description]
		 */
		initialize: function(options){
			this.setOptions(options);

			this._initLayout(this.options);

			return this;
		},

		/**
		 * [_initLayout description]
		 * @return {[type]} [description]
		 */
		_initLayout: function(opts) {
			//_log.debug('initialize', opts);
			var node = opts.node;
			this.settings = opts.settings || {};
			this.component = {};
			this.components = [];
			this.resizer = {};

			this._initContainer(opts);
			this._processComponents(node);
			this._initEvents();
		},

		/**
		 * [_initEvents description]
		 * @param  {[type]} opts [description]
		 * @return {[type]}      [description]
		 */
		_initEvents: function(opts) {
			var self = this;

			window.addEvent('resize', function() {
				//_log.debug('layout resize', this.container.getCoordinates());
				var coord = self.container.getCoordinates();
				if (coord.width < 720 && self.navi) {
					self.navi.minimize();
					//self.resizer.navi.hide();
				}
				self.fireEvent('drag');
			});

			(function() {
				self.fireEvent('drag');
			}).delay(1000);
		},

		/**
		 * [_initContainer description]
		 * @return {[type]} [description]
		 */
		_initContainer: function(opts) {

			this.container = new Container({
				resizable: false,
				'class': 'ui-layout layout-' + opts.node._name
			}).inject(opts.container);

			this.mask = new Element('div', {
				'class': 'layout-mask',
			}).inject(this.container);

			//_log.debug('Layout container', this.container);

			this.container.addClass('ui-layout');
			this.container.addClass('layout-' + opts.node._name);

			if (this.options.theme)
				this.container.addClass('theme-' + this.options.theme);

			opts.node.container = this.container;
		},

		/**
		 * [_process description]
		 * @param  {[type]} mnml [description]
		 * @return {[type]}      [description]
		 */
		_processComponents: function(node, type, level) {
			//_log.debug('_processComponents', node, type, level || 1);
			var list = node._list || [];
				level = level++ || 1;

			//_log.debug('---!!! axis', node._axis);

			if (type !== 'tab') {
				this._initFlexDirection(node.container, node._axis);
			}

			for (var i = 0, len = list.length; i < list.length; i++) {
				//_log.debug('--', list[i]);
				var name = list[i],
					comp = node[name] || {};

				comp.clss = comp.clss || this.options.clss;
				comp.opts = comp.opts || {};
				comp.opts.name = name;
				comp.opts.position = i + 1;
				comp.opts.nComp = list.length;

				if (name === "navi")
					comp.opts.useUnderlay = true;

				if (i === list.length - 1) {
					//_log.debug('last--', name);
					comp.opts.last = true;
				}

				if (type !== 'tab') {
					comp.opts.container = node.container;
				}

				var component = this._initComponent(comp);

				if (type === 'tab') {
					//_log.debug('tab', component);
					component.options.noResizer = true;
					node.container.addTab(component);
				}

				component.element.addClass('container-'+name);

				if (comp.node) {
					comp.node.container = component;

					if (component.options.clss === 'tab') {
						var c = this._processComponents(comp.node, 'tab', level);
					} else {
						this._processComponents(comp.node, null, level);
					}
				}
			}
		},

		/**
		 * [_initFlexDirection description]
		 * @param  {[type]} container [description]
		 * @param  {[type]} axis      [description]
		 * @return {[type]}           [description]
		 */
		_initFlexDirection: function(container, axis) {
			//_log.debug('_initFlexDirection', container, axis);

			if (!container) return;

			axis = axis || 'x';

			if (axis === 'x') {
				container.addClass('flex-horizontal');
			} else if (axis === 'y') {
				container.addClass('flex-vertical');
			}
		},

		/**
		 * [setDevice description]
		 * @param {[type]} device [description]
		 */
		setDevice: function(device) {
			//_log.debug('setDevice');

			this.device = device;

			this.fireEvent('device', device);
		},

		destroy: function() {
			this.container.destroy();
		}
	});

	return exports;
});
<|endoftext|>


<commit_before>/* * * + + + + + + + + + + + + + + + + + + + +
Temple360 - An A-frame web viewer for the design
& construction of the 2017 Burning Man temple
Author: Anastasia Victor
+ + + + + + + + + + + + + + + + + + + + * * */

require('aframe');
require('aframe-state-component');
require('aframe-text-geometry-component');
require('aframe-template-component');
require('aframe-layout-component');
require('aframe-animation-component');

require('./globals.js');
require('./materials.js');
require('./userInterface.js');

var isEqual = require('lodash.isequal');
var extras = require('aframe-extras'); //fix for A-frame GLtf 2.0 issues
extras.loaders.registerAll(); //Register 'A-frame extras' Loaders package and its dependencies.
var mainData = require('./mainData.js'); //Get JSON data
var sceneEl = document.querySelector('a-scene'); //Scene element

function getState(event, key){
	return event.target.sceneEl.systems["state"].getState().app[key].toJSON()
}

var localStorageHistoryPlugin = {
	getHistoryArray: function() {
		return JSON.parse(localStorage.getItem('historyArray'));
	},
	peekLastEvent: function() {
		localStorageHistoryArray = JSON.parse(localStorage.getItem('historyArray')) || [];
		return localStorageHistoryArray.pop();
	},
	pushEvent: function(event) {
		var historyArray = localStorage.getItem('historyArray') ?
			JSON.parse(localStorage.getItem('historyArray')) : [];
		historyArray.push(event);
		localStorage.setItem('historyArray', JSON.stringify(historyArray));
	},
	clearHistory: function() {
		localStorage.clear();
	},
};

/* * * + + + + + + + + + + + + + + + + + + + +
State manager --
+ + + + + + + + + + + + + + + + + + + + * * */

AFRAME.registerReducer('app', {
	initialState: {
		locations: mainData.locations,
		models: mainData.models,
		threeSixtyImages: mainData.threeSixtyImages,
		activeLocation: mainData.locations["origin"],
		activeDate: "2017-08-15",
		activeModel: {},
		activeThreeSixty: {},
		activeScene: {},
		history: localStorageHistoryPlugin,
	},

	handlers: {

		changeModels: function (state, action) {
			var models = action.models;
			state.models = models;
			console.log('modelsChanged',models)
			AFRAME.scenes[0].emit('modelsChanged', {models});
			return state;
		},

		changeThreeSixtyImages: function (state, action) {
			var threeSixtyImages = action.threeSixtyImages;
			state.threeSixtyImages = threeSixtyImages;
			console.log('threeSixtyImagesChanged',threeSixtyImages)
			AFRAME.scenes[0].emit('threeSixtyImagesChanged', {threeSixtyImages});
			return state;
		},

		changeLocations: function (state, action) {
			var locations = action.locations;
			state.locations = locations;
			console.log('locationsChanged', locations)
			AFRAME.scenes[0].emit('locationsChanged', {locations});
			return state;
		},

		changeActiveDate: function (state, action) {
			var activeDate = action.activeDate;
			state.activeDate = activeDate;
			console.log('activeDateChanged', activeDate)
			AFRAME.scenes[0].emit('activeDateChanged', {activeDate});
			this.initialState.history.pushEvent(action);
			return state;
		},

		changeActiveLocation: function (state, action) {
			var activeLocation = action.activeLocation;
			state.activeLocation = activeLocation;
			console.log('activeLocationChanged', activeLocation)
			AFRAME.scenes[0].emit('activeLocationChanged', {activeLocation});
			this.initialState.history.pushEvent(action);
			return state;
		},
		changeActiveThreeSixty: function (state, action) {
			var activeThreeSixty = action.activeThreeSixty;
			state.activeThreeSixty = activeThreeSixty;
			console.log('activeThreeSixty', activeThreeSixty)
			AFRAME.scenes[0].emit('activeThreeSixtyChanged', {activeThreeSixty});
			this.initialState.history.pushEvent(action);
			return state;
		},
		changeActiveModel: function (state, action) {
			var activeModel = action.activeModel;
			state.activeModel = activeModel;
			console.log('activeModelChanged', activeModel)
			AFRAME.scenes[0].emit('activeModelChanged', {activeModel});
			this.initialState.history.pushEvent(action);
			return state;
		},
		changeActiveScene: function (state, action) {
			var activeScene = action.activeScene;
			state.activeScene = activeScene;
			console.log('activeSceneChanged', activeScene)
			AFRAME.scenes[0].emit('activeSceneChanged', {activeScene});
			this.initialState.history.pushEvent(action);
			return state;
		},
	},
});

// Hack to ensure initial state gets published to components
window.onload = function() {
	document.querySelector('a-scene').addEventListener('loaded', function () {
		AFRAME.scenes[0].emit('changeModels', {
			models: mainData.models
		});

		AFRAME.scenes[0].emit('changeThreeSixtyImages', {
			threeSixtyImages: mainData.threeSixtyImages
		});

		AFRAME.scenes[0].emit('changeLocations', {
			locations: mainData.locations
		});

		AFRAME.scenes[0].emit('changeActiveLocation', {
			activeLocation: mainData.locations["southGate"]
		});

		AFRAME.scenes[0].emit('changeActiveDate', {
			activeDate: "2017-08-15"
		});

		AFRAME.scenes[0].emit('changeActiveThreeSixty', {
			activeThreeSixty: {}
		});

		AFRAME.scenes[0].emit('changeActiveModel', {
			activeModel: {}
		});

		AFRAME.scenes[0].emit('changeActiveScene', {
			activeScene: 'sceneHome'
		});

	})
}

/* * * + + + + + + + + + + + + + + + + + + + +
Scene Manager
+ + + + + + + + + + + + + + + + + + + + * * */
AFRAME.registerComponent('scene-manager', {
	schema: {
		sceneHome: {type: 'asset', default: 'templates/scene_home.html'},
		scene360: {type: 'asset', default: 'templates/scene_360.html'},
		scene3DModel: {type: 'asset', default: 'templates/scene_model.html'}
	},
	init: function (){
		var self = this
		var el = this.el;
		window.addEventListener('activeSceneChanged',(e)=> {
			nextScene = e.detail.activeScene;
			self.setScene(nextScene)
		});
	},
	setScene: function(nextScene){
		var scene = document.querySelector('a-scene');
		var managers = document.getElementById('managers');
		var sceneTemplate = document.getElementById('scene-template');
		var currentTemplate = sceneTemplate.getAttribute('template').src;

		if(nextScene == 'sceneHome'){
			if(currentTemplate == this.data.scene3DModel){
				this.resetEnv('scene3DModel');
			}
			sceneTemplate.setAttribute('template', 'src:' + this.data.sceneHome);

		}if(nextScene == 'scene360'){
			if(currentTemplate == this.data.scene3DModel){
				this.resetEnv('scene3DModel');
			}
			sceneTemplate.setAttribute('template', 'src:' + this.data.scene360);

		}if(nextScene == 'scene3DModel'){
			if(currentTemplate == this.data.sceneHome){
				this.resetEnv('sceneHome');
			}
			sceneTemplate.setAttribute('template', 'src:' + this.data.scene3DModel);
		}
	},
	resetEnv: function(currentTemplate){
		var env;
		if (currentTemplate == 'scene3DModel'){
			var env = document.querySelector('#model-env')
		}else{
			var env = document.querySelector('#home-env')
		}
		env.setAttribute('environment', {active:false});
	}
});<commit_msg>Change localStorage to sessionStorage.<commit_after>/* * * + + + + + + + + + + + + + + + + + + + +
Temple360 - An A-frame web viewer for the design
& construction of the 2017 Burning Man temple
Author: Anastasia Victor
+ + + + + + + + + + + + + + + + + + + + * * */

require('aframe');
require('aframe-state-component');
require('aframe-text-geometry-component');
require('aframe-template-component');
require('aframe-layout-component');
require('aframe-animation-component');

require('./globals.js');
require('./materials.js');
require('./userInterface.js');

var isEqual = require('lodash.isequal');
var extras = require('aframe-extras'); //fix for A-frame GLtf 2.0 issues
extras.loaders.registerAll(); //Register 'A-frame extras' Loaders package and its dependencies.
var mainData = require('./mainData.js'); //Get JSON data
var sceneEl = document.querySelector('a-scene'); //Scene element

function getState(event, key){
	return event.target.sceneEl.systems["state"].getState().app[key].toJSON()
}

var sessionStorageHistoryPlugin = {
	getHistoryArray: function() {
		return JSON.parse(sessionStorage.getItem('historyArray'));
	},
	peekLastEvent: function() {
		sessionStorageHistoryArray = JSON.parse(sessionStorage.getItem('historyArray')) || [];
		return sessionStorageHistoryArray.pop();
	},
	pushEvent: function(event) {
		var historyArray = sessionStorage.getItem('historyArray') ?
			JSON.parse(sessionStorage.getItem('historyArray')) : [];
		historyArray.push(event);
		sessionStorage.setItem('historyArray', JSON.stringify(historyArray));
	},
	clearHistory: function() {
		sessionStorage.clear();
	},
};

/* * * + + + + + + + + + + + + + + + + + + + +
State manager --
+ + + + + + + + + + + + + + + + + + + + * * */

AFRAME.registerReducer('app', {
	initialState: {
		locations: mainData.locations,
		models: mainData.models,
		threeSixtyImages: mainData.threeSixtyImages,
		activeLocation: mainData.locations["origin"],
		activeDate: "2017-08-15",
		activeModel: {},
		activeThreeSixty: {},
		activeScene: {},
		history: localStorageHistoryPlugin,
	},

	handlers: {

		changeModels: function (state, action) {
			var models = action.models;
			state.models = models;
			console.log('modelsChanged',models)
			AFRAME.scenes[0].emit('modelsChanged', {models});
			return state;
		},

		changeThreeSixtyImages: function (state, action) {
			var threeSixtyImages = action.threeSixtyImages;
			state.threeSixtyImages = threeSixtyImages;
			console.log('threeSixtyImagesChanged',threeSixtyImages)
			AFRAME.scenes[0].emit('threeSixtyImagesChanged', {threeSixtyImages});
			return state;
		},

		changeLocations: function (state, action) {
			var locations = action.locations;
			state.locations = locations;
			console.log('locationsChanged', locations)
			AFRAME.scenes[0].emit('locationsChanged', {locations});
			return state;
		},

		changeActiveDate: function (state, action) {
			var activeDate = action.activeDate;
			state.activeDate = activeDate;
			console.log('activeDateChanged', activeDate)
			AFRAME.scenes[0].emit('activeDateChanged', {activeDate});
			this.initialState.history.pushEvent(action);
			return state;
		},

		changeActiveLocation: function (state, action) {
			var activeLocation = action.activeLocation;
			state.activeLocation = activeLocation;
			console.log('activeLocationChanged', activeLocation)
			AFRAME.scenes[0].emit('activeLocationChanged', {activeLocation});
			this.initialState.history.pushEvent(action);
			return state;
		},
		changeActiveThreeSixty: function (state, action) {
			var activeThreeSixty = action.activeThreeSixty;
			state.activeThreeSixty = activeThreeSixty;
			console.log('activeThreeSixty', activeThreeSixty)
			AFRAME.scenes[0].emit('activeThreeSixtyChanged', {activeThreeSixty});
			this.initialState.history.pushEvent(action);
			return state;
		},
		changeActiveModel: function (state, action) {
			var activeModel = action.activeModel;
			state.activeModel = activeModel;
			console.log('activeModelChanged', activeModel)
			AFRAME.scenes[0].emit('activeModelChanged', {activeModel});
			this.initialState.history.pushEvent(action);
			return state;
		},
		changeActiveScene: function (state, action) {
			var activeScene = action.activeScene;
			state.activeScene = activeScene;
			console.log('activeSceneChanged', activeScene)
			AFRAME.scenes[0].emit('activeSceneChanged', {activeScene});
			this.initialState.history.pushEvent(action);
			return state;
		},
	},
});

// Hack to ensure initial state gets published to components
window.onload = function() {
	document.querySelector('a-scene').addEventListener('loaded', function () {
		AFRAME.scenes[0].emit('changeModels', {
			models: mainData.models
		});

		AFRAME.scenes[0].emit('changeThreeSixtyImages', {
			threeSixtyImages: mainData.threeSixtyImages
		});

		AFRAME.scenes[0].emit('changeLocations', {
			locations: mainData.locations
		});

		AFRAME.scenes[0].emit('changeActiveLocation', {
			activeLocation: mainData.locations["southGate"]
		});

		AFRAME.scenes[0].emit('changeActiveDate', {
			activeDate: "2017-08-15"
		});

		AFRAME.scenes[0].emit('changeActiveThreeSixty', {
			activeThreeSixty: {}
		});

		AFRAME.scenes[0].emit('changeActiveModel', {
			activeModel: {}
		});

		AFRAME.scenes[0].emit('changeActiveScene', {
			activeScene: 'sceneHome'
		});

	})
}

/* * * + + + + + + + + + + + + + + + + + + + +
Scene Manager
+ + + + + + + + + + + + + + + + + + + + * * */
AFRAME.registerComponent('scene-manager', {
	schema: {
		sceneHome: {type: 'asset', default: 'templates/scene_home.html'},
		scene360: {type: 'asset', default: 'templates/scene_360.html'},
		scene3DModel: {type: 'asset', default: 'templates/scene_model.html'}
	},
	init: function (){
		var self = this
		var el = this.el;
		window.addEventListener('activeSceneChanged',(e)=> {
			nextScene = e.detail.activeScene;
			self.setScene(nextScene)
		});
	},
	setScene: function(nextScene){
		var scene = document.querySelector('a-scene');
		var managers = document.getElementById('managers');
		var sceneTemplate = document.getElementById('scene-template');
		var currentTemplate = sceneTemplate.getAttribute('template').src;

		if(nextScene == 'sceneHome'){
			if(currentTemplate == this.data.scene3DModel){
				this.resetEnv('scene3DModel');
			}
			sceneTemplate.setAttribute('template', 'src:' + this.data.sceneHome);

		}if(nextScene == 'scene360'){
			if(currentTemplate == this.data.scene3DModel){
				this.resetEnv('scene3DModel');
			}
			sceneTemplate.setAttribute('template', 'src:' + this.data.scene360);

		}if(nextScene == 'scene3DModel'){
			if(currentTemplate == this.data.sceneHome){
				this.resetEnv('sceneHome');
			}
			sceneTemplate.setAttribute('template', 'src:' + this.data.scene3DModel);
		}
	},
	resetEnv: function(currentTemplate){
		var env;
		if (currentTemplate == 'scene3DModel'){
			var env = document.querySelector('#model-env')
		}else{
			var env = document.querySelector('#home-env')
		}
		env.setAttribute('environment', {active:false});
	}
});<|endoftext|>


<commit_before>/*
 * Say Cheese!
 * Lee Machin, 2012
 * http://leemach.in, http://new-bamboo.co.uk
 *
 * Minimal javascript library for integrating a webcam and snapshots into your app.
 *
 * Handles starting up the webcam and rendering the element, and also capturing shots
 * in a separate canvas element.
 *
 * Depends on video and canvas, and of course, getUserMedia. It's unlikely to work
 * on anything but the newest browsers.
 */

var SayCheese = (function($) {

  var SayCheese;

  navigator.getUserMedia = (navigator.getUserMedia ||
                            navigator.webkitGetUserMedia ||
                            navigator.mozGetUserMedia ||
                            navigator.msGetUserMedia ||
                            false);

  window.URL = (window.URL ||
                window.webkitURL);

  function eventCoords(evt) {
    return { x: evt.offsetX || evt.layerX, y: evt.offsetY || evt.layerY };
  };

  SayCheese = function SayCheese(element) {
    this.viewfinder = {},
    this.snapshots = [],
    this.canvas = null,
    this.context = null,
    this.video = null,
    this.events = {},
    this.stream = null;

    this.element = document.querySelectorAll(element)[0];
    this.element.style.position = 'relative';

    return this;
  };

  /**
   * Wrap the jQuery stuff so as to minimise the impact of the framework on
   * the rest of the code.
   */
  SayCheese.prototype.on = function on(evt, handler) {
    return $(this).on(evt, handler);
  };

  SayCheese.prototype.off = function off(evt, handler) {
    return $(this).off(evt, handler);
  };

  SayCheese.prototype.trigger = function trigger(evt, data) {
    // bubbling up the DOM makes things go a bit crazy. This assumes
    // preventDefault
    return $(this).triggerHandler(evt, data);
  };

  SayCheese.prototype.getStreamUrl = function getStreamUrl() {
    if (window.URL && window.URL.createObjectURL) {
      return window.URL.createObjectURL(this.stream);
    } else {
      return this.stream;
    }
  };

  SayCheese.prototype.createVideo = function createVideo() {
    this.video = document.createElement('video');
    this.video.autoplay = true;
  };

  SayCheese.prototype.setupCanvas = function setupCanvas() {
    this.canvas = document.createElement('canvas');
    this.canvas.width = this.video.offsetWidth;
    this.canvas.height = this.video.offsetHeight;

    this.canvas.style.position = 'absolute';
    this.canvas.style.top = this.video.offsetTop;
    this.canvas.style.left = this.video.offsetLeft;

    this.context = this.canvas.getContext('2d');

    this.element.appendChild(this.canvas);

    this.initViewfinder();

    return this.trigger('start');
  };

  /* The default viewfinder is just the exact size of the video */
  SayCheese.prototype.initViewfinder = function initViewfinder() {
    return this.viewfinder = {
      width: this.video.offsetWidth,
      height: this.video.offsetHeight
    };
  };

  SayCheese.prototype.takeSnapshot = function takeSnapshot() {
    var snapshot = document.createElement('canvas'),
        ctx      = snapshot.getContext('2d');

    snapshot.width  = this.viewfinder.width;
    snapshot.height = this.viewfinder.height;

    ctx.drawImage(this.video, 0, 0);

    this.snapshots.push(snapshot);
    this.trigger('snapshot', snapshot);

    ctx = null;
  };

  /* Start up the stream, if possible */
  SayCheese.prototype.start = function start() {

    // fail fast and softly if browser not supported
    if (navigator.getUserMedia === false) {
      this.trigger('error', 'NOT_SUPPORTED');
      return false;
    }

    var success = function success(stream) {
      this.stream = stream;
      this.createVideo();

      // video width and height don't exist until metadata is loaded
      this.video.addEventListener('loadedmetadata', this.setupCanvas.bind(this));
      this.video.src = this.getStreamUrl();
      this.element.appendChild(this.video);
    }.bind(this);

    /* error is also called when someone denies access */
    var error = function error(error) {
      this.trigger('error', error);
    }.bind(this);

    return navigator.getUserMedia({ video: true }, success, error);
  };

  SayCheese.prototype.stop = function stop() {
    return this.stream.stop();
  };

  return SayCheese;

})(jQuery);
<commit_msg>fix issue with code not working in firefox<commit_after>/*
 * Say Cheese!
 * Lee Machin, 2012
 * http://leemach.in, http://new-bamboo.co.uk
 *
 * Minimal javascript library for integrating a webcam and snapshots into your app.
 *
 * Handles starting up the webcam and rendering the element, and also capturing shots
 * in a separate canvas element.
 *
 * Depends on video and canvas, and of course, getUserMedia. It's unlikely to work
 * on anything but the newest browsers.
 */

var SayCheese = (function($) {

  var SayCheese;

  navigator.getUserMedia = (navigator.getUserMedia ||
                            navigator.webkitGetUserMedia ||
                            navigator.mozGetUserMedia ||
                            navigator.msGetUserMedia ||
                            false);

  window.URL = (window.URL ||
                window.webkitURL);

  function eventCoords(evt) {
    return { x: evt.offsetX || evt.layerX, y: evt.offsetY || evt.layerY };
  };

  SayCheese = function SayCheese(element) {
    this.viewfinder = {},
    this.snapshots = [],
    this.canvas = null,
    this.context = null,
    this.video = null,
    this.events = {},
    this.stream = null;

    this.element = document.querySelectorAll(element)[0];
    this.element.style.position = 'relative';

    return this;
  };

  /**
   * Wrap the jQuery stuff so as to minimise the impact of the framework on
   * the rest of the code.
   */
  SayCheese.prototype.on = function on(evt, handler) {
    return $(this).on(evt, handler);
  };

  SayCheese.prototype.off = function off(evt, handler) {
    return $(this).off(evt, handler);
  };

  SayCheese.prototype.trigger = function trigger(evt, data) {
    // bubbling up the DOM makes things go a bit crazy. This assumes
    // preventDefault
    return $(this).triggerHandler(evt, data);
  };

  SayCheese.prototype.getStreamUrl = function getStreamUrl() {
    if (window.URL && window.URL.createObjectURL) {
      return window.URL.createObjectURL(this.stream);
    } else {
      return this.stream;
    }
  };

  SayCheese.prototype.createVideo = function createVideo() {
    this.video = document.createElement('video');
    this.video.autoplay = true;
  };

  SayCheese.prototype.setupCanvas = function setupCanvas() {
    this.canvas = document.createElement('canvas');
    this.canvas.width = this.video.offsetWidth;
    this.canvas.height = this.video.offsetHeight;

    this.canvas.style.position = 'absolute';
    this.canvas.style.top = this.video.offsetTop;
    this.canvas.style.left = this.video.offsetLeft;

    this.context = this.canvas.getContext('2d');

    this.element.appendChild(this.canvas);

    this.initViewfinder();

    return this.trigger('start');
  };

  /* The default viewfinder is just the exact size of the video */
  SayCheese.prototype.initViewfinder = function initViewfinder() {
    return this.viewfinder = {
      width: this.video.offsetWidth,
      height: this.video.offsetHeight
    };
  };

  SayCheese.prototype.takeSnapshot = function takeSnapshot() {
    var snapshot = document.createElement('canvas'),
        ctx      = snapshot.getContext('2d');

    snapshot.width  = this.viewfinder.width;
    snapshot.height = this.viewfinder.height;

    ctx.drawImage(this.video, 0, 0);

    this.snapshots.push(snapshot);
    this.trigger('snapshot', snapshot);

    ctx = null;
  };

  /* Start up the stream, if possible */
  SayCheese.prototype.start = function start() {

    // fail fast and softly if browser not supported
    if (navigator.getUserMedia === false) {
      this.trigger('error', 'NOT_SUPPORTED');
      return false;
    }

    var success = function success(stream) {
      this.stream = stream;
      this.createVideo();

      if (navigator.mozGetUserMedia) {
        this.video.mozSrcObject = stream;
      } else {
        this.video.src = this.getStreamUrl();
      }

      this.video.addEventListener('loadedmetadata', this.setupCanvas.bind(this));
      this.element.appendChild(this.video);
    }.bind(this);

    /* error is also called when someone denies access */
    var error = function error(error) {
      this.trigger('error', error);
    }.bind(this);

    return navigator.getUserMedia({ video: true }, success, error);
  };

  SayCheese.prototype.stop = function stop() {
    return this.stream.stop();
  };

  return SayCheese;

})(jQuery);
<|endoftext|>


<commit_before>var app = angular.module("data-viewer", ["ngRoute", "datatables", "datatables.scroller"]);

app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "templates/home.html",
        controller: "homeCtrl"
    })
    .when("/about", {
        templateUrl : "templates/about.html",
        controller: "aboutCtrl"
    });
});

app.controller("homeCtrl", function($scope, $rootScope, dataService, DTOptionsBuilder) {
    $scope.dataService = dataService;
    $rootScope.pageTitle = "Home";

    $scope.dtOptions = DTOptionsBuilder.newOptions()
        .withScroller()
        .withOption('scrollY', 500);
});

app.controller("aboutCtrl", function($scope, $rootScope) {
    $rootScope.pageTitle = "About";
});

app.controller("headerCtrl", function($scope, $rootScope) {
    $rootScope.pageTitle = "Home";
})
<commit_msg>added defer rendering to fix race condition<commit_after>var app = angular.module("data-viewer", ["ngRoute", "datatables", "datatables.scroller"]);

app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "templates/home.html",
        controller: "homeCtrl"
    })
    .when("/about", {
        templateUrl : "templates/about.html",
        controller: "aboutCtrl"
    });
});

app.controller("homeCtrl", function($scope, $rootScope, dataService, DTOptionsBuilder) {
    $scope.dataService = dataService;
    $rootScope.pageTitle = "Home";

    $scope.dtOptions = DTOptionsBuilder.newOptions()
        .withScroller()
        .withOption('deferRender', true)
        .withOption('scrollY', 500);
});

app.controller("aboutCtrl", function($scope, $rootScope) {
    $rootScope.pageTitle = "About";
});

app.controller("headerCtrl", function($scope, $rootScope) {
    $rootScope.pageTitle = "Home";
})
<|endoftext|>


<commit_before>$(function(){

var game = new Game();
var keys = [];    //to detect multiple keys
var playerMovement = 20;
var player = $('#player');
//var enemeyPosition = $('.enemy').position();

function shoot(){
  var xPos = player.position().top;
  $('div#box').append('

');  //insert bullet
  $('.bullet').css({'top': xPos+25 + 'px'}).animate({left: '490px'}, 1200); //attach bullet to player position

    //add: push to array to tract bullets
    //add: after spacebar, release player position so bullet keeps own position
    //add: if collides with enemy position OR goes out of the window, splice out of array. toggle off/disapear/hide
}

//bullet boundery
  // function bulletBoundery(){
  //   if ($('.bullet').left == 490 ){
  //     // remove from array (splice)
  //   }
  // }

//I can't make it work. trying to set it to the border limit
function boundery() {
  if (player.position().top >= 200){
    player.animate({top: ='200px'});
  }
  if (player.position().top <= 0){
    player.animate({top: ='10px'});
  };
}

//changed to if statement. easier for me to see.
function keysPressed(e) {
  // store an entry for every key pressed
  keys[e.keyCode] = true;

  //spacebar
  if (keys[32]) {
    shoot();
    e.preventDefault();
  }
  //up arrow key
  if (keys[38]) {
    player.animate({top: '-=' + playerMovement}, 100);
    e.preventDefault();
  }
  //down arrow key
  if (keys[40]) {
    player.animate({top: '+=' + playerMovement}, 100);
    e.preventDefault();
  }
  boundery();
}

//once released, same keys in arrays become false.
function keysReleased(e) {
    keys[e.keyCode] = false;
}

//event listener
$(document).keyup(keysReleased);
$(document).keydown(keysPressed);

}); //end of doc.ready<commit_msg>tried: Bullets, PlayerBounderies & Bullet boundery still not working<commit_after>$(function(){

var game = new Game();
var keys = [];    //to detect multiple keys
var bullets = [];
var playerMovement = 20;
var player = $('#player');
//var enemeyPosition = $('.enemy').position();

//*Bullet still moves with #player horizonal axis*
function shoot(){
  var xPos = player.position().top;

  //insert bullet
  $('div#box').append('

');

  //attach bullet to player position
  $('.bullet').css({'top': xPos+25 + 'px'}).animate({left: '500px'}, 1500);;

  //loop through bullets to push in array
  for (var i=1;i<=1;i++){ //testing
    bullets.push(i);
  }

  //console.log
  console.log("bullets array " + bullets);
}

//*I can't make it work* Bullet boundery = (enemy hit || max width) then remove from array.
function bulletBoundery(){
  if ($('.bullet').position().left >= 500 ){ //max width
    bullets.splice(0,1);
  }
}

//*I can't make it work* Trying to set it to the border limit
function boundery() {
  if (player.position().top >= 200){
    player.animate({top: '200px'});
  }
  if (player.position().top <= 0){
    player.animate({top: '10px'});
  };
}

//changed to if statement. easier for me to see.
function keysPressed(e) {
  // store an entry for every key pressed
  keys[e.keyCode] = true;

  //spacebar
  if (keys[32]) {
    shoot();
    e.preventDefault();
  }
  //up arrow key
  if (keys[38]) {
    player.animate({top: '-=' + playerMovement}, 100);
    e.preventDefault();
  }
  //down arrow key
  if (keys[40]) {
    player.animate({top: '+=' + playerMovement}, 100);
    e.preventDefault();
  }

  boundery();
  bulletBoundery();

  //console.log
  console.log("keys array " + keys);
}

//once released, same keys in arrays become false.
function keysReleased(e) {
    keys[e.keyCode] = false;
}

//event listeners
$(document).keyup(keysReleased);
$(document).keydown(keysPressed);

}); //end of doc.ready<|endoftext|>


<commit_before>var createFretboard = function (n_strings, inlay_repr, dot_mark, show_numbers) {
    var createFret = function (numStrings, repr) {
        // a common fret is represented by '-' or undefined
        // '.' is a dotted fret with one dot '.'
        // ':' is a double dotted fret
        var isDotted = repr == '.' || repr == ':';
        var doubleDotted = repr == ':';
        if (isDotted) {
            var place = doubleDotted ? 1 : (numStrings / 2 - 1) | 0; // cast-to-int HACK!
        }
        // for N strings, we need to draw N-1 cell boxes
        var numBoxes = numStrings - 1;
        var fret_html = "
";
        for (var i = 0; i < numBoxes; i++) {
            if (isDotted && i == place) {
                fret_html += "" + dot_mark + "	";
                place = doubleDotted ? (numBoxes - 2) : place;
            } else {
                fret_html += ' 	';
            }
        }
        fret_html += "
";
        return fret_html;
    }
    var fret_for_repr = {
        '-': createFret(n_strings),
        '.': createFret(n_strings, '.'),
        ':': createFret(n_strings, ':')
    }
    var createNumberBox = function (number, visible) {
        return '' + number + '	';
    }
    var fretboard_elem = $('

');

    // create a fretboard
    for (var i = 0; i < inlay_repr.length; i++) {
        var fretType = inlay_repr[i];
        var $fret = $(fret_for_repr[fretType]);
        $fret.prepend(createNumberBox(i + 1, show_numbers));
        fretboard_elem.append($fret);
    }
    return fretboard_elem;
}
// handle url parameters
function get_url_parameters() {
    var params = {};
    var index_params = window.location.href.indexOf('#');
    if (index_params > 0) {
        var hashes = window.location.href.slice(index_params + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            var hash = hashes[i].split('=');
            params[hash[0]] = hash[1];
        }
    }
    return params;
}
function create_link(link_params) {
    var href = window.location.href;
    if (href.indexOf('#') > 0) {
        href = href.substring(0, href.indexOf('#'));
    }
    href += '#';
    for (var key in link_params) {
        href += key + '=' + link_params[key] + '&';
    }
    href = href.substring(0, href.length - 1);
    return href;
}
function update_form_with_url_params() {
    var params = get_url_parameters();
    // TODO: validate input?
    for (var key in params) {
        if (key == 'show_numbers') {
            $('#' + key).prop('checked', params[key] == 'true');
        } else {
            if (key) {
                $('#' + key).val(params[key]);
            }
        }
    }
}
var generateAllFretboards = function () {
    var how_many = $('#how_many').val();
    var dot_mark = '●'; // the dot mark character
    var inlay_variation = $('#inlay_variation').val();
    var num_strings = $('select#num_strings').val();
    var frets_per_diagram = $('select#frets_per_diagram').val();
    var show_numbers = $('#show_numbers').is(':checked');
    var size_diagram = $('select#size_diagram').val();
    var margin = $('select#fretboard_margin').val();

    var link_params = {
        how_many: how_many,
        inlay_variation: inlay_variation,
        size_diagram: size_diagram,
        num_strings: num_strings,
        frets_per_diagram: frets_per_diagram,
        show_numbers: show_numbers,
        fretboard_margin: margin
    };
    var href = create_link(link_params);
    $('#input_link_this').val(href);

    // This gets the fretboard representation ready with the right size
    //     '-----' is a fretboard with 5 frets and no marks
    //     '--.--:' is a fretboard with 6 frets, a dot in the third fret and double dots in the last fret
    var fretboardRepr = inlay_variation.substr(0, frets_per_diagram);

    // empty container and redraw fretboards
    var $main = $('#main');
    $main.empty();
    var $fretboard = createFretboard(num_strings, fretboardRepr, dot_mark, show_numbers);
    for (var i = 0; i < how_many; i++) {
        $main.append($fretboard.clone());
    }
    // adjust size
    var css_size_style = {
        'Tiny': { width: '18px', height: '24px'},
        'Small': { width: '22px', height: '30px'},
        'Medium': { width: '28px', height: '38px'},
        'Large': { width: '36px', height: '50px'},
        'X-Large': { width: '40px', height: '56px'}
    }
    $('.fretboard tr td').css(css_size_style[size_diagram]);
    $('.fretboard').css('margin', margin + 'cm');
}
$(function () {
    // this will load on dom-ready
    function fill_options(elem, options, defval) {
        // setup a select dropdown with options and default value
        $.each(options, function () {
            var html = $('<option value="' + this + '">' + this + '</option>');
            if (this == defval) {
                html.attr('selected', '1');
            }
            elem.append(html);
        });
    }

    function list_range(start, end) {
        // create a list from a range
        var arr = [];
        for (var i = start; i <= end; i += 1) {
            arr.push(i);
        }
        return arr;
    }

    // setup controls with defaults
    fill_options($('select#how_many'), list_range(1, 30), 3);
    fill_options($('select#frets_per_diagram'), list_range(4, 16), 14);
    fill_options($('select#num_strings'), list_range(4, 8), 6);
    fill_options($('select#size_diagram'), ['Tiny', 'Small', 'Medium', 'Large', 'X-Large'], 'Medium');
    fill_options($('select#fretboard_margin'), [0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.5, 1.6, 1.8, 2, 2.2, 2.4, 2.6, 2.8, 3.0], 0.8);
    $('select#inlay_variation').append('<option value="----------------">No Inlay</option>');
    $('select#inlay_variation').append('<option value="--.-.-.-.--:--.-" selected>Variation 1</option>');
    $('select#inlay_variation').append('<option value="--.-.-.--.-:--.-">Variation 2</option>');

    $('.print-action').click(function (e) {
        e.preventDefault();
        window.print();
    });

    $('#help_btn').click(function () {
        $('#help').show('fast');
    });
    $('.help_close_btn').click(function () {
        $('#help').hide('fast');
    });
    $('.settings-panel input').change(generateAllFretboards);
    $('.settings-panel select').change(generateAllFretboards);

    $('#toggleAdvanced').toggle(function () {
        $(this).addClass('active');
        $('.advanced').show();
    }, function () {
        $(this).removeClass('active');
        $('.advanced').hide();
    });

    $('#input_link_this').click(function () {
        $(this).select();
    });

    // generate with defaults
    update_form_with_url_params();
    generateAllFretboards();
    $(document).keyup(function (e) {
        // hotkeys
        var ESCAPE = 27;
        if (e.keyCode == ESCAPE) {
            $('#help').hide();
        }
    });
});

$(document).ready(function () {
    // isso provavelmente deveria estar ali em cima,
    // onde jah tem mais coisa carregando no dom-ready :)
    var body = $(document.body);

    body.on('activate', ".activatable", function () {
        var activatable = $(this);
        var listHolder = activatable.closest(".activatable-container");

        listHolder.find(".activatable").removeClass("active");
        activatable.addClass("active");
    });

    body.on('click', '.preset', function () {
        var preset = $(this);
        var presetContainer = $(this).closest('.activatable');
        var href = preset.attr('href');

        presetContainer.trigger('activate');

        window.location.href = href;
        update_form_with_url_params();
        generateAllFretboards();
    });
});<commit_msg>scroll, biéatch<commit_after>var createFretboard = function (n_strings, inlay_repr, dot_mark, show_numbers) {
    var createFret = function (numStrings, repr) {
        // a common fret is represented by '-' or undefined
        // '.' is a dotted fret with one dot '.'
        // ':' is a double dotted fret
        var isDotted = repr == '.' || repr == ':';
        var doubleDotted = repr == ':';
        if (isDotted) {
            var place = doubleDotted ? 1 : (numStrings / 2 - 1) | 0; // cast-to-int HACK!
        }
        // for N strings, we need to draw N-1 cell boxes
        var numBoxes = numStrings - 1;
        var fret_html = "
";
        for (var i = 0; i < numBoxes; i++) {
            if (isDotted && i == place) {
                fret_html += "" + dot_mark + "	";
                place = doubleDotted ? (numBoxes - 2) : place;
            } else {
                fret_html += ' 	';
            }
        }
        fret_html += "
";
        return fret_html;
    }
    var fret_for_repr = {
        '-': createFret(n_strings),
        '.': createFret(n_strings, '.'),
        ':': createFret(n_strings, ':')
    }
    var createNumberBox = function (number, visible) {
        return '' + number + '	';
    }
    var fretboard_elem = $('

');

    // create a fretboard
    for (var i = 0; i < inlay_repr.length; i++) {
        var fretType = inlay_repr[i];
        var $fret = $(fret_for_repr[fretType]);
        $fret.prepend(createNumberBox(i + 1, show_numbers));
        fretboard_elem.append($fret);
    }
    return fretboard_elem;
}
// handle url parameters
function get_url_parameters() {
    var params = {};
    var index_params = window.location.href.indexOf('#');
    if (index_params > 0) {
        var hashes = window.location.href.slice(index_params + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            var hash = hashes[i].split('=');
            params[hash[0]] = hash[1];
        }
    }
    return params;
}
function create_link(link_params) {
    var href = window.location.href;
    if (href.indexOf('#') > 0) {
        href = href.substring(0, href.indexOf('#'));
    }
    href += '#';
    for (var key in link_params) {
        href += key + '=' + link_params[key] + '&';
    }
    href = href.substring(0, href.length - 1);
    return href;
}
function update_form_with_url_params() {
    var params = get_url_parameters();
    // TODO: validate input?
    for (var key in params) {
        if (key == 'show_numbers') {
            $('#' + key).prop('checked', params[key] == 'true');
        } else {
            if (key) {
                $('#' + key).val(params[key]);
            }
        }
    }
}
var generateAllFretboards = function () {
    var how_many = $('#how_many').val();
    var dot_mark = '●'; // the dot mark character
    var inlay_variation = $('#inlay_variation').val();
    var num_strings = $('select#num_strings').val();
    var frets_per_diagram = $('select#frets_per_diagram').val();
    var show_numbers = $('#show_numbers').is(':checked');
    var size_diagram = $('select#size_diagram').val();
    var margin = $('select#fretboard_margin').val();

    var link_params = {
        how_many: how_many,
        inlay_variation: inlay_variation,
        size_diagram: size_diagram,
        num_strings: num_strings,
        frets_per_diagram: frets_per_diagram,
        show_numbers: show_numbers,
        fretboard_margin: margin
    };
    var href = create_link(link_params);
    $('#input_link_this').val(href);

    // This gets the fretboard representation ready with the right size
    //     '-----' is a fretboard with 5 frets and no marks
    //     '--.--:' is a fretboard with 6 frets, a dot in the third fret and double dots in the last fret
    var fretboardRepr = inlay_variation.substr(0, frets_per_diagram);

    // empty container and redraw fretboards
    var $main = $('#main');
    $main.empty();
    var $fretboard = createFretboard(num_strings, fretboardRepr, dot_mark, show_numbers);
    for (var i = 0; i < how_many; i++) {
        $main.append($fretboard.clone());
    }
    // adjust size
    var css_size_style = {
        'Tiny': { width: '18px', height: '24px'},
        'Small': { width: '22px', height: '30px'},
        'Medium': { width: '28px', height: '38px'},
        'Large': { width: '36px', height: '50px'},
        'X-Large': { width: '40px', height: '56px'}
    }
    $('.fretboard tr td').css(css_size_style[size_diagram]);
    $('.fretboard').css('margin', margin + 'cm');
}
$(function () {
    // this will load on dom-ready
    function fill_options(elem, options, defval) {
        // setup a select dropdown with options and default value
        $.each(options, function () {
            var html = $('<option value="' + this + '">' + this + '</option>');
            if (this == defval) {
                html.attr('selected', '1');
            }
            elem.append(html);
        });
    }

    function list_range(start, end) {
        // create a list from a range
        var arr = [];
        for (var i = start; i <= end; i += 1) {
            arr.push(i);
        }
        return arr;
    }

    // setup controls with defaults
    fill_options($('select#how_many'), list_range(1, 30), 3);
    fill_options($('select#frets_per_diagram'), list_range(4, 16), 14);
    fill_options($('select#num_strings'), list_range(4, 8), 6);
    fill_options($('select#size_diagram'), ['Tiny', 'Small', 'Medium', 'Large', 'X-Large'], 'Medium');
    fill_options($('select#fretboard_margin'), [0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.5, 1.6, 1.8, 2, 2.2, 2.4, 2.6, 2.8, 3.0], 0.8);
    $('select#inlay_variation').append('<option value="----------------">No Inlay</option>');
    $('select#inlay_variation').append('<option value="--.-.-.-.--:--.-" selected>Variation 1</option>');
    $('select#inlay_variation').append('<option value="--.-.-.--.-:--.-">Variation 2</option>');

    $('.print-action').click(function (e) {
        e.preventDefault();
        window.print();
    });

    $('#help_btn').click(function () {
        $('#help').show('fast');
    });
    $('.help_close_btn').click(function () {
        $('#help').hide('fast');
    });
    $('.settings-panel input').change(generateAllFretboards);
    $('.settings-panel select').change(generateAllFretboards);

    $('#toggleAdvanced').toggle(function () {
        $(this).addClass('active');
        $('.advanced').show();
    }, function () {
        $(this).removeClass('active');
        $('.advanced').hide();
    });

    $('#input_link_this').click(function () {
        $(this).select();
    });

    $('.getting-started-btn').click(function (e) {
        scrollTo(0, 1011);
        e.preventDefault();
        return false;
    })

    // generate with defaults
    update_form_with_url_params();
    generateAllFretboards();
    $(document).keyup(function (e) {
        // hotkeys
        var ESCAPE = 27;
        if (e.keyCode == ESCAPE) {
            $('#help').hide();
        }
    });
});

$(document).ready(function () {
    // isso provavelmente deveria estar ali em cima,
    // onde jah tem mais coisa carregando no dom-ready :)
    var body = $(document.body);

    body.on('activate', ".activatable", function () {
        var activatable = $(this);
        var listHolder = activatable.closest(".activatable-container");

        listHolder.find(".activatable").removeClass("active");
        activatable.addClass("active");
    });

    body.on('click', '.preset', function () {
        var preset = $(this);
        var presetContainer = $(this).closest('.activatable');
        var href = preset.attr('href');

        presetContainer.trigger('activate');

        window.location.href = href;
        update_form_with_url_params();
        generateAllFretboards();
    });
});<|endoftext|>


<commit_before>
var chooseDirectoryBtn = document.querySelector('#chooseDirectoryID');
var textarea = document.querySelector('textarea');

function errorHandler(e) {
	console.error(e);
}

var entries = []

// var Movie = class {
// 	constructor(filename, filePath, parent ){
// 		this.filename = filename;
// 		this.filePath = filePath;
// 		this.parent = parent;
// 	}
// }

var moviesObjectArray = []

//Can improve this :(
	function sanitizeFilename(filename){
		return filename.replace(/(dvdrip|xvid| cd[0-9]|dvdscr|brrip|divx|[\{\(\[]?[0-9]{4}).*/g,"").replace(/\./g," ");
	}

//this can be improved!

function getFileExtension(filename){
	return filename.slice(filename.lastIndexOf('.'), filename.length).replace(".","");
}

function loadDirEntry(_chosenEntry) {
	console.log("loadDirEntry called")
	chosenEntry = _chosenEntry;
	if (chosenEntry.isDirectory) {
		var dirReader = chosenEntry.createReader();
		// var entries = [];
    // Call the reader.readEntries() until no more results are returned.
    var readEntries = function() {

    	console.log("reading entries");
    	dirReader.readEntries (function(results) {
    		// console.log("results ==> ",results.length);
    		// console.log("results ==> ",results);

    		if (!results.length) {
    			textarea.value = entries.join("\n");
    		}
    		else {
    			results.forEach(function(item) {

    				entries = entries.concat(item.fullPath + " isDirectory ===> " + item.isDirectory + "\n " + sanitizeFilename(item.name) + "\n");
    				//creating a Movie object
    				if (!item.isDirectory){
    					// console.log(item);
    					item.getMetadata(function(metadata) {
    						console.log("metadata ==> ", metadata);
    						moviesObjectArray.push({
    							filename: sanitizeFilename(item.name),
    							fullPath: item.fullPath,
    							parentPath: _chosenEntry.fullPath,
    							size: metadata.size/1024,
    							modificationDate: metadata.modificationTime,
    							fileExtension: getFileExtension(item.name)
    						});
    					});

    				}
    				console.log(item)
    				if (item.isDirectory){
    					console.log("DIRECTORY")

    					// Running the recursion here!

    					loadDirEntry(item);
    				}
    			});
    			readEntries();
    		}
    	}, errorHandler);
};

    readEntries(); // Start reading dirs.
    // for (var i in moviesObjectArray){
    // 	queryOmdb(moviesObjectArray[i].filename);
    // }

}
}

chooseDirectoryBtn.addEventListener('click', function(e) {
	console.log("click event ==> ", e);
	chrome.fileSystem.chooseEntry({type: 'openDirectory'}, function(theEntry, folderFiles) {
		if (!theEntry) {
			console.log("No directory selected");
			return;
		}
		console.log("theEntry ===> ", theEntry);
		console.log("folderFiles ===> ", folderFiles);
		loadDirEntry(theEntry);
	});
});

<commit_msg>Uncommented some code<commit_after>
var chooseDirectoryBtn = document.querySelector('#chooseDirectoryID');
var textarea = document.querySelector('textarea');

function errorHandler(e) {
	console.error(e);
}

var entries = []

// var Movie = class {
// 	constructor(filename, filePath, parent ){
// 		this.filename = filename;
// 		this.filePath = filePath;
// 		this.parent = parent;
// 	}
// }

var moviesObjectArray = []

//Can improve this :(
	function sanitizeFilename(filename){
		return filename.replace(/(dvdrip|xvid| cd[0-9]|dvdscr|brrip|divx|[\{\(\[]?[0-9]{4}).*/g,"").replace(/\./g," ");
	}

//this can be improved!

function getFileExtension(filename){
	return filename.slice(filename.lastIndexOf('.'), filename.length).replace(".","");
}

function loadDirEntry(_chosenEntry) {
	console.log("loadDirEntry called")
	chosenEntry = _chosenEntry;
	if (chosenEntry.isDirectory) {
		var dirReader = chosenEntry.createReader();
		// var entries = [];
    // Call the reader.readEntries() until no more results are returned.
    var readEntries = function() {

    	console.log("reading entries");
    	dirReader.readEntries (function(results) {
    		// console.log("results ==> ",results.length);
    		// console.log("results ==> ",results);

    		if (!results.length) {
    			textarea.value = entries.join("\n");
    		}
    		else {
    			results.forEach(function(item) {

    				entries = entries.concat(item.fullPath + " isDirectory ===> " + item.isDirectory + "\n " + sanitizeFilename(item.name) + "\n");
    				//creating a Movie object
    				if (!item.isDirectory){
    					// console.log(item);
    					item.getMetadata(function(metadata) {
    						console.log("metadata ==> ", metadata);
    						moviesObjectArray.push({
    							filename: sanitizeFilename(item.name),
    							fullPath: item.fullPath,
    							parentPath: _chosenEntry.fullPath,
    							size: metadata.size/1024,
    							modificationDate: metadata.modificationTime,
    							fileExtension: getFileExtension(item.name)
    						});
    					});

    				}
    				console.log(item)
    				if (item.isDirectory){
    					console.log("DIRECTORY")

    					// Running the recursion here!

    					loadDirEntry(item);
    				}
    			});
    			readEntries();
    		}
    	}, errorHandler);
};

    readEntries(); // Start reading dirs.
    for (var i in moviesObjectArray){
    	queryOmdb(moviesObjectArray[i].filename);
    }
}
}

chooseDirectoryBtn.addEventListener('click', function(e) {
	console.log("click event ==> ", e);
	chrome.fileSystem.chooseEntry({type: 'openDirectory'}, function(theEntry, folderFiles) {
		if (!theEntry) {
			console.log("No directory selected");
			return;
		}
		console.log("theEntry ===> ", theEntry);
		console.log("folderFiles ===> ", folderFiles);
		loadDirEntry(theEntry);
	});
});

<|endoftext|>


<commit_before>/**
 * @author Mike Dolbow
 * An application support script for demonstrating capabilities of Esri REST Endpoints.
 */

/**
 * Globals
 *
*/

var map;
var mapOptions = {
		maxZoom:7,
		minZoom:7,
		zoomControl:'false',
		center: [37.0,-90.0],
		zoom:7,
		maxBounds:[
			[34.5,-98.0],
			[41.0,-79.0]
			]
	};
var dynMapServiceURL = '//server.arcgisonline.com/arcgis/rest/services/Demographics/USA_Population_by_Sex/MapServer';

/**
 * On Click function for btnQueryRandDemo.
 * Picks a letter of the alphabet at random, and fires a query against the Detailed Counties
 * layer in order to get many results, and display some details from the first result. (Might need to exclude "X", but "Z" works)
 */

function getRandomCounty() {
	//pick a random letter to start a query with, excluding X
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWYZ';
	var randomChar = chars[Math.round(Math.random() * (chars.length - 1))];
	var url1 = "https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/4/query?outFields=NAME%2C+POP2007&returnGeometry=false&f=json&text="+randomChar;

	//Make an AJAX request against the Esri service to acquire counties that begin with the random letter
    $.ajax({
	    url: url1,
	    dataType: "jsonp",
	    cache: "false"
	})
 	.done(function( data ) {
		$("#emQueryRandURL").html('Detailed Counties Starting with '+randomChar+'<\/a>');
		$("#emQueryNoCounties").html(data.features.length);
		$("#emQueryFirstCounty").html(data.features[0].attributes.NAME);
		$("#emQueryPop").html(data.features[0].attributes.POP2007);
	});

}

function initpnpmap() {
		map = L.map('map', mapOptions);
		map.removeControl(map.zoomControl);
		var marker = L.marker(map.getCenter()).addTo(map);

		var MapQuestOpen_OSM = L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpeg', {
			attribution: 'Tiles Courtesy of PolyMaps, MapQuest — Map data © OpenStreetMap contributors, CC-BY-SA',
			subdomains: '1234'
		});
		map.addLayer(MapQuestOpen_OSM);

		L.esri.dynamicMapLayer({
		    url: dynMapServiceURL,
		    opacity: 0.5
		  }).addTo(map);

		map.whenReady(function() {
		    map.on('moveend', function() {
		    	   	marker.setLatLng(map.getCenter());
		    	   	mapquery(map.getCenter());
		    	});
		});

	}

function mapquery(pntLatLng) {
	console.log("Map was moved to: "+pntLatLng.lat+", "+pntLatLng.lng);
	var queryURL = dynMapServiceURL+'/3/query?geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelIntersects&outFields=*&returnGeometry=false&f=json&geometry='+pntLatLng.lng+'%2C'+pntLatLng.lat;
	$("#emPnPURL").html('Query URL (new window)<\/a>');
	//Make an AJAX request against the Esri service to acquire demographics info at the lat long
	//sample query: https://server.arcgisonline.com/arcgis/rest/services/Demographics/USA_Population_by_Sex/MapServer/3/query?geometry=-96.21826%2C47.88688&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelIntersects&outFields=*&returnGeometry=false&f=pjson
    $.ajax({
	    url: queryURL,
	    dataType: "jsonp",
	    cache: "false"
	})
 	.done(function( data, url ) {
 		//console.table(data);
		$("#emPnPCounty").html(data.features[0].attributes.NAME+", "+data.features[0].attributes.ST_ABBREV);
		$("#emPnPPop").html(data.features[0].attributes.TOTPOP_CY);
	});
}

<commit_msg>Update app.js<commit_after>/**
 * @author Mike Dolbow
 * An application support script for demonstrating capabilities of Esri REST Endpoints.
 */

/**
 * Globals
 *
*/

var map;
var mapOptions = {
		maxZoom:7,
		minZoom:7,
		zoomControl:'false',
		center: [37.0,-90.0],
		zoom:7,
		maxBounds:[
			[34.5,-98.0],
			[41.0,-79.0]
			]
	};
var dynMapServiceURL = '//server.arcgisonline.com/arcgis/rest/services/Demographics/USA_Population_by_Sex/MapServer';

/**
 * On Click function for btnQueryRandDemo.
 * Picks a letter of the alphabet at random, and fires a query against the Detailed Counties
 * layer in order to get many results, and display some details from the first result. (Might need to exclude "X", but "Z" works)
 */

function getRandomCounty() {
	//pick a random letter to start a query with, excluding X
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWYZ';
	var randomChar = chars[Math.round(Math.random() * (chars.length - 1))];
	var url1 = "https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/4/query?outFields=NAME%2C+POP2007&returnGeometry=false&f=json&text="+randomChar;

	//Make an AJAX request against the Esri service to acquire counties that begin with the random letter
    $.ajax({
	    url: url1,
	    dataType: "jsonp",
	    cache: "false"
	})
 	.done(function( data ) {
		$("#emQueryRandURL").html('Detailed Counties Starting with '+randomChar+'<\/a>');
		$("#emQueryNoCounties").html(data.features.length);
		$("#emQueryFirstCounty").html(data.features[0].attributes.NAME);
		$("#emQueryPop").html(data.features[0].attributes.POP2007);
	});

}

function initpnpmap() {
		map = L.map('map', mapOptions);
		map.removeControl(map.zoomControl);
		var marker = L.marker(map.getCenter()).addTo(map);

		var basemapTileLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}', {
				maxZoom: 17,
				type: 'map',
				ext: 'jpg',
				subdomains: '1234',
				attribution: 'Esri, HERE, DeLorme, Intermap, increment P Corp., GEBCO, USGS, FAO, NPS, NRCAN, GeoBase, IGN, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), swisstopo, MapmyIndia, © OpenStreetMap contributors, and the GIS User Community'
			});
		map.addLayer(basemapTileLayer);

		L.esri.dynamicMapLayer({
		    url: dynMapServiceURL,
		    opacity: 0.5
		  }).addTo(map);

		map.whenReady(function() {
		    map.on('moveend', function() {
		    	   	marker.setLatLng(map.getCenter());
		    	   	mapquery(map.getCenter());
		    	});
		});

	}

function mapquery(pntLatLng) {
	console.log("Map was moved to: "+pntLatLng.lat+", "+pntLatLng.lng);
	var queryURL = dynMapServiceURL+'/3/query?geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelIntersects&outFields=*&returnGeometry=false&f=json&geometry='+pntLatLng.lng+'%2C'+pntLatLng.lat;
	$("#emPnPURL").html('Query URL (new window)<\/a>');
	//Make an AJAX request against the Esri service to acquire demographics info at the lat long
	//sample query: https://server.arcgisonline.com/arcgis/rest/services/Demographics/USA_Population_by_Sex/MapServer/3/query?geometry=-96.21826%2C47.88688&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelIntersects&outFields=*&returnGeometry=false&f=pjson
    $.ajax({
	    url: queryURL,
	    dataType: "jsonp",
	    cache: "false"
	})
 	.done(function( data, url ) {
 		//console.table(data);
		$("#emPnPCounty").html(data.features[0].attributes.NAME+", "+data.features[0].attributes.ST_ABBREV);
		$("#emPnPPop").html(data.features[0].attributes.TOTPOP_CY);
	});
}

<|endoftext|>


<commit_before>'use strict';
<commit_msg>added to js<commit_after>'use strict';

//get list items from list 1
var list1item1 = document.getElementsByClassName('unchecked')[0];
var list1item2 = document.getElementsByClassName('unchecked')[1];
var list1item3 = document.getElementsByClassName('unchecked')[2];
var list1item4 = document.getElementsByClassName('unchecked')[3];
var list1item5 = document.getElementsByClassName('unchecked')[4];
var list1item6 = document.getElementsByClassName('unchecked')[5];

//get list items from list 2
var list2item1 = document.getElementsByClassName('unchecked')[0];
var list2item2 = document.getElementsByClassName('unchecked')[1];
var list2item3 = document.getElementsByClassName('unchecked')[2];
var list2item4 = document.getElementsByClassName('unchecked')[3];
var list2item5 = document.getElementsByClassName('unchecked')[4];
var list2item6 = document.getElementsByClassName('unchecked')[5];

/*
var picturesOfPats1of2 = document.getElementsByClassName('sub-banners')[0];
var picturesOfPats2of2 = document.getElementsByClassName('sub-banners-2')[0];
var upArrow = document.getElementsByClassName('up')[0];
var downArrow = document.getElementsByClassName('down')[0];

function togglePix() {

  if (upArrow.getAttribute('class') === 'up inactivearrow') {
    picturesOfPats1of2.setAttribute('class', 'sub-banners active');
    picturesOfPats2of2.setAttribute('class', 'sub-banners-2 active');
    upArrow.setAttribute('class', 'up activearrow');
    downArrow.setAttribute('class', 'down inactivearrow');
  } else {
    picturesOfPats1of2.setAttribute('class', 'sub-banners inactive');
    picturesOfPats2of2.setAttribute('class', 'sub-banners-2 inactive');
    upArrow.setAttribute('class', 'up inactivearrow');
    downArrow.setAttribute('class', 'down activearrow');
  }
}

downArrow.addEventListener('click', togglePix);
upArrow.addEventListener('click', togglePix);
*/
<|endoftext|>