<commit_before>/// gulp-run
/// ==================================================
/// Pipe to shell commands in gulp.

'use strict';

var child_process = require('child_process');
var pathlib = require('path');
var stream = require('stream');
var util = require('util');

var _ = require('lodash');
var color = require('cli-color');
var Vinyl = require('vinyl');

var Logger = require('./lib/logger');

/// `var cmd = run(command, [options])`
/// --------------------------------------------------
/// Gets a through stream for a shell command to which you can pipe vinyl files. For each file
/// piped, a new process is spawned, the file is read into the processes's stdin, and a file
/// containing the processes's stdout is pushed.
///
/// Additionally, `./node_modules/.bin` is prepended to the PATH for the child process, so you have
/// access to all the binaries provided by your module's dependencies.
///
/// ### Arguments
/// 1. `command` *(String)*: The command to run. It can be a [template] interpolating the vinyl file
///     as the variable `file`.
/// 2. `[options]` *(Object)*:
///     - `env` *(Object)*: The environmental variables for the child process. Defaults to
///         `process.env`. The path `node_modules/.bin` is automatically prepended to the PATH.
///     - `cwd` *(String)*: The initial working directory for the child process. Defaults to
///         `process.cwd()`.
///     - `silent` *(Boolean)*: If true, do not print the command's output. This is the same as
///         setting verbosity to 1. Defaults to `false`.
///     - `verbosity` *(Number)*: Sets the verbosity level. Defaults to `2`.
///         - `0` never outputs anything.
///         - `1` outputs basic logs.
///         - `2` outputs basic logs and the stdout of the child process.
///
/// [template]: http://lodash.com/docs#template
///
/// ### Returns
/// *(stream.Transform in Object Mode)*: The through stream you so desire.
///
/// ### Example
/// ```javascript
/// gulp.task('even-lines', function () {
///     gulp.src('path/to/input/*')            // Get input files.
///         .pipe(run('awk "NR % 2 == 0"'))    // Use awk to extract the even lines.
///         .pipe(gulp.dest('path/to/output')) // Profit.
/// })
/// ```

var run = module.exports = function (command, opts) {
	var command_stream = new stream.Transform({objectMode: true}); // The stream of vinyl files.

	// Options
	opts = _.defaults(opts||{}, {
		cwd: process.cwd(),
		env: process.env,
		silent: false,
		verbosity: (opts && opts.silent) ? 1 : 2
	});

	// Compile the command template.
	var command_template = _.template(command);

	// Setup logging
	var logger = new Logger(opts.verbosity);
	logger.stream.pipe(process.stdout);

	// exec(command, [input], [callback])
	// --------------------------------------------------
	// TODO: Document

	var exec = function (command, input, callback) {
		var child; // The child process.
		var env; // The environmental variables for the child.
		var out_stream; // The contents of the returned vinyl file.

		// Parse arguments.
		if (typeof arguments[1] === 'function') {
			input = null;
			callback = arguments[1];
		}

		// Log start message.
		var start_message = '$ ' + color.cyan(command);
		if (input && input.relative) {
			start_message += ' <<< ' + input.relative;
		}
		logger.log(1, start_message);

		// Setup environment of child process.
		opts.env.PATH = pathlib.join('node_modules', '.bin') + ':' + opts.env.PATH;

		// Spawn the process.
		child = child_process.spawn('sh', ['-c', command], {env:opts.env, cwd:opts.cwd});

		// When the child process is done.
		child.on('close', function (code) {
			var err; // Only defined if an error occured

			// Handle errors
			if (code !== 0) {
				var error_message = "`" + command + "` exited with code " + code;
				err = new Error(error_message);
				logger.log(1, error_message);
			}

			if (typeof callback === 'function') {
				process.nextTick(callback.bind(undefined, err));
			}
		});

		// Handle input.
		if (input && typeof input.pipe === 'function') {
			input.pipe(child.stdin);
		} else if (input !== undefined && input !== null) {
			child.stdin.end(input.toString());
		} else {
			child.stdin.end();
		}

		// Handle output.
		out_stream = new stream.Transform();
		out_stream._transform = function (chunk, enc, callback) {
			out_stream.push(chunk);
			logger.write(2, chunk, enc, callback);
		};
		child.stdout.pipe(out_stream);
		child.stderr.pipe(logger.stream);

		// Return a vinyl file wrapping the command's stdout.
		return new Vinyl({
			path: command.split(/\s+/)[0], // first word of the command
			contents: out_stream
		});

	}

	// The stream.Transform interface
	// --------------------------------------------------
	// This method is called automatically for each file piped into the stream. It spawns a
	// command for each file, using the file's contents as stdin, and pushes downstream a new file
	// wrapping stdout.

	command_stream._transform = function (file, enc, done) {
		var output;

		// Spawn the command.
		output = exec(command_template({file:file}), file, function (err) {
			if (err) command_stream.emit('error', err);
			else process.nextTick(done);
		});

		// Push downstream a vinyl file wrapping the command's stdout.
		command_stream.push(output);
	}

	/// `cmd.exec([callback])`
	/// --------------------------------------------------
	/// Executes the command immediately, returning a stream of vinyl. A single file containing
	/// the command's stdout is pushed down the stream.
	///
	/// The name of the file pushed down the stream is the first word of the command.
	/// See [gulp-rename] if you need more flexibility.
	///
	/// ### Arguments
	/// 1. `[callback]` *(Function)*: Execution is asynchronous. The callback is called once the
	///     command's stdout has closed.
	///
	/// ### Returns
	/// *(stream.Readable in Object Mode)*: A stream containing exactly one vinyl file. The file's
	/// contents is the stdout stream of the command.
	///
	/// ### Example
	/// ```javascript
	/// gulp.task('hello-world', function () {
	///     run('echo Hello World').exec() // prints "[echo] Hello World\n"
	///         .pipe(gulp.dest('output')) // Writes "Hello World\n" to output/echo
	/// })
	/// ```

	command_stream.exec = function (callback) {
		var output; // A vinyl file whose contents is the stdout of the command.
		var wrapper; // The higher-level vinyl stream. `output` is the only thing piped through.

		// Spawn the command.
		output = exec(command_template(), null, function (err) {
			if (err) wrapper.emit('error', err);
			if (typeof callback === 'function') {
				process.nextTick(callback.bind(undefined, err));
			}
		});

		// Wrap the output in a vinyl stream.
		wrapper = new stream.PassThrough({objectMode:true});
		wrapper.end(output);

		return wrapper;
	}

	return command_stream;
}
<commit_msg>Fix bug when receiving more than one file in a stream.<commit_after>/// gulp-run
/// ==================================================
/// Pipe to shell commands in gulp.

'use strict';

var child_process = require('child_process');
var pathlib = require('path');
var stream = require('stream');
var util = require('util');

var _ = require('lodash');
var color = require('cli-color');
var Vinyl = require('vinyl');

var Logger = require('./lib/logger');

/// `var cmd = run(command, [options])`
/// --------------------------------------------------
/// Gets a through stream for a shell command to which you can pipe vinyl files. For each file
/// piped, a new process is spawned, the file is read into the processes's stdin, and a file
/// containing the processes's stdout is pushed.
///
/// Additionally, `./node_modules/.bin` is prepended to the PATH for the child process, so you have
/// access to all the binaries provided by your module's dependencies.
///
/// ### Arguments
/// 1. `command` *(String)*: The command to run. It can be a [template] interpolating the vinyl file
///     as the variable `file`.
/// 2. `[options]` *(Object)*:
///     - `env` *(Object)*: The environmental variables for the child process. Defaults to
///         `process.env`. The path `node_modules/.bin` is automatically prepended to the PATH.
///     - `cwd` *(String)*: The initial working directory for the child process. Defaults to
///         `process.cwd()`.
///     - `silent` *(Boolean)*: If true, do not print the command's output. This is the same as
///         setting verbosity to 1. Defaults to `false`.
///     - `verbosity` *(Number)*: Sets the verbosity level. Defaults to `2`.
///         - `0` never outputs anything.
///         - `1` outputs basic logs.
///         - `2` outputs basic logs and the stdout of the child process.
///
/// [template]: http://lodash.com/docs#template
///
/// ### Returns
/// *(stream.Transform in Object Mode)*: The through stream you so desire.
///
/// ### Example
/// ```javascript
/// gulp.task('even-lines', function () {
///     gulp.src('path/to/input/*')            // Get input files.
///         .pipe(run('awk "NR % 2 == 0"'))    // Use awk to extract the even lines.
///         .pipe(gulp.dest('path/to/output')) // Profit.
/// })
/// ```

var run = module.exports = function (command, opts) {
	var command_stream = new stream.Transform({objectMode: true}); // The stream of vinyl files.

	// Options
	opts = _.defaults(opts||{}, {
		cwd: process.cwd(),
		env: process.env,
		silent: false,
		verbosity: (opts && opts.silent) ? 1 : 2
	});

	// Compile the command template.
	var command_template = _.template(command);

	// exec(command, [input], [callback])
	// --------------------------------------------------
	// TODO: Document

	var exec = function (command, input, callback) {
		var child; // The child process.
		var env; // The environmental variables for the child.
		var out_stream; // The contents of the returned vinyl file.

		// Parse arguments.
		if (typeof arguments[1] === 'function') {
			input = null;
			callback = arguments[1];
		}

		// Setup logging.
		var logger = new Logger(opts.verbosity);
		logger.stream.pipe(process.stdout);

		// Log start message.
		var start_message = '$ ' + color.cyan(command);
		if (input && input.relative) {
			start_message += ' <<< ' + input.relative;
		}
		logger.log(1, start_message);

		// Setup environment of child process.
		opts.env.PATH = pathlib.join('node_modules', '.bin') + ':' + opts.env.PATH;

		// Spawn the process.
		child = child_process.spawn('sh', ['-c', command], {env:opts.env, cwd:opts.cwd});

		// When the child process is done.
		child.on('close', function (code) {
			var err; // Only defined if an error occured

			// Handle errors
			if (code !== 0) {
				var error_message = "`" + command + "` exited with code " + code;
				err = new Error(error_message);
				logger.log(1, error_message);
			}

			if (typeof callback === 'function') {
				process.nextTick(callback.bind(undefined, err));
			}
		});

		// Handle input.
		if (input && typeof input.pipe === 'function') {
			input.pipe(child.stdin);
		} else if (input !== undefined && input !== null) {
			child.stdin.end(input.toString());
		} else {
			child.stdin.end();
		}

		// Handle output.
		out_stream = new stream.Transform();
		out_stream._transform = function (chunk, enc, callback) {
			out_stream.push(chunk);
			logger.write(2, chunk, enc, callback);
		};
		child.stdout.pipe(out_stream);
		child.stderr.pipe(logger.stream);

		// Return a vinyl file wrapping the command's stdout.
		return new Vinyl({
			path: command.split(/\s+/)[0], // first word of the command
			contents: out_stream
		});

	}

	// The stream.Transform interface
	// --------------------------------------------------
	// This method is called automatically for each file piped into the stream. It spawns a
	// command for each file, using the file's contents as stdin, and pushes downstream a new file
	// wrapping stdout.

	command_stream._transform = function (file, enc, done) {
		var output;

		// Spawn the command.
		output = exec(command_template({file:file}), file, function (err) {
			if (err) command_stream.emit('error', err);
			else process.nextTick(done);
		});

		// Push downstream a vinyl file wrapping the command's stdout.
		command_stream.push(output);
	}

	/// `cmd.exec([callback])`
	/// --------------------------------------------------
	/// Executes the command immediately, returning a stream of vinyl. A single file containing
	/// the command's stdout is pushed down the stream.
	///
	/// The name of the file pushed down the stream is the first word of the command.
	/// See [gulp-rename] if you need more flexibility.
	///
	/// ### Arguments
	/// 1. `[callback]` *(Function)*: Execution is asynchronous. The callback is called once the
	///     command's stdout has closed.
	///
	/// ### Returns
	/// *(stream.Readable in Object Mode)*: A stream containing exactly one vinyl file. The file's
	/// contents is the stdout stream of the command.
	///
	/// ### Example
	/// ```javascript
	/// gulp.task('hello-world', function () {
	///     run('echo Hello World').exec() // prints "[echo] Hello World\n"
	///         .pipe(gulp.dest('output')) // Writes "Hello World\n" to output/echo
	/// })
	/// ```

	command_stream.exec = function (callback) {
		var output; // A vinyl file whose contents is the stdout of the command.
		var wrapper; // The higher-level vinyl stream. `output` is the only thing piped through.

		// Spawn the command.
		output = exec(command_template(), null, function (err) {
			if (err) wrapper.emit('error', err);
			if (typeof callback === 'function') {
				process.nextTick(callback.bind(undefined, err));
			}
		});

		// Wrap the output in a vinyl stream.
		wrapper = new stream.PassThrough({objectMode:true});
		wrapper.end(output);

		return wrapper;
	}

	return command_stream;
}
<|endoftext|>


<commit_before>OMAR.views.FederatedRasterSearch = Backbone.View.extend({
    el:"#rasterSearchPageId",
    bboxView:null,
    initialize:function(params){

        this.bboxView = new OMAR.views.BBOX();
        this.bboxModel = this.bboxView.model;

        this.pointView = new OMAR.views.PointView();
        this.pointModel = this.pointView.model;

        this.dateTimeRangeView = new OMAR.views.SimpleDateRangeView();
        this.dateTimeRangeModel = this.dateTimeRangeView.model;
        this.omarServerCollectionView = new OMAR.views.OmarServerCollectionView(
            {model:new OMAR.models.OmarServerCollection()}
        );
        this.mapView = new OMAR.views.Map(params.map);
        this.mapView.setBboxModel(this.bboxModel);
        this.mapView.setPointModel(this.pointModel);

        this.mapView.setServerCollection(this.omarServerCollectionView.model);
        this.setElement(this.el);

        this.dateTimeRangeModel.bind('change', this.updateFootprintCql, this)
        this.rasterEntryDataModelView = new OMAR.views.RasterEntryDataModelView();
        this.omarServerCollectionView.bind('onModelClicked', this.serverClicked, this);
    },
    events: {
        "click #SearchRasterId": "searchRaster"
    },
    showTab:function(event, ui){
        if(ui.index == 0)
        {
        }
        else if(ui.index == 1)
        {
            this.centerResize();
        }
        if(ui.index == 2)
        {
            this.rasterEntryDataModelView.resizeView();
        }
    },
    serverClicked:function(id){
        var cqlFilter = this.toCql();

        var model = this.omarServerCollectionView.getLastClickedModel();
        if(model)
        {
            this.rasterEntryDataModelView.wfsModel.set(
                {"url":model.get("url")+"/wfs",
                    "filter":cqlFilter}
            );
        }

        this.tabView.tabs("select", 2);
        $(this.tabView).find("#ResultsLabelId").text(model.get("nickname"));
    },
    render:function(){
        if(this.bboxView)
        {
            this.bboxView.render();
        }
        if(this.pointView)
        {
            this.pointView.render();
        }
        if(this.dateTimeRangeView)
        {
            this.dateTimeRangeView.render();
        }

        if(this.mapView)
        {
            this.mapView.render();
        }

        if(this.rasterEntryDataModelView)
        {
            this.rasterEntryDataModelView.render();
        }
        // lets make sure that that the map object exists
        // before we start the AJAX calls for fetching the server lists
        //
        if(this.omarServerCollectionView)
        {
            var collection =  this.omarServerCollectionView;

            collection.model.fetch({success:function(){collection.render()},
                update: true, remove: false,date:{cache:false}});
            window.setTimeout(this.updateServers.bind(this),5000);
        }

        this.mapView.setCqlFilterToFootprintLayers(this.toFootprintCql());
        this.tabView = $( "#tabView" ).tabs(
            {   "active":1,
                "show": $.proxy(this.showTab, this)
            });

    },
    updateFootprintCql:function(){
        this.mapView.setCqlFilterToFootprintLayers(this.toFootprintCql());
    },
    updateServers:function(){
        var collection =  this.omarServerCollectionView;
        collection.model.fetch({success:function(){},
            update: true, remove: false,date:{cache:false}});
        window.setTimeout(this.updateServers.bind(this),5000);
    },
    toCql:function(){
        var result = "";
        var timeQueryCql = this.dateTimeRangeModel.toCql("acquisition_date");
      // var spatialQueryCql = this.bboxModel.toCql("ground_geom");
          var spatialQueryCql = this.pointModel.toCql("ground_geom");
        if(timeQueryCql&&spatialQueryCql)
        {
            result = "(("+spatialQueryCql+")AND(" +timeQueryCql+"))";
        }
        else if(spatialQueryCql)
        {
            result=spatialQueryCql;
        }
        else
        {
            result = timeQueryCql;
        }
        return result;
    },
    centerResize:function(){
        this.rasterEntryDataModelView.resizeView();
        this.mapView.resizeView();
    },
    toFootprintCql:function(){
        var result = "";
        var timeQueryCql = this.dateTimeRangeModel.toCql("acquisition_date");

        // add all criteria here later.   Fo now we will just do time
        //
        result = timeQueryCql;

        return result;
    },
    searchRaster:function(){
        var cqlFilter = this.toCql();

        this.omarServerCollectionView.wfsServerCount.attributes.filter = cqlFilter;
        this.omarServerCollectionView.wfsServerCount.trigger("change");
        var model = this.omarServerCollectionView.getLastClickedModel();
        if(model)
        {
            this.rasterEntryDataModelView.wfsModel.set(
                {"url":model.get("url")+"/wfs",
                 "filter":cqlFilter}
            );
        }
     }
});

OMAR.federatedRasterSearch = null;
OMAR.pages.FederatedRasterSearch = (function($, params){
    OMAR.federatedRasterSearch = new OMAR.views.FederatedRasterSearch(params);
    return OMAR.federatedRasterSearch;
});

$(document).ready(function () {

    // OUTER-LAYOUT

    $('body').layout({
            center__paneSelector:   ".outer-center"
        ,   west__paneSelector:     ".outer-west"
        ,   east__paneSelector:     ".outer-east"
        ,   west__size:             125
        ,   east__size:             125
        ,   spacing_open:           8  // ALL panes
        ,   spacing_closed:         12 // ALL panes
        //, north__spacing_open:    0
        //, south__spacing_open:    0
        ,   north__maxSize:         200
        ,   south__maxSize:         200

            // MIDDLE-LAYOUT (child of outer-center-pane)
        ,   center__childOptions: {
                center__paneSelector:   ".middle-center"
            ,   west__paneSelector:     ".middle-west"
            ,   east__paneSelector:     ".middle-east"
            ,   west__size:             100
            ,   east__size:             100
            ,   spacing_open:           0  // ALL panes
            ,   spacing_closed:         0 // ALL panes

                // INNER-LAYOUT (child of middle-center-pane)
            ,   center__childOptions: {
                    center__paneSelector:   ".inner-center"
                ,   west__paneSelector:     ".inner-west"
                ,   east__paneSelector:     ".inner-east"
                ,   west__size:             225
                ,   west__minSize:          225
                ,   east__size:             75
                ,   spacing_open:           8  // ALL panes
                ,   spacing_closed:         8  // ALL panes
                ,   west__spacing_closed:   12
                ,   east__spacing_closed:   12
                , onresize_end:function(){if(OMAR.federatedRasterSearch) OMAR.federatedRasterSearch.centerResize();}
                }
            }
        });

    init();
    OMAR.federatedRasterSearch.centerResize();
    $( "#accordion" ).accordion();

    $("#jMenu").jMenu({
                  openClick : false,
                  ulWidth : 100,
                  effects : {
                    effectSpeedOpen : 200,
                    effectSpeedClose : 200,
                    effectTypeOpen : 'slide',
                    effectTypeClose : 'hide',
                    effectOpen : 'linear',
                    effectClose : 'linear'
                  },
                  TimeBeforeOpening : 100,
                  TimeBeforeClosing : 100,
                  animatedText : true,
                  paddingLeft: 10
                });

});

function generateKmlQuery() {
    alert("kml query code goes here.")
}

function refreshFootprints() {
    alert("refresh footprints code goes here.")
}

function search() {
    alert("search code goes here.")
}

function foo() {
    alert("search code goes here.")
}
<commit_msg>reverted bac to bbox<commit_after>OMAR.views.FederatedRasterSearch = Backbone.View.extend({
    el:"#rasterSearchPageId",
    bboxView:null,
    initialize:function(params){

        this.bboxView = new OMAR.views.BBOX();
        this.bboxModel = this.bboxView.model;

        this.pointView = new OMAR.views.PointView();
        this.pointModel = this.pointView.model;

        this.dateTimeRangeView = new OMAR.views.SimpleDateRangeView();
        this.dateTimeRangeModel = this.dateTimeRangeView.model;
        this.omarServerCollectionView = new OMAR.views.OmarServerCollectionView(
            {model:new OMAR.models.OmarServerCollection()}
        );
        this.mapView = new OMAR.views.Map(params.map);
        this.mapView.setBboxModel(this.bboxModel);
        this.mapView.setPointModel(this.pointModel);

        this.mapView.setServerCollection(this.omarServerCollectionView.model);
        this.setElement(this.el);

        this.dateTimeRangeModel.bind('change', this.updateFootprintCql, this)
        this.rasterEntryDataModelView = new OMAR.views.RasterEntryDataModelView();
        this.omarServerCollectionView.bind('onModelClicked', this.serverClicked, this);
    },
    events: {
        "click #SearchRasterId": "searchRaster"
    },
    showTab:function(event, ui){
        if(ui.index == 0)
        {
        }
        else if(ui.index == 1)
        {
            this.centerResize();
        }
        if(ui.index == 2)
        {
            this.rasterEntryDataModelView.resizeView();
        }
    },
    serverClicked:function(id){
        var cqlFilter = this.toCql();

        var model = this.omarServerCollectionView.getLastClickedModel();
        if(model)
        {
            this.rasterEntryDataModelView.wfsModel.set(
                {"url":model.get("url")+"/wfs",
                    "filter":cqlFilter}
            );
        }

        this.tabView.tabs("select", 2);
        $(this.tabView).find("#ResultsLabelId").text(model.get("nickname"));
    },
    render:function(){
        if(this.bboxView)
        {
            this.bboxView.render();
        }
        if(this.pointView)
        {
            this.pointView.render();
        }
        if(this.dateTimeRangeView)
        {
            this.dateTimeRangeView.render();
        }

        if(this.mapView)
        {
            this.mapView.render();
        }

        if(this.rasterEntryDataModelView)
        {
            this.rasterEntryDataModelView.render();
        }
        // lets make sure that that the map object exists
        // before we start the AJAX calls for fetching the server lists
        //
        if(this.omarServerCollectionView)
        {
            var collection =  this.omarServerCollectionView;

            collection.model.fetch({success:function(){collection.render()},
                update: true, remove: false,date:{cache:false}});
            window.setTimeout(this.updateServers.bind(this),5000);
        }

        this.mapView.setCqlFilterToFootprintLayers(this.toFootprintCql());
        this.tabView = $( "#tabView" ).tabs(
            {   "active":1,
                "show": $.proxy(this.showTab, this)
            });

    },
    updateFootprintCql:function(){
        this.mapView.setCqlFilterToFootprintLayers(this.toFootprintCql());
    },
    updateServers:function(){
        var collection =  this.omarServerCollectionView;
        collection.model.fetch({success:function(){},
            update: true, remove: false,date:{cache:false}});
        window.setTimeout(this.updateServers.bind(this),5000);
    },
    toCql:function(){
        var result = "";
        var timeQueryCql = this.dateTimeRangeModel.toCql("acquisition_date");
       var spatialQueryCql = this.bboxModel.toCql("ground_geom");
      //    var spatialQueryCql = this.pointModel.toCql("ground_geom");
        if(timeQueryCql&&spatialQueryCql)
        {
            result = "(("+spatialQueryCql+")AND(" +timeQueryCql+"))";
        }
        else if(spatialQueryCql)
        {
            result=spatialQueryCql;
        }
        else
        {
            result = timeQueryCql;
        }
        return result;
    },
    centerResize:function(){
        this.rasterEntryDataModelView.resizeView();
        this.mapView.resizeView();
    },
    toFootprintCql:function(){
        var result = "";
        var timeQueryCql = this.dateTimeRangeModel.toCql("acquisition_date");

        // add all criteria here later.   Fo now we will just do time
        //
        result = timeQueryCql;

        return result;
    },
    searchRaster:function(){
        var cqlFilter = this.toCql();

        this.omarServerCollectionView.wfsServerCount.attributes.filter = cqlFilter;
        this.omarServerCollectionView.wfsServerCount.trigger("change");
        var model = this.omarServerCollectionView.getLastClickedModel();
        if(model)
        {
            this.rasterEntryDataModelView.wfsModel.set(
                {"url":model.get("url")+"/wfs",
                 "filter":cqlFilter}
            );
        }
     }
});

OMAR.federatedRasterSearch = null;
OMAR.pages.FederatedRasterSearch = (function($, params){
    OMAR.federatedRasterSearch = new OMAR.views.FederatedRasterSearch(params);
    return OMAR.federatedRasterSearch;
});

$(document).ready(function () {

    // OUTER-LAYOUT

    $('body').layout({
            center__paneSelector:   ".outer-center"
        ,   west__paneSelector:     ".outer-west"
        ,   east__paneSelector:     ".outer-east"
        ,   west__size:             125
        ,   east__size:             125
        ,   spacing_open:           8  // ALL panes
        ,   spacing_closed:         12 // ALL panes
        //, north__spacing_open:    0
        //, south__spacing_open:    0
        ,   north__maxSize:         200
        ,   south__maxSize:         200

            // MIDDLE-LAYOUT (child of outer-center-pane)
        ,   center__childOptions: {
                center__paneSelector:   ".middle-center"
            ,   west__paneSelector:     ".middle-west"
            ,   east__paneSelector:     ".middle-east"
            ,   west__size:             100
            ,   east__size:             100
            ,   spacing_open:           0  // ALL panes
            ,   spacing_closed:         0 // ALL panes

                // INNER-LAYOUT (child of middle-center-pane)
            ,   center__childOptions: {
                    center__paneSelector:   ".inner-center"
                ,   west__paneSelector:     ".inner-west"
                ,   east__paneSelector:     ".inner-east"
                ,   west__size:             225
                ,   west__minSize:          225
                ,   east__size:             75
                ,   spacing_open:           8  // ALL panes
                ,   spacing_closed:         8  // ALL panes
                ,   west__spacing_closed:   12
                ,   east__spacing_closed:   12
                , onresize_end:function(){if(OMAR.federatedRasterSearch) OMAR.federatedRasterSearch.centerResize();}
                }
            }
        });

    init();
    OMAR.federatedRasterSearch.centerResize();
    $( "#accordion" ).accordion();

    $("#jMenu").jMenu({
                  openClick : false,
                  ulWidth : 100,
                  effects : {
                    effectSpeedOpen : 200,
                    effectSpeedClose : 200,
                    effectTypeOpen : 'slide',
                    effectTypeClose : 'hide',
                    effectOpen : 'linear',
                    effectClose : 'linear'
                  },
                  TimeBeforeOpening : 100,
                  TimeBeforeClosing : 100,
                  animatedText : true,
                  paddingLeft: 10
                });

});

function generateKmlQuery() {
    alert("kml query code goes here.")
}

function refreshFootprints() {
    alert("refresh footprints code goes here.")
}

function search() {
    alert("search code goes here.")
}

function foo() {
    alert("search code goes here.")
}
<|endoftext|>


<commit_before>function NameController($window, $timeout, ShareBandNameService, FormDataService, SocialMediaShareService) {
  var ctrl = this;

  ctrl.loadingPage = true;
  ctrl.bandName = ShareBandNameService;

  ctrl.removeBodyClass = (className) => {
    let body = angular.element(document.querySelector('body'));
    body.removeClass(className);
  }

  ctrl.hideLoadingPage = () => {
    ctrl.removeBodyClass('bg-loading');
    ctrl.loadingPage = false;
  }

  ctrl.resetBandName = function() {
    ctrl.bandName.name = '';
    ctrl.bandName.genre_id = '';
    FormDataService.formData = {};
  }

  ctrl.twtrBandName = () => {
    return ctrl.bandName.name.replace(/\s/g, '+');
  }

  ctrl.fbFeed = SocialMediaShareService.fbFeed;
  ctrl.twtrTweet = SocialMediaShareService.twtrTweet;

  SocialMediaShareService.fbSDK;

  $timeout(ctrl.hideLoadingPage, 3000);

}

angular
  .module('app')
  .controller('NameController', NameController);<commit_msg>rename argument passed into removeBodyClass in NameController<commit_after>function NameController($window, $timeout, ShareBandNameService, FormDataService, SocialMediaShareService) {
  var ctrl = this;

  ctrl.loadingPage = true;
  ctrl.bandName = ShareBandNameService;

  ctrl.removeBodyClass = (className) => {
    let body = angular.element(document.querySelector('body'));
    body.removeClass(className);
  }

  ctrl.hideLoadingPage = () => {
    ctrl.removeBodyClass('bg-color-loading');
    ctrl.loadingPage = false;
  }

  ctrl.resetBandName = function() {
    ctrl.bandName.name = '';
    ctrl.bandName.genre_id = '';
    FormDataService.formData = {};
  }

  ctrl.twtrBandName = () => {
    return ctrl.bandName.name.replace(/\s/g, '+');
  }

  ctrl.fbFeed = SocialMediaShareService.fbFeed;
  ctrl.twtrTweet = SocialMediaShareService.twtrTweet;

  SocialMediaShareService.fbSDK;

  $timeout(ctrl.hideLoadingPage, 3000);

}

angular
  .module('app')
  .controller('NameController', NameController);<|endoftext|>


<commit_before>define([ "Maneuver" ], function(Maneuver)
{
    var RangeRuler =
    {
        ONE: "one",
        TWO: "two",
        THREE: "three",
        properties:
        {
            "one":
            {
                minDistance: 0, // Minimum distance. (mm)
                maxDistance: 100, // Maximum distance. (mm)
                displayName: "1",
                value: "one",
            },
            "two":
            {
                minDistance: 101, // Minimum distance. (mm)
                maxDistance: 200, // Maximum distance. (mm)
                displayName: "2",
                value: "two",
            },
            "three":
            {
                minDistance: 201, // Minimum distance. (mm)
                maxDistance: 300, // Maximum distance. (mm)
                displayName: "3",
                value: "three",
            },
        },

        values: function()
        {
            return Object.getOwnPropertyNames(this.properties);
        },
    }

    RangeRuler.findRange = function(distance)
    {
        var answer;

        var values = this.values();

        for (var i = 0; i < values.length; i++)
        {
            var r = values[i];
            var min = this.properties[r].minDistance;
            var max = this.properties[r].maxDistance;

            if ((min <= distance) && (distance <= max))
            {
                answer = r;
                break;
            }
        }

        return answer;
    }

    RangeRuler.getRange = function(attacker, attackerPosition, defender, defenderPosition)
    {
        InputValidator.validateNotNull("attacker", attacker);
        InputValidator.validateNotNull("attackerPosition", attackerPosition);
        InputValidator.validateNotNull("defender", defender);
        InputValidator.validateNotNull("defenderPosition", defenderPosition);

        var attackerBase = attacker.shipBaseKey();
        var defenderBase = defender.shipBaseKey();

        var attackerPolygon = Maneuver.computePolygon(attackerBase, attackerPosition.x(), attackerPosition.y(),
                attackerPosition.heading());
        var defenderPolygon = Maneuver.computePolygon(defenderBase, defenderPosition.x(), defenderPosition.y(),
                defenderPosition.heading());

        // FIXME
        // var distance = SHAPE_UTILS.computeMinimumDistance(attackerPolygon,
        // defenderPolygon);
        var distance = attackerPosition.computeDistance(defenderPosition);
        // LOGGER.trace("distance = "+distance);

        return RangeRuler.findRange(Math.round(distance));
    }

    if (Object.freeze)
    {
        Object.freeze(RangeRuler);
    };

    return RangeRuler;
});
<commit_msg>Changed RangeRuler.getRange() to use the minimum distance.<commit_after>define([ "Maneuver", "Position" ], function(Maneuver, Position)
{
    var RangeRuler =
    {
        ONE: "one",
        TWO: "two",
        THREE: "three",
        properties:
        {
            "one":
            {
                minDistance: 0, // Minimum distance. (mm)
                maxDistance: 100, // Maximum distance. (mm)
                displayName: "1",
                value: "one",
            },
            "two":
            {
                minDistance: 101, // Minimum distance. (mm)
                maxDistance: 200, // Maximum distance. (mm)
                displayName: "2",
                value: "two",
            },
            "three":
            {
                minDistance: 201, // Minimum distance. (mm)
                maxDistance: 300, // Maximum distance. (mm)
                displayName: "3",
                value: "three",
            },
        },

        values: function()
        {
            return Object.getOwnPropertyNames(this.properties);
        },
    }

    RangeRuler.findRange = function(distance)
    {
        var answer;

        var values = this.values();

        for (var i = 0; i < values.length; i++)
        {
            var r = values[i];
            var min = this.properties[r].minDistance;
            var max = this.properties[r].maxDistance;

            if ((min <= distance) && (distance <= max))
            {
                answer = r;
                break;
            }
        }

        return answer;
    }

    RangeRuler.getRange = function(attacker, attackerPosition, defender, defenderPosition)
    {
        InputValidator.validateNotNull("attacker", attacker);
        InputValidator.validateNotNull("attackerPosition", attackerPosition);
        InputValidator.validateNotNull("defender", defender);
        InputValidator.validateNotNull("defenderPosition", defenderPosition);

        var distance = attackerPosition.computeDistance(defenderPosition);

        var attackerPolygon = Maneuver.computePolygon(attacker.shipBaseKey(), attackerPosition.x(), attackerPosition
                .y(), attackerPosition.heading());
        var defenderPolygon = Maneuver.computePolygon(defender.shipBaseKey(), defenderPosition.x(), defenderPosition
                .y(), defenderPosition.heading());

        var points0 = attackerPolygon.points();
        var points1 = defenderPolygon.points();

        for (var i = 0; i < points0.length; i += 2)
        {
            if (Position.isPointInPlayArea(points0[i], points0[i + 1]))
            {
                var position0 = new Position(points0[i], points0[i + 1], 0);

                for (var j = 0; j < points1.length; j += 2)
                {
                    if (Position.isPointInPlayArea(points1[j], points1[j + 1]))
                    {
                        var position1 = new Position(points1[j], points1[j + 1], 0);
                        var myDistance = position0.computeDistance(position1);
                        distance = Math.min(myDistance, distance);
                    }
                }
            }
        }

        LOGGER.trace("distance = " + distance);

        return RangeRuler.findRange(Math.round(distance));
    }

    if (Object.freeze)
    {
        Object.freeze(RangeRuler);
    };

    return RangeRuler;
});
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');

gulp.task('static', function () {
  return gulp.src('**/*.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
  nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
  return gulp.src('generators/**/*.js')
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  var mochaErr;

  gulp.src('test/**/*.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      mochaErr = err;
    })
    .pipe(istanbul.writeReports())
    .on('end', function () {
      cb(mochaErr);
    });
});

gulp.task('watch', function () {
  gulp.watch(['generators/**/*.js', 'test/**'], ['test']);
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['static', 'test']);
<commit_msg>Removing nsp zone until it's fixed. jfigueruela will report it<commit_after>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');

gulp.task('static', function () {
  return gulp.src('**/*.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

//gulp.task('nsp', function (cb) {
//  nsp({package: path.resolve('package.json')}, cb);
//});

gulp.task('pre-test', function () {
  return gulp.src('generators/**/*.js')
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  var mochaErr;

  gulp.src('test/**/*.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      mochaErr = err;
    })
    .pipe(istanbul.writeReports())
    .on('end', function () {
      cb(mochaErr);
    });
});

gulp.task('watch', function () {
  gulp.watch(['generators/**/*.js', 'test/**'], ['test']);
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['static', 'test']);
<|endoftext|>


<commit_before>(function () {
    var app = angular.module('shocktrade');

    /**
     * Game Search Controller
     * @author lawrence.daniels@gmail.com
     */
    app.controller('GameSearchController', ['$scope', '$location', '$log', '$routeParams', '$timeout', 'toaster', 'ContestService', 'MySession', 'NewGameDialog',
        function ($scope, $location, $log, $routeParams, $timeout, toaster, ContestService, MySession, NewGameDialog) {

            // public variables
            $scope.myContests = [];
            $scope.searchResults = [];
            $scope.searchTerm = "";
            $scope.selectedContest = null;
            $scope.splitScreen = false;

            // search variables
            $scope.searchOptions = {
                activeOnly: false,
                available: false,
                friendsOnly: false,
                levelCap: "1",
                levelCapAllowed: false,
                perksAllowed: false,
                robotsAllowed: false
            };

            ///////////////////////////////////////////////////////////////////////////
            //          Public Functions
            ///////////////////////////////////////////////////////////////////////////

            $scope.initGames = function () {
                $scope.contestSearch($scope.searchOptions);
            };

            $scope.enterGame = function (contest) {
                MySession.setContest(contest);
                $location.path("/dashboard/" + contest.OID());
            };

            $scope.getAvailableCount = function () {
                var count = 0;
                angular.forEach($scope.searchResults, function (r) {
                    if (r.status === 'ACTIVE') count++;
                });
                return count;
            };

            $scope.getAvailableSlots = function (contest, row) { // 0,1
                var slots = [];
                if (contest) {
                    var participants = contest.participants || [];
                    var start = row * 8; // 0=0, 1=8, 2=16
                    var end = row * 8 + 8; // 0=7, 1=8, 2=15
                    for (var n = start; n < end; n++) {
                        slots.push((n < participants.length) ? participants[n] : null);
                    }
                }
                return slots;
            };

            $scope.contestSearch = function (searchOptions) {
                $scope.startLoading();

                ContestService.findContests(searchOptions).then(
                    function (contests) {
                        $scope.searchResults = contests;
                        $scope.stopLoading();
                    },
                    function (err) {
                        toaster.pop('error', 'Error!', "Failed to execute Contest Search");
                        $scope.stopLoading();
                    });
            };

            $scope.getSearchResults = function (searchTerm) {
                var term = (searchTerm || "").trim().toLowerCase();
                if (term.length === 0) return $scope.searchResults;
                else {
                    // $log.info("searchTerm = " + searchTerm);
                    return $scope.searchResults.filter(function (c) {
                        return c.name.toLowerCase().indexOf(term) != -1;
                    });
                }
            };

            $scope.contestStatusClass = function (contest) {
                if (contest == null) return "";
                else if (contest.status == 'ACTIVE') return "positive";
                else if (contest.status == 'CLOSED') return "negative";
                else return "";
            };

            $scope.getStatusClass = function (c, maxPlayers) {
                if (!c) return null;
                else {
                    var playerCount = ((c && c.participants) || []).length;
                    if (playerCount + 1 < maxPlayers) return "positive";
                    else if (playerCount + 1 === maxPlayers) return "warning";
                    else if (playerCount >= maxPlayers) return "negative";
                    else if (c.status === 'ACTIVE') return 'positive';
                    else if (c.status === 'CLOSED') return 'negative';
                    else return "null";
                }
            };

            $scope.trophy = function (place) {
                switch (place) {
                    case '1st':
                        return "contests/gold.png";
                    case '2nd':
                        return "contests/silver.png";
                    case '3rd':
                        return "contests/bronze.png";
                    default:
                        return "status/transparent.png";
                }
            };

            ///////////////////////////////////////////////////////////////////////////
            //          My Contest Functions
            ///////////////////////////////////////////////////////////////////////////

            $scope.getMyContests = function () {
                return $scope.myContests;
            };

            $scope.getMyRankings = function (contest) {
                if (!contest) return {};
                else {
                    var rankings = ContestService.getPlayerRankings(contest, MySession.getUserName());
                    return rankings.player;
                }
            };

            $scope.newGamePopup = function () {
                NewGameDialog.popup({
                    "success": function (contest) {
                        $scope.myContests.push(contest);
                    },
                    "error": function(err) {
                        toaster.pop('error', 'Failed to create game', null);
                    }
                });
            };

            function loadMyContests() {
                var userID = MySession.getUserID();
                if (!userID) return [];
                else {
                    $scope.myContests = [];

                    $log.info("Loading 'My Contests'...");
                    ContestService.getContestsByPlayerID(userID)
                        .success(function (contests) {
                            $log.info("Loaded " + contests.length + " contest(s)");
                            $scope.myContests = contests;
                        })
                        .error(function (response) {
                            toaster.pop('error', "Failed to load 'My Contests'", null)
                        });
                }
            }

            ///////////////////////////////////////////////////////////////////////////
            //          Contest Selection Functions
            ///////////////////////////////////////////////////////////////////////////

            $scope.isSplitScreen = function () {
                return $scope.splitScreen && ($scope.selectedContest != null);
            };

            $scope.selectContest = function (contest) {
                $log.info("Selecting contest '" + contest.name + "' (" + contest.OID() + ")");
                $scope.selectedContest = contest;
                $scope.splitScreen = true;

                if (!contest.rankings) {
                    ContestService.getPlayerRankings(contest, MySession.getUserName());
                }
            };

            $scope.toggleSplitScreen = function () {
                $scope.splitScreen = false;
            };

            function isContestSelected(contestId) {
                return $scope.selectedContest && ($scope.selectedContest.OID() === contestId);
            }

            ///////////////////////////////////////////////////////////////////////////
            //          Contest Management Functions
            ///////////////////////////////////////////////////////////////////////////

            $scope.containsPlayer = function (contest, userProfile) {
                return userProfile.id && ContestService.findPlayerByID(contest, userProfile.OID()) != null;
            };

            $scope.isContestOwner = function (contest) {
                return contest && contest.creator.name === MySession.getUserName();
            };

            $scope.isDeletable = function (contest) {
                return $scope.isContestOwner(contest) && (!contest.startTime || contest.participants.length == 1);
            };

            $scope.isParticipant = function (contest) {
                var id = MySession.getUserID();
                return id && ContestService.findPlayerByID(contest, id) != null;
            };

            $scope.deleteContest = function (contest) {
                contest.deleting = true;
                $log.info("Deleting contest " + contest.name + "...");
                ContestService.deleteContest(contest.OID())
                    .success(function (response) {
                        //removeContestFromList(contest.OID());
                        $scope.contestSearch($scope.searchOptions);

                        $timeout(function () {
                            contest.deleting = false;
                        }, 500);
                    })
                    .error(function (err) {
                        toaster.pop('error', 'Error!', "Failed to delete contest");
                        $log.error("An error occurred while deleting the contest");
                        $timeout(function () {
                            contest.deleting = false;
                        }, 500);
                    });
            };

            $scope.isJoinable = function (contest) {
                return MySession.authenticated && contest && !contest.invitationOnly && !$scope.isContestOwner(contest) && !$scope.isParticipant(contest);
            };

            $scope.joinContest = function (contest) {
                contest.joining = true;
                ContestService.joinContest(contest.OID(), {
                    player: {
                        "id": MySession.getUserID(),
                        "name": MySession.getUserName(),
                        "facebookID": MySession.fbUserID
                    }
                }).success(function (contest) {
                    if (!contest) {
                        toaster.pop('error', 'Error!', "Failed to join game");
                        $log.error("Returned contest was null")
                    }
                    else if (contest.error) {
                        toaster.pop('error', 'Error!', contest.error);
                        $log.error(contest.error);
                    }
                    else {
                        $scope.contest = contest;
                        MySession.setContest(contest);
                        //MySession.deduct(contest.startingBalance);
                        updateWithRankings(MySession.getUserName(), contest)
                    }

                    $timeout(function () {
                        contest.joining = false;
                    }, 500);

                }).error(function (err) {
                    toaster.pop('error', 'Error!', "Failed to join contest");
                    $log.error("An error occurred while joining the contest");
                    $timeout(function () {
                        contest.joining = false;
                    }, 500);
                });
            };

            $scope.joinedParticipant = function (contest, userProfile) {
                return $scope.containsPlayer(contest, userProfile);
            };

            $scope.quitContest = function (contest) {
                contest.quitting = true;
                ContestService.quitContest(contest.OID(), MySession.getUserID())
                    .success(function (updatedContest) {
                        if (!updatedContest.error) {
                            $scope.contest = updatedContest;
                            MySession.setContest(updatedContest);
                        }
                        else {
                            $log.error("error = " + updatedContest.error);
                            toaster.pop('error', 'Error!', "Unable to process your quit command at this time.")
                        }

                        $timeout(function () {
                            contest.quitting = false;
                        }, 500);
                    })
                    .error(function (err) {
                        $log.error("An error occurred while joining the contest");
                        $timeout(function () {
                            contest.quitting = false;
                        }, 500);
                    });
            };

            $scope.startContest = function (contest) {
                contest.starting = true;
                ContestService.startContest(contest.OID())
                    .success(function (contest) {
                        if (contest.error) {
                            toaster.pop('error', 'Error!', contest.error);
                            $log.error(contest.error);
                        }

                        $timeout(function () {
                            contest.starting = false;
                        }, 500);
                    })
                    .error(function (err) {
                        $log.error("An error occurred while starting the contest");
                        $timeout(function () {
                            contest.starting = false;
                        }, 500);
                    });
            };

            //////////////////////////////////////////////////////////////////////
            //              Style/CSS Functions
            //////////////////////////////////////////////////////////////////////

            $scope.getSelectionClass = function (c) {
                return $scope.selectedContest && ($scope.selectedContest.OID() === c.OID()) ? 'selected' : (c.status === 'ACTIVE' ? '' : 'null')
            };

            //////////////////////////////////////////////////////////////////////
            //              Broadcast Event Listeners
            //////////////////////////////////////////////////////////////////////

            function indexOfContest(contestId) {
                for (var n = 0; n < $scope.searchResults.length; n++) {
                    var contest = $scope.searchResults[n];
                    if (contest.OID() === contestId) return n;
                }
                return -1;
            }

            function updateContestInList(searchResults, contestId) {
                for (var n = 0; n < searchResults.length; n++) {
                    if (searchResults[n].OID() === contestId) {
                        var index = n;
                        ContestService.getContestByID(contestId)
                            .success(function (loadedContest) {
                                searchResults[index] = loadedContest;
                            })
                            .error(function (xhr, status, error) {
                                $log.error("Error selecting feed: " + xhr.error);
                                toaster.pop('error', 'Error!', "Error loading game");
                            });
                    }
                }
            }

            function removeContestFromList(searchResults, contestId) {
                var index = indexOfContest(contestId);
                if (index != -1) {
                    $log.info("Removed contest " + contestId + " from the list...");
                    searchResults.splice(index, 1);
                }

                if ($scope.selectedContest && $scope.selectedContest.OID() === contestId) {
                    $scope.selectedContest = null;
                }
            }

            ///////////////////////////////////////////////////////////////////////////
            //          Event Listeners
            ///////////////////////////////////////////////////////////////////////////

            /**
             * Listen for contest creation events
             */
            $scope.$on("contest_created", function (event, contest) {
                $log.info("New contest created '" + contest.name + "'");
                $scope.searchResults.push(contest);
                loadMyContests();
                MySession.refresh();
            });

            /**
             * Listen for contest deletion events
             */
            $scope.$on("contest_deleted", function (event, contest) {
                $log.info("Contest '" + contest.name + "' deleted");
                $scope.selectedContest = null;
                $scope.searchResults.push(contest);
                loadMyContests();
                MySession.refresh();
            });

            /**
             * Listen for contest update events
             */
            $scope.$on("contest_updated", function (event, contest) {
                $log.info("Contest '" + contest.name + "' updated");
                var contestId = contest.OID();

                // update the contest in our search results
                updateContestInList($scope.searchResults, contestId);
                updateContestInList($scope.myContests, contestId);

                // make sure we're pointing at the updated contest
                if (isContestSelected(contestId)) {
                    $scope.selectedContest = contest;
                }
            });

            $scope.$watch("MySession.userProfile._id", function () {
                loadMyContests();
            });

        }]);

})();<commit_msg>removed obsolete reference<commit_after>(function () {
    var app = angular.module('shocktrade');

    /**
     * Game Search Controller
     * @author lawrence.daniels@gmail.com
     */
    app.controller('GameSearchController', ['$scope', '$location', '$log', '$routeParams', '$timeout', 'toaster', 'ContestService', 'MySession', 'NewGameDialog',
        function ($scope, $location, $log, $routeParams, $timeout, toaster, ContestService, MySession, NewGameDialog) {

            // public variables
            $scope.myContests = [];
            $scope.searchResults = [];
            $scope.searchTerm = "";
            $scope.selectedContest = null;
            $scope.splitScreen = false;

            // search variables
            $scope.searchOptions = {
                activeOnly: false,
                available: false,
                friendsOnly: false,
                levelCap: "1",
                levelCapAllowed: false,
                perksAllowed: false,
                robotsAllowed: false
            };

            ///////////////////////////////////////////////////////////////////////////
            //          Public Functions
            ///////////////////////////////////////////////////////////////////////////

            $scope.initGames = function () {
                $scope.contestSearch($scope.searchOptions);
            };

            $scope.enterGame = function (contest) {
                MySession.setContest(contest);
                $location.path("/dashboard/" + contest.OID());
            };

            $scope.getAvailableCount = function () {
                var count = 0;
                angular.forEach($scope.searchResults, function (r) {
                    if (r.status === 'ACTIVE') count++;
                });
                return count;
            };

            $scope.getAvailableSlots = function (contest, row) { // 0,1
                var slots = [];
                if (contest) {
                    var participants = contest.participants || [];
                    var start = row * 8; // 0=0, 1=8, 2=16
                    var end = row * 8 + 8; // 0=7, 1=8, 2=15
                    for (var n = start; n < end; n++) {
                        slots.push((n < participants.length) ? participants[n] : null);
                    }
                }
                return slots;
            };

            $scope.contestSearch = function (searchOptions) {
                $scope.startLoading();

                ContestService.findContests(searchOptions).then(
                    function (contests) {
                        $scope.searchResults = contests;
                        $scope.stopLoading();
                    },
                    function (err) {
                        toaster.pop('error', 'Error!', "Failed to execute Contest Search");
                        $scope.stopLoading();
                    });
            };

            $scope.getSearchResults = function (searchTerm) {
                var term = (searchTerm || "").trim().toLowerCase();
                if (term.length === 0) return $scope.searchResults;
                else {
                    // $log.info("searchTerm = " + searchTerm);
                    return $scope.searchResults.filter(function (c) {
                        return c.name.toLowerCase().indexOf(term) != -1;
                    });
                }
            };

            $scope.contestStatusClass = function (contest) {
                if (contest == null) return "";
                else if (contest.status == 'ACTIVE') return "positive";
                else if (contest.status == 'CLOSED') return "negative";
                else return "";
            };

            $scope.getStatusClass = function (c, maxPlayers) {
                if (!c) return null;
                else {
                    var playerCount = ((c && c.participants) || []).length;
                    if (playerCount + 1 < maxPlayers) return "positive";
                    else if (playerCount + 1 === maxPlayers) return "warning";
                    else if (playerCount >= maxPlayers) return "negative";
                    else if (c.status === 'ACTIVE') return 'positive';
                    else if (c.status === 'CLOSED') return 'negative';
                    else return "null";
                }
            };

            $scope.trophy = function (place) {
                switch (place) {
                    case '1st':
                        return "contests/gold.png";
                    case '2nd':
                        return "contests/silver.png";
                    case '3rd':
                        return "contests/bronze.png";
                    default:
                        return "status/transparent.png";
                }
            };

            ///////////////////////////////////////////////////////////////////////////
            //          My Contest Functions
            ///////////////////////////////////////////////////////////////////////////

            $scope.getMyContests = function () {
                return $scope.myContests;
            };

            $scope.getMyRankings = function (contest) {
                if (!contest) return {};
                else {
                    var rankings = ContestService.getPlayerRankings(contest, MySession.getUserName());
                    return rankings.player;
                }
            };

            $scope.newGamePopup = function () {
                NewGameDialog.popup({
                    "success": function (contest) {
                        $scope.myContests.push(contest);
                    },
                    "error": function(err) {
                        toaster.pop('error', 'Failed to create game', null);
                    }
                });
            };

            function loadMyContests() {
                var userID = MySession.getUserID();
                if (!userID) return [];
                else {
                    $scope.myContests = [];

                    $log.info("Loading 'My Contests'...");
                    ContestService.getContestsByPlayerID(userID)
                        .success(function (contests) {
                            $log.info("Loaded " + contests.length + " contest(s)");
                            $scope.myContests = contests;
                        })
                        .error(function (response) {
                            toaster.pop('error', "Failed to load 'My Contests'", null)
                        });
                }
            }

            ///////////////////////////////////////////////////////////////////////////
            //          Contest Selection Functions
            ///////////////////////////////////////////////////////////////////////////

            $scope.isSplitScreen = function () {
                return $scope.splitScreen && ($scope.selectedContest != null);
            };

            $scope.selectContest = function (contest) {
                $log.info("Selecting contest '" + contest.name + "' (" + contest.OID() + ")");
                $scope.selectedContest = contest;
                $scope.splitScreen = true;

                if (!contest.rankings) {
                    ContestService.getPlayerRankings(contest, MySession.getUserName());
                }
            };

            $scope.toggleSplitScreen = function () {
                $scope.splitScreen = false;
            };

            function isContestSelected(contestId) {
                return $scope.selectedContest && ($scope.selectedContest.OID() === contestId);
            }

            ///////////////////////////////////////////////////////////////////////////
            //          Contest Management Functions
            ///////////////////////////////////////////////////////////////////////////

            $scope.containsPlayer = function (contest, userProfile) {
                return userProfile.id && ContestService.findPlayerByID(contest, userProfile.OID()) != null;
            };

            $scope.isContestOwner = function (contest) {
                return contest && contest.creator.name === MySession.getUserName();
            };

            $scope.isDeletable = function (contest) {
                return $scope.isContestOwner(contest) && (!contest.startTime || contest.participants.length == 1);
            };

            $scope.isParticipant = function (contest) {
                var id = MySession.getUserID();
                return id && ContestService.findPlayerByID(contest, id) != null;
            };

            $scope.deleteContest = function (contest) {
                contest.deleting = true;
                $log.info("Deleting contest " + contest.name + "...");
                ContestService.deleteContest(contest.OID())
                    .success(function (response) {
                        //removeContestFromList(contest.OID());
                        $scope.contestSearch($scope.searchOptions);

                        $timeout(function () {
                            contest.deleting = false;
                        }, 500);
                    })
                    .error(function (err) {
                        toaster.pop('error', 'Error!', "Failed to delete contest");
                        $log.error("An error occurred while deleting the contest");
                        $timeout(function () {
                            contest.deleting = false;
                        }, 500);
                    });
            };

            $scope.isJoinable = function (contest) {
                return MySession.authenticated && contest && !contest.invitationOnly && !$scope.isContestOwner(contest) && !$scope.isParticipant(contest);
            };

            $scope.joinContest = function (contest) {
                contest.joining = true;
                ContestService.joinContest(contest.OID(), {
                    player: {
                        "id": MySession.getUserID(),
                        "name": MySession.getUserName(),
                        "facebookID": MySession.fbUserID
                    }
                }).success(function (contest) {
                    if (!contest) {
                        toaster.pop('error', 'Error!', "Failed to join game");
                        $log.error("Returned contest was null")
                    }
                    else if (contest.error) {
                        toaster.pop('error', 'Error!', contest.error);
                        $log.error(contest.error);
                    }
                    else {
                        $scope.contest = contest;
                        MySession.setContest(contest);
                        //MySession.deduct(contest.startingBalance);
                        //updateWithRankings(MySession.getUserName(), contest)
                    }

                    $timeout(function () {
                        contest.joining = false;
                    }, 500);

                }).error(function (err) {
                    toaster.pop('error', 'Error!', "Failed to join contest");
                    $log.error("An error occurred while joining the contest");
                    $timeout(function () {
                        contest.joining = false;
                    }, 500);
                });
            };

            $scope.joinedParticipant = function (contest, userProfile) {
                return $scope.containsPlayer(contest, userProfile);
            };

            $scope.quitContest = function (contest) {
                contest.quitting = true;
                ContestService.quitContest(contest.OID(), MySession.getUserID())
                    .success(function (updatedContest) {
                        if (!updatedContest.error) {
                            $scope.contest = updatedContest;
                            MySession.setContest(updatedContest);
                        }
                        else {
                            $log.error("error = " + updatedContest.error);
                            toaster.pop('error', 'Error!', "Unable to process your quit command at this time.")
                        }

                        $timeout(function () {
                            contest.quitting = false;
                        }, 500);
                    })
                    .error(function (err) {
                        $log.error("An error occurred while joining the contest");
                        $timeout(function () {
                            contest.quitting = false;
                        }, 500);
                    });
            };

            $scope.startContest = function (contest) {
                contest.starting = true;
                ContestService.startContest(contest.OID())
                    .success(function (contest) {
                        if (contest.error) {
                            toaster.pop('error', 'Error!', contest.error);
                            $log.error(contest.error);
                        }

                        $timeout(function () {
                            contest.starting = false;
                        }, 500);
                    })
                    .error(function (err) {
                        $log.error("An error occurred while starting the contest");
                        $timeout(function () {
                            contest.starting = false;
                        }, 500);
                    });
            };

            //////////////////////////////////////////////////////////////////////
            //              Style/CSS Functions
            //////////////////////////////////////////////////////////////////////

            $scope.getSelectionClass = function (c) {
                return $scope.selectedContest && ($scope.selectedContest.OID() === c.OID()) ? 'selected' : (c.status === 'ACTIVE' ? '' : 'null')
            };

            //////////////////////////////////////////////////////////////////////
            //              Broadcast Event Listeners
            //////////////////////////////////////////////////////////////////////

            function indexOfContest(contestId) {
                for (var n = 0; n < $scope.searchResults.length; n++) {
                    var contest = $scope.searchResults[n];
                    if (contest.OID() === contestId) return n;
                }
                return -1;
            }

            function updateContestInList(searchResults, contestId) {
                for (var n = 0; n < searchResults.length; n++) {
                    if (searchResults[n].OID() === contestId) {
                        var index = n;
                        ContestService.getContestByID(contestId)
                            .success(function (loadedContest) {
                                searchResults[index] = loadedContest;
                            })
                            .error(function (xhr, status, error) {
                                $log.error("Error selecting feed: " + xhr.error);
                                toaster.pop('error', 'Error!', "Error loading game");
                            });
                    }
                }
            }

            function removeContestFromList(searchResults, contestId) {
                var index = indexOfContest(contestId);
                if (index != -1) {
                    $log.info("Removed contest " + contestId + " from the list...");
                    searchResults.splice(index, 1);
                }

                if ($scope.selectedContest && $scope.selectedContest.OID() === contestId) {
                    $scope.selectedContest = null;
                }
            }

            ///////////////////////////////////////////////////////////////////////////
            //          Event Listeners
            ///////////////////////////////////////////////////////////////////////////

            /**
             * Listen for contest creation events
             */
            $scope.$on("contest_created", function (event, contest) {
                $log.info("New contest created '" + contest.name + "'");
                $scope.searchResults.push(contest);
                loadMyContests();
                MySession.refresh();
            });

            /**
             * Listen for contest deletion events
             */
            $scope.$on("contest_deleted", function (event, contest) {
                $log.info("Contest '" + contest.name + "' deleted");
                $scope.selectedContest = null;
                $scope.searchResults.push(contest);
                loadMyContests();
                MySession.refresh();
            });

            /**
             * Listen for contest update events
             */
            $scope.$on("contest_updated", function (event, contest) {
                $log.info("Contest '" + contest.name + "' updated");
                var contestId = contest.OID();

                // update the contest in our search results
                updateContestInList($scope.searchResults, contestId);
                updateContestInList($scope.myContests, contestId);

                // make sure we're pointing at the updated contest
                if (isContestSelected(contestId)) {
                    $scope.selectedContest = contest;
                }
            });

            $scope.$watch("MySession.userProfile._id", function () {
                loadMyContests();
            });

        }]);

})();<|endoftext|>


<commit_before>var gulp = require('gulp');
var less = require('gulp-less');
var rename = require('gulp-rename');
var coffee = require('gulp-coffee');
var concat = require('gulp-concat');
var uncss = require('gulp-uncss');
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var replace = require('gulp-replace');
var browserSync = require('browser-sync');
var changed = require('gulp-changed');
var rimraf = require('gulp-rimraf');

gulp.task('coffee', function() {
    var stream = gulp.src('./coffeescript/*.coffee')
    .pipe(changed('./coffeescript/*.coffee'))
    .pipe(coffee())
    .pipe(concat('app.js'))
    .pipe(gulp.dest('./js/'))
    .pipe(browserSync.reload({stream:true}));
    return stream;
});

gulp.task('coffee-plugins', function() {
  var stream = gulp.src('./p_coffeescript/*.coffee')
    .pipe(changed('./p_coffeescript/*.coffee'))
    .pipe(coffee())
    .pipe(gulp.dest('./js/plugins/'))
    .pipe(browserSync.reload({stream:true}));
    return stream;
});

gulp.task('less', function () {
  var stream = gulp.src('./less/global.less')
    .pipe(changed('./less/**/*.*'))
    .pipe(less())
    .pipe(rename('app.css'))
    .pipe(gulp.dest('./css/'))
    .pipe(browserSync.reload({stream:true}));
    return stream;
});

gulp.task('clean-css', function(cb) {
  gulp.src('./css/app.css')
  .pipe(uncss({
    html: ['index.html']
  }))
  .pipe(gulp.dest('./css/'));
  cb();
});

gulp.task('minify-css', ['clean-css'], function() {
    var stream = gulp.src('./css/app.css')
      .pipe(minifycss())
      .pipe(rename('app.min.css'))
      .pipe(gulp.dest('./css/'));
    return stream;
});

gulp.task('compress-js', function() {
    var stream = gulp.src('./js/app.js')
    .pipe(uglify())
    .pipe(rename('app.min.js'))
    .pipe(gulp.dest('./js/'));
    return stream;
});

var htmlFilesIndex = ['./templates/base/meta/index.html', './templates/base/header.html', './templates/index.html', './templates/base/footer.html'];

gulp.task('build-index', function() {
    var stream = gulp.src(htmlFilesIndex)
    .pipe(changed('./templates/*.html'))
    .pipe(concat('index.html'))
    .pipe(gulp.dest('./'))
    .pipe(browserSync.reload({stream:true}));
  return stream;
});

gulp.task('clean', function() {
  return gulp.src('dist', { read: false })
    .pipe(rimraf());
});

gulp.task('move', ['clean'], function() {
  var stream = gulp.src(['./bower_components/**/*.*', './css/**/*.*', './js/**/*.*', './*.html'], { base: './' })
  .pipe(gulp.dest('dist'));
  return stream;
});

gulp.task('dist-changes', ['move'], function() {
  var stream = gulp.src(['./dist/*.html'])
  .pipe(replace('app.css', 'app.min.css'))
  .pipe(gulp.dest('dist/'))
  .pipe(replace('app.js', 'app.min.js'))
  .pipe(gulp.dest('dist/'));
  return stream;
});

gulp.task('browser-sync', function() {
    browserSync.init(null, {
      server: {
        baseDir: "./"
      }
    });
});

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

gulp.task('build', ['minify-css', 'compress-js']);

gulp.task('default', ['browser-sync'], function() {
  gulp.watch('./coffeescript/*.coffee', ['coffee'])
  gulp.watch('./p_coffeescript/*.coffee', ['coffee-plugins'])
  gulp.watch('./less/*.less', ['less'])
  gulp.watch('./templates/**/*.*', ['build-index'])
});
<commit_msg>Small fixes and comments added to gulpfile<commit_after>var gulp = require('gulp');
var less = require('gulp-less');
var rename = require('gulp-rename');
var coffee = require('gulp-coffee');
var concat = require('gulp-concat');
var uncss = require('gulp-uncss');
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var replace = require('gulp-replace');
var browserSync = require('browser-sync');
var changed = require('gulp-changed');
var rimraf = require('gulp-rimraf');

// compile CoffeeScript
gulp.task('coffee', function() {
    var stream = gulp.src('./coffeescript/*.coffee')
    .pipe(changed('./coffeescript/*.coffee'))
    .pipe(coffee())
    .pipe(concat('app.js'))
    .pipe(gulp.dest('./js/'))
    .pipe(browserSync.reload({stream:true}));
    return stream;
});

// compile your custom plugins in CoffeeScript
gulp.task('coffee-plugins', function() {
  var stream = gulp.src('./p_coffeescript/*.coffee')
    .pipe(changed('./p_coffeescript/*.coffee'))
    .pipe(coffee())
    .pipe(gulp.dest('./js/plugins/'))
    .pipe(browserSync.reload({stream:true}));
    return stream;
});

// Compile your less files
gulp.task('less', function () {
  var stream = gulp.src('./less/global.less')
    .pipe(changed('./less/**/*.*'))
    .pipe(less())
    .pipe(rename('app.css'))
    .pipe(gulp.dest('./css/'))
    .pipe(browserSync.reload({stream:true}));
    return stream;
});

// Clean CSS from unused classes
gulp.task('clean-css', function(cb) {
  gulp.src('./css/app.css')
  .pipe(uncss({
    html: ['index.html']
  }))
  .pipe(gulp.dest('./css/'));
  cb();
});

// Minify CSS file
gulp.task('minify-css', ['clean-css'], function() {
    var stream = gulp.src('./css/app.css')
      .pipe(minifycss())
      .pipe(rename('app.min.css'))
      .pipe(gulp.dest('./css/'));
    return stream;
});

// Minify your main javascript file
gulp.task('compress-js', function() {
    var stream = gulp.src('./js/app.js')
    .pipe(uglify())
    .pipe(rename('app.min.js'))
    .pipe(gulp.dest('./js/'));
    return stream;
});

// Create a variable array with all the files needed by your webpages, in this case the index
var htmlFilesIndex = ['./templates/base/meta/index.html', './templates/base/header.html', './templates/index.html', './templates/base/footer.html'];

// this is an ideal about page which is made with the global header, footer, a custom content and a custom meta html
// var htmlFilesAbout = ['./templates/base/meta/about.html', './templates/base/header.html', './templates/index.html', './templates/base/footer.html'];

// build pages with provided files
gulp.task('build', function() {
    gulp.src(htmlFilesIndex)
    .pipe(changed('./templates/*.html'))
    .pipe(concat('index.html'))
    .pipe(gulp.dest('./'))
    .pipe(browserSync.reload({stream:true}));

    // gulp.src(yourHtmlFiles)
    // .pipe(changed('./templates/*.html'))
    // .pipe(concat('about.html'))
    // .pipe(gulp.dest('./'))
    // .pipe(browserSync.reload({stream:true}));
});

// clean the dist folder
gulp.task('clean', function() {
  return gulp.src('dist', { read: false })
    .pipe(rimraf());
});

// Move the needed files and folders into a dist folder which can be deployed to the webserver
gulp.task('move', ['clean'], function() {
  var stream = gulp.src(['./bower_components/**/*.*', './css/**/*.*', './js/**/*.*', './*.html'], { base: './' })
  .pipe(gulp.dest('dist'));
  return stream;
});

// Modify into the dist folder the html files
// to use the minified CSS and JS sources
gulp.task('dist-changes', ['move'], function() {
  var stream = gulp.src(['./dist/*.html'])
  .pipe(replace('app.css', 'app.min.css'))
  .pipe(gulp.dest('dist/'))
  .pipe(replace('app.js', 'app.min.js'))
  .pipe(gulp.dest('dist/'));
  return stream;
});

// browser-sync serve the work to
// your browser of choice
gulp.task('browser-sync', function() {
    browserSync.init(null, {
      server: {
        baseDir: "./"
      }
    });
});

// Final tasks
gulp.task('dist', ['dist-changes']);

gulp.task('build', ['minify-css', 'compress-js']);

gulp.task('default', ['browser-sync'], function() {
  gulp.watch('./coffeescript/*.coffee', ['coffee'])
  gulp.watch('./p_coffeescript/*.coffee', ['coffee-plugins'])
  gulp.watch('./less/*.less', ['less'])
  gulp.watch('./templates/**/*.*', ['build-index'])
});
<|endoftext|>


<commit_before>(function(root) {

  'use strict';

  root.app = root.app || {};
  root.app.View = root.app.View || {};
  root.app.Mixin = root.app.Mixin || {};
  root.app.Helper = root.app.Helper || {};

  var Status = Backbone.Model.extend({
    defaults: { isHidden: false }
  });

  root.app.View.sliderView = Backbone.View.extend({

    el: '#map-slider',

    events: {
      'click .play': 'onPlay'
    },

    initialize: function(options) {
      this.router = options.router;
      this.status = new Status();

      this.cacheVars();
      this.slider();
    },

    cacheVars: function() {
      this.currentDay = new Date('01/01/1991');
    },

    convertDate: function(date) {
      var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

      var day = date.getDate();
      var month = date.getMonth(); // -> Jan is 0
      var year = date.getFullYear() // getYear not recommended

      var dateString = (day + " " + months[month] + " " + year);
      return dateString;
    },

    slider: function() {
      var sliderBox = this.$el.find('#slider');

      var startDate = new Date('05/24/1992');
      var endDate = new Date('01/26/2015');

      var margin = 12;

      this.outerWidth = sliderBox.width();
      this.innerWidth = sliderBox.width() - 2 * margin;

      this.outerHeight = sliderBox.height();
      this.innerHeight = 3;

      this.maxDays = 365;

      var x = d3.time.scale()
        .range([0, this.innerWidth])
        .clamp(true)
        .domain([startDate, endDate])

      // var x = d3.scale.linear()
      //   .range([0, this.innerWidth])
      //   .clamp(true)
      //   .domain([0, this.maxDays]);

      var progress, trail;
      var circle;
      var tooltip = $('.slider-tooltip');

      var self = this;

      var brush = this.brush = d3.svg.brush()
        .x(x)
        .extent([0,0])
        .clamp(true)
        .on('brush', function() {
          var value = brush.extent()[1];
          if (d3.event.sourceEvent) {
            value = x.invert(d3.mouse(this)[0]);
            brush.extent([value, value]);
            self.currentDay = value;
            tooltip
              .css({left: x(brush.extent()[0])})
              .html(self.convertDate(self.currentDay));
            circle
              .attr('cx', x(brush.extent()[0]));
          }
          progress.attr('width', x(value));
        })
        .on('brushend', this.onBrushEnd);

      var svg = d3.select('#slider')
        .append('svg')
        .attr('class', 'svg-timeline')
        .attr('width', this.outerWidth)
        .attr('height', this.outerHeight);

      trail = svg.append('g')
        .attr('class', 'trail')
        .attr('transform', 'translate(12 11)')
        .style('fill', 'white')
        .call(brush);

      trail.selectAll('.background')
        .attr('height', this.innerHeight);

      trail.selectAll('.extent, .resize').remove();

      progress = trail.append('rect')
        .attr('class', 'progress')
        .style('fill', '#175ca0')
        .attr('width', 0)
        .attr('height', this.innerHeight);

      circle = trail.append('circle')
        .attr('class', 'circle')
        .attr("cx", 0)
        .attr("cy", 1)
        .attr("r", 7.5)
        .style("fill", "#175ca0");

      progress
        .call(brush.extent([0,0]))
        .call(brush.event);

      tooltip
        .css({left: x(brush.extent()[0])})
        .html(self.convertDate(self.currentDay));

      this.tooltip = tooltip;
      this.svg = svg;
      this.progress = progress;
      this.circle = circle;
      this.x = x;

    },

    onPlay: function() {
      var play = $('.play')[0];
      play.classList.toggle('paused');
      var isPlaying = !play.classList.contains('paused');

      if (isPlaying) {
        this.play();
      } else {
        this.pause();
      }

    },

    play: function() {
      var self = this;
      var maxWidth = this.innerWidth;

      this.progress
        .transition()
        .duration(5000)
        .ease('linear')
        .attr('width', this.innerWidth);

      this.circle
        .transition()
        .duration(5000)
        .ease('linear')
        .attr('cx', this.innerWidth);

      if (this.interval) {
        clearInterval(this.interval);
      }

      this.interval = setInterval(function() {
        var width = self.progress.attr('width');
        if (Number(width) >= self.innerWidth) {
          self.progress.attr('width', 0);
          self.circle.attr('cx', 0);
          self.play();
          return;
        }
        var value = self.x.invert(width);
        self.brush.extent([value, value]);
        self.currentDay = value;
        self.tooltip
          .css({left: self.x(self.brush.extent()[0])})
          .html(self.convertDate(self.currentDay));
        self.trigger('timeline:change', value);
      }, 1);

    },

    pause: function() {
      this.progress
        .interrupt();

      this.circle
        .interrupt();

    }

  });

})(this);
<commit_msg>calculates the duration of the animation<commit_after>(function(root) {

  'use strict';

  root.app = root.app || {};
  root.app.View = root.app.View || {};
  root.app.Mixin = root.app.Mixin || {};
  root.app.Helper = root.app.Helper || {};

  var Status = Backbone.Model.extend({
    defaults: { isHidden: false }
  });

  root.app.View.sliderView = Backbone.View.extend({

    el: '#map-slider',

    events: {
      'click .play': 'onPlay'
    },

    initialize: function(options) {
      this.router = options.router;
      this.status = new Status();

      this.cacheVars();
      this.slider();
    },

    cacheVars: function() {
      this.currentDay = new Date('01/01/1991');
    },

    convertDate: function(date) {
      var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

      var day = date.getDate();
      var month = date.getMonth(); // -> Jan is 0
      var year = date.getFullYear() // getYear not recommended

      var dateString = (day + " " + months[month] + " " + year);
      return dateString;
    },

    slider: function() {
      var sliderBox = this.$el.find('#slider');

      var startDate = new Date('05/24/1992');
      var endDate = new Date('01/26/2015');

      var margin = 12;

      this.outerWidth = sliderBox.width();
      this.innerWidth = sliderBox.width() - 2 * margin;

      this.outerHeight = sliderBox.height();
      this.innerHeight = 3;

      this.maxDays = 365;

      var x = d3.time.scale()
        .range([0, this.innerWidth])
        .clamp(true)
        .domain([startDate, endDate])

      // var x = d3.scale.linear()
      //   .range([0, this.innerWidth])
      //   .clamp(true)
      //   .domain([0, this.maxDays]);

      var progress, trail;
      var circle;
      var tooltip = $('.slider-tooltip');

      var self = this;

      var brush = this.brush = d3.svg.brush()
        .x(x)
        .extent([0,0])
        .clamp(true)
        .on('brush', function() {
          var value = brush.extent()[1];
          if (d3.event.sourceEvent) {
            value = x.invert(d3.mouse(this)[0]);
            brush.extent([value, value]);
            self.currentDay = value;
            tooltip
              .css({left: x(brush.extent()[0])})
              .html(self.convertDate(self.currentDay));
            circle
              .attr('cx', x(brush.extent()[0]));
          }
          progress.attr('width', x(value));
        })
        .on('brushend', this.onBrushEnd);

      var svg = d3.select('#slider')
        .append('svg')
        .attr('class', 'svg-timeline')
        .attr('width', this.outerWidth)
        .attr('height', this.outerHeight);

      trail = svg.append('g')
        .attr('class', 'trail')
        .attr('transform', 'translate(12 11)')
        .style('fill', 'white')
        .call(brush);

      trail.selectAll('.background')
        .attr('height', this.innerHeight);

      trail.selectAll('.extent, .resize').remove();

      progress = trail.append('rect')
        .attr('class', 'progress')
        .style('fill', '#175ca0')
        .attr('width', 0)
        .attr('height', this.innerHeight);

      circle = trail.append('circle')
        .attr('class', 'circle')
        .attr("cx", 0)
        .attr("cy", 1)
        .attr("r", 7.5)
        .style("fill", "#175ca0");

      progress
        .call(brush.extent([0,0]))
        .call(brush.event);

      tooltip
        .css({left: x(brush.extent()[0])})
        .html(self.convertDate(self.currentDay));

      this.tooltip = tooltip;
      this.svg = svg;
      this.progress = progress;
      this.circle = circle;
      this.x = x;

    },

    onPlay: function() {
      var play = $('.play')[0];
      play.classList.toggle('paused');
      var isPlaying = !play.classList.contains('paused');

      if (isPlaying) {
        this.play();
      } else {
        this.pause();
      }

    },

    play: function() {
      var self = this;

      var duration = 5000; //ms
      var percentageMoved = Number(this.progress.attr('width')) / this.innerWidth; // of 1, not 100
      var percentageLeft = 1 - percentageMoved;
      var durationLeft = duration * percentageLeft;

      this.progress
        .transition()
        .duration(durationLeft)
        .ease('linear')
        .attr('width', this.innerWidth);

      this.circle
        .transition()
        .duration(durationLeft)
        .ease('linear')
        .attr('cx', this.innerWidth);

      if (this.interval) {
        clearInterval(this.interval);
      }

      this.interval = setInterval(function() {
        var width = self.progress.attr('width');
        if (Number(width) >= self.innerWidth) {
          self.progress.attr('width', 0);
          self.circle.attr('cx', 0);
          self.play();
          return;
        }
        var value = self.x.invert(width);
        self.brush.extent([value, value]);
        self.currentDay = value;
        self.tooltip
          .css({left: self.x(self.brush.extent()[0])})
          .html(self.convertDate(self.currentDay));
        self.trigger('timeline:change', value);
      }, 1);

    },

    pause: function() {
      this.progress
        .interrupt();

      this.circle
        .interrupt();

    }

  });

})(this);
<|endoftext|>