<commit_before>goog.provide('ol.VectorImageTile');

goog.require('ol');
goog.require('ol.Tile');
goog.require('ol.TileState');
goog.require('ol.array');
goog.require('ol.dom');
goog.require('ol.events');
goog.require('ol.extent');
goog.require('ol.events.EventType');
goog.require('ol.featureloader');

/**
 * @constructor
 * @extends {ol.Tile}
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @param {ol.TileState} state State.
 * @param {string} src Data source url.
 * @param {ol.format.Feature} format Feature format.
 * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function.
 * @param {ol.TileCoord} urlTileCoord Wrapped tile coordinate for source urls.
 * @param {ol.TileUrlFunctionType} tileUrlFunction Tile url function.
 * @param {ol.tilegrid.TileGrid} sourceTileGrid Tile grid of the source.
 * @param {ol.tilegrid.TileGrid} tileGrid Tile grid of the renderer.
 * @param {Object.<string,ol.VectorTile>} sourceTiles Source tiles.
 * @param {number} pixelRatio Pixel ratio.
 * @param {ol.proj.Projection} projection Projection.
 * @param {function(new: ol.VectorTile, ol.TileCoord, ol.TileState, string,
 *     ol.format.Feature, ol.TileLoadFunctionType)} tileClass Class to
 *     instantiate for source tiles.
 * @param {function(this: ol.source.VectorTile, ol.events.Event)} handleTileChange
 *     Function to call when a source tile's state changes.
 */
ol.VectorImageTile = function(tileCoord, state, src, format, tileLoadFunction,
    urlTileCoord, tileUrlFunction, sourceTileGrid, tileGrid, sourceTiles,
    pixelRatio, projection, tileClass, handleTileChange) {

  ol.Tile.call(this, tileCoord, state);

  /**
   * @private
   * @type {CanvasRenderingContext2D}
   */
  this.context_ = null;

  /**
   * @private
   * @type {ol.FeatureLoader}
   */
  this.loader_;

  /**
   * @private
   * @type {ol.TileReplayState}
   */
  this.replayState_ = {
    dirty: false,
    renderedRenderOrder: null,
    renderedRevision: -1,
    renderedTileRevision: -1
  };

  /**
   * @private
   * @type {Object.<string,ol.VectorTile>}
   */
  this.sourceTiles_ = sourceTiles;

  /**
   * Keys of source tiles used by this tile. Use with {@link #getTile}.
   * @type {Array.<string>}
   */
  this.tileKeys = [];

  /**
   * @type {string}
   */
  this.src_ = src;

  /**
   * @type {ol.TileCoord}
   */
  this.wrappedTileCoord = urlTileCoord;

  /**
   * @type {Array.<ol.EventsKey>}
   */
  this.loadListenerKeys_ = [];

  /**
   * @type {Array.<ol.EventsKey>}
   */
  this.sourceTileListenerKeys_ = [];

  if (urlTileCoord) {
    var extent = tileGrid.getTileCoordExtent(urlTileCoord);
    var resolution = tileGrid.getResolution(tileCoord[0]);
    var sourceZ = sourceTileGrid.getZForResolution(resolution);
    sourceTileGrid.forEachTileCoord(extent, sourceZ, function(sourceTileCoord) {
      var sharedExtent = ol.extent.getIntersection(extent,
          sourceTileGrid.getTileCoordExtent(sourceTileCoord));
      if (ol.extent.getWidth(sharedExtent) / resolution >= 0.5 &&
          ol.extent.getHeight(sharedExtent) / resolution >= 0.5) {
        // only include source tile if overlap is at least 1 pixel
        var sourceTileKey = sourceTileCoord.toString();
        var sourceTile = sourceTiles[sourceTileKey];
        if (!sourceTile) {
          var tileUrl = tileUrlFunction(sourceTileCoord, pixelRatio, projection);
          sourceTile = sourceTiles[sourceTileKey] = new tileClass(sourceTileCoord,
              tileUrl == undefined ? ol.TileState.EMPTY : ol.TileState.IDLE,
              tileUrl == undefined ? '' : tileUrl,
              format, tileLoadFunction);
          this.sourceTileListenerKeys_.push(
              ol.events.listen(sourceTile, ol.events.EventType.CHANGE, handleTileChange));
        }
        sourceTile.consumers++;
        this.tileKeys.push(sourceTileKey);
      }
    }.bind(this));
  }

};
ol.inherits(ol.VectorImageTile, ol.Tile);

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.disposeInternal = function() {
  for (var i = 0, ii = this.tileKeys.length; i < ii; ++i) {
    var sourceTileKey = this.tileKeys[i];
    var sourceTile = this.getTile(sourceTileKey);
    sourceTile.consumers--;
    if (sourceTile.consumers == 0) {
      delete this.sourceTiles_[sourceTileKey];
      sourceTile.dispose();
    }
  }
  this.tileKeys.length = 0;
  this.sourceTiles_ = null;
  if (this.state == ol.TileState.LOADING) {
    this.loadListenerKeys_.forEach(ol.events.unlistenByKey);
    this.loadListenerKeys_.length = 0;
  }
  if (this.interimTile) {
    this.interimTile.dispose();
  }
  this.state = ol.TileState.ABORT;
  this.changed();
  this.sourceTileListenerKeys_.forEach(ol.events.unlistenByKey);
  this.sourceTileListenerKeys_.length = 0;
  ol.Tile.prototype.disposeInternal.call(this);
};

/**
 * @return {CanvasRenderingContext2D} The rendering context.
 */
ol.VectorImageTile.prototype.getContext = function() {
  if (!this.context_) {
    this.context_ = ol.dom.createCanvasContext2D();
  }
  return this.context_;
};

/**
 * Get the Canvas for this tile.
 * @return {HTMLCanvasElement} Canvas.
 */
ol.VectorImageTile.prototype.getImage = function() {
  return this.replayState_.renderedTileRevision == -1 ?
    null : this.context_.canvas;
};

/**
 * @return {ol.TileReplayState} The replay state.
 */
ol.VectorImageTile.prototype.getReplayState = function() {
  return this.replayState_;
};

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.getKey = function() {
  return this.tileKeys.join('/') + '/' + this.src_;
};

/**
 * @param {string} tileKey Key (tileCoord) of the source tile.
 * @return {ol.VectorTile} Source tile.
 */
ol.VectorImageTile.prototype.getTile = function(tileKey) {
  return this.sourceTiles_[tileKey];
};

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.load = function() {
  var leftToLoad = 0;
  var errors = false;
  if (this.state == ol.TileState.IDLE) {
    this.setState(ol.TileState.LOADING);
  }
  if (this.state == ol.TileState.LOADING) {
    this.tileKeys.forEach(function(sourceTileKey) {
      var sourceTile = this.getTile(sourceTileKey);
      if (sourceTile.state == ol.TileState.IDLE) {
        sourceTile.setLoader(this.loader_);
        sourceTile.load();
      } else if (sourceTile.state == ol.TileState.ERROR) {
        errors = true;
      } else if (sourceTile.state == ol.TileState.EMPTY) {
        ol.array.remove(this.tileKeys, sourceTileKey);
      }
      if (sourceTile.state == ol.TileState.LOADING) {
        var key = ol.events.listen(sourceTile, ol.events.EventType.CHANGE, function(e) {
          var state = sourceTile.getState();
          if (state == ol.TileState.LOADED ||
              state == ol.TileState.ERROR) {
            --leftToLoad;
            ol.events.unlistenByKey(key);
            ol.array.remove(this.loadListenerKeys_, key);
            if (state == ol.TileState.ERROR) {
              ol.array.remove(this.tileKeys, sourceTileKey);
              errors = true;
            }
            if (leftToLoad == 0) {
              this.setState(this.tileKeys.length > 0 ?
                ol.TileState.LOADED : ol.TileState.ERROR);
            }
          }
        }.bind(this));
        this.loadListenerKeys_.push(key);
        ++leftToLoad;
      }
    }.bind(this));
  }
  if (leftToLoad == 0) {
    setTimeout(function() {
      this.setState(this.tileKeys.length > 0 ?
        ol.TileState.LOADED :
        (errors ? ol.TileState.ERROR : ol.TileState.EMPTY));
    }.bind(this), 0);
  }
};

/**
 * Sets the loader for a tile.
 * @param {ol.VectorTile} tile Vector tile.
 * @param {string} url URL.
 */
ol.VectorImageTile.defaultLoadFunction = function(tile, url) {
  var loader = ol.featureloader.loadFeaturesXhr(
      url, tile.getFormat(), tile.onLoad_.bind(tile), tile.onError_.bind(tile));

  tile.setLoader(loader);
};
<commit_msg>Remove error tiles after loading is finished<commit_after>goog.provide('ol.VectorImageTile');

goog.require('ol');
goog.require('ol.Tile');
goog.require('ol.TileState');
goog.require('ol.array');
goog.require('ol.dom');
goog.require('ol.events');
goog.require('ol.extent');
goog.require('ol.events.EventType');
goog.require('ol.featureloader');

/**
 * @constructor
 * @extends {ol.Tile}
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @param {ol.TileState} state State.
 * @param {string} src Data source url.
 * @param {ol.format.Feature} format Feature format.
 * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function.
 * @param {ol.TileCoord} urlTileCoord Wrapped tile coordinate for source urls.
 * @param {ol.TileUrlFunctionType} tileUrlFunction Tile url function.
 * @param {ol.tilegrid.TileGrid} sourceTileGrid Tile grid of the source.
 * @param {ol.tilegrid.TileGrid} tileGrid Tile grid of the renderer.
 * @param {Object.<string,ol.VectorTile>} sourceTiles Source tiles.
 * @param {number} pixelRatio Pixel ratio.
 * @param {ol.proj.Projection} projection Projection.
 * @param {function(new: ol.VectorTile, ol.TileCoord, ol.TileState, string,
 *     ol.format.Feature, ol.TileLoadFunctionType)} tileClass Class to
 *     instantiate for source tiles.
 * @param {function(this: ol.source.VectorTile, ol.events.Event)} handleTileChange
 *     Function to call when a source tile's state changes.
 */
ol.VectorImageTile = function(tileCoord, state, src, format, tileLoadFunction,
    urlTileCoord, tileUrlFunction, sourceTileGrid, tileGrid, sourceTiles,
    pixelRatio, projection, tileClass, handleTileChange) {

  ol.Tile.call(this, tileCoord, state);

  /**
   * @private
   * @type {CanvasRenderingContext2D}
   */
  this.context_ = null;

  /**
   * @private
   * @type {ol.FeatureLoader}
   */
  this.loader_;

  /**
   * @private
   * @type {ol.TileReplayState}
   */
  this.replayState_ = {
    dirty: false,
    renderedRenderOrder: null,
    renderedRevision: -1,
    renderedTileRevision: -1
  };

  /**
   * @private
   * @type {Object.<string,ol.VectorTile>}
   */
  this.sourceTiles_ = sourceTiles;

  /**
   * Keys of source tiles used by this tile. Use with {@link #getTile}.
   * @type {Array.<string>}
   */
  this.tileKeys = [];

  /**
   * @type {string}
   */
  this.src_ = src;

  /**
   * @type {ol.TileCoord}
   */
  this.wrappedTileCoord = urlTileCoord;

  /**
   * @type {Array.<ol.EventsKey>}
   */
  this.loadListenerKeys_ = [];

  /**
   * @type {Array.<ol.EventsKey>}
   */
  this.sourceTileListenerKeys_ = [];

  if (urlTileCoord) {
    var extent = tileGrid.getTileCoordExtent(urlTileCoord);
    var resolution = tileGrid.getResolution(tileCoord[0]);
    var sourceZ = sourceTileGrid.getZForResolution(resolution);
    sourceTileGrid.forEachTileCoord(extent, sourceZ, function(sourceTileCoord) {
      var sharedExtent = ol.extent.getIntersection(extent,
          sourceTileGrid.getTileCoordExtent(sourceTileCoord));
      if (ol.extent.getWidth(sharedExtent) / resolution >= 0.5 &&
          ol.extent.getHeight(sharedExtent) / resolution >= 0.5) {
        // only include source tile if overlap is at least 1 pixel
        var sourceTileKey = sourceTileCoord.toString();
        var sourceTile = sourceTiles[sourceTileKey];
        if (!sourceTile) {
          var tileUrl = tileUrlFunction(sourceTileCoord, pixelRatio, projection);
          sourceTile = sourceTiles[sourceTileKey] = new tileClass(sourceTileCoord,
              tileUrl == undefined ? ol.TileState.EMPTY : ol.TileState.IDLE,
              tileUrl == undefined ? '' : tileUrl,
              format, tileLoadFunction);
          this.sourceTileListenerKeys_.push(
              ol.events.listen(sourceTile, ol.events.EventType.CHANGE, handleTileChange));
        }
        sourceTile.consumers++;
        this.tileKeys.push(sourceTileKey);
      }
    }.bind(this));
  }

};
ol.inherits(ol.VectorImageTile, ol.Tile);

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.disposeInternal = function() {
  for (var i = 0, ii = this.tileKeys.length; i < ii; ++i) {
    var sourceTileKey = this.tileKeys[i];
    var sourceTile = this.getTile(sourceTileKey);
    sourceTile.consumers--;
    if (sourceTile.consumers == 0) {
      delete this.sourceTiles_[sourceTileKey];
      sourceTile.dispose();
    }
  }
  this.tileKeys.length = 0;
  this.sourceTiles_ = null;
  if (this.state == ol.TileState.LOADING) {
    this.loadListenerKeys_.forEach(ol.events.unlistenByKey);
    this.loadListenerKeys_.length = 0;
  }
  if (this.interimTile) {
    this.interimTile.dispose();
  }
  this.state = ol.TileState.ABORT;
  this.changed();
  this.sourceTileListenerKeys_.forEach(ol.events.unlistenByKey);
  this.sourceTileListenerKeys_.length = 0;
  ol.Tile.prototype.disposeInternal.call(this);
};

/**
 * @return {CanvasRenderingContext2D} The rendering context.
 */
ol.VectorImageTile.prototype.getContext = function() {
  if (!this.context_) {
    this.context_ = ol.dom.createCanvasContext2D();
  }
  return this.context_;
};

/**
 * Get the Canvas for this tile.
 * @return {HTMLCanvasElement} Canvas.
 */
ol.VectorImageTile.prototype.getImage = function() {
  return this.replayState_.renderedTileRevision == -1 ?
    null : this.context_.canvas;
};

/**
 * @return {ol.TileReplayState} The replay state.
 */
ol.VectorImageTile.prototype.getReplayState = function() {
  return this.replayState_;
};

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.getKey = function() {
  return this.tileKeys.join('/') + '/' + this.src_;
};

/**
 * @param {string} tileKey Key (tileCoord) of the source tile.
 * @return {ol.VectorTile} Source tile.
 */
ol.VectorImageTile.prototype.getTile = function(tileKey) {
  return this.sourceTiles_[tileKey];
};

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.load = function() {
  var leftToLoad = 0;
  if (this.state == ol.TileState.IDLE) {
    this.setState(ol.TileState.LOADING);
  }
  if (this.state == ol.TileState.LOADING) {
    this.tileKeys.forEach(function(sourceTileKey) {
      var sourceTile = this.getTile(sourceTileKey);
      if (sourceTile.state == ol.TileState.IDLE) {
        sourceTile.setLoader(this.loader_);
        sourceTile.load();
      }
      if (sourceTile.state == ol.TileState.LOADING) {
        var key = ol.events.listen(sourceTile, ol.events.EventType.CHANGE, function(e) {
          var state = sourceTile.getState();
          if (state == ol.TileState.LOADED ||
              state == ol.TileState.ERROR) {
            --leftToLoad;
            ol.events.unlistenByKey(key);
            ol.array.remove(this.loadListenerKeys_, key);
            if (leftToLoad == 0) {
              this.finishLoading_();
            }
          }
        }.bind(this));
        this.loadListenerKeys_.push(key);
        ++leftToLoad;
      }
    }.bind(this));
  }
  if (leftToLoad == 0) {
    setTimeout(this.finishLoading_.bind(this), 0);
  }
};

/**
 * @private
 */
ol.VectorImageTile.prototype.finishLoading_ = function() {
  var errors = false;
  var tile;
  for (var i = this.tileKeys.length - 1; i >= 0; --i) {
    tile = this.getTile(this.tileKeys[i]);
    if (tile.getState() == ol.TileState.ERROR) {
      errors = true;
    }
    if (tile.getState() != ol.TileState.LOADED) {
      this.tileKeys.splice(i, 1);
    }
  }
  this.setState(this.tileKeys.length > 0 ?
    ol.TileState.LOADED :
    (errors ? ol.TileState.ERROR : ol.TileState.EMPTY));
};

/**
 * Sets the loader for a tile.
 * @param {ol.VectorTile} tile Vector tile.
 * @param {string} url URL.
 */
ol.VectorImageTile.defaultLoadFunction = function(tile, url) {
  var loader = ol.featureloader.loadFeaturesXhr(
      url, tile.getFormat(), tile.onLoad_.bind(tile), tile.onError_.bind(tile));

  tile.setLoader(loader);
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var lint = require('./lib');
var mocha = require('gulp-mocha');
var git = require('gulp-git');
var bump = require('gulp-bump');

// Lint task - Meta AF
gulp.task('lint', lint({ src: './lib/*.js' }));

// Tests
gulp.task('test', ['lint'], function() {
  return gulp.src('./test/index.js', { read: false })
    .pipe(mocha({ reporter: 'dot' }));
});

// Bump patch version
gulp.task('bump', ['test'], function() {
  return gulp.src(['./package.json'])
    .pipe(bump())
    .pipe(gulp.dest('./'));
});

// Bump minor version
gulp.task('bump:minor', ['test'], function() {
  return gulp.src(['./package.json'])
    .pipe(bump({ type: 'minor' }))
    .pipe(gulp.dest('./'));
});

// Bump major version
gulp.task('bump:major', ['test'], function() {
  return gulp.src(['./package.json'])
    .pipe(bump({ type: 'major' }))
    .pipe(gulp.dest('./'));
});

// Tag release in git
gulp.task('tag', function() {
  var pkg = require('./package.json');
  var v = 'v' + pkg.version;
  var message = 'Release ' + v;

  return gulp.src('./')
    .pipe(git.commit(message))
    .pipe(git.tag(v, message))
    .pipe(git.push('origin', 'master', '--tags'))
    .pipe(gulp.dest('./'));
});

// Release to git
gulp.task('release', ['bump', 'tag']);
gulp.task('release:minor', ['bump:minor', 'tag']);
gulp.task('release:major', ['bump:major', 'tag']);
<commit_msg>change tag task<commit_after>var gulp = require('gulp');
var lint = require('./lib');
var mocha = require('gulp-mocha');
var git = require('gulp-git');
var bump = require('gulp-bump');

// Lint task - Meta AF
gulp.task('lint', lint({ src: './lib/*.js' }));

// Tests
gulp.task('test', ['lint'], function() {
  return gulp.src('./test/index.js', { read: false })
    .pipe(mocha({ reporter: 'dot' }));
});

// Bump patch version
gulp.task('bump', ['test'], function() {
  return gulp.src(['./package.json'])
    .pipe(bump())
    .pipe(gulp.dest('./'));
});

// Bump minor version
gulp.task('bump:minor', ['test'], function() {
  return gulp.src(['./package.json'])
    .pipe(bump({ type: 'minor' }))
    .pipe(gulp.dest('./'));
});

// Bump major version
gulp.task('bump:major', ['test'], function() {
  return gulp.src(['./package.json'])
    .pipe(bump({ type: 'major' }))
    .pipe(gulp.dest('./'));
});

// Tag release in git
gulp.task('tag', function() {
  var pkg = require('./package.json');
  var v = 'v' + pkg.version;
  var message = 'Release ' + v;

  return gulp.src('.')
    .pipe(git.commit(message))
    .pipe(git.tag(v, message))
    .on('end', function() {
      this.pipe(git.push('origin', 'master', '--tags'))
        .end();
    });
});

// Release to git
gulp.task('release', ['bump', 'tag']);
gulp.task('release:minor', ['bump:minor', 'tag']);
gulp.task('release:major', ['bump:major', 'tag']);
<|endoftext|>


<commit_before>$(document).ready(function ()
{
    $("#history-back").click(function ()
    {
        history.back();
    });
});<commit_msg>update $ function<commit_after>$(function ()
{
    $("#history-back").click(function ()
    {
        history.back();
    });
});<|endoftext|>


<commit_before>$(window).load(function() {
	$('div.source pre, pre code').each(function(i, e) {
		e.innerHTML = e.innerHTML.replace(/\n/g, "
").replace(/\t/g, "  ");
	});
})

<commit_msg>Fix navbar due to js processing<commit_after>$(window).load(function() {
	$('div.source pre, pre code').each(function(i, e) {
		e.innerHTML = e.innerHTML.replace(/\n/g, "
").replace(/\t/g, "  ");
	});
	$("#toc-bar").affix({});
})

<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const babel = require('gulp-babel');
const plumber = require('gulp-plumber');
const stylus = require('gulp-stylus');
const poststylus = require('poststylus');
const rucksack = require('rucksack-css');
const flexibility = require('postcss-flexibility');
const prefixer = require('autoprefixer');
const fontMagician = require('postcss-font-magician');
const gcmq = require('gulp-group-css-media-queries');
const cssnano = require('gulp-cssnano');
const sourcemaps = require('gulp-sourcemaps');
const lost = require('lost');
const rupture = require('rupture');
const postcss = require('gulp-postcss');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const pug = require('gulp-pug');
const data = require('gulp-data');
const imagemin = require('gulp-imagemin');
const browserSync = require('browser-sync');
const svgmin = require('gulp-svgmin');
const svgstore = require('gulp-svgstore');
const cheerio = require('gulp-cheerio');
const mdcss = require('mdcss');
const fs = require('fs');
const del = require('del');

const srcApp = {
  js: [
    'src/js/**/*.js'
  ],
  css: 'src/styl/**/*.styl',
  styl: 'src/styl/style.styl',
  html: 'src/pug/*.pug',
  icons: 'src/svg/icons/*',
  svg: 'src/svg/',
  img: 'src/img/**/*',
  data: 'src/data/',
  helpers: 'src/helpers/'
};

const buildApp = {
  build: 'build/**/*',
  js: 'build/js/',
  css: 'build/css/',
  html: 'build/',
  img: 'build/img',
  svg: 'build/svg'
};

let dataJson = {};
let files = [];

gulp.task('clean', () => {
  return del(buildApp.build);
});

gulp.task('css', () => {
  return gulp.src(srcApp.styl)
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(stylus({
      use: [
        rupture(),
        poststylus([
          lost(),
          fontMagician(),
          rucksack(),
          flexibility(),
          prefixer()
        ])
      ],
      compress: false
    }))
    .pipe(gcmq())
    .pipe(cssnano())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(buildApp.css));
});

gulp.task('styleguide', () => {
  return gulp.src(srcApp.styl)
    .pipe(plumber())
    .pipe(stylus({
      use: [
        rupture(),
        poststylus([
          lost(),
          fontMagician(),
          rucksack({
            autoprefixer: true
          })
        ])
      ],
      compress: false
    }))
    .pipe(postcss([
      mdcss({
        //logo: '',
        destination: 'build/styleguide',
        title: 'Styleguide',
        examples: {
          css: ['../css/style.css']
        },
      })
    ]));
});

gulp.task('js', () => {
  return gulp.src(srcApp.js)
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(buildApp.js));
});

gulp.task('read:data', () => {
  const dataAdapter = require('./' + srcApp.helpers + 'dataAdapter');
  fs.readdir(srcApp.data, (err, items) => {
    files = items.map(item => item.split('.')[0]);
    items.forEach((file, index) => dataJson[files[index]] = dataAdapter(srcApp.data + file));
  });
});

gulp.task('html', () => {
  return gulp.src(srcApp.html)
    .pipe(plumber())
    .pipe(data(dataJson))
    .pipe(pug())
    .pipe(gulp.dest(buildApp.html));
});

gulp.task('images', () => {
  return gulp.src(srcApp.img)
    .pipe(plumber())
    .pipe(imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest(buildApp.img));
});

gulp.task('svg', () => {
  gulp.src(srcApp.svg)
    .pipe(svgmin())
    .pipe(gulp.dest(srcApp.svg));
  gulp.src(srcApp.svg)
    .pipe(svgmin())
    .pipe(gulp.dest(buildApp.svg));
});

gulp.task('icons', () => {
  return gulp.src(srcApp.icons)
    .pipe(svgmin())
    .pipe(svgstore({ fileName: 'icons.svg', inlineSvg: true }))
    .pipe(cheerio({
      run: function ($, file) {
        $('svg').addClass('hide');
        $('[fill]').removeAttr('fill');
      },

      parserOptions: { xmlMode: true }
    }))
    .pipe(gulp.dest(buildApp.svg));
});

gulp.task('watch', () => {
  gulp.watch(srcApp.html, { debounceDelay: 300 }, ['html']);
  gulp.watch(srcApp.data + '**/*', { debounceDelay: 300 }, ['read:data', 'html']);
  gulp.watch(srcApp.css, ['css']);
  gulp.watch(srcApp.js, ['js']);
  gulp.watch(srcApp.img, ['images']);
  gulp.watch(srcApp.icons, ['icons']);
});

gulp.task('browser-sync', () => {
  var files = [
    buildApp.build
  ];

  browserSync.init(files, {
    server: {
      baseDir: './build/'
    },
  });

});

gulp.task('build', ['clean'], () => {
  gulp.start(
    'styleguide',
    'css',
    'read:data',
    'html',
    'js',
    'images',
    'svg',
    'icons'
  );
});

gulp.task('default', [
  'build',
  'watch',
  'browser-sync'
]);
<commit_msg>Remove flexibility<commit_after>'use strict';

const gulp = require('gulp');
const babel = require('gulp-babel');
const plumber = require('gulp-plumber');
const stylus = require('gulp-stylus');
const poststylus = require('poststylus');
const rucksack = require('rucksack-css');
const prefixer = require('autoprefixer');
const fontMagician = require('postcss-font-magician');
const gcmq = require('gulp-group-css-media-queries');
const cssnano = require('gulp-cssnano');
const sourcemaps = require('gulp-sourcemaps');
const lost = require('lost');
const rupture = require('rupture');
const postcss = require('gulp-postcss');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const pug = require('gulp-pug');
const data = require('gulp-data');
const imagemin = require('gulp-imagemin');
const browserSync = require('browser-sync');
const svgmin = require('gulp-svgmin');
const svgstore = require('gulp-svgstore');
const cheerio = require('gulp-cheerio');
const mdcss = require('mdcss');
const fs = require('fs');
const del = require('del');

const srcApp = {
  js: [
    'src/js/**/*.js'
  ],
  css: 'src/styl/**/*.styl',
  styl: 'src/styl/style.styl',
  html: 'src/pug/*.pug',
  icons: 'src/svg/icons/*',
  svg: 'src/svg/',
  img: 'src/img/**/*',
  data: 'src/data/',
  helpers: 'src/helpers/'
};

const buildApp = {
  build: 'build/**/*',
  js: 'build/js/',
  css: 'build/css/',
  html: 'build/',
  img: 'build/img',
  svg: 'build/svg'
};

let dataJson = {};
let files = [];

gulp.task('clean', () => {
  return del(buildApp.build);
});

gulp.task('css', () => {
  return gulp.src(srcApp.styl)
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(stylus({
      use: [
        rupture(),
        poststylus([
          lost(),
          fontMagician(),
          rucksack(),
          prefixer()
        ])
      ],
      compress: false
    }))
    .pipe(gcmq())
    .pipe(cssnano())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(buildApp.css));
});

gulp.task('styleguide', () => {
  return gulp.src(srcApp.styl)
    .pipe(plumber())
    .pipe(stylus({
      use: [
        rupture(),
        poststylus([
          lost(),
          fontMagician(),
          rucksack({
            autoprefixer: true
          })
        ])
      ],
      compress: false
    }))
    .pipe(postcss([
      mdcss({
        //logo: '',
        destination: 'build/styleguide',
        title: 'Styleguide',
        examples: {
          css: ['../css/style.css']
        },
      })
    ]));
});

gulp.task('js', () => {
  return gulp.src(srcApp.js)
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(buildApp.js));
});

gulp.task('read:data', () => {
  const dataAdapter = require('./' + srcApp.helpers + 'dataAdapter');
  fs.readdir(srcApp.data, (err, items) => {
    files = items.map(item => item.split('.')[0]);
    items.forEach((file, index) => dataJson[files[index]] = dataAdapter(srcApp.data + file));
  });
});

gulp.task('html', () => {
  return gulp.src(srcApp.html)
    .pipe(plumber())
    .pipe(data(dataJson))
    .pipe(pug())
    .pipe(gulp.dest(buildApp.html));
});

gulp.task('images', () => {
  return gulp.src(srcApp.img)
    .pipe(plumber())
    .pipe(imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest(buildApp.img));
});

gulp.task('svg', () => {
  gulp.src(srcApp.svg)
    .pipe(svgmin())
    .pipe(gulp.dest(srcApp.svg));
  gulp.src(srcApp.svg)
    .pipe(svgmin())
    .pipe(gulp.dest(buildApp.svg));
});

gulp.task('icons', () => {
  return gulp.src(srcApp.icons)
    .pipe(svgmin())
    .pipe(svgstore({ fileName: 'icons.svg', inlineSvg: true }))
    .pipe(cheerio({
      run: function ($, file) {
        $('svg').addClass('hide');
        $('[fill]').removeAttr('fill');
      },

      parserOptions: { xmlMode: true }
    }))
    .pipe(gulp.dest(buildApp.svg));
});

gulp.task('watch', () => {
  gulp.watch(srcApp.html, { debounceDelay: 300 }, ['html']);
  gulp.watch(srcApp.data + '**/*', { debounceDelay: 300 }, ['read:data', 'html']);
  gulp.watch(srcApp.css, ['css']);
  gulp.watch(srcApp.js, ['js']);
  gulp.watch(srcApp.img, ['images']);
  gulp.watch(srcApp.icons, ['icons']);
});

gulp.task('browser-sync', () => {
  var files = [
    buildApp.build
  ];

  browserSync.init(files, {
    server: {
      baseDir: './build/'
    },
  });

});

gulp.task('build', ['clean'], () => {
  gulp.start(
    'styleguide',
    'css',
    'read:data',
    'html',
    'js',
    'images',
    'svg',
    'icons'
  );
});

gulp.task('default', [
  'build',
  'watch',
  'browser-sync'
]);
<|endoftext|>


<commit_before>(function () {
    Metamaps.Views = {};

    var initialized = false;

Metamaps.Views.init = function () {

    Metamaps.Views.MapperCard = Backbone.View.extend({

        template: Hogan.compile( $('#mapperCardTemplate').html() ),

        tagName: "div",

        className: "mapper",

        render: function () {
            this.$el.html( this.template.render(this.model) );
            return this;
        }
    });

    Metamaps.Views.MapCard = Backbone.View.extend({

        template: Hogan.compile( $('#mapCardTemplate').html() ),

        tagName: "div",

        className: "map",

        id: function() {
            return this.model.id;
        },

        initialize: function () {
            this.listenTo(this.model, "change", this.render);
        },

        render: function () {
            this.$el.html( this.template.render(this.model.attrForCards()) );
            return this;
        }

    });

    var mapsWrapper = Backbone.View.extend({

        initialize: function (opts) {

        },
        setCollection: function (collection) {
            if (this.collection) this.stopListening(this.collection);
            this.collection = collection;
            this.listenTo(this.collection, 'add', this.render);
            this.listenTo(this.collection, 'successOnFetch', this.handleSuccess);
            this.listenTo(this.collection, 'errorOnFetch', this.handleError);
        },
        render: function (mapperObj) {

            var that = this;

            this.el.innerHTML = "";

            // in case it is a page where we have to display the mapper card
            if (mapperObj) {
                var view = new Metamaps.Views.MapperCard({ model: mapperObj });

                that.el.appendChild( view.render().el );
            }

            this.collection.each(function (map) {
                var view = new Metamaps.Views.MapCard({ model: map });

                that.el.appendChild( view.render().el );
            });
            this.$el.append('

');
            var m = Metamaps.Famous.maps.surf;
            m.setContent(this.el);
            setTimeout(function(){
                var height = $(that.el).height() + 32 + 56;
                m.setSize([undefined, height]);
            }, 100);

            if (!initialized) {
                m.deploy(m._currTarget);
                initialized = true;
                setTimeout(function(){
                    var height = $(that.el).height() + 32 + 56;
                    m.setSize([undefined, height]);
                }, 100);
            }

            Metamaps.Loading.hide();

            console.log("OK current page is " + Metamaps.currentPage);
            console.log(Metamaps);
            setTimeout((function(localCurrentPage){ return function(){
                console.log("YEAH current page is " + Metamaps.currentPage);
                console.log("YEAH current page passed is " + localCurrentPage);
                console.log(Metamaps);
                var path = (Metamaps.currentSection == "") ? "" : "/explore/" + localCurrentPage;

                // alter url if for mapper profile page
                if (that.collection && that.collection.mapperId) {
                    path += "/" + that.collection.mapperId;
                }

                Metamaps.Router.navigate(path);
            }})(Metamaps.currentPage), 500);
        },
        handleSuccess: function () {
            var that = this;

            if (this.collection && this.collection.id === "mapper") {
                this.fetchUserThenRender();
            }
            else {
                this.render();
            }
        },
        handleError: function () {
            console.log('error loading maps!'); //TODO
        },
        fetchUserThenRender: function () {
            var that = this;
            // first load the mapper object and then call the render function
            $.ajax({
                url: "/users/" + this.collection.mapperId + "/details.json",
                success: function (response) {
                    that.render(response);
                },
                error: function () {

                }
            });
        }
    });

    Metamaps.Views.exploreMaps = new mapsWrapper();
};

})();
<commit_msg>remove console.logs whoops<commit_after>(function () {
    Metamaps.Views = {};

    var initialized = false;

Metamaps.Views.init = function () {

    Metamaps.Views.MapperCard = Backbone.View.extend({

        template: Hogan.compile( $('#mapperCardTemplate').html() ),

        tagName: "div",

        className: "mapper",

        render: function () {
            this.$el.html( this.template.render(this.model) );
            return this;
        }
    });

    Metamaps.Views.MapCard = Backbone.View.extend({

        template: Hogan.compile( $('#mapCardTemplate').html() ),

        tagName: "div",

        className: "map",

        id: function() {
            return this.model.id;
        },

        initialize: function () {
            this.listenTo(this.model, "change", this.render);
        },

        render: function () {
            this.$el.html( this.template.render(this.model.attrForCards()) );
            return this;
        }

    });

    var mapsWrapper = Backbone.View.extend({

        initialize: function (opts) {

        },
        setCollection: function (collection) {
            if (this.collection) this.stopListening(this.collection);
            this.collection = collection;
            this.listenTo(this.collection, 'add', this.render);
            this.listenTo(this.collection, 'successOnFetch', this.handleSuccess);
            this.listenTo(this.collection, 'errorOnFetch', this.handleError);
        },
        render: function (mapperObj) {

            var that = this;

            this.el.innerHTML = "";

            // in case it is a page where we have to display the mapper card
            if (mapperObj) {
                var view = new Metamaps.Views.MapperCard({ model: mapperObj });

                that.el.appendChild( view.render().el );
            }

            this.collection.each(function (map) {
                var view = new Metamaps.Views.MapCard({ model: map });

                that.el.appendChild( view.render().el );
            });
            this.$el.append('

');
            var m = Metamaps.Famous.maps.surf;
            m.setContent(this.el);
            setTimeout(function(){
                var height = $(that.el).height() + 32 + 56;
                m.setSize([undefined, height]);
            }, 100);

            if (!initialized) {
                m.deploy(m._currTarget);
                initialized = true;
                setTimeout(function(){
                    var height = $(that.el).height() + 32 + 56;
                    m.setSize([undefined, height]);
                }, 100);
            }

            Metamaps.Loading.hide();

            setTimeout((function(localCurrentPage){ return function(){
                var path = (Metamaps.currentSection == "") ? "" : "/explore/" + localCurrentPage;

                // alter url if for mapper profile page
                if (that.collection && that.collection.mapperId) {
                    path += "/" + that.collection.mapperId;
                }

                Metamaps.Router.navigate(path);
            }})(Metamaps.currentPage), 500);
        },
        handleSuccess: function () {
            var that = this;

            if (this.collection && this.collection.id === "mapper") {
                this.fetchUserThenRender();
            }
            else {
                this.render();
            }
        },
        handleError: function () {
            console.log('error loading maps!'); //TODO
        },
        fetchUserThenRender: function () {
            var that = this;
            // first load the mapper object and then call the render function
            $.ajax({
                url: "/users/" + this.collection.mapperId + "/details.json",
                success: function (response) {
                    that.render(response);
                },
                error: function () {

                }
            });
        }
    });

    Metamaps.Views.exploreMaps = new mapsWrapper();
};

})();
<|endoftext|>


<commit_before>angular.module('courseReg', [])
    .controller('CoureRegController', ['$scope', '$http', function($scope, $http){
        $scope.courseRegList;

        var clickListener = function(e)
        {

           if(e.target.id == "sendEmail")
           {
               emailjs.send("gmail","gmail",{name:$("#username").html(), email:$("#email").html(), tel:$("#tel").html()}).then(
                   function(response) {
                       alert("המייל נשלח בהצלחה");
                   },
                   function(error) {
                       alert("נכשל");
                   }
               );
           }

        }

        $scope.loadCourseReg = function()
        {
            $http.get('/course')
                .success(function(res){
                    $scope.courseRegList = res;
                    $("#sendEmail").click(clickListener);
                })
                .catch(function(err) {
                    console.log('Get courses error.');
                });
        };
        $scope.loadCourseReg();
    }]);

<commit_msg>minor changes<commit_after>angular.module('courseReg', [])
    .controller('CoureRegController', ['$scope', '$http', function($scope, $http){
        $scope.courseRegList;

        var clickListener = function(e)
        {

           if(e.target.id == "sendEmail")
           {
               emailjs.send("gmail","gmail",{name:$("#username").val(), email:$("#email").val(), tel:$("#tel").val()}).then(
                   function(response) {
                       alert("המייל נשלח בהצלחה");
                   },
                   function(error) {
                       alert("נכשל");
                   }
               );
           }

        }

        $scope.loadCourseReg = function()
        {
            $http.get('/course')
                .success(function(res){
                    $scope.courseRegList = res;
                    $("#sendEmail").click(clickListener);
                })
                .catch(function(err) {
                    console.log('Get courses error.');
                });
        };
        $scope.loadCourseReg();
    }]);

<|endoftext|>


<commit_before>/*
 * Audiovisualization using the html canvas element.
 * Please note: this is an offline-only version. For this version to be used online you need an XMLHttpRequest to load the music file!
 * ©2017, Dominik Hofacker
 * https://www.behance.net/dominikhofacker
 * Please consider supporting this project on behance:
 * https://www.behance.net/gallery/49260123/Web-Audio-Visualization
 */

var rafID = null;
var analyser = null;
var c = null;
var cDraw = null;
var ctx = null;
var micropone = null;
var ctxDraw = null;

var loader;
var filename;
var renderer;
var skull;
var sunglasses;
var headphones;
var pivot;
var cube_mesh;
var scene;
var camera;
var fileChosen = false;
var RADIUS = 2;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var loadedVar = 0, totalVar = 0;

const HIGHLIGHT_COLORS = [0x4200ff, 0x00ffff, 0xff0000, 0xff00ff];
const LOADING_WRAPPER_HEIGHT = 100;

//handle different prefix of the audio context
var AudioContext = AudioContext || webkitAudioContext;
//create the context.
var context = new AudioContext();

//using requestAnimationFrame instead of timeout...
if (!window.requestAnimationFrame)
	window.requestAnimationFrame = window.webkitRequestAnimationFrame;

$(function () {

		/*$(".inputfile + label, .button").addClass("animated fadeInUp");
		$('.inputfile + label, .button').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
                $('.inputfile + label, .button').removeClass('fadeInUp');
         });*/

		$('#loading_wrapper').css("top", ($(window).height() / 2 - LOADING_WRAPPER_HEIGHT));

		//handle different types navigator objects of different browsers
		navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
	            navigator.mozGetUserMedia || navigator.msGetUserMedia;
	    //eigene Init
	    loader = new BufferLoader();
            //loader.visualize = visualize;
            //init canvas
	    initBinCanvas();
		//start updating
		rafID = window.requestAnimationFrame(updateVisualization);

});

function handleFiles(files) {
    if(files.length === 0){
        return;
    }
	fileChosen = true;
    setupAudioNodes();

	var fileReader  = new FileReader();
    fileReader.onload = function(){
         var arrayBuffer = this.result;
         console.log(arrayBuffer);
         console.log(arrayBuffer.byteLength);
     };
     fileReader.readAsArrayBuffer(files[0]);
     var url = URL.createObjectURL(files[0]);

	var request = new XMLHttpRequest();
	request.open('GET', url, true);
	request.responseType = 'arraybuffer';

 	// When loaded decode the data
	request.onload = function() {
		// decode the data
		context.decodeAudioData(request.response, function(buffer) {
		// when the audio is decoded play the sound
		sourceNode.buffer = buffer;
		sourceNode.start(0);
		//on error
		}, function(e) {
			console.log(e);
		});
	};
	request.send();

	camera.position.z = 375;
	camera.position.y = 0;

	$(".inputfile + label, .button").addClass("animated fadeOutDown");
}

function playSample() {

	fileChosen = true;
    setupAudioNodes();

	var request = new XMLHttpRequest();
	request.open('GET', 'src/sample.mp3', true);
	request.responseType = 'arraybuffer';

 	// When loaded decode the data
	request.onload = function() {
		// decode the data
		context.decodeAudioData(request.response, function(buffer) {
		// when the audio is decoded play the sound
		sourceNode.buffer = buffer;
		sourceNode.start(0);
		//on error
		}, function(e) {
			console.log(e);
		});
	};
	request.send();

	camera.position.z = 375;
	camera.position.y = 0;

	$(".inputfile + label, .button").addClass("animated fadeOutDown");
	$("#viewer_discretion").html("You are listening to Jordan Schor - Cosmic (feat. Nathan Brumley).");
}

function initBinCanvas () {

	//TODO
	scene = new THREE.Scene();
	scene.background = new THREE.Color( 0x00000);
	camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100000);
	renderer = new THREE.WebGLRenderer();
	renderer.setSize(window.innerWidth, window.innerHeight);
	renderer.setPixelRatio( window.devicePixelRatio );
	document.body.appendChild(renderer.domElement);

	var geometry = new THREE.BoxGeometry(560, 560, 100000, 15, 55, 100);

	var cubeMat = new THREE.MeshBasicMaterial({color: '#4200ff', wireframe: true});
	var testMat = new THREE.MeshStandardMaterial({
		roughness: 0,
		color: 'white'
	});
	cube_mesh = new THREE.Mesh(geometry, cubeMat);
	scene.add(cube_mesh);

	//MATERIALS###################################################################
	var material = new THREE.MeshBasicMaterial({vertexColors: THREE.VertexColors});
	var objMat = new THREE.MeshStandardMaterial({
		color: 'yellow',
		wireframe: true,
		roughness: .3
	});
	var newMat = new THREE.MeshPhongMaterial({
		color: '#6e3bff'
	});
	var headphoneMat = new THREE.MeshStandardMaterial({
		roughness: 0.4,
		color: 'yellow',
		wireframe: false
	});
	var box = new THREE.Box3();
	pivot = new THREE.Group(); //group objs and center pivot of skull

	//LOADING OBJs#################################################################
	var manager = new THREE.LoadingManager();
		manager.onProgress = function ( item, loaded, total ) {
			console.log( item, loaded, total ); //loaded 1 total 3
			loadedVar = loaded;
			totalVar = total;
	};
	var onProgress = function ( xhr ) {
		if ( xhr.lengthComputable ) {
			var percentComplete = xhr.loaded / xhr.total * 100;
			console.log( Math.round(percentComplete, 2) + '% loaded' );
			$(".label").html(Math.round(percentComplete, 2) + '% loaded');
			//console.log("LOADED VAR:" + loadedVar + "\n TOTAL VAR:" + totalVar);
			if (percentComplete === 100 && loadedVar === 2) {
				$(".inputfile + label, .button").css("visibility", "visible");
				$(".inputfile + label, .button").addClass("animated fadeInUp");
				$('.inputfile + label, .button').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
						$('.inputfile + label, .button').removeClass('fadeInUp');
				});
				$("#loading_screen").addClass("animated fadeOut");
				$("#loading_screen").one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
						$("#loading_screen").css("display", "none");
						$("#viewer_discretion").html("This music visualizer may be harmful to viewers who are prone to epilepsy. Viewer discretion is advised.");
				});
			}
		}
	};
	var onError = function ( xhr ) {
	};
	var loader3D = new THREE.OBJLoader( manager );
	// load a resource
	loader3D.load(
		// resource URL
		'src/skull_lowpoly.obj',
		// Function when resource is loaded
		function ( object ) {
			object.traverse(function (child) {
				if ( child instanceof THREE.Mesh ) {

						child.material = newMat;
						child.shading = THREE.FlatShading;

					}
			});
			object.position.y = 0;
			object.position.x = 0;
			box.setFromObject( object );
			box.getCenter( object.position ); // this re-sets the mesh position
			object.position.multiplyScalar( - 1 );
			pivot.add( object );
			skull = object;
	}, onProgress, onError );

	loader3D.load(
		'src/sunglasses.obj',
		function ( object ) {
			object.traverse(function( child ) {
				if (child instanceof THREE.Mesh) {
					child.material = objMat;
					child.shading = THREE.SmoothShading;
				}
			});
			object.position.x = 0;
			object.position.y = -3;
			object.position.z = 10;
			pivot.add( object );
			sunglasses = object;
	}, onProgress, onError );

	loader3D.load(
		'src/headphones.obj',
		function ( object ) {
			object.traverse(function( child ) {
				if (child instanceof THREE.Mesh) {
					child.material = headphoneMat;
					child.shading = THREE.SmoothShading;
				}
			});
			object.position.x = 0;
			object.position.y = 3;
			object.position.z = 30;
			pivot.add( object );
			headphones = object;
	}, onProgress, onError );

	scene.add( pivot );

	//scene.add(skull);
	//camera.position.z = 375;
	camera.position.z = 500;
	camera.position.y = 500;

	var ambient = new THREE.AmbientLight( 0x101030 );
	scene.add( ambient );

	var directionalLight = new THREE.DirectionalLight( 0xffeedd );
	directionalLight.position.set( 0, 0, 1 );
	scene.add( directionalLight );

	document.addEventListener( 'mousemove', onDocumentMouseMove, false );
	window.addEventListener( 'resize', onWindowResize, false );

}

function onWindowResize() {

	windowHalfX = window.innerWidth / 2;
	windowHalfY = window.innerHeight / 2;

	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize( window.innerWidth, window.innerHeight );

	$('#loading_wrapper').css("top", ($(window).height() / 2 - LOADING_WRAPPER_HEIGHT));

	console.log("Window.height" + $(window).height());

}

function onDocumentMouseMove( event ) {

	mouseX = ( event.clientX - windowHalfX ) / 3;
	mouseY = ( event.clientY - windowHalfY ) / 3;

}

var audioBuffer;
var sourceNode;
function setupAudioNodes() {
	// setup a analyser
	analyser = context.createAnalyser();
	// create a buffer source node
	sourceNode = context.createBufferSource();
	//connect source to analyser as link
	sourceNode.connect(analyser);
	// and connect source to destination
	sourceNode.connect(context.destination);
}

function reset () {
	if (typeof sourceNode !== "undefined") {
		sourceNode.stop(0);
	}
	if (typeof microphone !== "undefined") {
		microphone = null;
	}
}

function updateVisualization () {

	// get the average, bincount is fftsize / 2
	if (fileChosen) {
		var array = new Uint8Array(analyser.frequencyBinCount);
		analyser.getByteFrequencyData(array);

		drawBars(array);
	}
	camera.position.x += ( mouseX - camera.position.x) * .05;
	//console.log("Camer pos x: " + camera.position.x);
	camera.position.y += ( - mouseY - camera.position.y) * .05;
	camera.lookAt( scene.position );
	renderer.render(scene, camera);

	rafID = window.requestAnimationFrame(updateVisualization);
}

function smoothenArr(array)
{
	var smooth_array = new Array(array.length);
	for (var i = 0; i<array.length-2; i++)
	smooth_array[i]=(array[i] + array[i+1])/2;

	smooth_array[array.length-1]=array[array.length-1];

	return smooth_array;
}

function drawBars (array) {

	//just show bins with a value over the treshold
	var threshold = 0;
	//the max count of bins for the visualization
	var maxBinCount = array.length;
	//space between bins
	var space = 3;

    var bass = Math.floor(array[1]); //1Hz Frequenz
	var snare = Math.floor(array[250]);
	//console.log("Array length " + array.length);
	console.log("BASS: " + bass);
    RADIUS = bass * .004;
	RADIUS = RADIUS < .75 ? .75 : RADIUS;
	//console.log("Radius:" + RADIUS);
	pivot.scale.x = RADIUS;
	pivot.scale.y = RADIUS;
	pivot.scale.z = RADIUS;

	//var dx = Math.random()*10;
  	//var dy = Math.random()*10;

	//cube_mesh.position.x = bass >= 255 ? dx : 0;
	//cube_mesh.position.y = bass >= 255 ? dy : 0;

	if (snare > 0) {
		if (snare > 100) {
			if (snare > 230) {
				cube_mesh.rotation.z +=  .01;
			}
			else {
				cube_mesh.rotation.z +=  .005;
			}
		} else {
			cube_mesh.rotation.z +=  .001;
		}
	}

	if (bass > 230) {
		cube_mesh.material.color.setHex( HIGHLIGHT_COLORS[Math.floor(Math.random() * HIGHLIGHT_COLORS.length)] );
		cube_mesh.position.z += 10;
		//cube_mesh.rotation.z +=  .01;
		if (cube_mesh.position.z >= 2800) {
			cube_mesh.position.z = 0;
		}
	} else {
		cube_mesh.material.color.setHex( HIGHLIGHT_COLORS[0] );
	}
	//cube_mesh.position.y = dy;
	//go over each bin
	for ( var i = 0; i < maxBinCount; i++ ){

	}
}

<commit_msg>final improvements<commit_after>/*
 * Audiovisualization using the html canvas element.
 * Please note: this is an offline-only version. For this version to be used online you need an XMLHttpRequest to load the music file!
 * ©2017, Dominik Hofacker
 * https://www.behance.net/dominikhofacker
 * Please consider supporting this project on behance:
 * https://www.behance.net/gallery/49260123/Web-Audio-Visualization
 */

var rafID = null;
var analyser = null;
var c = null;
var cDraw = null;
var ctx = null;
var micropone = null;
var ctxDraw = null;

var loader;
var filename;
var renderer;
var skull;
var sunglasses;
var headphones;
var pivot;
var cube_mesh;
var scene;
var camera;
var fileChosen = false;
var RADIUS = 2;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var loadedVar = 0, totalVar = 0;

const HIGHLIGHT_COLORS = [0x4200ff, 0x00ffff, 0xff0000, 0xff00ff];
const LOADING_WRAPPER_HEIGHT = 100;

//handle different prefix of the audio context
var AudioContext = AudioContext || webkitAudioContext;
//create the context.
var context = new AudioContext();

//using requestAnimationFrame instead of timeout...
if (!window.requestAnimationFrame)
	window.requestAnimationFrame = window.webkitRequestAnimationFrame;

$(function () {

		/*$(".inputfile + label, .button").addClass("animated fadeInUp");
		$('.inputfile + label, .button').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
                $('.inputfile + label, .button').removeClass('fadeInUp');
         });*/

		$('#loading_wrapper').css("top", ($(window).height() / 2 - LOADING_WRAPPER_HEIGHT));

		//handle different types navigator objects of different browsers
		navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
	            navigator.mozGetUserMedia || navigator.msGetUserMedia;
	    //eigene Init
	    loader = new BufferLoader();
            //loader.visualize = visualize;
            //init canvas
	    initBinCanvas();
		//start updating
		rafID = window.requestAnimationFrame(updateVisualization);

});

function handleFiles(files) {
    if(files.length === 0){
        return;
    }
	fileChosen = true;
    setupAudioNodes();

	var fileReader  = new FileReader();
    fileReader.onload = function(){
         var arrayBuffer = this.result;
         console.log(arrayBuffer);
         console.log(arrayBuffer.byteLength);
     };
     fileReader.readAsArrayBuffer(files[0]);
     var url = URL.createObjectURL(files[0]);

	var request = new XMLHttpRequest();
	request.open('GET', url, true);
	request.responseType = 'arraybuffer';

 	// When loaded decode the data
	request.onload = function() {
		// decode the data
		context.decodeAudioData(request.response, function(buffer) {
		// when the audio is decoded play the sound
		sourceNode.buffer = buffer;
		sourceNode.start(0);
		//on error
		}, function(e) {
			console.log(e);
		});
	};
	request.send();

	camera.position.z = 375;
	camera.position.y = 0;

	$(".inputfile + label, .button").addClass("animated fadeOutDown");
	$("#viewer_discretion").html("Copyright 2017, Dominik Hofacker. All Rights Reserved.");
}

function playSample() {

	fileChosen = true;
    setupAudioNodes();

	var request = new XMLHttpRequest();
	request.open('GET', 'src/sample.mp3', true);
	request.responseType = 'arraybuffer';

 	// When loaded decode the data
	request.onload = function() {
		// decode the data
		context.decodeAudioData(request.response, function(buffer) {
		// when the audio is decoded play the sound
		sourceNode.buffer = buffer;
		sourceNode.start(0);
		//on error
		}, function(e) {
			console.log(e);
		});
	};
	request.send();

	camera.position.z = 375;
	camera.position.y = 0;

	$(".inputfile + label, .button").addClass("animated fadeOutDown");
	$("#viewer_discretion").html("You are listening to Jordan Schor - Cosmic (feat. Nathan Brumley).");
}

function initBinCanvas () {

	//TODO
	scene = new THREE.Scene();
	scene.background = new THREE.Color( 0x00000);
	camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100000);
	renderer = new THREE.WebGLRenderer();
	renderer.setSize(window.innerWidth, window.innerHeight);
	renderer.setPixelRatio( window.devicePixelRatio );
	document.body.appendChild(renderer.domElement);

	var geometry = new THREE.BoxGeometry(560, 560, 100000, 15, 55, 100);

	var cubeMat = new THREE.MeshBasicMaterial({color: '#4200ff', wireframe: true});
	var testMat = new THREE.MeshStandardMaterial({
		roughness: 0,
		color: 'white'
	});
	cube_mesh = new THREE.Mesh(geometry, cubeMat);
	scene.add(cube_mesh);

	//MATERIALS###################################################################
	var material = new THREE.MeshBasicMaterial({vertexColors: THREE.VertexColors});
	var objMat = new THREE.MeshStandardMaterial({
		color: 'yellow',
		wireframe: true,
		roughness: .3
	});
	var newMat = new THREE.MeshPhongMaterial({
		color: '#6e3bff'
	});
	var headphoneMat = new THREE.MeshStandardMaterial({
		roughness: 0.4,
		color: 'yellow',
		wireframe: false
	});
	var box = new THREE.Box3();
	pivot = new THREE.Group(); //group objs and center pivot of skull

	//LOADING OBJs#################################################################
	var manager = new THREE.LoadingManager();
		manager.onProgress = function ( item, loaded, total ) {
			console.log( item, loaded, total ); //loaded 1 total 3
			loadedVar = loaded;
			totalVar = total;
	};
	var onProgress = function ( xhr ) {
		if ( xhr.lengthComputable ) {
			var percentComplete = xhr.loaded / xhr.total * 100;
			console.log( Math.round(percentComplete, 2) + '% loaded' );
			$(".label").html(Math.round(percentComplete, 2) + '% loaded');
			//console.log("LOADED VAR:" + loadedVar + "\n TOTAL VAR:" + totalVar);
			if (percentComplete === 100 && loadedVar === 2) {
				$(".inputfile + label, .button").css("visibility", "visible");
				$(".inputfile + label, .button").addClass("animated fadeInUp");
				$('.inputfile + label, .button').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
						$('.inputfile + label, .button').removeClass('fadeInUp');
				});
				$("#loading_screen").addClass("animated fadeOut");
				$("#loading_screen").one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
						$("#loading_screen").css("display", "none");
						$("#viewer_discretion").html("This music visualizer may be harmful to viewers who are prone to epilepsy. Viewer discretion is advised.");
				});
			}
		}
	};
	var onError = function ( xhr ) {
	};
	var loader3D = new THREE.OBJLoader( manager );
	// load a resource
	loader3D.load(
		// resource URL
		'src/skull_lowpoly.obj',
		// Function when resource is loaded
		function ( object ) {
			object.traverse(function (child) {
				if ( child instanceof THREE.Mesh ) {

						child.material = newMat;
						child.shading = THREE.FlatShading;

					}
			});
			object.position.y = 0;
			object.position.x = 0;
			box.setFromObject( object );
			box.getCenter( object.position ); // this re-sets the mesh position
			object.position.multiplyScalar( - 1 );
			pivot.add( object );
			skull = object;
	}, onProgress, onError );

	loader3D.load(
		'src/sunglasses.obj',
		function ( object ) {
			object.traverse(function( child ) {
				if (child instanceof THREE.Mesh) {
					child.material = objMat;
					child.shading = THREE.SmoothShading;
				}
			});
			object.position.x = 0;
			object.position.y = -3;
			object.position.z = 10;
			pivot.add( object );
			sunglasses = object;
	}, onProgress, onError );

	loader3D.load(
		'src/headphones.obj',
		function ( object ) {
			object.traverse(function( child ) {
				if (child instanceof THREE.Mesh) {
					child.material = headphoneMat;
					child.shading = THREE.SmoothShading;
				}
			});
			object.position.x = 0;
			object.position.y = 3;
			object.position.z = 30;
			pivot.add( object );
			headphones = object;
	}, onProgress, onError );

	scene.add( pivot );

	//scene.add(skull);
	//camera.position.z = 375;
	camera.position.z = 500;
	camera.position.y = 500;

	var ambient = new THREE.AmbientLight( 0x101030 );
	scene.add( ambient );

	var directionalLight = new THREE.DirectionalLight( 0xffeedd );
	directionalLight.position.set( 0, 0, 1 );
	scene.add( directionalLight );

	document.addEventListener( 'mousemove', onDocumentMouseMove, false );
	window.addEventListener( 'resize', onWindowResize, false );

}

function onWindowResize() {

	windowHalfX = window.innerWidth / 2;
	windowHalfY = window.innerHeight / 2;

	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize( window.innerWidth, window.innerHeight );

	$('#loading_wrapper').css("top", ($(window).height() / 2 - LOADING_WRAPPER_HEIGHT));

	console.log("Window.height" + $(window).height());

}

function onDocumentMouseMove( event ) {

	mouseX = ( event.clientX - windowHalfX ) / 3;
	mouseY = ( event.clientY - windowHalfY ) / 3;

}

var audioBuffer;
var sourceNode;
function setupAudioNodes() {
	// setup a analyser
	analyser = context.createAnalyser();
	// create a buffer source node
	sourceNode = context.createBufferSource();
	//connect source to analyser as link
	sourceNode.connect(analyser);
	// and connect source to destination
	sourceNode.connect(context.destination);
}

function reset () {
	if (typeof sourceNode !== "undefined") {
		sourceNode.stop(0);
	}
	if (typeof microphone !== "undefined") {
		microphone = null;
	}
}

function updateVisualization () {

	// get the average, bincount is fftsize / 2
	if (fileChosen) {
		var array = new Uint8Array(analyser.frequencyBinCount);
		analyser.getByteFrequencyData(array);

		drawBars(array);
	}
	camera.position.x += ( mouseX - camera.position.x) * .05;
	//console.log("Camer pos x: " + camera.position.x);
	camera.position.y += ( - mouseY - camera.position.y) * .05;
	camera.lookAt( scene.position );
	renderer.render(scene, camera);

	rafID = window.requestAnimationFrame(updateVisualization);
}

function smoothenArr(array)
{
	var smooth_array = new Array(array.length);
	for (var i = 0; i<array.length-2; i++)
	smooth_array[i]=(array[i] + array[i+1])/2;

	smooth_array[array.length-1]=array[array.length-1];

	return smooth_array;
}

function drawBars (array) {

	//just show bins with a value over the treshold
	var threshold = 0;
	//the max count of bins for the visualization
	var maxBinCount = array.length;
	//space between bins
	var space = 3;

    var bass = Math.floor(array[1]); //1Hz Frequenz
	var snare = Math.floor(array[250]);
	//console.log("Array length " + array.length);
	console.log("BASS: " + bass);
    RADIUS = bass * .004;
	RADIUS = RADIUS < .75 ? .75 : RADIUS;
	//console.log("Radius:" + RADIUS);
	pivot.scale.x = RADIUS;
	pivot.scale.y = RADIUS;
	pivot.scale.z = RADIUS;

	//var dx = Math.random()*10;
  	//var dy = Math.random()*10;

	//cube_mesh.position.x = bass >= 255 ? dx : 0;
	//cube_mesh.position.y = bass >= 255 ? dy : 0;

	if (snare > 0) {
		if (snare > 100) {
			if (snare > 230) {
				cube_mesh.rotation.z +=  .01;
			}
			else {
				cube_mesh.rotation.z +=  .005;
			}
		} else {
			cube_mesh.rotation.z +=  .001;
		}
	}

	if (bass > 230) {
		cube_mesh.material.color.setHex( HIGHLIGHT_COLORS[Math.floor(Math.random() * HIGHLIGHT_COLORS.length)] );
		cube_mesh.position.z += 10;
		//cube_mesh.rotation.z +=  .01;
		if (cube_mesh.position.z >= 2800) {
			cube_mesh.position.z = 0;
		}
	} else {
		cube_mesh.material.color.setHex( HIGHLIGHT_COLORS[0] );
	}
	//cube_mesh.position.y = dy;
	//go over each bin
	for ( var i = 0; i < maxBinCount; i++ ){

	}
}

<|endoftext|>


<commit_before>function initLayout() {
	$(":input").val("");
	$(".js-name").text("");
	$(".js-city").text("");
	$(".spinner").css("display", "none");
	$(".input-section-visible").hide(0).removeClass("input-section-visible").addClass("input-section-hidden");
	$(".input-section-hidden").hide(0)
	$(".details-hidden").hide(0);
	$(".js-from:last").show(0);
	$(".js-to:last").show(0);
	toggleInputHideClass("init");
}

function toggleInput(el) {
	if ($(el).next(".js-from").length > 0 ||
		  $(el).next(".js-to").length > 0 ||
		  $(el).next(".js-time-date").length > 0){
		$(el).next(":first").slideToggle(300, function () {
			$(":input").val("");
			});
	}
	else
		$(el).slideToggle(300, function () {
			showSuggests(".js-section", -1);
			toggleInputHideClass(el);
			$(":input").val("");
		});
}

function showSuggests(section, number, busstop) {
	$(section).find(".js-suggest").each( function (index, el) {
		if ($(el).parents(section) && index == number) {
			$(el).show();
			//$(el).slideToggle(400);
			$(el).find(".js-name").text(
				(busstop.name != "") ? busstop.name + ", " : "");
			$(el).find(".js-city").text(busstop.city);
		}
		else {
			if (index > number) {
				$(el).hide();
			//	$(el).slideToggle(400);
				$(el).find(".js-name").text();
				$(el).find(".js-city").text();
			}
		}
	});
}

function showSelectedBusstop(section, busstop) {
	$(section + ":first").find(".js-name").text(busstop.name + ", ");
	$(section + ":first").find(".js-city").text(busstop.city);
}

function showSelectetTime(time) {
	$(".js-time-date:first").find(".js-name").text(time[1] + ", ");
	$(".js-time-date:first").find(".js-city").text(time[0]);
}

// Moves the next input section into visible and
// and proves if the next feld is already fulled
function toggleInputHideClass(el) {
	//To validate the next input feld
	if (el == "init") proveNextSection("init");
	else if ($(el).hasClass("js-from")) proveNextSection("js-from");
	else if ($(el).hasClass("js-to")) proveNextSection("js-to");
	else if ($(el).hasClass("js-time-date")) proveNextSection("js-time-date");

	$(".input-section-hidden:first").show(0).removeClass("input-section-hidden").addClass("input-section-visible");
}

function showStartRequestStuff() {
	$(".spinner").css("display", "block");
	$("#cancel").show(0).removeClass("icon-hidden-left").addClass("icon-visible");
	$(".js-overview").hide().children().hide();
	$(".js-overview").find(".js-time").text("");
	$(".js-overview").find(".js-duration").text("");
}

function showOverview() {
	var routeData = getRouteData();
	if (routeData != undefined) {
		for (var i = 1; i < routeData.length; i++) {
				if (routeData[i] != null)
					genOverviewElement(routeData[i].overview, i);
		}
	}
	else {
		console.log("Noconnection");
	}

}
function genOverviewElement(data, index) {
	index--;
	console.log(index);
	$(".js-overview").show().children()[index].style.display = "block";
	$(".js-overview").find(".js-time")[index].innerHTML = (data.depTime + " - " + data.arrTime);
	$(".js-overview").find(".js-duration")[index].innerHTML = (data.duration);
}

function changeToDetails(index) {
	console.log("go to Detail");
	$(".js-transit").hide();
	$(".js-intermediate").hide();
	$(".search-visible:first").show(0).removeClass("search-visible").addClass("search-hidden");

	$(".details-hidden:first").show(0).removeClass("details-hidden").addClass("details-visible");
	$("#cancel").removeClass("icon-visible").addClass("icon-hidden-left");
	$("#back").show(0).removeClass("icon-hidden-right").addClass("icon-visible");
	genDetails(index);
}

function genDetails(index) {
	var data = getRouteData()[index].connections;
	console.log(index);
	var tBlock = $(".js-transit:first");
	var iBlock = $(".js-intermediate:first");
	var i = 0;
	while (i < data.length) {
		if (data[i].depTime != undefined) {
			tBlock.show();
			tBlock.find(".js-time:first").text(data[i].depTime);
			tBlock.find(".js-time:last").text(data[i].arrTime);
			tBlock.find(".js-name:first").text(data[i].depBusstop[1] + ", ");
			tBlock.find(".js-name:last").text(data[i].arrBusstop[1] + ", ");
			tBlock.find(".js-city:first").text(data[i].depBusstop[0]);
			tBlock.find(".js-city:last").text(data[i].arrBusstop[0]);
			tBlock.find(".js-lineNo").text("Line " + data[i].lineNo);

		}
		if (data[i].waitTime != "")
			iBlock.show().find("p").text(data[i].waitTime);

		i++;
		tBlock = tBlock.nextAll(".js-transit:first");
		iBlock = iBlock.nextAll(".js-intermediate:first");
	}
}
function changeToSearch() {
	console.log("go Back");
	$(".details-visible:first").removeClass("details-visible").addClass("details-hidden");
	$(".search-hidden:first").show(0).removeClass("search-hidden").addClass("search-visible");
	$("#back").removeClass("icon-visible").addClass("icon-hidden-right");
	$("#cancel").show(0).removeClass("icon-hidden-left").addClass("icon-visible");
}
<commit_msg>[input] add focus to input felds<commit_after>function initLayout() {
	$(":input").val("");
	$(".js-name").text("");
	$(".js-city").text("");
	$(".spinner").css("display", "none");
	$(".input-section-visible").hide(0).removeClass("input-section-visible").addClass("input-section-hidden");
	$(".input-section-hidden").hide(0)
	$(".details-hidden").hide(0);
	$(".js-from:last").show(0);
	$(".js-to:last").show(0);
	toggleInputHideClass("init");
}

function toggleInput(el) {
	if ($(el).next(".js-from").length > 0 ||
		  $(el).next(".js-to").length > 0 ||
		  $(el).next(".js-time-date").length > 0){
		$(el).next(":first").slideToggle(300, function () {
			$(":input").val("");
			}).find(":input:first").focus();
	}
	else
		$(el).slideToggle(300, function () {
			showSuggests(".js-section", -1);
			toggleInputHideClass(el);
			$(":input").val("");
		}).find(":input:first").focus();
}

function showSuggests(section, number, busstop) {
	$(section).find(".js-suggest").each( function (index, el) {
		if ($(el).parents(section) && index == number) {
			$(el).show();
			//$(el).slideToggle(400);
			$(el).find(".js-name").text(
				(busstop.name != "") ? busstop.name + ", " : "");
			$(el).find(".js-city").text(busstop.city);
		}
		else {
			if (index > number) {
				$(el).hide();
			//	$(el).slideToggle(400);
				$(el).find(".js-name").text();
				$(el).find(".js-city").text();
			}
		}
	});
}

function showSelectedBusstop(section, busstop) {
	$(section + ":first").find(".js-name").text(busstop.name + ", ");
	$(section + ":first").find(".js-city").text(busstop.city);
}

function showSelectetTime(time) {
	$(".js-time-date:first").find(".js-name").text(time[1] + ", ");
	$(".js-time-date:first").find(".js-city").text(time[0]);
}

// Moves the next input section into visible and
// and proves if the next feld is already fulled
function toggleInputHideClass(el) {
	//To validate the next input feld
	if (el == "init") proveNextSection("init");
	else if ($(el).hasClass("js-from")) proveNextSection("js-from");
	else if ($(el).hasClass("js-to")) proveNextSection("js-to");
	else if ($(el).hasClass("js-time-date")) proveNextSection("js-time-date");

	$(".input-section-hidden:first").show(0).removeClass("input-section-hidden").addClass("input-section-visible").find(":input:first").focus();
}

function showStartRequestStuff() {
	$(".spinner").css("display", "block");
	$("#cancel").show(0).removeClass("icon-hidden-left").addClass("icon-visible");
	$(".js-overview").hide().children().hide();
	$(".js-overview").find(".js-time").text("");
	$(".js-overview").find(".js-duration").text("");
}

function showOverview() {
	var routeData = getRouteData();
	if (routeData != undefined) {
		for (var i = 1; i < routeData.length; i++) {
				if (routeData[i] != null)
					genOverviewElement(routeData[i].overview, i);
		}
	}
	else {
		console.log("Noconnection");
	}

}
function genOverviewElement(data, index) {
	index--;
	console.log(index);
	$(".js-overview").show().children()[index].style.display = "block";
	$(".js-overview").find(".js-time")[index].innerHTML = (data.depTime + " - " + data.arrTime);
	$(".js-overview").find(".js-duration")[index].innerHTML = (data.duration);
}

function changeToDetails(index) {
	console.log("go to Detail");
	$(".js-transit").hide();
	$(".js-intermediate").hide();
	$(".search-visible:first").show(0).removeClass("search-visible").addClass("search-hidden");

	$(".details-hidden:first").show(0).removeClass("details-hidden").addClass("details-visible");
	$("#cancel").removeClass("icon-visible").addClass("icon-hidden-left");
	$("#back").show(0).removeClass("icon-hidden-right").addClass("icon-visible");
	genDetails(index);
}

function genDetails(index) {
	var data = getRouteData()[index].connections;
	console.log(index);
	var tBlock = $(".js-transit:first");
	var iBlock = $(".js-intermediate:first");
	var i = 0;
	while (i < data.length) {
		if (data[i].depTime != undefined) {
			tBlock.show();
			tBlock.find(".js-time:first").text(data[i].depTime);
			tBlock.find(".js-time:last").text(data[i].arrTime);
			tBlock.find(".js-name:first").text(data[i].depBusstop[1] + ", ");
			tBlock.find(".js-name:last").text(data[i].arrBusstop[1] + ", ");
			tBlock.find(".js-city:first").text(data[i].depBusstop[0]);
			tBlock.find(".js-city:last").text(data[i].arrBusstop[0]);
			tBlock.find(".js-lineNo").text("Line " + data[i].lineNo);

		}
		if (data[i].waitTime != "")
			iBlock.show().find("p").text(data[i].waitTime);

		i++;
		tBlock = tBlock.nextAll(".js-transit:first");
		iBlock = iBlock.nextAll(".js-intermediate:first");
	}
}
function changeToSearch() {
	console.log("go Back");
	$(".details-visible:first").removeClass("details-visible").addClass("details-hidden");
	$(".search-hidden:first").show(0).removeClass("search-hidden").addClass("search-visible");
	$("#back").removeClass("icon-visible").addClass("icon-hidden-right");
	$("#cancel").show(0).removeClass("icon-hidden-left").addClass("icon-visible");
}
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    del = require('del'),
    browserify = require('browserify'),
    transform = require('vinyl-transform'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    ts = require('gulp-typescript'),
    less = require('gulp-less'),
    cssmin = require("gulp-minify-css"),
    es = require('event-stream'),
    concat = require('gulp-concat'),
    mocha = require('gulp-mocha'),
    karma = require('gulp-karma'),
    browserSync = require('browser-sync'),
    autoprefixer = require('gulp-autoprefixer'),
    jeditor = require('gulp-json-editor');
    git = require('gulp-git');

var errorsFatal = true;

var dest = {
    lib: './build/lib',
    style: './build/css',
    test: './build/test',
    dist: './dist',
    distCore: './dist/core',
    distViz: './dist/viz',
    distStandalone: './dist/standalone',
    distNpm: './dist-modules',
    distNpmCore: './dist-modules/connect-js',
    distNpmViz: './dist-modules/connect-js-viz',
};

var exampleDest = {
    lib: './examples/build/lib',
    style: './examples/build/css',
    dist: './examples/dist'
};

var sources = {
    readme: './README.md',
    npmConfig: './package.json',
    lib: './lib/**/*.ts',
    compiledLibCore: dest.lib + '/core/**/*.js',
    compiledLibViz: dest.lib + '/viz/**/*.js',
    compiledLibStandalone: dest.lib + '/standalone.js',
    compiledTdCore: dest.lib + '/core/**/*.d.ts',
    compiledTdViz: dest.lib + '/viz/**/*.d.ts',
    compiledStyle: dest.style + '/connect-viz.css',
    style: './style/**/connect-viz.less',
    less: './style/**/*.less',
    test: './test/**/*.ts',
    compiledTest: dest.test + '/**/*.ts',
    ionIconsCss: './bower_components/ionicons/css/ionicons.css',
    ionIconsFonts: './bower_components/ionicons/fonts/*',
    c3Css: './node_modules/connect-js-c3/c3.css'
};

var exampleSources = {
    connectJs: dest.dist + '/**/*.js',
    connectCss: dest.dist + '/**/*.css',
    lib: './examples/script/*.js',
    html: './examples/*.html',
    style: './examples/style/**/*.less'
};

var typings = {
    library: './typings/**/*.d.ts',
    lib: './build/lib/**/*.d.ts'
};

var tsProject = ts.createProject({
    typescript: require('typescript'),
    noExternalResolve: false,
    sortOutput: true,
    declarationFiles: true,
    noEmitOnError: true,
    module: 'commonjs',
    target: 'ES5'
});

function handleError(error) {
    console.log(error.stack);

    if(errorsFatal)
        throw error;
}

gulp.task('compile:lib',  function() {
    var tsResult = gulp.src([sources.lib, typings.library])
       .pipe(ts(tsProject))
       .on('error', handleError);

    var js = tsResult.js
        .pipe(gulp.dest(dest.lib));

    var dts = tsResult.dts
        .pipe(gulp.dest(dest.lib));

    return es.merge(js, dts);
});

gulp.task('compile:style',  function() {
    return gulp.src(sources.style)
       .pipe(less())
       .pipe(autoprefixer())
       .pipe(gulp.dest(dest.style))
       .on('error', handleError);
});

gulp.task('compile:tests', ['clean:test', 'build'], function() {
    var tsResult = gulp.src([sources.test, typings.lib, typings.library])
       .pipe(ts(tsProject))
       .on('error', handleError);

    return tsResult.js
        .pipe(gulp.dest(dest.test));
});

gulp.task('test:karma', ['compile:tests'], function () {
    return gulp.src(sources.compiledTest)
        .pipe(karma({
            action: 'run',
            configFile: 'karma.conf.js'
        }))
        .on('error', handleError);
});

gulp.task('test:mocha', ['compile:tests'], function () {
    var reporter = process.env.TEAMCITY_VERSION
        ? 'mocha-teamcity-reporter'
        : 'list';

    return gulp.src(sources.compiledTest)
        .pipe(mocha({
            reporter: reporter
        }))
        .on('error', handleError);
});

gulp.task('browserify', ['build'], function() {
    var browserifiedCore = transform(function(filename) {
        var b = browserify(filename, {
            basedir: dest.lib
        });

        return b.bundle();
    });

    var browserifiedViz = transform(function(filename) {
        var b = browserify(filename, {
            basedir: dest.lib
        })
        .ignore('connect-js')
        .external('d3')
        .external('connect-js-c3');

        return b.bundle();
    });

    var core = gulp.src(dest.lib + '/core/index.js')
        .pipe(browserifiedCore)
        .pipe(rename('connect.js'))
        .pipe(gulp.dest(dest.distCore))
        .on('error', handleError);

    var viz = gulp.src(dest.lib + '/viz/index.js')
        .pipe(browserifiedViz)
        .pipe(rename('connect-viz.js'))
        .pipe(gulp.dest(dest.distViz))
        .on('error', handleError);

    return es.merge(core, viz);
});

gulp.task('fonts', function() {
    return gulp.src(sources.ionIconsFonts)
        .pipe(gulp.dest(dest.dist + '/fonts'));
});

gulp.task('minifyCss', ['build'], function() {
    return gulp.src(sources.compiledStyle)
        .pipe(autoprefixer())
        .pipe(gulp.dest(dest.distViz))
        .pipe(cssmin())
        .pipe(rename('connect-viz.min.css'))
        .pipe(gulp.dest(dest.distViz))
        .on('error', handleError);
});

gulp.task('uglify', ['browserify'], function() {
     var core = gulp.src(dest.distCore + '/connect.js')
        .pipe(uglify())
        .pipe(rename('connect.min.js'))
        .pipe(gulp.dest(dest.distCore))
        .on('error', handleError);

    var viz = gulp.src(dest.distViz + '/connect-viz.js')
        .pipe(uglify())
        .pipe(rename('connect-viz.min.js'))
        .pipe(gulp.dest(dest.distViz))
        .on('error', handleError);

    return es.merge(core, viz);
});

gulp.task('copy-less', function() {
    return gulp.src(sources.less)
        .pipe(gulp.dest(dest.distViz + '/less'))
        .on('error', handleError);
});

gulp.task('npm:readme',  function() {
    var readmeSrc = gulp.src(sources.readme)
        .on('error', handleError);

    var core = readmeSrc
        .pipe(gulp.dest(dest.distNpmCore));

    var viz = readmeSrc
        .pipe(gulp.dest(dest.distNpmViz));

    return es.merge(core, viz);
});

gulp.task('npm:src',  ['compile:lib'], function() {
    var coreJs = gulp.src(sources.compiledLibCore)
        .pipe(gulp.dest(dest.distNpmCore + '/js'))
        .on('error', handleError);

    var vizJs = gulp.src(sources.compiledLibViz)
        .pipe(gulp.dest(dest.distNpmViz + '/js'))
        .on('error', handleError);

    var coreTd = gulp.src(sources.compiledTdCore)
        .pipe(gulp.dest(dest.distNpmCore + '/ts'))
        .on('error', handleError);

    var vizTd = gulp.src(sources.compiledTdViz)
        .pipe(gulp.dest(dest.distNpmViz + '/ts'))
        .on('error', handleError);

    return es.merge(coreJs, vizJs, coreTd, vizTd);
});

gulp.task('npm:style', ['compile:style'],  function() {
    var less = gulp.src(sources.less)
        .pipe(gulp.dest(dest.distNpmViz + '/less'))
        .on('error', handleError);

    var combinedCss = gulp.src(sources.compiledStyle)
        .pipe(gulp.dest(dest.distNpmViz + '/css'))
        .on('error', handleError);

    return es.merge(less, combinedCss);
});

gulp.task('npm:config',  function() {
    var corePackage = gulp.src(sources.npmConfig)
        .pipe(jeditor(function (packageJson){
            delete packageJson.dependencies['connect-js-c3'];
            delete packageJson.dependencies['d3'];
            return packageJson;
        }))
        .pipe(gulp.dest(dest.distNpmCore))
        .on('error', handleError);

    var vizPackage = gulp.src(sources.npmConfig)
        .pipe(jeditor({
            'name': 'connect-js-viz'
        }))
        .pipe(jeditor(function (packageJson){
            packageJson.dependencies['connect-js'] = packageJson.version;
            return packageJson;
        }))
        .pipe(gulp.dest(dest.distNpmViz))
        .on('error', handleError);

    return es.merge(corePackage, vizPackage);
});

gulp.task('clean:lib', function() {
    return del(dest.lib);
});

gulp.task('clean:style', function() {
    return del(dest.style);
});

gulp.task('clean:test', function() {
    return del(dest.test);
});

gulp.task('clean:dist', function() {
    return es.merge(del(dest.dist), del(dest.npm));
});

gulp.task('reload-dist', ['dist'], browserSync.reload);

gulp.task('watch', ['dist'], function() {
    errorsFatal = false;

    gulp.watch([sources.lib, sources.style], ['dist']);
});

gulp.task('serve', ['dist'], function() {
    browserSync({
        server: {
            baseDir: dest.dist,
            https: true
        }
    });

    gulp.watch([sources.lib, sources.style], ['reload-dist']);
});

gulp.task('examples:compile:lib',  function() {
    return gulp.src([exampleSources.lib])
       .pipe(gulp.dest(exampleDest.lib))
       .on('error', handleError);
});

gulp.task('examples:compile:style',  function() {
    var css = gulp.src(exampleSources.style)
       .pipe(less())
       .pipe(gulp.dest(exampleDest.style))
       .on('error', handleError);

    var copyConnect = gulp.src([exampleSources.connectCss])
       .pipe(gulp.dest(exampleDest.dist))
       .on('error', handleError);

   return es.merge(css, copyConnect);
});

gulp.task('examples:browserify', ['examples:build'], function() {
    var browserified = transform(function(filename) {
        var b = browserify(filename, {
            basedir: exampleDest.lib
        });

        return b.bundle();
    });

    var browserfy = gulp.src(exampleDest.lib + '/visualizations.js')
        .pipe(browserified)
        .pipe(rename('examples.js'))
        .pipe(gulp.dest(exampleDest.dist))
        .on('error', handleError);

    var copyConnect = gulp.src([exampleSources.connectJs])
       .pipe(gulp.dest(exampleDest.dist))
       .on('error', handleError);

    return es.merge(browserfy, copyConnect);
});

gulp.task('examples:combineCss', ['examples:build'], function() {
    return gulp.src(exampleDest.style + '/*.css')
        .pipe(autoprefixer())
        .pipe(concat('examples.css'))
        .pipe(gulp.dest(exampleDest.dist))
        .on('error', handleError);
});

gulp.task('examples:copyHtml', ['examples:build'], function() {
    return gulp.src(exampleSources.html)
        .pipe(gulp.dest(exampleDest.dist))
        .on('error', handleError);
});

gulp.task('examples:clean:dist', function() {
    return del(exampleDest.dist);
});

gulp.task('examples:clean:lib', function() {
    return del(exampleDest.lib);
});

gulp.task('examples:clean:style', function() {
    return del(exampleDest.style);
});

gulp.task('examples:serve', ['examples'], function() {
    browserSync({
        server: {
            baseDir: exampleDest.dist,
            https: true
        }
    });
});

gulp.task('standalone:js', ['build'], function() {
    var browserifiedStandalone = transform(function(filename) {
        var b = browserify(filename, {
            basedir: dest.lib
        })
        .ignore('connect-js');

        return b.bundle();
    });

    return gulp.src(sources.compiledLibStandalone)
        .pipe(browserifiedStandalone)
        .pipe(rename('connect-all.js'))
        .pipe(gulp.dest(dest.distStandalone))
        .pipe(uglify())
        .pipe(rename('connect-all.min.js'))
        .pipe(gulp.dest(dest.distStandalone))
        .on('error', handleError);
});

gulp.task('standalone:css', ['minifyCss'], function() {
    var styles = [
        sources.ionIconsCss,
        sources.c3Css,
        dest.distViz + '/connect-viz.css'
    ];

    return gulp.src(styles)
        .pipe(concat('connect-all.css'))
        .pipe(gulp.dest(dest.distStandalone))
        .pipe(cssmin())
        .pipe(rename('connect-all.min.css'))
        .pipe(gulp.dest(dest.distStandalone))
});

gulp.task('build', ['compile:lib', 'compile:style']);
gulp.task('examples:build', ['examples:compile:lib', 'examples:compile:style']);
gulp.task('test', ['compile:tests', 'test:karma', 'test:mocha']);
gulp.task('dist:bower', ['build', 'fonts', 'minifyCss', 'browserify', 'uglify', 'copy-less']);
gulp.task('dist:npm', ['npm:src', 'npm:config', 'npm:style', 'npm:readme']);
gulp.task('dist:standalone', ['standalone:js', 'standalone:css']);
gulp.task('dist', ['dist:bower', 'dist:npm', 'dist:standalone']);
gulp.task('examples', ['examples:combineCss', 'examples:browserify', 'examples:copyHtml']);
gulp.task('default', ['build']);<commit_msg>Fix gulp file so that the compiled test files are found and run<commit_after>var gulp = require('gulp'),
    del = require('del'),
    browserify = require('browserify'),
    transform = require('vinyl-transform'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    ts = require('gulp-typescript'),
    less = require('gulp-less'),
    cssmin = require("gulp-minify-css"),
    es = require('event-stream'),
    concat = require('gulp-concat'),
    mocha = require('gulp-mocha'),
    karma = require('gulp-karma'),
    browserSync = require('browser-sync'),
    autoprefixer = require('gulp-autoprefixer'),
    jeditor = require('gulp-json-editor');
    git = require('gulp-git');

var errorsFatal = true;

var dest = {
    lib: './build/lib',
    style: './build/css',
    test: './build/test',
    dist: './dist',
    distCore: './dist/core',
    distViz: './dist/viz',
    distStandalone: './dist/standalone',
    distNpm: './dist-modules',
    distNpmCore: './dist-modules/connect-js',
    distNpmViz: './dist-modules/connect-js-viz',
};

var exampleDest = {
    lib: './examples/build/lib',
    style: './examples/build/css',
    dist: './examples/dist'
};

var sources = {
    readme: './README.md',
    npmConfig: './package.json',
    lib: './lib/**/*.ts',
    compiledLibCore: dest.lib + '/core/**/*.js',
    compiledLibViz: dest.lib + '/viz/**/*.js',
    compiledLibStandalone: dest.lib + '/standalone.js',
    compiledTdCore: dest.lib + '/core/**/*.d.ts',
    compiledTdViz: dest.lib + '/viz/**/*.d.ts',
    compiledStyle: dest.style + '/connect-viz.css',
    style: './style/**/connect-viz.less',
    less: './style/**/*.less',
    test: './test/**/*.ts',
    compiledTest: dest.test + '/**/*.js',
    ionIconsCss: './bower_components/ionicons/css/ionicons.css',
    ionIconsFonts: './bower_components/ionicons/fonts/*',
    c3Css: './node_modules/connect-js-c3/c3.css'
};

var exampleSources = {
    connectJs: dest.dist + '/**/*.js',
    connectCss: dest.dist + '/**/*.css',
    lib: './examples/script/*.js',
    html: './examples/*.html',
    style: './examples/style/**/*.less'
};

var typings = {
    library: './typings/**/*.d.ts',
    lib: './build/lib/**/*.d.ts'
};

var tsProject = ts.createProject({
    typescript: require('typescript'),
    noExternalResolve: false,
    sortOutput: true,
    declarationFiles: true,
    noEmitOnError: true,
    module: 'commonjs',
    target: 'ES5'
});

function handleError(error) {
    console.log(error.stack);

    if(errorsFatal)
        throw error;
}

gulp.task('compile:lib',  function() {
    var tsResult = gulp.src([sources.lib, typings.library])
       .pipe(ts(tsProject))
       .on('error', handleError);

    var js = tsResult.js
        .pipe(gulp.dest(dest.lib));

    var dts = tsResult.dts
        .pipe(gulp.dest(dest.lib));

    return es.merge(js, dts);
});

gulp.task('compile:style',  function() {
    return gulp.src(sources.style)
       .pipe(less())
       .pipe(autoprefixer())
       .pipe(gulp.dest(dest.style))
       .on('error', handleError);
});

gulp.task('compile:tests', ['clean:test', 'build'], function() {
    var tsResult = gulp.src([sources.test, typings.lib, typings.library])
       .pipe(ts(tsProject))
       .on('error', handleError);

    return tsResult.js
        .pipe(gulp.dest(dest.test));
});

gulp.task('test:karma', ['compile:tests'], function () {
    return gulp.src(sources.compiledTest)
        .pipe(karma({
            action: 'run',
            configFile: 'karma.conf.js'
        }))
        .on('error', handleError);
});

gulp.task('test:mocha', ['compile:tests'], function () {
    var reporter = process.env.TEAMCITY_VERSION
        ? 'mocha-teamcity-reporter'
        : 'list';

    return gulp.src(sources.compiledTest)
        .pipe(mocha({
            reporter: reporter
        }))
        .on('error', handleError);
});

gulp.task('browserify', ['build'], function() {
    var browserifiedCore = transform(function(filename) {
        var b = browserify(filename, {
            basedir: dest.lib
        });

        return b.bundle();
    });

    var browserifiedViz = transform(function(filename) {
        var b = browserify(filename, {
            basedir: dest.lib
        })
        .ignore('connect-js')
        .external('d3')
        .external('connect-js-c3');

        return b.bundle();
    });

    var core = gulp.src(dest.lib + '/core/index.js')
        .pipe(browserifiedCore)
        .pipe(rename('connect.js'))
        .pipe(gulp.dest(dest.distCore))
        .on('error', handleError);

    var viz = gulp.src(dest.lib + '/viz/index.js')
        .pipe(browserifiedViz)
        .pipe(rename('connect-viz.js'))
        .pipe(gulp.dest(dest.distViz))
        .on('error', handleError);

    return es.merge(core, viz);
});

gulp.task('fonts', function() {
    return gulp.src(sources.ionIconsFonts)
        .pipe(gulp.dest(dest.dist + '/fonts'));
});

gulp.task('minifyCss', ['build'], function() {
    return gulp.src(sources.compiledStyle)
        .pipe(autoprefixer())
        .pipe(gulp.dest(dest.distViz))
        .pipe(cssmin())
        .pipe(rename('connect-viz.min.css'))
        .pipe(gulp.dest(dest.distViz))
        .on('error', handleError);
});

gulp.task('uglify', ['browserify'], function() {
     var core = gulp.src(dest.distCore + '/connect.js')
        .pipe(uglify())
        .pipe(rename('connect.min.js'))
        .pipe(gulp.dest(dest.distCore))
        .on('error', handleError);

    var viz = gulp.src(dest.distViz + '/connect-viz.js')
        .pipe(uglify())
        .pipe(rename('connect-viz.min.js'))
        .pipe(gulp.dest(dest.distViz))
        .on('error', handleError);

    return es.merge(core, viz);
});

gulp.task('copy-less', function() {
    return gulp.src(sources.less)
        .pipe(gulp.dest(dest.distViz + '/less'))
        .on('error', handleError);
});

gulp.task('npm:readme',  function() {
    var readmeSrc = gulp.src(sources.readme)
        .on('error', handleError);

    var core = readmeSrc
        .pipe(gulp.dest(dest.distNpmCore));

    var viz = readmeSrc
        .pipe(gulp.dest(dest.distNpmViz));

    return es.merge(core, viz);
});

gulp.task('npm:src',  ['compile:lib'], function() {
    var coreJs = gulp.src(sources.compiledLibCore)
        .pipe(gulp.dest(dest.distNpmCore + '/js'))
        .on('error', handleError);

    var vizJs = gulp.src(sources.compiledLibViz)
        .pipe(gulp.dest(dest.distNpmViz + '/js'))
        .on('error', handleError);

    var coreTd = gulp.src(sources.compiledTdCore)
        .pipe(gulp.dest(dest.distNpmCore + '/ts'))
        .on('error', handleError);

    var vizTd = gulp.src(sources.compiledTdViz)
        .pipe(gulp.dest(dest.distNpmViz + '/ts'))
        .on('error', handleError);

    return es.merge(coreJs, vizJs, coreTd, vizTd);
});

gulp.task('npm:style', ['compile:style'],  function() {
    var less = gulp.src(sources.less)
        .pipe(gulp.dest(dest.distNpmViz + '/less'))
        .on('error', handleError);

    var combinedCss = gulp.src(sources.compiledStyle)
        .pipe(gulp.dest(dest.distNpmViz + '/css'))
        .on('error', handleError);

    return es.merge(less, combinedCss);
});

gulp.task('npm:config',  function() {
    var corePackage = gulp.src(sources.npmConfig)
        .pipe(jeditor(function (packageJson){
            delete packageJson.dependencies['connect-js-c3'];
            delete packageJson.dependencies['d3'];
            return packageJson;
        }))
        .pipe(gulp.dest(dest.distNpmCore))
        .on('error', handleError);

    var vizPackage = gulp.src(sources.npmConfig)
        .pipe(jeditor({
            'name': 'connect-js-viz'
        }))
        .pipe(jeditor(function (packageJson){
            packageJson.dependencies['connect-js'] = packageJson.version;
            return packageJson;
        }))
        .pipe(gulp.dest(dest.distNpmViz))
        .on('error', handleError);

    return es.merge(corePackage, vizPackage);
});

gulp.task('clean:lib', function() {
    return del(dest.lib);
});

gulp.task('clean:style', function() {
    return del(dest.style);
});

gulp.task('clean:test', function() {
    return del(dest.test);
});

gulp.task('clean:dist', function() {
    return es.merge(del(dest.dist), del(dest.npm));
});

gulp.task('reload-dist', ['dist'], browserSync.reload);

gulp.task('watch', ['dist'], function() {
    errorsFatal = false;

    gulp.watch([sources.lib, sources.style], ['dist']);
});

gulp.task('serve', ['dist'], function() {
    browserSync({
        server: {
            baseDir: dest.dist,
            https: true
        }
    });

    gulp.watch([sources.lib, sources.style], ['reload-dist']);
});

gulp.task('examples:compile:lib',  function() {
    return gulp.src([exampleSources.lib])
       .pipe(gulp.dest(exampleDest.lib))
       .on('error', handleError);
});

gulp.task('examples:compile:style',  function() {
    var css = gulp.src(exampleSources.style)
       .pipe(less())
       .pipe(gulp.dest(exampleDest.style))
       .on('error', handleError);

    var copyConnect = gulp.src([exampleSources.connectCss])
       .pipe(gulp.dest(exampleDest.dist))
       .on('error', handleError);

   return es.merge(css, copyConnect);
});

gulp.task('examples:browserify', ['examples:build'], function() {
    var browserified = transform(function(filename) {
        var b = browserify(filename, {
            basedir: exampleDest.lib
        });

        return b.bundle();
    });

    var browserfy = gulp.src(exampleDest.lib + '/visualizations.js')
        .pipe(browserified)
        .pipe(rename('examples.js'))
        .pipe(gulp.dest(exampleDest.dist))
        .on('error', handleError);

    var copyConnect = gulp.src([exampleSources.connectJs])
       .pipe(gulp.dest(exampleDest.dist))
       .on('error', handleError);

    return es.merge(browserfy, copyConnect);
});

gulp.task('examples:combineCss', ['examples:build'], function() {
    return gulp.src(exampleDest.style + '/*.css')
        .pipe(autoprefixer())
        .pipe(concat('examples.css'))
        .pipe(gulp.dest(exampleDest.dist))
        .on('error', handleError);
});

gulp.task('examples:copyHtml', ['examples:build'], function() {
    return gulp.src(exampleSources.html)
        .pipe(gulp.dest(exampleDest.dist))
        .on('error', handleError);
});

gulp.task('examples:clean:dist', function() {
    return del(exampleDest.dist);
});

gulp.task('examples:clean:lib', function() {
    return del(exampleDest.lib);
});

gulp.task('examples:clean:style', function() {
    return del(exampleDest.style);
});

gulp.task('examples:serve', ['examples'], function() {
    browserSync({
        server: {
            baseDir: exampleDest.dist,
            https: true
        }
    });
});

gulp.task('standalone:js', ['build'], function() {
    var browserifiedStandalone = transform(function(filename) {
        var b = browserify(filename, {
            basedir: dest.lib
        })
        .ignore('connect-js');

        return b.bundle();
    });

    return gulp.src(sources.compiledLibStandalone)
        .pipe(browserifiedStandalone)
        .pipe(rename('connect-all.js'))
        .pipe(gulp.dest(dest.distStandalone))
        .pipe(uglify())
        .pipe(rename('connect-all.min.js'))
        .pipe(gulp.dest(dest.distStandalone))
        .on('error', handleError);
});

gulp.task('standalone:css', ['minifyCss'], function() {
    var styles = [
        sources.ionIconsCss,
        sources.c3Css,
        dest.distViz + '/connect-viz.css'
    ];

    return gulp.src(styles)
        .pipe(concat('connect-all.css'))
        .pipe(gulp.dest(dest.distStandalone))
        .pipe(cssmin())
        .pipe(rename('connect-all.min.css'))
        .pipe(gulp.dest(dest.distStandalone))
});

gulp.task('build', ['compile:lib', 'compile:style']);
gulp.task('examples:build', ['examples:compile:lib', 'examples:compile:style']);
gulp.task('test', ['compile:tests', 'test:karma', 'test:mocha']);
gulp.task('dist:bower', ['build', 'fonts', 'minifyCss', 'browserify', 'uglify', 'copy-less']);
gulp.task('dist:npm', ['npm:src', 'npm:config', 'npm:style', 'npm:readme']);
gulp.task('dist:standalone', ['standalone:js', 'standalone:css']);
gulp.task('dist', ['dist:bower', 'dist:npm', 'dist:standalone']);
gulp.task('examples', ['examples:combineCss', 'examples:browserify', 'examples:copyHtml']);
gulp.task('default', ['build']);<|endoftext|>