<commit_before>//= require jquery
//= require jquery_ujs
//= require jquery.slick
//= require refile
//= require lodash
//= require video
//= require turbolinks
//= require_self

function withVideoPlayer(slick, current, callback) {
  var slide = $(slick.$slides[current]),
      element = slide.find('.video-player');

  if (element.length) {
    var player = videojs(element.attr('id'));
    callback(player)
  }
}

$(document)
  .on('turbolinks:load', function(event) {
    // Load static VideoJS player elements
    $('.video__player .video-player').each(function(i, element) {
      var player = videojs($(element).attr('id'));
      player.play();
    });

    // Configure slick-slider for .filmstrip components
    $('.filmstrip').slick({
      slidesToShow: 4,
      swipeToSlide: true
    });

    // Configure slick-slider for the home page slideshow
    $('.home-page__slideshow')
      .on('afterChange', function(event, slick, currentSlide) {
        withVideoPlayer(slick, currentSlide, function(player) {
          slick.pause();
          player.play();
        });
      })
      .on('beforeChange', function(event, slick, currentSlide) {
        withVideoPlayer(slick, currentSlide, function(player) {
          player.pause();
          player.dispose();
        });

        slick.play();
      })
      .slick({
        slidesToShow: 1,
        swipeToSlide: true,
        autoplay: true
      });

  })
  .on('turbolinks:before-visit', function() {
    // Dispose VideoJS elements before unloading the page
    $('.video-player').each(function(i, element) {
      videojs($(element).attr('id')).dispose();
    });
  })
<commit_msg>Turn off slick-slider autoplay<commit_after>//= require jquery
//= require jquery_ujs
//= require jquery.slick
//= require refile
//= require lodash
//= require video
//= require turbolinks
//= require_self

function withVideoPlayer(slick, current, callback) {
  var slide = $(slick.$slides[current]),
      element = slide.find('.video-player');

  if (element.length) {
    var player = videojs(element.attr('id'));
    callback(player)
  }
}

$(document)
  .on('turbolinks:load', function(event) {
    // Load static VideoJS player elements
    $('.video__player .video-player').each(function(i, element) {
      var player = videojs($(element).attr('id'));
      player.play();
    });

    // Configure slick-slider for .filmstrip components
    $('.filmstrip').slick({
      slidesToShow: 4,
      swipeToSlide: true
    });

    // Configure slick-slider for the home page slideshow
    $('.home-page__slideshow')
      .on('afterChange', function(event, slick, currentSlide) {
        withVideoPlayer(slick, currentSlide, function(player) {
          slick.pause();
          player.play();
        });
      })
      .on('beforeChange', function(event, slick, currentSlide) {
        withVideoPlayer(slick, currentSlide, function(player) {
          player.pause();
          player.dispose();
        });

        slick.play();
      })
      .slick({
        slidesToShow: 1,
        swipeToSlide: true,
        autoplay: false
      });

  })
  .on('turbolinks:before-visit', function() {
    // Dispose VideoJS elements before unloading the page
    $('.video-player').each(function(i, element) {
      videojs($(element).attr('id')).dispose();
    });
  })
<|endoftext|>


<commit_before>/**
 * Passport Middleware
 *
 * Policy for Sails that initializes Passport.js and as well as its built-in
 * session support.
 *
 * In a typical web application, the credentials used to authenticate a user
 * will only be transmitted during the login request. If authentication
 * succeeds, a session will be established and maintained via a cookie set in
 * the user's browser.
 *
 * Each subsequent request will not contain credentials, but rather the unique
 * cookie that identifies the session. In order to support login sessions,
 * Passport will serialize and deserialize user instances to and from the
 * session.
 *
 * For more information on the Passport.js middleware, check out:
 * http://passportjs.org/guide/configure/
 *
 * @param {Object}   req
 * @param {Obecjt}   res
 * @param {Function} next
 */
module.exports = function (req, res, next) {
  // Initialize Passport
  passport.initialize()(req, res, function () {
    // Use the built-in sessions
    passport.session()(req, res, function () {
      // Make the user available throughout the frontend
      res.locals.user = req.user;

      next();
    });
  });
};
<commit_msg>Fix typo<commit_after>/**
 * Passport Middleware
 *
 * Policy for Sails that initializes Passport.js and as well as its built-in
 * session support.
 *
 * In a typical web application, the credentials used to authenticate a user
 * will only be transmitted during the login request. If authentication
 * succeeds, a session will be established and maintained via a cookie set in
 * the user's browser.
 *
 * Each subsequent request will not contain credentials, but rather the unique
 * cookie that identifies the session. In order to support login sessions,
 * Passport will serialize and deserialize user instances to and from the
 * session.
 *
 * For more information on the Passport.js middleware, check out:
 * http://passportjs.org/guide/configure/
 *
 * @param {Object}   req
 * @param {Object}   res
 * @param {Function} next
 */
module.exports = function (req, res, next) {
  // Initialize Passport
  passport.initialize()(req, res, function () {
    // Use the built-in sessions
    passport.session()(req, res, function () {
      // Make the user available throughout the frontend
      res.locals.user = req.user;

      next();
    });
  });
};
<|endoftext|>


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

// libraries
//= require jquery
//= require jquery_ujs

// vendor plugins
//= require details.polyfill

// module loader
//= require module_loader

// modules
//= require radio_buttons_module
//= require checkbox_module
//= require income
//= require evidence_confirmation
//= require equal_height_boxes
//= require cookies
//= require login
//= require fee_field

$(function(){
  // fire init method of moj module loader
  window.moj.init();
});
<commit_msg>remove unecessary moj.init() call from application<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//

// libraries
//= require jquery
//= require jquery_ujs

// vendor plugins
//= require details.polyfill

// module loader
//= require module_loader

// modules
//= require radio_buttons_module
//= require checkbox_module
//= require income
//= require evidence_confirmation
//= require equal_height_boxes
//= require cookies
//= require login
//= require fee_field
<|endoftext|>


<commit_before>/*global define*/
define(['../Core/createGuid',
        '../Core/Cartographic',
        '../Core/Color',
        '../Core/ClockRange',
        '../Core/ClockStep',
        '../Core/DeveloperError',
        '../Core/RuntimeError',
        '../Core/Ellipsoid',
        '../Core/Event',
        '../Core/Iso8601',
        '../Core/loadXML',
        './ConstantProperty',
        './DynamicProperty',
        './DynamicClock',
        './DynamicObject',
        './DynamicObjectCollection',
        './DynamicPoint',
        './DynamicPolyline',
        './DynamicPolygon',
        './DynamicLabel',
        './DynamicBillboard',
        '../ThirdParty/when'
        ], function(
                createGuid,
                Cartographic,
                Color,
                ClockRange,
                ClockStep,
                DeveloperError,
                RuntimeError,
                Ellipsoid,
                Event,
                Iso8601,
                loadXML,
                ConstantProperty,
                DynamicProperty,
                DynamicClock,
                DynamicObject,
                DynamicObjectCollection,
                DynamicPoint,
                DynamicPolyline,
                DynamicPolygon,
                DynamicLabel,
                DynamicBillboard,
                when) {
    "use strict";

    //Copied from GeoJsonDataSource
    var ConstantPositionProperty = function(value) {
        this._value = value;
    };

    ConstantPositionProperty.prototype.getValueCartesian = function(time, result) {
        var value = this._value;
        if (typeof value.clone === 'function') {
            return value.clone(result);
        }
        return value;
    };

    ConstantPositionProperty.prototype.setValue = function(value) {
        this._value = value;
    };

    function createObject(kml, dynamicObjectCollection) {
        var id = kml.id;
        if (typeof id === 'undefined') {
            id = createGuid();
        } else {
            var finalId = id;
            while (typeof dynamicObjectCollection.getObject(finalId) !== 'undefined') {
                finalId = createGuid();
            }
            id = finalId;
        }
        var dynamicObject = dynamicObjectCollection.getOrCreateObject(id);
        dynamicObject.kml = kml;
        return dynamicObject;
    }

    //Helper functions
    function readCoordinates(el) {
        var text = "", coords = [], i;
        for (i = 0; i < el.childNodes.length; i++) {
            text = text + el.childNodes[i].nodeValue;
        }
        var coordsArray = text.split(/[\s\n]+/);
        var finalCoords = [];
        for(var j = 0; coordsArray[j]; j++){
            var regExp = /(\-?\+?[0-9]+\.?[0-9]*)(,\-?\+?[0-9]+\.?[0-9]*)(,[0-9]+\.?[0-9]?)?$/;
            coords[j] = regExp.exec(coordsArray[j]);
            coords[j].shift(); //the first element is not needed, remove it
            finalCoords.push([]); //new inner array
            finalCoords[j][0] = parseFloat(coords[j][0], 10);
            finalCoords[j][1] = parseFloat(coords[j][1].substring(1), 10);
            finalCoords[j][2] = coords[j][2] && parseFloat(coords[j][2].substring(1), 10);
        }
        for(var k = 0; k < finalCoords.length; k++){
            if (isNaN(finalCoords[k][0]) || isNaN(finalCoords[k][1])) {
                throw new RuntimeError('Longitude and latitude are required.');
            }
        }
        if(finalCoords.length === 1){
            return finalCoords[0]; //single tuple
        }
        return finalCoords;
    }

    function crsFunction(coordinates) {
        var cartographic = Cartographic.fromDegrees(coordinates[0], coordinates[1], coordinates[2]);
        return Ellipsoid.WGS84.cartographicToCartesian(cartographic);
    }

    function coordinatesArrayToCartesianArray(coordinates) {
        var positions = new Array(coordinates.length);
        for ( var i = 0; i < coordinates.length; i++) {
            positions[i] = crsFunction(coordinates[i]);
        }
        return positions;
    }

    function getId(node){
        var id = node.attributes.id && node.attributes.id.nodeValue;
        if (typeof id === 'undefined') {
            id = createGuid();
        }
        return id;
    }

    function getElementValue(node, elementType){
        var element = node.getElementsByTagName(elementType)[0];
        if (elementType === 'hotSpot' && typeof element !== 'undefined'){
            var hotSpot = {
                    x: element.attributes.x.nodeValue,
                    y: element.attributes.y.nodeValue,
                    xunits: element.attributes.xunits.nodeValue,
                    yunits: element.attributes.yunits.nodeValue
            };
            return hotSpot;
        }
        return element && element.firstChild.data; //protecting from TypeError
    }

    function getStylesFromXml(xml){
        var stylesArray = xml.getElementsByTagName('Style');
        var styleCollection = new DynamicObjectCollection();
        for ( var i = 0, len = stylesArray.length; i < len; i++){
            var styleNode = stylesArray.item(i);
            styleNode.id = '#' + getId(styleNode);
            var styleObject = styleCollection.getOrCreateObject(styleNode.id);
            processStyle(styleNode, styleObject);
        }
        return styleCollection;
    }

    function getRemoteStyle(url){
        return loadXML(url).then(function(kml) {
            return getStylesFromXml(kml, url);
        }, function(error) {
            this._error.raiseEvent(this, error);
        });
    }

    function getColor(node, colorType){
        var color;
        if(typeof colorType ===  'undefined'){
            color = getElementValue(node,'color');
        } else {
            color = getElementValue(node, colorType);
        }
        color = parseInt(color,16);
        if(isNaN(color)){
            return undefined;
        }
        return color;
    }

    // KML processing functions
    function processPlacemark(dataSource, dynamicObject, placemark, dynamicObjectCollection, styleCollection) {
        dynamicObject.name = getElementValue(placemark, 'name');
        if(typeof dynamicObject.label !== 'undefined'){
            dynamicObject.label.text = new ConstantProperty(dynamicObject.name);
        }
        // I want to iterate over every placemark
        for(var i = 0, len = placemark.childNodes.length; i < len; i++){
            var node = placemark.childNodes.item(i);
            //Checking if the node holds a supported Geometry type
            if(geometryTypes.hasOwnProperty(node.nodeName)){
                placemark.geometry = node.nodeName;
                var geometryType = placemark.geometry;
                var geometryHandler = geometryTypes[geometryType];
                if (typeof geometryHandler === 'undefined') {
                    throw new RuntimeError('Unknown geometry type: ' + geometryType);
                }
                geometryHandler(dataSource, placemark, node, dynamicObjectCollection, styleCollection);
            }
        }

    }

    function processPoint(dataSource, kml, node, dynamicObjectCollection, styleCollection) {
        //TODO extrude, altitudeMode, gx:altitudeMode
        var el = node.getElementsByTagName('coordinates');
        var coordinates = [];
        for (var j = 0; j < el.length; j++) {
            coordinates = coordinates.concat(readCoordinates(el[j]));
        }
        var cartesian3 = crsFunction(coordinates);
        var dynamicObject = dynamicObjectCollection.getOrCreateObject(kml.id);
        dynamicObject.position = new ConstantPositionProperty(cartesian3);
    }

    function processLineString(dataSource, kml, node, dynamicObjectCollection, styleCollection){
        //TODO gx:altitudeOffset, extrude, tessellate, altitudeMode, gx:altitudeMode, gx:drawOrder
        var el = node.getElementsByTagName('coordinates');
        var coordinates = [];
        for (var j = 0; j < el.length; j++) {
            coordinates = coordinates.concat(readCoordinates(el[j]));
        }
        var dynamicObject = dynamicObjectCollection.getOrCreateObject(kml.id);
        dynamicObject.vertexPositions = new ConstantPositionProperty(coordinatesArrayToCartesianArray(coordinates));
    }

    function processLinearRing(dataSource, kml, node){
        var el = node.getElementsByTagName('coordinates');
        var coordinates = [];
        for (var j = 0; j < el.length; j++) {
            coordinates = coordinates.concat(readCoordinates(el[j]));
        }
        //TODO gx:altitudeOffset, extrude, tessellate, altitudeMode, altitudeModeEnum, altitudeMode
    }

    //Object that holds all supported Geometry
    var geometryTypes = {
            Point : processPoint,
            LineString : processLineString,
            LinearRing : processLinearRing
            //TODO Polygon, MultiGeometry, Model, gxTrack, gxMultitrack
    };

    function processStyle(styleNode, dynamicObject) {
        for(var i = 0, len = styleNode.childNodes.length; i < len; i++){
            var node = styleNode.childNodes.item(i);

            if(node.nodeName === "IconStyle"){
                dynamicObject.billboard = new DynamicBillboard();
                //Map style to billboard properties
                //TODO heading, hotSpot and ColorMode
                var scale = getElementValue(node, 'scale');
                var icon = getElementValue(node,'href');
                var color = getColor(node);

                dynamicObject.billboard.image = icon && new ConstantProperty(icon);
                dynamicObject.billboard.scale = scale && new ConstantProperty(scale);
                dynamicObject.billboard.color = color && new ConstantProperty(Color.fromRgba(color));
            }
            else if(node.nodeName ===  "LabelStyle")   {
                dynamicObject.label = new DynamicLabel();
                //Map style to label properties
                //TODO ColorMode
                var labelScale = getElementValue(node, 'scale');
                var labelColor = getColor(node);

                dynamicObject.label.scale = labelScale && new ConstantProperty(labelScale);
                dynamicObject.label.fillColor = labelColor && new ConstantProperty(Color.fromRgba(labelColor)); //not sure how to set font color
                dynamicObject.label.text = dynamicObject.name && new ConstantProperty(dynamicObject.name);
            }
            else if(node.nodeName ===  "LineStyle")   {
                dynamicObject.polyline = new DynamicPolyline();
                //Map style to line properties
                //TODO PhysicalWidth, Visibility, ColorMode
                var lineColor = getColor(node);
                var lineWidth = getElementValue(node,'width');
                var lineOuterColor = getColor(node,'gx:outerColor');
                var lineOuterWidth = getElementValue(node,'gx:outerWidth');

                dynamicObject.polyline.color = lineColor && new ConstantProperty(Color.fromRgba(lineColor));
                dynamicObject.polyline.width = lineWidth && new ConstantProperty(lineWidth);
                dynamicObject.polyline.outlineColor = lineOuterColor && new ConstantProperty(Color.fromRgba(lineOuterColor));
                dynamicObject.polyline.outlineWidth = lineOuterWidth && new ConstantProperty(lineOuterWidth);
            }
            else if(node.nodeName === "PolyStyle")   {
                dynamicObject.polygon = new DynamicPolygon();
                //Map style to polygon properties
                //TODO Fill, Outline
            }
        }
    }

    function loadKML(dataSource, kml, sourceUri) {
        var dynamicObjectCollection = dataSource._dynamicObjectCollection;
        var styleCollection = getStylesFromXml(kml);

        var array = kml.getElementsByTagName('Placemark');
        for (var i = 0, len = array.length; i < len; i++){
            var inlineStyleCollection = getStylesFromXml(array[i]);
            var placemark = array[i];
            placemark.id = getId(placemark);
            var placemarkDynamicObject = dynamicObjectCollection.getOrCreateObject(placemark.id);
            //check for inline styles
            if(inlineStyleCollection._array.length > 0){
                for(var k = 0; k < inlineStyleCollection._array.length; k++){
                    placemarkDynamicObject.merge(inlineStyleCollection._array[k]);
                }
            } else {
                var styleUrl = array[i].getElementsByTagName('styleUrl');
                for(var j = 0, size = styleUrl.length; j < size; j++){
                    var styleId = getElementValue(array[j], 'styleUrl');
                    if(styleId[0] === '#'){ //then check for local file styles
                        var styleObj = styleCollection.getObject(styleId);
                        placemarkDynamicObject.merge(styleObj);
                    } else { // get remote styles lastly
                        var externalStyleCollection;
                        var externalStyleObj;

                        var externalArray = styleId.split('#');
                        var externalPath = externalArray[0];
                        var externalStyleId = '#' + externalArray[1];
                        if(typeof dataSource.externalStyles[externalPath] === 'undefined'){
                            if(externalPath.substring(0,3 === 'http')){
                                //externalStyleCollection = getRemoteStyle(externalPath).then(function(styles){ });
                                dataSource.externalStyles[externalPath] = externalStyleCollection;
                                externalStyleObj = externalStyleCollection.getObject(externalStyleId);
                                placemarkDynamicObject.merge(externalStyleObj);

                            } else {
                                //TODO Load an external file from a relative path
                            }
                        } else {
                            externalStyleCollection = dataSource.externalStyles[externalPath];
                            externalStyleObj = externalStyleCollection.getObject(externalStyleId);
                            placemarkDynamicObject.merge(externalStyleObj);
                        }
                    }
                }
            }
            processPlacemark(dataSource, placemarkDynamicObject, placemark, dynamicObjectCollection, styleCollection);
        }
    }

    /**
     * A {@link DataSource} which processes KML.
     * @alias KmlDataSource
     * @constructor
     */
    var KmlDataSource = function(){
        this._changed = new Event();
        this._error = new Event();
        this._clock = undefined;
        this._dynamicObjectCollection = new DynamicObjectCollection();
        this._timeVarying = true;
        this.externalStyles = {}; //cache to hold external styles
    };

    /**
     * Gets an event that will be raised when non-time-varying data changes
     * or if the return value of getIsTimeVarying changes.
     * @memberof DataSource
     *
     * @returns {Event} The event.
     */
    KmlDataSource.prototype.getChangedEvent = function() {
        return this._changed;
    };

    /**
     * Gets an event that will be raised if an error is encountered during processing.
     * @memberof KmlDataSource
     *
     * @returns {Event} The event.
     */
    KmlDataSource.prototype.getErrorEvent = function() {
        return this._error;
    };

    /**
     * Gets the top level clock defined in KML or the availability of the
     * underlying data if no clock is defined.  If the KML document only contains
     * infinite data, undefined will be returned.
     * @memberof KmlDataSource
     *
     * @returns {DynamicClock} The clock associated with the current KML data, or undefined if none exists.
     */
    KmlDataSource.prototype.getClock = function() {
        return undefined;
    };

    /**
     * Gets the DynamicObjectCollection generated by this data source.
     * @memberof DataSource
     *
     * @returns {DynamicObjectCollection} The collection of objects generated by this data source.
     */
    KmlDataSource.prototype.getDynamicObjectCollection = function() {
        return this._dynamicObjectCollection;
    };

    /**
     * Gets a value indicating if the data varies with simulation time.  If the return value of
     * this function changes, the changed event will be raised.
     * @memberof DataSource
     *
     * @returns {Boolean} True if the data is varies with simulation time, false otherwise.
     */
    KmlDataSource.prototype.getIsTimeVarying = function() {
        return true;
    };

    /**
     * Replaces any existing data with the provided KML.
     *
     * @param {Object} KML The KML to be processed.
     * @param {String} source The source of the KML.
     *
     * @exception {DeveloperError} KML is required.
     */
    KmlDataSource.prototype.load = function(kml, source) {
        if (typeof kml === 'undefined') {
            throw new DeveloperError('kml is required.');
        }

        this._dynamicObjectCollection.clear();
        loadKML(this, kml, source);
        this._changed.raiseEvent(this);
    };

    /**
     * Asynchronously loads the KML at the provided url, replacing any existing data.
     *
     * @param {Object} url The url to be processed.
     *
     * @returns {Promise} a promise that will resolve when the KML is processed.
     *
     * @exception {DeveloperError} url is required.
     */
    KmlDataSource.prototype.loadUrl = function(url) {
        if (typeof url === 'undefined') {
            throw new DeveloperError('url is required.');
        }

        var dataSource = this;
        return when(loadXML(url), function(kml) {
            return dataSource.load(kml, url);
        }, function(error) {
            dataSource._error.raiseEvent(dataSource, error);
            return when.reject(error);
        });
    };
    return KmlDataSource;
});<commit_msg>Cleanup code<commit_after>/*global define*/
define(['../Core/createGuid',
        '../Core/Cartographic',
        '../Core/Color',
        '../Core/ClockRange',
        '../Core/ClockStep',
        '../Core/DeveloperError',
        '../Core/RuntimeError',
        '../Core/Ellipsoid',
        '../Core/Event',
        '../Core/Iso8601',
        '../Core/loadXML',
        './ConstantProperty',
        './DynamicProperty',
        './DynamicClock',
        './DynamicObject',
        './DynamicObjectCollection',
        './DynamicPoint',
        './DynamicPolyline',
        './DynamicPolygon',
        './DynamicLabel',
        './DynamicBillboard',
        '../ThirdParty/when'
        ], function(
                createGuid,
                Cartographic,
                Color,
                ClockRange,
                ClockStep,
                DeveloperError,
                RuntimeError,
                Ellipsoid,
                Event,
                Iso8601,
                loadXML,
                ConstantProperty,
                DynamicProperty,
                DynamicClock,
                DynamicObject,
                DynamicObjectCollection,
                DynamicPoint,
                DynamicPolyline,
                DynamicPolygon,
                DynamicLabel,
                DynamicBillboard,
                when) {
    "use strict";

    //Copied from GeoJsonDataSource
    var ConstantPositionProperty = function(value) {
        this._value = value;
    };

    ConstantPositionProperty.prototype.getValueCartesian = function(time, result) {
        var value = this._value;
        if (typeof value.clone === 'function') {
            return value.clone(result);
        }
        return value;
    };

    ConstantPositionProperty.prototype.setValue = function(value) {
        this._value = value;
    };

    function createObject(kml, dynamicObjectCollection) {
        var id = kml.id;
        if (typeof id === 'undefined') {
            id = createGuid();
        } else {
            var finalId = id;
            while (typeof dynamicObjectCollection.getObject(finalId) !== 'undefined') {
                finalId = createGuid();
            }
            id = finalId;
        }
        var dynamicObject = dynamicObjectCollection.getOrCreateObject(id);
        dynamicObject.kml = kml;
        return dynamicObject;
    }

    //Helper functions
    function readCoordinates(el) {
        var text = "", coords = [], i;
        for (i = 0; i < el.childNodes.length; i++) {
            text = text + el.childNodes[i].nodeValue;
        }
        var coordsArray = text.split(/[\s\n]+/);
        var finalCoords = [];
        for(var j = 0; coordsArray[j]; j++){
            var regExp = /(\-?\+?[0-9]+\.?[0-9]*)(,\-?\+?[0-9]+\.?[0-9]*)(,[0-9]+\.?[0-9]?)?$/;
            coords[j] = regExp.exec(coordsArray[j]);
            coords[j].shift(); //the first element is not needed, remove it
            finalCoords.push([]); //new inner array
            finalCoords[j][0] = parseFloat(coords[j][0], 10);
            finalCoords[j][1] = parseFloat(coords[j][1].substring(1), 10);
            finalCoords[j][2] = coords[j][2] && parseFloat(coords[j][2].substring(1), 10);
        }
        for(var k = 0; k < finalCoords.length; k++){
            if (isNaN(finalCoords[k][0]) || isNaN(finalCoords[k][1])) {
                throw new RuntimeError('Longitude and latitude are required.');
            }
        }
        if(finalCoords.length === 1){
            return finalCoords[0]; //single tuple
        }
        return finalCoords;
    }

    function crsFunction(coordinates) {
        var cartographic = Cartographic.fromDegrees(coordinates[0], coordinates[1], coordinates[2]);
        return Ellipsoid.WGS84.cartographicToCartesian(cartographic);
    }

    function coordinatesArrayToCartesianArray(coordinates) {
        var positions = new Array(coordinates.length);
        for ( var i = 0; i < coordinates.length; i++) {
            positions[i] = crsFunction(coordinates[i]);
        }
        return positions;
    }

    function getId(node){
        var id = node.attributes.id && node.attributes.id.nodeValue;
        if (typeof id === 'undefined') {
            id = createGuid();
        }
        return id;
    }

    function getElementValue(node, elementType){
        var element = node.getElementsByTagName(elementType)[0];
        if (elementType === 'hotSpot' && typeof element !== 'undefined'){
            var hotSpot = {
                    x: element.attributes.x.nodeValue,
                    y: element.attributes.y.nodeValue,
                    xunits: element.attributes.xunits.nodeValue,
                    yunits: element.attributes.yunits.nodeValue
            };
            return hotSpot;
        }
        return element && element.firstChild.data; //protecting from TypeError
    }

    function getStylesFromXml(xml){
        var stylesArray = xml.getElementsByTagName('Style');
        var styleCollection = new DynamicObjectCollection();
        for ( var i = 0, len = stylesArray.length; i < len; i++){
            var styleNode = stylesArray.item(i);
            styleNode.id = '#' + getId(styleNode);
            var styleObject = styleCollection.getOrCreateObject(styleNode.id);
            processStyle(styleNode, styleObject);
        }
        return styleCollection;
    }

    function getRemoteStyle(url){
        return loadXML(url).then(function(kml) {
            return getStylesFromXml(kml, url);
        }, function(error) {
            this._error.raiseEvent(this, error);
        });
    }

    function getColor(node, colorType){
        var color;
        if(typeof colorType ===  'undefined'){
            color = getElementValue(node,'color');
        } else {
            color = getElementValue(node, colorType);
        }
        color = parseInt(color,16);
        if(isNaN(color)){
            return undefined;
        }
        return color;
    }

    // KML processing functions
    function processPlacemark(dataSource, dynamicObject, placemark, dynamicObjectCollection, styleCollection) {
        dynamicObject.name = getElementValue(placemark, 'name');
        if(typeof dynamicObject.label !== 'undefined'){
            dynamicObject.label.text = new ConstantProperty(dynamicObject.name);
        }
        // I want to iterate over every placemark
        for(var i = 0, len = placemark.childNodes.length; i < len; i++){
            var node = placemark.childNodes.item(i);
            //Checking if the node holds a supported Geometry type
            if(geometryTypes.hasOwnProperty(node.nodeName)){
                placemark.geometry = node.nodeName;
                var geometryType = placemark.geometry;
                var geometryHandler = geometryTypes[geometryType];
                if (typeof geometryHandler === 'undefined') {
                    throw new RuntimeError('Unknown geometry type: ' + geometryType);
                }
                geometryHandler(dataSource, dynamicObject, placemark, node);
            }
        }

    }

    function processPoint(dataSource, dynamicObject, kml, node) {
        //TODO extrude, altitudeMode, gx:altitudeMode
        var el = node.getElementsByTagName('coordinates');
        var coordinates = [];
        for (var j = 0; j < el.length; j++) {
            coordinates = coordinates.concat(readCoordinates(el[j]));
        }
        var cartesian3 = crsFunction(coordinates);
        dynamicObject.position = new ConstantPositionProperty(cartesian3);
    }

    function processLineString(dataSource, dynamicObject, kml, node){
        //TODO gx:altitudeOffset, extrude, tessellate, altitudeMode, gx:altitudeMode, gx:drawOrder
        var el = node.getElementsByTagName('coordinates');
        var coordinates = [];
        for (var j = 0; j < el.length; j++) {
            coordinates = coordinates.concat(readCoordinates(el[j]));
        }
        dynamicObject.vertexPositions = new ConstantPositionProperty(coordinatesArrayToCartesianArray(coordinates));
    }

    function processLinearRing(dataSource, dynamicObject, kml, node){
        var el = node.getElementsByTagName('coordinates');
        var coordinates = [];
        for (var j = 0; j < el.length; j++) {
            coordinates = coordinates.concat(readCoordinates(el[j]));
        }
        //TODO gx:altitudeOffset, extrude, tessellate, altitudeMode, altitudeModeEnum, altitudeMode
    }

    //Object that holds all supported Geometry
    var geometryTypes = {
            Point : processPoint,
            LineString : processLineString,
            LinearRing : processLinearRing
            //TODO Polygon, MultiGeometry, Model, gxTrack, gxMultitrack
    };

    function processStyle(styleNode, dynamicObject) {
        for(var i = 0, len = styleNode.childNodes.length; i < len; i++){
            var node = styleNode.childNodes.item(i);

            if(node.nodeName === "IconStyle"){
                dynamicObject.billboard = new DynamicBillboard();
                //Map style to billboard properties
                //TODO heading, hotSpot and ColorMode
                var scale = getElementValue(node, 'scale');
                var icon = getElementValue(node,'href');
                var color = getColor(node);

                dynamicObject.billboard.image = icon && new ConstantProperty(icon);
                dynamicObject.billboard.scale = scale && new ConstantProperty(scale);
                dynamicObject.billboard.color = color && new ConstantProperty(Color.fromRgba(color));
            }
            else if(node.nodeName ===  "LabelStyle")   {
                dynamicObject.label = new DynamicLabel();
                //Map style to label properties
                //TODO ColorMode
                var labelScale = getElementValue(node, 'scale');
                var labelColor = getColor(node);

                dynamicObject.label.scale = labelScale && new ConstantProperty(labelScale);
                dynamicObject.label.fillColor = labelColor && new ConstantProperty(Color.fromRgba(labelColor)); //not sure how to set font color
                dynamicObject.label.text = dynamicObject.name && new ConstantProperty(dynamicObject.name);
            }
            else if(node.nodeName ===  "LineStyle")   {
                dynamicObject.polyline = new DynamicPolyline();
                //Map style to line properties
                //TODO PhysicalWidth, Visibility, ColorMode
                var lineColor = getColor(node);
                var lineWidth = getElementValue(node,'width');
                var lineOuterColor = getColor(node,'gx:outerColor');
                var lineOuterWidth = getElementValue(node,'gx:outerWidth');

                dynamicObject.polyline.color = lineColor && new ConstantProperty(Color.fromRgba(lineColor));
                dynamicObject.polyline.width = lineWidth && new ConstantProperty(lineWidth);
                dynamicObject.polyline.outlineColor = lineOuterColor && new ConstantProperty(Color.fromRgba(lineOuterColor));
                dynamicObject.polyline.outlineWidth = lineOuterWidth && new ConstantProperty(lineOuterWidth);
            }
            else if(node.nodeName === "PolyStyle")   {
                dynamicObject.polygon = new DynamicPolygon();
                //Map style to polygon properties
                //TODO Fill, Outline
            }
        }
    }

    function loadKML(dataSource, kml, sourceUri) {
        var dynamicObjectCollection = dataSource._dynamicObjectCollection;
        var styleCollection = getStylesFromXml(kml);

        var array = kml.getElementsByTagName('Placemark');
        for (var i = 0, len = array.length; i < len; i++){
            var inlineStyleCollection = getStylesFromXml(array[i]);
            var placemark = array[i];
            placemark.id = getId(placemark);
            var placemarkDynamicObject = dynamicObjectCollection.getOrCreateObject(placemark.id);
            //check for inline styles
            var styleObjects = inlineStyleCollection.getObjects();
            var styleObjectsLength = styleObjects.length;
            if(styleObjectsLength > 0){
                for(var k = 0; k < styleObjectsLength; k++){
                    placemarkDynamicObject.merge(styleObjects[k]);
                }
            } else {
                var styleUrl = array[i].getElementsByTagName('styleUrl');
                for(var j = 0, size = styleUrl.length; j < size; j++){
                    var styleId = getElementValue(array[j], 'styleUrl');
                    if(styleId[0] === '#'){ //then check for local file styles
                        var styleObj = styleCollection.getObject(styleId);
                        placemarkDynamicObject.merge(styleObj);
                    } else { // get remote styles lastly
                        var externalStyleCollection;
                        var externalStyleObj;

                        var externalArray = styleId.split('#');
                        var externalPath = externalArray[0];
                        var externalStyleId = '#' + externalArray[1];
                        if(typeof dataSource.externalStyles[externalPath] === 'undefined'){
                            if(externalPath.substring(0,3 === 'http')){
                                //externalStyleCollection = getRemoteStyle(externalPath).then(function(styles){ });
                                dataSource.externalStyles[externalPath] = externalStyleCollection;
                                externalStyleObj = externalStyleCollection.getObject(externalStyleId);
                                placemarkDynamicObject.merge(externalStyleObj);

                            } else {
                                //TODO Load an external file from a relative path
                            }
                        } else {
                            externalStyleCollection = dataSource.externalStyles[externalPath];
                            externalStyleObj = externalStyleCollection.getObject(externalStyleId);
                            placemarkDynamicObject.merge(externalStyleObj);
                        }
                    }
                }
            }
            processPlacemark(dataSource, placemarkDynamicObject, placemark, dynamicObjectCollection, styleCollection);
        }
    }

    /**
     * A {@link DataSource} which processes KML.
     * @alias KmlDataSource
     * @constructor
     */
    var KmlDataSource = function(){
        this._changed = new Event();
        this._error = new Event();
        this._clock = undefined;
        this._dynamicObjectCollection = new DynamicObjectCollection();
        this._timeVarying = true;
        this.externalStyles = {}; //cache to hold external styles
    };

    /**
     * Gets an event that will be raised when non-time-varying data changes
     * or if the return value of getIsTimeVarying changes.
     * @memberof DataSource
     *
     * @returns {Event} The event.
     */
    KmlDataSource.prototype.getChangedEvent = function() {
        return this._changed;
    };

    /**
     * Gets an event that will be raised if an error is encountered during processing.
     * @memberof KmlDataSource
     *
     * @returns {Event} The event.
     */
    KmlDataSource.prototype.getErrorEvent = function() {
        return this._error;
    };

    /**
     * Gets the top level clock defined in KML or the availability of the
     * underlying data if no clock is defined.  If the KML document only contains
     * infinite data, undefined will be returned.
     * @memberof KmlDataSource
     *
     * @returns {DynamicClock} The clock associated with the current KML data, or undefined if none exists.
     */
    KmlDataSource.prototype.getClock = function() {
        return undefined;
    };

    /**
     * Gets the DynamicObjectCollection generated by this data source.
     * @memberof DataSource
     *
     * @returns {DynamicObjectCollection} The collection of objects generated by this data source.
     */
    KmlDataSource.prototype.getDynamicObjectCollection = function() {
        return this._dynamicObjectCollection;
    };

    /**
     * Gets a value indicating if the data varies with simulation time.  If the return value of
     * this function changes, the changed event will be raised.
     * @memberof DataSource
     *
     * @returns {Boolean} True if the data is varies with simulation time, false otherwise.
     */
    KmlDataSource.prototype.getIsTimeVarying = function() {
        return true;
    };

    /**
     * Replaces any existing data with the provided KML.
     *
     * @param {Object} KML The KML to be processed.
     * @param {String} source The source of the KML.
     *
     * @exception {DeveloperError} KML is required.
     */
    KmlDataSource.prototype.load = function(kml, source) {
        if (typeof kml === 'undefined') {
            throw new DeveloperError('kml is required.');
        }

        this._dynamicObjectCollection.clear();
        loadKML(this, kml, source);
        this._changed.raiseEvent(this);
    };

    /**
     * Asynchronously loads the KML at the provided url, replacing any existing data.
     *
     * @param {Object} url The url to be processed.
     *
     * @returns {Promise} a promise that will resolve when the KML is processed.
     *
     * @exception {DeveloperError} url is required.
     */
    KmlDataSource.prototype.loadUrl = function(url) {
        if (typeof url === 'undefined') {
            throw new DeveloperError('url is required.');
        }

        var dataSource = this;
        return when(loadXML(url), function(kml) {
            return dataSource.load(kml, url);
        }, function(error) {
            dataSource._error.raiseEvent(dataSource, error);
            return when.reject(error);
        });
    };
    return KmlDataSource;
});<|endoftext|>


<commit_before>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require local_time
//= require bootstrap-sprockets
//= require_tree .

function getDisplayedRows() {
  return $(".js-table-notifications tr.notification")
}

// gets all marked rows (or unmarked rows if unmarked is true)
function getMarkedRows(unmarked) {
  return unmarked ? getDisplayedRows().has("input:not(:checked)") : getDisplayedRows().has("input:checked")
}

function getIdsFromRows(rows) {
  return $('button.select_all').hasClass('all_selected') ?
    'all' : $.map(rows, function(row) {return $(row).find("input").val()})
}

// returns true if there are any marked rows (or unmarked rows if unmarked is true)
function hasMarkedRows(unmarked) {
  return getMarkedRows(unmarked).length > 0
}

function getCurrentRow() {
  return getDisplayedRows().has('td.js-current')
}

function getMarkedOrCurrentRows() {
  return hasMarkedRows() ? getMarkedRows() : getCurrentRow()
}

function moveCursorToClickedRow(event) {
  // Don't event.preventDefault(), since we want the normal clicking behavior for links, starring, etc
  var oldCurrent = getCurrentRow();
  var target = $(this);
  setRowCurrent(oldCurrent, false);
  setRowCurrent(target, true);
}

function updateFavicon() {
  $.get( "/notifications/unread_count", function(data) {
    var unread_count = data["count"];
    if ( unread_count > 0 ) {
      var old_link = document.getElementById('favicon-count');
      if ( old_link ) {
        $(old_link).remove();
      }

      var canvas = document.createElement('canvas'),
        ctx,
        img = document.createElement('img'),
        link = document.getElementById('favicon').cloneNode(true),
        txt = unread_count + '';

      link.id = "favicon-count";

      if (canvas.getContext) {
        canvas.height = canvas.width = 16;
        ctx = canvas.getContext('2d');
        img.onload = function () {
          ctx.drawImage(this, 0, 0);

          ctx.fillStyle = '#f93e00';
          var width = ctx.measureText(txt).width;
          ctx.fillRect(0, 0, width+2, 12);

          ctx.font = 'bold 10px "helvetica", sans-serif';
          ctx.fillStyle = '#fff';
          ctx.fillText(txt, 1, 10);

          link.href = canvas.toDataURL('image/png');
          document.body.appendChild(link);
        };
        img.src = "/favicon-16x16.png";
      }
    }
  });
}

document.addEventListener("turbolinks:load", function() {
  $('button.archive_selected, button.unarchive_selected').click(toggleArchive);
  $('button.select_all').click(toggleSelectAll);
  $('button.mute_selected').click(mute);
  $('button.mark_read_selected').click(markReadSelected);
  $('tr.notification').click(moveCursorToClickedRow);

  $('input.archive, input.unarchive').change(function() {
    if ( hasMarkedRows() ) {
      var prop = hasMarkedRows(true) ? 'indeterminate' : 'checked';
      $(".js-select_all").prop(prop, true);
      $('button.archive_selected, button.unarchive_selected, button.mute_selected').removeClass('hidden');
      if ( prop === 'checked' ) {
        $('button.select_all').removeClass('hidden');
      } else {
        $('button.select_all').addClass('hidden');
      }
    } else {
      $(".js-select_all").prop('checked', false);
      $('button.archive_selected, button.unarchive_selected, button.mute_selected, button.select_all').addClass('hidden');
    }
    var marked_unread_length = getMarkedRows().filter('.active').length;
    if ( marked_unread_length > 0 ) {
      $('button.mark_read_selected').removeClass('hidden');
    } else {
      $('button.mark_read_selected').addClass('hidden');
    }
  });
  $('.toggle-star').click(function() {
    $(this).toggleClass("star-active star-inactive");
    $.post('/notifications/'+$(this).data('id')+'/star')
  });
  $('.sync .octicon').on('click', function() {
    $(this).toggleClass('spinning')
  });
  recoverPreviousCursorPosition();

  $('.js-select_all').change(function() {
    checkAll($(".js-select_all").prop('checked'))
  })

  $('[data-toggle="tooltip"]').tooltip()

  updateFavicon()
});

document.addEventListener("turbolinks:before-cache", function() {
  $('td.js-current').removeClass("current js-current");
});

// Add shortcut events only once
$(document).ready(enableKeyboardShortcuts);

$(document).on('click', '[data-toggle="offcanvas"]', function () {
  $('.flex-content').toggleClass('active')
});

if(!('ontouchstart' in window))
{
  $(function () {
    $('[data-toggle="tooltip"]').tooltip()
  })
}

function enableKeyboardShortcuts() {
  window.row_index = 1;
  window.current_id = undefined;

  $(document).keydown(function(e) {
    // disable shortcuts for the seach box
    if (e.target.id !== 'search-box') {
      var shortcutFunction = shortcuts[e.which];
      if (shortcutFunction) { shortcutFunction(e) }
    }
  });
}

var shortcuts = {
  65:  checkSelectAll,    // a
  68:  markReadSelected,  // d
  74:  cursorDown,        // j
  75:  cursorUp,          // k
  83:  toggleStar,        // s
  88:  markCurrent,       // x
  89:  toggleArchive,     // y
  69:  toggleArchive,     // e
  77:  mute,              // m
  13:  openCurrentLink,   // Enter
  79:  openCurrentLink,   // o
  191: openModal,         // ?
  190: sync,              // .
  82:  sync               // r
};

function cursorDown() {
  moveCursor('up')
}

function cursorUp() {
  moveCursor('down')
}

function markCurrent() {
  getCurrentRow().find("input[type=checkbox]").click();
}

function checkAll(checked) {
  getDisplayedRows().find('input').prop("checked", checked).trigger('change');
}

function checkSelectAll() {
  $(".js-select_all").click()
}

function mute() {
  if (getDisplayedRows().length === 0) return;
  if ( $(".js-table-notifications tr").length === 0 ) return;
  var ids = getIdsFromRows(getMarkedOrCurrentRows());
  $.post( "/notifications/mute_selected", { 'id[]': ids}).done(function() {resetCursorAfterRowsRemoved(ids)});
}

function markReadSelected() {
  if (getDisplayedRows().length === 0) return;
  var rows = getMarkedOrCurrentRows();
  $.post("/notifications/mark_read_selected", {'id[]': getIdsFromRows(rows)}).done(function () {
    rows.removeClass('active');
    updateFavicon();
  })
}

function markRead(id) {
  $.post( "/notifications/"+id+"/mark_read").done(function() {
    updateFavicon();
  });
  $('#notification-'+id).removeClass('active');
}

function toggleArchive() {
  if (getDisplayedRows().length === 0) return;

  var cssClass, value;

  if ( $(".archive_toggle").hasClass("archive_selected") ) {
    cssClass = '.archive'
    value = true
  } else {
    cssClass = '.unarchive'
    value = false
  }

  var ids = getIdsFromRows(getMarkedOrCurrentRows());

  $.post( "/notifications/archive_selected" + location.search, { 'id[]': ids, 'value': value } ).done(function() {resetCursorAfterRowsRemoved(ids)});
}

function toggleSelectAll() {
  $.map($('button.select_all > span'), function( val, i ) {
    $(val).toggleClass('bold')
  });
  $('button.select_all').toggleClass('all_selected')
}

function resetCursorAfterRowsRemoved(ids) {
  var current = getCurrentRow();
  while ( $.inArray(getIdsFromRows(current)[0], ids) > -1 && current.next().length > 0) {
    current = current.next();
  }
  window.current_id = getIdsFromRows(current)[0];
  if ( $.inArray(window.current_id, ids ) > -1 ) {
    window.current_id = getIdsFromRows(getMarkedRows(true).last())[0];
  }
  Turbolinks.visit("/"+location.search);
}

function toggleStar() {
  getCurrentRow().find('.toggle-star').click();
}

function openModal() {
  $("#help-box").modal();
}

function openCurrentLink(e) {
  e.preventDefault(e);
  getCurrentRow().find('td.notification-subject .link')[0].click();
}

function sync() {
  $("a.sync").click();
}

function autoSync() {
  hasMarkedRows() || sync()
}

function setAutoSyncTimer() {
  var refresh_interval = $('.js-table-notifications').data('refresh-interval');
  if (isNaN(refresh_interval)) return;
  refresh_interval > 0 && setInterval(autoSync, refresh_interval)
}

$(document).ready(setAutoSyncTimer);

function scrollToCursor() {
  var current = $('td.js-current');
  var table_offset = $('.js-table-notifications').position().top;
  var cursor_offset = current.offset().top;
  var cursor_relative_offset = current.position().top;
  var cursor_height = current.height();
  var menu_height = $(".js-octobox-menu").height();
  var scroll_top = $(document).scrollTop();
  var window_height = $(window).height();
  if ( cursor_offset < menu_height + scroll_top ) {
    $("html, body").animate({
      scrollTop: table_offset + cursor_relative_offset - cursor_height
    }, 0);
  }
  if ( cursor_offset > scroll_top + window_height - cursor_height ) {
    $("html, body").animate({
      scrollTop: cursor_offset - window_height + 2*cursor_height
    }, 0);
  }
}

function setRowCurrent(row, add) {
  var classes = 'current js-current';
  var td = row.find('td.notification-checkbox');
  add ? td.addClass(classes) : td.removeClass(classes)
}

function moveCursor(upOrDown) {
  var oldCurrent = getCurrentRow();
  var target = upOrDown === 'up' ? oldCurrent.next() : oldCurrent.prev();
  if(target.length > 0) {
    setRowCurrent(oldCurrent, false);
    setRowCurrent(target, true);
    scrollToCursor();
  }
}

function recoverPreviousCursorPosition() {
  if ( current_id === undefined ) {
    row_index = Math.min(row_index, $(".js-table-notifications tr").length);
    row_index = Math.max(row_index, 1);
  } else {
    row_index = $('#notification-'+current_id).index() + 1;
    current_id = undefined;
  }
  $(".js-table-notifications tbody tr:nth-child(" + row_index + ")").first().find("td").first().addClass("current js-current");
}

// Clicking a row marks it current
$(document).ready(function() {
  $("tr.notification").click(function() {
    $(".current.js-current").removeClass("current js-current");
    $( this ).find("td").first().addClass("current js-current");
  })
});
<commit_msg>Disable tooltips on focus for mobile (#365)<commit_after>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require local_time
//= require bootstrap-sprockets
//= require_tree .

function getDisplayedRows() {
  return $(".js-table-notifications tr.notification")
}

// gets all marked rows (or unmarked rows if unmarked is true)
function getMarkedRows(unmarked) {
  return unmarked ? getDisplayedRows().has("input:not(:checked)") : getDisplayedRows().has("input:checked")
}

function getIdsFromRows(rows) {
  return $('button.select_all').hasClass('all_selected') ?
    'all' : $.map(rows, function(row) {return $(row).find("input").val()})
}

// returns true if there are any marked rows (or unmarked rows if unmarked is true)
function hasMarkedRows(unmarked) {
  return getMarkedRows(unmarked).length > 0
}

function getCurrentRow() {
  return getDisplayedRows().has('td.js-current')
}

function getMarkedOrCurrentRows() {
  return hasMarkedRows() ? getMarkedRows() : getCurrentRow()
}

function moveCursorToClickedRow(event) {
  // Don't event.preventDefault(), since we want the normal clicking behavior for links, starring, etc
  var oldCurrent = getCurrentRow();
  var target = $(this);
  setRowCurrent(oldCurrent, false);
  setRowCurrent(target, true);
}

function updateFavicon() {
  $.get( "/notifications/unread_count", function(data) {
    var unread_count = data["count"];
    if ( unread_count > 0 ) {
      var old_link = document.getElementById('favicon-count');
      if ( old_link ) {
        $(old_link).remove();
      }

      var canvas = document.createElement('canvas'),
        ctx,
        img = document.createElement('img'),
        link = document.getElementById('favicon').cloneNode(true),
        txt = unread_count + '';

      link.id = "favicon-count";

      if (canvas.getContext) {
        canvas.height = canvas.width = 16;
        ctx = canvas.getContext('2d');
        img.onload = function () {
          ctx.drawImage(this, 0, 0);

          ctx.fillStyle = '#f93e00';
          var width = ctx.measureText(txt).width;
          ctx.fillRect(0, 0, width+2, 12);

          ctx.font = 'bold 10px "helvetica", sans-serif';
          ctx.fillStyle = '#fff';
          ctx.fillText(txt, 1, 10);

          link.href = canvas.toDataURL('image/png');
          document.body.appendChild(link);
        };
        img.src = "/favicon-16x16.png";
      }
    }
  });
}

document.addEventListener("turbolinks:load", function() {
  $('button.archive_selected, button.unarchive_selected').click(toggleArchive);
  $('button.select_all').click(toggleSelectAll);
  $('button.mute_selected').click(mute);
  $('button.mark_read_selected').click(markReadSelected);
  $('tr.notification').click(moveCursorToClickedRow);

  $('input.archive, input.unarchive').change(function() {
    if ( hasMarkedRows() ) {
      var prop = hasMarkedRows(true) ? 'indeterminate' : 'checked';
      $(".js-select_all").prop(prop, true);
      $('button.archive_selected, button.unarchive_selected, button.mute_selected').removeClass('hidden');
      if ( prop === 'checked' ) {
        $('button.select_all').removeClass('hidden');
      } else {
        $('button.select_all').addClass('hidden');
      }
    } else {
      $(".js-select_all").prop('checked', false);
      $('button.archive_selected, button.unarchive_selected, button.mute_selected, button.select_all').addClass('hidden');
    }
    var marked_unread_length = getMarkedRows().filter('.active').length;
    if ( marked_unread_length > 0 ) {
      $('button.mark_read_selected').removeClass('hidden');
    } else {
      $('button.mark_read_selected').addClass('hidden');
    }
  });
  $('.toggle-star').click(function() {
    $(this).toggleClass("star-active star-inactive");
    $.post('/notifications/'+$(this).data('id')+'/star')
  });
  $('.sync .octicon').on('click', function() {
    $(this).toggleClass('spinning')
  });
  recoverPreviousCursorPosition();

  $('.js-select_all').change(function() {
    checkAll($(".js-select_all").prop('checked'))
  })

  $('[data-toggle="tooltip"]').tooltip({trigger: 'tooltip'})

  updateFavicon()
});

document.addEventListener("turbolinks:before-cache", function() {
  $('td.js-current').removeClass("current js-current");
});

// Add shortcut events only once
$(document).ready(enableKeyboardShortcuts);

$(document).on('click', '[data-toggle="offcanvas"]', function () {
  $('.flex-content').toggleClass('active')
});

if(!('ontouchstart' in window))
{
  $(function () {
    $('[data-toggle="tooltip"]').tooltip()
  })
}

function enableKeyboardShortcuts() {
  window.row_index = 1;
  window.current_id = undefined;

  $(document).keydown(function(e) {
    // disable shortcuts for the seach box
    if (e.target.id !== 'search-box') {
      var shortcutFunction = shortcuts[e.which];
      if (shortcutFunction) { shortcutFunction(e) }
    }
  });
}

var shortcuts = {
  65:  checkSelectAll,    // a
  68:  markReadSelected,  // d
  74:  cursorDown,        // j
  75:  cursorUp,          // k
  83:  toggleStar,        // s
  88:  markCurrent,       // x
  89:  toggleArchive,     // y
  69:  toggleArchive,     // e
  77:  mute,              // m
  13:  openCurrentLink,   // Enter
  79:  openCurrentLink,   // o
  191: openModal,         // ?
  190: sync,              // .
  82:  sync               // r
};

function cursorDown() {
  moveCursor('up')
}

function cursorUp() {
  moveCursor('down')
}

function markCurrent() {
  getCurrentRow().find("input[type=checkbox]").click();
}

function checkAll(checked) {
  getDisplayedRows().find('input').prop("checked", checked).trigger('change');
}

function checkSelectAll() {
  $(".js-select_all").click()
}

function mute() {
  if (getDisplayedRows().length === 0) return;
  if ( $(".js-table-notifications tr").length === 0 ) return;
  var ids = getIdsFromRows(getMarkedOrCurrentRows());
  $.post( "/notifications/mute_selected", { 'id[]': ids}).done(function() {resetCursorAfterRowsRemoved(ids)});
}

function markReadSelected() {
  if (getDisplayedRows().length === 0) return;
  var rows = getMarkedOrCurrentRows();
  $.post("/notifications/mark_read_selected", {'id[]': getIdsFromRows(rows)}).done(function () {
    rows.removeClass('active');
    updateFavicon();
  })
}

function markRead(id) {
  $.post( "/notifications/"+id+"/mark_read").done(function() {
    updateFavicon();
  });
  $('#notification-'+id).removeClass('active');
}

function toggleArchive() {
  if (getDisplayedRows().length === 0) return;

  var cssClass, value;

  if ( $(".archive_toggle").hasClass("archive_selected") ) {
    cssClass = '.archive'
    value = true
  } else {
    cssClass = '.unarchive'
    value = false
  }

  var ids = getIdsFromRows(getMarkedOrCurrentRows());

  $.post( "/notifications/archive_selected" + location.search, { 'id[]': ids, 'value': value } ).done(function() {resetCursorAfterRowsRemoved(ids)});
}

function toggleSelectAll() {
  $.map($('button.select_all > span'), function( val, i ) {
    $(val).toggleClass('bold')
  });
  $('button.select_all').toggleClass('all_selected')
}

function resetCursorAfterRowsRemoved(ids) {
  var current = getCurrentRow();
  while ( $.inArray(getIdsFromRows(current)[0], ids) > -1 && current.next().length > 0) {
    current = current.next();
  }
  window.current_id = getIdsFromRows(current)[0];
  if ( $.inArray(window.current_id, ids ) > -1 ) {
    window.current_id = getIdsFromRows(getMarkedRows(true).last())[0];
  }
  Turbolinks.visit("/"+location.search);
}

function toggleStar() {
  getCurrentRow().find('.toggle-star').click();
}

function openModal() {
  $("#help-box").modal();
}

function openCurrentLink(e) {
  e.preventDefault(e);
  getCurrentRow().find('td.notification-subject .link')[0].click();
}

function sync() {
  $("a.sync").click();
}

function autoSync() {
  hasMarkedRows() || sync()
}

function setAutoSyncTimer() {
  var refresh_interval = $('.js-table-notifications').data('refresh-interval');
  if (isNaN(refresh_interval)) return;
  refresh_interval > 0 && setInterval(autoSync, refresh_interval)
}

$(document).ready(setAutoSyncTimer);

function scrollToCursor() {
  var current = $('td.js-current');
  var table_offset = $('.js-table-notifications').position().top;
  var cursor_offset = current.offset().top;
  var cursor_relative_offset = current.position().top;
  var cursor_height = current.height();
  var menu_height = $(".js-octobox-menu").height();
  var scroll_top = $(document).scrollTop();
  var window_height = $(window).height();
  if ( cursor_offset < menu_height + scroll_top ) {
    $("html, body").animate({
      scrollTop: table_offset + cursor_relative_offset - cursor_height
    }, 0);
  }
  if ( cursor_offset > scroll_top + window_height - cursor_height ) {
    $("html, body").animate({
      scrollTop: cursor_offset - window_height + 2*cursor_height
    }, 0);
  }
}

function setRowCurrent(row, add) {
  var classes = 'current js-current';
  var td = row.find('td.notification-checkbox');
  add ? td.addClass(classes) : td.removeClass(classes)
}

function moveCursor(upOrDown) {
  var oldCurrent = getCurrentRow();
  var target = upOrDown === 'up' ? oldCurrent.next() : oldCurrent.prev();
  if(target.length > 0) {
    setRowCurrent(oldCurrent, false);
    setRowCurrent(target, true);
    scrollToCursor();
  }
}

function recoverPreviousCursorPosition() {
  if ( current_id === undefined ) {
    row_index = Math.min(row_index, $(".js-table-notifications tr").length);
    row_index = Math.max(row_index, 1);
  } else {
    row_index = $('#notification-'+current_id).index() + 1;
    current_id = undefined;
  }
  $(".js-table-notifications tbody tr:nth-child(" + row_index + ")").first().find("td").first().addClass("current js-current");
}

// Clicking a row marks it current
$(document).ready(function() {
  $("tr.notification").click(function() {
    $(".current.js-current").removeClass("current js-current");
    $( this ).find("td").first().addClass("current js-current");
  })
});
<|endoftext|>


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


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

// Not sure where to put this, does not work globaly if I put it into a specific js.erb file
$(document).ready(function () {
	// Initiates all bootrap dropdowns.
	$('.dropdown-toggle').dropdown();
});	<commit_msg>removed global dropdown javascript<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require_tree .
//= require i18n
//= require i18n/translations

<|endoftext|>


<commit_before>import React from 'react'
import QuickInterface from 'quick-interface'
import createSpecialParamSettings from './createSpecialParamSettings'

function showItemSettingsDialog() {
  BETON.require('item-settings-dialog').show()
}

function handleSelectClick(id) {
  const {actions, selectors} = BETON.require('project-manager')
  const {type} = selectors.getItemById({id})
  const currentTrackId = type === 'track'
    ? id
    : selectors.getParentTrackOfParam(trackId).id
  const timelineId =
    selectors.getParentTimelineOfTrack({trackId: currentTrackId}).id

  actions.setLastSelectedItemId({itemId: id})
  actions.setCurrentTrackIdOfTimeline({timelineId, currentTrackId})
}

function handleToggleOpen(id) {
  const {actions, selectors} = BETON.require('project-manager')
  const {type} = selectors.getItemById({id})
  if (type === 'param') {
    actions.toggleOpenInTimelineOfParam({paramId: id})
  }
  else if (type === 'track') {
    actions.toggleOpenInTimelineOfTrack({trackId: id})
  }
}

function createTrackSettings({id, name, openInTimeline}) {
  const {getParentTimelineOfTrack} = BETON.require('project-manager').selectors
  const parentTimeline = getParentTimelineOfTrack({trackId: id})
  return {
    open: openInTimeline,
    onClick: handleSelectClick.bind(null, id),
    onToggleOpen: handleToggleOpen.bind(null, id),
    buttons:  [
      {
        icon: 'plus',
        tooltip: 'add a new param to this track',
        onClick: () => {
          BETON.require('project-manager').actions.addParamToTrack({
            trackId: id,
          })
          showItemSettingsDialog()
        }
      }
    ],
    highlighted: parentTimeline.currentTrackId === id,
    contextMenu: {
      items: [
        {
          label: 'new track',
          icon: 'plus',
          onClick: () => {
            BETON.require('project-manager').actions.addTrackToTimeline({
              timelineId: parentTimeline.id,
            })
            showItemSettingsDialog()
          }
        }, {
          label: 'new param',
          icon: 'add',
          onClick: () => {
            BETON.require('project-manager').actions.addParamToTrack({
              trackId: id,
            })
            showItemSettingsDialog()
          }
        }, {
          items: [
            {
              label: 'settings',
              icon: 'cog',
              onClick: () => {
                handleSelectClick()
                showItemSettingsDialog()
              }
            }
          ]
        }
      ]
    }
  }
}

function createParamSettings({id, name, openInTimeline}) {
  return {
    labels: [name],
    open: openInTimeline,
    onClick: handleSelectClick.bind(null, id),
    onToggleOpen: handleToggleOpen.bind(null, id),
    contextMenu: [{
      items: [
        {
          label: 'settings',
          icon: 'cog',
          onClick: () => {
            handleSelectClick()
            showItemSettingsDialog()
          }
        }
      ]
    }],
    ...createSpecialParamSettings({id, name})
  }
}

const renderParams = params => {
  const {getItemById} = BETON.require('project-manager').selectors
  return params
    .map(paramId => getItemById({id: paramId}))
    .map(({id, name, openInTimeline}) => (
      <QuickInterface {...{
        key: id,
        id,
        name,
        openInTimeline,
        createSettings: createParamSettings
      }}/>
    ))
}

const renderTracks = tracks => {
  const {getItemById} = BETON.require('project-manager').selectors
  return tracks
    .map(trackId => getItemById({id: trackId}))
    .map(({id, name, openInTimeline, params}) => (
      <QuickInterface {...{
        key: id,
        id,
        name,
        openInTimeline,
        createSettings: createTrackSettings
      }}>
        {renderParams(params)}
      </QuickInterface>
    ))
}

export default tracks => (
  <QuickInterface createSettings={() => ({hiddenHead: true})}>
    {renderTracks(tracks)}
  </QuickInterface>
)
<commit_msg>remove name labels<commit_after>import React from 'react'
import QuickInterface from 'quick-interface'
import createSpecialParamSettings from './createSpecialParamSettings'

function showItemSettingsDialog() {
  BETON.require('item-settings-dialog').show()
}

function handleSelectClick(id) {
  const {actions, selectors} = BETON.require('project-manager')
  const {type} = selectors.getItemById({id})
  const currentTrackId = type === 'track'
    ? id
    : selectors.getParentTrackOfParam(trackId).id
  const timelineId =
    selectors.getParentTimelineOfTrack({trackId: currentTrackId}).id

  actions.setLastSelectedItemId({itemId: id})
  actions.setCurrentTrackIdOfTimeline({timelineId, currentTrackId})
}

function handleToggleOpen(id) {
  const {actions, selectors} = BETON.require('project-manager')
  const {type} = selectors.getItemById({id})
  if (type === 'param') {
    actions.toggleOpenInTimelineOfParam({paramId: id})
  }
  else if (type === 'track') {
    actions.toggleOpenInTimelineOfTrack({trackId: id})
  }
}

function createTrackSettings({id, name, openInTimeline}) {
  const {getParentTimelineOfTrack} = BETON.require('project-manager').selectors
  const parentTimeline = getParentTimelineOfTrack({trackId: id})
  return {
    open: openInTimeline,
    onClick: handleSelectClick.bind(null, id),
    onToggleOpen: handleToggleOpen.bind(null, id),
    buttons:  [
      {
        icon: 'plus',
        tooltip: 'add a new param to this track',
        onClick: () => {
          BETON.require('project-manager').actions.addParamToTrack({
            trackId: id,
          })
          showItemSettingsDialog()
        }
      }
    ],
    highlighted: parentTimeline.currentTrackId === id,
    contextMenu: {
      items: [
        {
          label: 'new track',
          icon: 'plus',
          onClick: () => {
            BETON.require('project-manager').actions.addTrackToTimeline({
              timelineId: parentTimeline.id,
            })
            showItemSettingsDialog()
          }
        }, {
          label: 'new param',
          icon: 'add',
          onClick: () => {
            BETON.require('project-manager').actions.addParamToTrack({
              trackId: id,
            })
            showItemSettingsDialog()
          }
        }, {
          items: [
            {
              label: 'settings',
              icon: 'cog',
              onClick: () => {
                handleSelectClick()
                showItemSettingsDialog()
              }
            }
          ]
        }
      ]
    }
  }
}

function createParamSettings({id, name, openInTimeline}) {
  return {
    open: openInTimeline,
    onClick: handleSelectClick.bind(null, id),
    onToggleOpen: handleToggleOpen.bind(null, id),
    contextMenu: [{
      items: [
        {
          label: 'settings',
          icon: 'cog',
          onClick: () => {
            handleSelectClick()
            showItemSettingsDialog()
          }
        }
      ]
    }],
    ...createSpecialParamSettings({id, name})
  }
}

const renderParams = params => {
  const {getItemById} = BETON.require('project-manager').selectors
  return params
    .map(paramId => getItemById({id: paramId}))
    .map(({id, name, openInTimeline}) => (
      <QuickInterface {...{
        key: id,
        id,
        name,
        openInTimeline,
        createSettings: createParamSettings
      }}/>
    ))
}

const renderTracks = tracks => {
  const {getItemById} = BETON.require('project-manager').selectors
  return tracks
    .map(trackId => getItemById({id: trackId}))
    .map(({id, name, openInTimeline, params}) => (
      <QuickInterface {...{
        key: id,
        id,
        name,
        openInTimeline,
        createSettings: createTrackSettings
      }}>
        {renderParams(params)}
      </QuickInterface>
    ))
}

export default tracks => (
  <QuickInterface createSettings={() => ({hiddenHead: true})}>
    {renderTracks(tracks)}
  </QuickInterface>
)
<|endoftext|>


<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//= require jquery.js
//# require jquery.min.js
//= require jquery.tipTip.js
//= require humane.js
//= require jquery_ujs.js
//# require jquery-ui.js
//# require prototip.js
//= require domains
//= require domain_templates
//= require users
//= require views
//= require audits
//= require bind
//= require select2.min.js
//= require_tree

$(document).ready(function() {

    // ----------------- ajax activity indicator -----------------
    // $('body').append('
<img src="<%= image_path('loading.gif') %>"/>
');
    // $('body').append('

');

    // setup tooltips where required
    $('.help-icon').each(function(i, icon){
        $(icon).tipTip({
            content: $( "#" + $(icon).data("help") ).text()
        });
    });

    // ----------------- setup tooltips of search boxes -----------------
    $('.search-field').each(function(i, field) {
        $(field).tipTip({
            content: $("#" + $(field).data("help")).text(),
			delay: 2000,
			activation: "click"
        });
    });

	// ----------------- ajax flash messages -----------------
	var flashMessageDelay = {
		error:   5000,
		warning: 5000,
		notice:  2000
	};
	var flashMessageIcon = {
		error:   'warning-sign',
		warning: 'warning-sign',
		notice:  'info-sign'
	};
	$.fn.flashMessage = function(message, messageType, delay) {
		var container = $('.flash-ajax.flash-' + messageType);
		if (container.length == 0) {
			if (console) console.log('creating flash container (type: ' + messageType + ')');
			var container = $('

');
			container.hide();
			$('body').append(container);
		}
		container.find('.message').html(message);
		container.fadeIn().delay(delay || flashMessageDelay[messageType]).fadeOut('slow');
	};

	// ----------------- ajax pagination ---------------
	// will_paginate does not support link attributes yet.
	// See: https://github.com/mislav/will_paginate/pull/100
	$('.pagination a').live('click', function () {
		$.rails.handleRemote($(this));
		return false;
	});
});

// ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function() {
    $('#ajaxBusy').show();
}).ajaxStop(function(){
    $('#ajaxBusy').hide();
});

$(document).ajaxComplete(function(evt, xhr, options) {
	var message     = xhr.getResponseHeader('x-flash');
	var messageType = xhr.getResponseHeader('x-flash-type');

	if (message && messageType)
		$.fn.flashMessage(message, messageType);
});

//* rest of file omitted */
<commit_msg>Fix domain<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//= require jquery.js
//= require select2.min.js
//# require jquery.min.js
//= require jquery.tipTip.js
//= require humane.js
//= require jquery_ujs.js
//# require jquery-ui.js
//# require prototip.js
//= require domains
//= require domain_templates
//= require users
//= require views
//= require audits
//= require bind
//= require_tree

$(document).ready(function() {

    // ----------------- ajax activity indicator -----------------
    // $('body').append('
<img src="<%= image_path('loading.gif') %>"/>
');
    // $('body').append('

');

    // setup tooltips where required
    $('.help-icon').each(function(i, icon){
        $(icon).tipTip({
            content: $( "#" + $(icon).data("help") ).text()
        });
    });

    // ----------------- setup tooltips of search boxes -----------------
    $('.search-field').each(function(i, field) {
        $(field).tipTip({
            content: $("#" + $(field).data("help")).text(),
			delay: 2000,
			activation: "click"
        });
    });

	// ----------------- ajax flash messages -----------------
	var flashMessageDelay = {
		error:   5000,
		warning: 5000,
		notice:  2000
	};
	var flashMessageIcon = {
		error:   'warning-sign',
		warning: 'warning-sign',
		notice:  'info-sign'
	};
	$.fn.flashMessage = function(message, messageType, delay) {
		var container = $('.flash-ajax.flash-' + messageType);
		if (container.length == 0) {
			if (console) console.log('creating flash container (type: ' + messageType + ')');
			var container = $('

');
			container.hide();
			$('body').append(container);
		}
		container.find('.message').html(message);
		container.fadeIn().delay(delay || flashMessageDelay[messageType]).fadeOut('slow');
	};

	// ----------------- ajax pagination ---------------
	// will_paginate does not support link attributes yet.
	// See: https://github.com/mislav/will_paginate/pull/100
	$('.pagination a').live('click', function () {
		$.rails.handleRemote($(this));
		return false;
	});
});

// ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function() {
    $('#ajaxBusy').show();
}).ajaxStop(function(){
    $('#ajaxBusy').hide();
});

$(document).ajaxComplete(function(evt, xhr, options) {
	var message     = xhr.getResponseHeader('x-flash');
	var messageType = xhr.getResponseHeader('x-flash-type');

	if (message && messageType)
		$.fn.flashMessage(message, messageType);
});

//* rest of file omitted */
<|endoftext|>


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


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

$(document).on('turbolinks:load', function() {
  $(document).foundation();
  $('body').on('click', '[data-open="ajax-reveal"]', function(e) {
    e.preventDefault();
    $.ajax({
      url: $(this).data('url'),
      success: function(result) {
        $('.reveal-content').html(result);
      },
      error: function(result) {
        $('.reveal-content').html('Error loading content. Please close popup and retry.');
      }
    });
  });
  $('body').on('click', '.delete-array-field', function(e) {
    if($(this).parents('.fieldset').find('.input-group').length == 1) {
      alert('Cannot remove all the fields');
    } else {
      $(this).parents('.input-group').remove();
    }
  });
  $('body').on('click', '.clone-array-field', function(e) {
    var clonedField = $(this).prev('.input-group').clone();
    clonedField.find('input').val(null);
    $(this).before(clonedField);
  });
});
<commit_msg>Auto focus newly added field<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require turbolinks
//= require jquery3
//= require jquery_ujs
//= require jquery_nested_form
//= require foundation
//= require_tree .

$(document).on('turbolinks:load', function() {
  $(document).foundation();
  $('body').on('click', '[data-open="ajax-reveal"]', function(e) {
    e.preventDefault();
    $.ajax({
      url: $(this).data('url'),
      success: function(result) {
        $('.reveal-content').html(result);
      },
      error: function(result) {
        $('.reveal-content').html('Error loading content. Please close popup and retry.');
      }
    });
  });
  $('body').on('click', '.delete-array-field', function(e) {
    if($(this).parents('.fieldset').find('.input-group').length == 1) {
      alert('Cannot remove all the fields');
    } else {
      $(this).parents('.input-group').remove();
    }
  });
  $('body').on('click', '.clone-array-field', function(e) {
    var clonedField = $(this).prev('.input-group').clone();
    clonedField.find('input').val(null);
    $(this).before(clonedField);
    $(this).prev('.input-group').find('input').focus();
  });
});
<|endoftext|>


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

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

<|endoftext|>