<commit_before>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed 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
 *
 *      https://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
 *
 */

'use strict';

// Include Gulp & tools we'll use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src([
    'app/scripts/**/*.js',
    '!app/scripts/bootstrap.js',
    '!app/scripts/jquery.js'
    ])
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy all files at the root level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess',
    'GAE/*'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

gulp.task('copy_js', function () {
  return gulp.src([
    'node_modules/bootstrap/dist/js/*.min.js',
    'node_modules/jquery/dist/*.min.js'
  ], {
    dot: true
  }).pipe(gulp.dest('dist/scripts'))
    .pipe($.size({title: 'copy_js'}));
});

// Copy web fonts to dist
gulp.task('fonts', function () {
  return gulp.src([
    'app/fonts/**',
    'node_modules/bootstrap/dist/fonts/**'
	])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Compile and automatically prefix stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
    'app/styles/*.scss',
    'app/styles/**/*.css',
    'app/styles/components/components.scss',
    'node_modules/bootstrap/dist/css/bootstrap.min.css'
  ])
    .pipe($.sourcemaps.init())
    .pipe($.changed('.tmp/styles', {extension: '.css'}))
    .pipe($.sass({
      precision: 10,
      onError: console.error.bind(console, 'Sass error:')
    }))
    .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate and minify styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Scan your HTML for assets & optimize them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/**/*.html')
    .pipe(assets)
    // Concatenate and minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove any unused CSS
    // Note: if not using the Style Guide, you can delete it from
    //       the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html',
        'app/styleguide.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate and minify styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Update production Style Guide paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean output directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Watch files for changes & reload
gulp.task('serve', ['styles'], function () {
  del.bind(null, ['app/scripts/bootstrap.js'], {dot: true});
  gulp.src([
    'node_modules/bootstrap/dist/js/bootstrap.js',
    'node_modules/jquery/dist/jquery.js'
  ], {
    dot: true
  }).pipe(gulp.dest('app/scripts'));
  browserSync({
    notify: false,
    // Customize the BrowserSync console logging prefix
    logPrefix: 'WSK',
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: ['.tmp', 'app']
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    logPrefix: 'WSK',
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: 'dist'
  });
});

// Build production files, the default task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy', 'copy_js'], cb);
});

// Run PageSpeed Insights
gulp.task('pagespeed', function (cb) {
  // Update the below URL to the public URL of your site
  pagespeed.output('example.com', {
    strategy: 'mobile',
    // By default we use the PageSpeed Insights free (no API key) tier.
    // Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
    // key: 'YOUR_API_KEY'
  }, cb);
});

// Load custom tasks from the `tasks` directory
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
<commit_msg>Removed image caching so all images would build<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed 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
 *
 *      https://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
 *
 */

'use strict';

// Include Gulp & tools we'll use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src([
    'app/scripts/**/*.js',
    '!app/scripts/bootstrap.js',
    '!app/scripts/jquery.js'
    ])
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.imagemin({
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy all files at the root level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess',
    'GAE/*'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

gulp.task('copy_js', function () {
  return gulp.src([
    'node_modules/bootstrap/dist/js/*.min.js',
    'node_modules/jquery/dist/*.min.js'
  ], {
    dot: true
  }).pipe(gulp.dest('dist/scripts'))
    .pipe($.size({title: 'copy_js'}));
});

// Copy web fonts to dist
gulp.task('fonts', function () {
  return gulp.src([
    'app/fonts/**',
    'node_modules/bootstrap/dist/fonts/**'
	])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Compile and automatically prefix stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
    'app/styles/*.scss',
    'app/styles/**/*.css',
    'app/styles/components/components.scss',
    'node_modules/bootstrap/dist/css/bootstrap.min.css'
  ])
    .pipe($.sourcemaps.init())
    .pipe($.changed('.tmp/styles', {extension: '.css'}))
    .pipe($.sass({
      precision: 10,
      onError: console.error.bind(console, 'Sass error:')
    }))
    .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate and minify styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Scan your HTML for assets & optimize them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/**/*.html')
    .pipe(assets)
    // Concatenate and minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove any unused CSS
    // Note: if not using the Style Guide, you can delete it from
    //       the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html',
        'app/styleguide.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate and minify styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Update production Style Guide paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean output directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Watch files for changes & reload
gulp.task('serve', ['styles'], function () {
  del.bind(null, ['app/scripts/bootstrap.js'], {dot: true});
  gulp.src([
    'node_modules/bootstrap/dist/js/bootstrap.js',
    'node_modules/jquery/dist/jquery.js'
  ], {
    dot: true
  }).pipe(gulp.dest('app/scripts'));
  browserSync({
    notify: false,
    // Customize the BrowserSync console logging prefix
    logPrefix: 'WSK',
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: ['.tmp', 'app']
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    logPrefix: 'WSK',
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: 'dist'
  });
});

// Build production files, the default task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy', 'copy_js'], cb);
});

// Run PageSpeed Insights
gulp.task('pagespeed', function (cb) {
  // Update the below URL to the public URL of your site
  pagespeed.output('example.com', {
    strategy: 'mobile',
    // By default we use the PageSpeed Insights free (no API key) tier.
    // Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
    // key: 'YOUR_API_KEY'
  }, cb);
});

// Load custom tasks from the `tasks` directory
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
<|endoftext|>


<commit_before>var config = require('getconfig');
var bucker = require('bucker').createLogger();
var redis = require("redis");
var uid = require('node-uuid');
var moment = require('moment');
var githubhook = require('githubhook');
var client = redis.createClient(config.redis.port, config.redis.host);
var github = githubhook({ port: config.github.port, logger: bucker });

client.on('error', function (err) {
    bucker.log('redis error ' + err);
});

github.listen();

github.on('*', function (event, repo, ref, data) {
    bucker.log('sending ' + repo + ' ' + ref + ' event');

    eventData = {
        id: uuid.v1(),
        type: 'github',
        parent_id: '',
        timestamp: moment.utc().unix() * 1000;,
        payload: { 'repo': repo, 'ref': ref, 'data': data }
    };

    client.publish('github', JSON.stringify(eventData, null, 2));
});<commit_msg>semicolons don't belong there<commit_after>var config = require('getconfig');
var bucker = require('bucker').createLogger();
var redis = require("redis");
var uid = require('node-uuid');
var moment = require('moment');
var githubhook = require('githubhook');
var client = redis.createClient(config.redis.port, config.redis.host);
var github = githubhook({ port: config.github.port, logger: bucker });

client.on('error', function (err) {
    bucker.log('redis error ' + err);
});

github.listen();

github.on('*', function (event, repo, ref, data) {
    bucker.log('sending ' + repo + ' ' + ref + ' event');

    eventData = {
        id: uuid.v1(),
        type: 'github',
        parent_id: '',
        timestamp: moment.utc().unix() * 1000,
        payload: { 'repo': repo, 'ref': ref, 'data': data }
    };

    client.publish('github', JSON.stringify(eventData, null, 2));
});<|endoftext|>


<commit_before>'use strict';

const vendorController = {};

vendorController.render = function(ctx, next) {
  vendorController.fetchExp(ctx.params.id);
  next();
};

vendorController.fetchExp = function(commId) {
  superagent
    .get('/lunch/vendors')
    .set('authorization', localStorage.getItem('token'))
    .end((err, res) => {
      if (err) throw err;
      vendorView.populateHandlebars(res.body);
    });
};<commit_msg>Update vendor-controller.js<commit_after>'use strict';

const vendorController = {};

vendorController.render = function(ctx, next) {
  vendorController.fetchExp(ctx.params.id);
  next();
};

vendorController.fetchExp = function() {
  superagent
    .get('/lunch/vendors')
    .set('authorization', localStorage.getItem('token'))
    .end((err, res) => {
      if (err) throw err;
      vendorView.populateHandlebars(res.body);
    });
};
<|endoftext|>


<commit_before>var timeouts = {
    keydown: null
}

var entryForm = {
    form: function(){return $("#entry_form");},
    fields: {
        url: function(){return $('input#entry_url');},
        title: function(){return $('input#entry_title');},
        categories: function(){return $('input[name="entry[category]"]');},
        notificationSpan: function(){return $('span#metainfo-notification');}
    }
}

var application = {
    getMetaInfo: function($urlElement){
        entryForm.fields.notificationSpan().html('trying to retrieve URL meta data ...');
        $.ajax({
            url: mentalNote.route.url_metainfo,
            dataType: 'json',
            data: {
                url: $urlElement.val()
            },
            success: function(data){
                entryForm.fields.notificationSpan().html('');

                if (entryForm.fields.title().val() == '') {
                    entryForm.fields.title().val(data.title);
                }

                var id = entryForm.fields.categories().filter('[value=' + data.category + ']').attr('id');
                if (id) {
                    $('[for=' + id + ']').trigger('click');
                }
            },
            error: function() {
                entryForm.fields.notificationSpan().html('error retrieving URL meta data');
            }
        });
    },
    getMetaInfoDelayed: function(){
        var $element = $(this);
        clearTimeout(timeouts.keydown);
        timeouts.keydown = setTimeout(function(){application.getMetaInfo($element)}, 500);
    },
    registerEvents: function($domElement) {

        entryForm.fields.url().keydown(application.getMetaInfoDelayed);
        entryForm.form().keydown(function(event) {
            if (event.ctrlKey && event.keyCode == 13) {
                entryForm.form().submit();
            }
        });

        $domElement.find('.modal-ajax-form').modalAjaxForm({
            onComplete: function($element){
                application.registerEvents($element);
                $element.find(':text').first().focus();
                if (mentalNote.addUrl.length > 0) {
                    entryForm.fields.url()
                        .val(mentalNote.addUrl)
                        .trigger('keydown')
                    ;
                    mentalNote.addUrl = undefined;
                }
            }
        });

        var tagInput = $("#entry_tags");
        if (tagInput.length > 0) {

            tagInput.select2({
                tokenSeperator: [','],
                tags: application.searchTags()
            });
        }

        $('.visit-link').mousedown(function(e){
            $.ajax($(this).data('link'),{
                  type: 'POST'
            });
        });

        $('div.entry-list').jscroll({
            loadingHtml: '
loading ...
',
            padding: 20,
            nextSelector: 'ul.pagination li.next a',
            contentSelector: 'div.entry-list'
        });

    },
    searchTags: function(query) {
        var tags = null;
        $.ajax({
            url: mentalNote.route.tag_search,
            dataType: 'json',
            success: function(data) {
                tags = data;
            },
            async: false
        });

        return tags;
    },
    checkForAddURL: function() {
        var $button = $("#add-url");
        if (mentalNote.addUrl.length > 0) {
            $button.trigger('click');
        }
    }
}

// all JS is already loading defered
// therefore document.ready und window.load already happened
// and won't be triggered again

application.registerEvents($(document));
$('.deferred-image').imageloader();

application.checkForAddURL();

<commit_msg>fixes #26<commit_after>var timeouts = {
    keydown: null
}

var entryForm = {
    form: function(){return $("#entry_form");},
    fields: {
        url: function(){return $('input#entry_url');},
        title: function(){return $('input#entry_title');},
        categories: function(){return $('input[name="entry[category]"]');},
        notificationSpan: function(){return $('span#metainfo-notification');}
    }
}

var application = {
    getMetaInfo: function($urlElement){
        entryForm.fields.notificationSpan().html('trying to retrieve URL meta data ...');
        $.ajax({
            url: mentalNote.route.url_metainfo,
            dataType: 'json',
            data: {
                url: $urlElement.val()
            },
            success: function(data){
                entryForm.fields.notificationSpan().html('');

                if (entryForm.fields.title().val() == '') {
                    entryForm.fields.title().val(data.title);
                }

                var id = entryForm.fields.categories().filter('[value=' + data.category + ']').attr('id');
                if (id) {
                    $('[for=' + id + ']').trigger('click');
                }
            },
            error: function() {
                entryForm.fields.notificationSpan().html('error retrieving URL meta data');
            }
        });
    },
    getMetaInfoDelayed: function(){
        var $element = $(this);
        clearTimeout(timeouts.keydown);
        timeouts.keydown = setTimeout(function(){application.getMetaInfo($element)}, 500);
    },
    registerEvents: function($domElement) {

        entryForm.fields.url().keydown(application.getMetaInfoDelayed);
        entryForm.form().keydown(function(event) {
            if (event.ctrlKey && event.keyCode == 13) {
                entryForm.form().submit();
            }
        });

        $domElement.find('.modal-ajax-form').modalAjaxForm({
            onComplete: function($element){
                application.registerEvents($element);
                $element.find(':text').first().focus();
                if (mentalNote.addUrl.length > 0) {
                    entryForm.fields.url()
                        .val(mentalNote.addUrl)
                        .trigger('keydown')
                    ;
                    mentalNote.addUrl = undefined;
                }
            }
        });

        var tagInput = $("#entry_tags");
        if (tagInput.length > 0) {

            tagInput.select2({
                tokenSeperator: [','],
                tags: application.searchTags()
            });
        }

        $('.visit-link').mousedown(function(e){
            $.ajax($(this).data('link'),{
                  type: 'POST'
            });
        });

        $('div.entry-list').jscroll({
            loadingHtml: '
loading ...
',
            padding: 20,
            nextSelector: 'ul.pagination li.next a',
            contentSelector: 'div.entry-list',
            callback: function() { $('.deferred-image').imageloader(); }
        });

    },
    searchTags: function(query) {
        var tags = null;
        $.ajax({
            url: mentalNote.route.tag_search,
            dataType: 'json',
            success: function(data) {
                tags = data;
            },
            async: false
        });

        return tags;
    },
    checkForAddURL: function() {
        var $button = $("#add-url");
        if (mentalNote.addUrl.length > 0) {
            $button.trigger('click');
        }
    }
}

// all JS is already loading defered
// therefore document.ready und window.load already happened
// and won't be triggered again

application.registerEvents($(document));
$('.deferred-image').imageloader();

application.checkForAddURL();

<|endoftext|>


<commit_before>(function () {
  'use strict';

  var module = angular.module('sticky', []);

  // Directive: sticky
  //
  module.directive('sticky', ['$window', function ($window) {
      return {
        restrict: 'A', // this directive can only be used as an attribute.
        scope: {
          disabled: '=disabledSticky'
        },
        link: function linkFn($scope, $elem, $attrs) {
          // Setting scope
          var stickyLine;
          var stickyBottomLine;
          var placeholder;
          var isSticking = false;
          var originalOffset;

          // Optional Classes
          var stickyClass = $attrs.stickyClass || '';
          var unstickyClass = $attrs.unstickyClass || '';
          var bodyClass = $attrs.bodyClass || '';

          // Find scrollbar
          var scrollbar = deriveScrollingViewport ($elem);

          // Define elements
          var windowElement = angular.element($window);
          var scrollbarElement = angular.element(scrollbar);
          var $body = angular.element(document.body);

          // Define options
          var usePlaceholder = ($attrs.usePlaceholder !== 'false');
          var anchor = $attrs.anchor === 'bottom' ? 'bottom' : 'top';
          var confine = ($attrs.confine === 'true');
          // flag: can react to recalculating the initial CSS dimensions later as link executes prematurely. defaults to immediate checking
          var isStickyLayoutDeferred = $attrs.isStickyLayoutDeferred !== undefined ? ($attrs.isStickyLayoutDeferred === 'true') : false;

          // flag: is sticky content constantly observed for changes. Should be true if content uses ngBind to show text that may vary in size over time
          var isStickyLayoutWatched = $attrs.isStickyLayoutWatched !== undefined ? ($attrs.isStickyLayoutWatched === 'true') : true;

          var offset = $attrs.offset ? parseInt ($attrs.offset.replace(/px;?/, '')) : 0;
          var onStickyContentLayoutHeightWatchUnbind;

          // initial style
          var initialStyle = $elem.attr('style') || '';
          var initialCSS;

          /**
           * Initialize Sticky
           */
          var initSticky = function() {
            // Listeners
            scrollbarElement.on('scroll', checkIfShouldStick);
            windowElement.on('resize', $scope.$apply.bind($scope, onResize));

            memorizeDimensions (); // remember sticky's layout dimensions

            // Clean up
            $scope.$on('$destroy', onDestroy);
          };

          /**
           * need to recall sticky's DOM attributes ( make sure layout has occured)
           */
          function memorizeDimensions() {
            // immediate assignment, but there is the potential for wrong values if content not ready
            calculateStickyContentInitialDimensions ();

            // option to calculate the dimensions when layout is "ready"
            if (isStickyLayoutDeferred) {

              // logic: when this directive link() runs before the content has had a chance to layout on browser, height could be 0
              if (!$elem[0].getBoundingClientRect().height) {

                onStickyContentLayoutHeightWatchUnbind = $scope.$watch(
                    function() {
                      return $elem.height();
                    },

                    // state change: sticky content's height set
                    function onStickyContentLayoutInitialHeightSet(newValue, oldValue) {
                      if (newValue > 0) {
                        // now can memorize
                        calculateStickyContentInitialDimensions ();

                        if (!isStickyLayoutWatched) {
                          // preference was to do just a one-time async watch on the sticky's content; now stop watching
                          onStickyContentLayoutHeightWatchUnbind ();
                        }

                      }

                    }
                );
              }

              // any processing for when sticky layout is immediate
            } else {

            }

          }

          /**
           * set the dimensions for the defaults of the content block occupied by the sticky element
           */
          function calculateStickyContentInitialDimensions() {

            initialCSS = {
              zIndex: $elem.css('z-index'),
              top: $elem.css('top'),
              position: $elem.css('position'),
              marginTop: $elem.css('margin-top'),
              marginBottom: $elem.css('margin-bottom'),
              cssLeft: $elem.css('left'),
              height: $elem.css('height')
            };

          }

          /**
           * only change content box dimensions
           */
          function calculateStickyContentUpdateDimensions() {
            initialCSS.width = $elem.css('width');
            initialCSS.height = $elem.css('height');
          }

          /**
           * Determine if the element should be sticking or not.
           */
          var checkIfShouldStick = function() {

            // Check media query and disabled attribute
            if (($scope.disabled === true || mediaQueryMatches ()) && isSticking) {
              return unStickElement ();
            }

            // What's the document client top for?
            var scrollbarPosition = scrollbarYPos () - (document.documentElement.clientTop || 0);
            var shouldStick;

            if (anchor === 'top') {
              if (confine === true) {
                shouldStick = scrollbarPosition > stickyLine && scrollbarPosition <= stickyBottomLine;
              } else {
                shouldStick = scrollbarPosition > stickyLine;
              }
            } else {
              shouldStick = scrollbarPosition <= stickyLine;
            }

            // Switch the sticky mode if the element crosses the sticky line
            // $attrs.stickLimit - when it's equal to true it enables the user
            // to turn off the sticky function when the elem height is
            // bigger then the viewport
            var closestLine = getClosest (scrollbarPosition, stickyLine, stickyBottomLine);
            if (shouldStick && !shouldStickWithLimit ($attrs.stickLimit) && !isSticking) {
              stickElement (closestLine);
            } else if (!shouldStick && isSticking) {
              unStickElement (closestLine, scrollbarPosition);
            } else if (confine && !shouldStick && closestLine === 'bottom' && $elem.css('position') !== 'absolute') {
              // If we are confined to the parent, refresh, and past the stickyBottomLine
              // We should "remember" the original offset and unstick the element which places it at the stickyBottomLine
              originalOffset = elementsOffsetFromTop ($elem[0]);

              unStickElement (closestLine, scrollbarPosition);
            }
          };

          /**
           * determine the respective node that handles scrolling, defaulting to browser window
           */
          function deriveScrollingViewport(stickyNode) {
            // derive relevant scrolling by ascending the DOM tree
            var match = stickyNode.closest("sticky-scroll");
            return (match.length === 1) ? match.get(0) : $window;
          }

          /**
           * Seems to be undocumented functionality
           */
          function shouldStickWithLimit(shouldApplyWithLimit) {
            if (shouldApplyWithLimit === 'true') {
              return ($window.innerHeight - ($elem[0].offsetHeight + parseInt (offset)) < 0);
            } else {
              return false;
            }
          }

          /**
           * Finds the closest value from a set of numbers in an array.
           */
          function getClosest(scrollTop, stickyLine, stickyBottomLine) {
            var closest = 'top';
            var topDistance = Math.abs(scrollTop - stickyLine);
            var bottomDistance = Math.abs(scrollTop - stickyBottomLine);

            if (topDistance > bottomDistance) {
              closest = 'bottom';
            }

            return closest;
          }

          /**
           * Unsticks the element
           */
          function unStickElement(fromDirection) {
            $elem.attr('style', initialStyle);
            isSticking = false;

            $body.removeClass(bodyClass);
            $elem.removeClass(stickyClass);
            $elem.removeClass(stickyClass);
            $elem.addClass(unstickyClass);

            if (fromDirection === 'top') {
              $elem
                  .css('z-index', 10)
                  .css('width', $elem[0].offsetWidth)
                  .css('top', initialCSS.top)
                  .css('position', initialCSS.position)
                  .css('left', initialCSS.cssLeft)
                  .css('margin-top', initialCSS.marginTop)
                  .css('height', initialCSS.height);
            } else if (fromDirection === 'bottom' && confine === true) {
              $elem
                  .css('z-index', 10)
                  .css('width', $elem[0].offsetWidth)
                  .css('top', '')
                  .css('bottom', 0)
                  .css('position', 'absolute')
                  .css('left', initialCSS.cssLeft)
                  .css('margin-top', initialCSS.marginTop)
                  .css('margin-bottom', initialCSS.marginBottom)
                  .css('height', initialCSS.height);
            }

            if (placeholder && fromDirection === anchor) {
              placeholder.remove();
            }
          }

          /**
           * Sticks the element
           */
          function stickElement(closestLine) {
            // Set sticky state
            isSticking = true;

            initialCSS.offsetWidth = $elem[0].offsetWidth;

            $body.addClass(bodyClass);
            $elem.removeClass(unstickyClass);
            $elem.addClass(stickyClass);

            if (usePlaceholder && closestLine === anchor) {
              placeholder = angular.element('<div>');
              placeholder.css('height', $elem[0].offsetHeight + 'px');
              $elem.after(placeholder);
            }

            $elem
                .css('z-index', '10')
                .css('width', $elem[0].offsetWidth + 'px')
                .css('position', 'fixed')
                .css('left', $elem.css('left').replace('px', '') + 'px')
                .css(anchor, (offset + elementsOffsetFromTop (scrollbar)) + 'px')
                .css('margin-top', 0);

            if (anchor === 'bottom') {
              $elem.css('margin-bottom', 0);
            }
          }

          /**
           * Clean up directive
           */
          var onDestroy = function() {
            scrollbarElement.off('scroll', checkIfShouldStick);
            windowElement.off('resize', onResize);

            $body.removeClass(bodyClass);

            if (placeholder) {
              placeholder.remove();
            }
          };

          /**
           * Updates on resize.
           */
          var onResize = function() {
            unStickElement (anchor);
            checkIfShouldStick ();
          };

          /**
           * Triggered on load / digest cycle
           */
          var onDigest = function() {
            if ($scope.disabled === true) {
              return unStickElement ();
            }

            if (anchor === 'top') {
              return (originalOffset || elementsOffsetFromTop ($elem[0])) - elementsOffsetFromTop (scrollbar) + scrollbarYPos ();
            } else {
              return elementsOffsetFromTop ($elem[0]) - scrollbarHeight () + $elem[0].offsetHeight + scrollbarYPos ();
            }
          };

          /**
           * Triggered on change
           */
          var onChange = function(newVal, oldVal) {
            if (( newVal !== oldVal || typeof stickyLine === 'undefined' ) && !isSticking) {
              stickyLine = newVal - offset;

              // IF the sticky is confined, we want to make sure the parent is relatively positioned,
              // otherwise it won't bottom out properly

              if (confine) {
                $elem.parent().css({
                  'position': 'relative'
                });
              }

              // Get Parent height, so we know when to bottom out for confined stickies
              var parent = $elem.parent()[0];
              // Offset parent height by the elements height, if we're not using a placeholder
              var parentHeight = parseInt (parent.offsetHeight) - (usePlaceholder ? 0 : $elem[0].offsetHeight);

              // and now lets ensure we adhere to the bottom margins
              // TODO: make this an attribute? Maybe like ignore-margin?
              var marginBottom = parseInt ($elem.css('margin-bottom').replace(/px;?/, '')) || 0;

              // specify the bottom out line for the sticky to unstick
              var elementsDistanceFromTop = elementsOffsetFromTop ($elem[0]);
              var parentsDistanceFromTop = elementsOffsetFromTop (parent)
              var scrollbarDistanceFromTop = elementsOffsetFromTop (scrollbar);

              var elementsDistanceFromScrollbarStart = elementsDistanceFromTop - scrollbarDistanceFromTop;
              var elementsDistanceFromBottom = parentsDistanceFromTop + parentHeight - elementsDistanceFromTop;

              stickyBottomLine = elementsDistanceFromScrollbarStart + elementsDistanceFromBottom - $elem[0].offsetHeight - marginBottom - offset + +scrollbarYPos ();

              checkIfShouldStick ();
            }
          };

          /**
           * Helper Functions
           */

          /**
           * Fetch top offset of element
           */
          function elementsOffsetFromTop(element) {
            var offset = 0;

            if (element.getBoundingClientRect) {
              offset = element.getBoundingClientRect().top;
            }

            return offset;
          }

          /**
           * Retrieves top scroll distance
           */
          function scrollbarYPos() {
            var position;

            if (typeof scrollbar.scrollTop !== 'undefined') {
              position = scrollbar.scrollTop;
            } else if (typeof scrollbar.pageYOffset !== 'undefined') {
              position = scrollbar.pageYOffset;
            } else {
              position = document.documentElement.scrollTop;
            }

            return position;
          }

          /**
           * Determine scrollbar's height
           */
          function scrollbarHeight() {
            var height;

            if (scrollbarElement[0] instanceof HTMLElement) {
              // isn't bounding client rect cleaner than insane regex mess?
              height = $window.getComputedStyle(scrollbarElement[0], null)
                  .getPropertyValue('height')
                  .replace(/px;?/, '');
            } else {
              height = $window.innerHeight;
            }

            return parseInt (height) || 0;
          }

          /**
           * Checks if the media matches
           */
          function mediaQueryMatches() {
            var mediaQuery = $attrs.mediaQuery || false;
            var matchMedia = $window.matchMedia;

            return mediaQuery && !(matchMedia ('(' + mediaQuery + ')').matches || matchMedia (mediaQuery).matches);
          }

          // Setup watcher on digest and change
          $scope.$watch(onDigest, onChange);

          // Init the directive
          initSticky ();

          /**
           * +++++++++ public methods ( via parent ) +++++++++++++
           */

          /**
           * manually trigger a recalculation of the directive's private state of initial dimensions
           * Used when there are external factors that affect layout of the children DOM nodes of this element
           * Method exported into presumed parent scope, since this very directive uses isolate mode
           * long name chosen as to not collide with shared scope
           * Is this a common practice in Angular when battling isolate directives?
           */
            $scope.$parent.stickyUpdateModel = function() {
              calculateStickyContentUpdateDimensions();
            };

          /**
           * integration method allows for an outside client to reset the pinned state back to unpinned.
           * Useful for when refreshing the scrollable DIV content completely
           */

          /**
           * integration method allows for an outside client to reset the pinned state back to unpinned.
           * Useful for when refreshing the scrollable DIV content completely
           */
          $scope.$parent.stickyResetLayout = function() {

            function _resetScrollPosition() {

              // reset means content is scrolled to anchor position
              if (anchor === "top") {
                // window based scroller
                if (scrollbar === $window) {
                  $window.scrollTo(0, 0);
                  // DIV based sticky scroller
                } else {
                  if (scrollbar.scrollTop > 0) {
                    scrollbar.scrollTop = 0;
                  }
                }
              }
            }

            // only if pinned, force unpinning, otherwise height is inadvertently reset to 0
            if (isSticking) {
              unStickElement (anchor);
            }
            // remove hardcoded height
            $elem.css({"width": "", "height": "", "position": "", "top": ""});

            calculateStickyContentUpdateDimensions ();
            _resetScrollPosition ();
          };

        }
      };
    }]
  );

  // Shiv: matchMedia
  //
  window.matchMedia = window.matchMedia || (function () {
      var warning = 'angular-sticky: This browser does not support ' +
        'matchMedia, therefore the minWidth option will not work on ' +
        'this browser. Polyfill matchMedia to fix this issue.';

      if (window.console && console.warn) {
        console.warn(warning);
      }

      return function () {
        return {
          matches: true
        };
      };
    }());
}());
<commit_msg>another attribute on the initial CSS should be "reset"<commit_after>(function () {
  'use strict';

  var module = angular.module('sticky', []);

  // Directive: sticky
  //
  module.directive('sticky', ['$window', function ($window) {
      return {
        restrict: 'A', // this directive can only be used as an attribute.
        scope: {
          disabled: '=disabledSticky'
        },
        link: function linkFn($scope, $elem, $attrs) {
          // Setting scope
          var stickyLine;
          var stickyBottomLine;
          var placeholder;
          var isSticking = false;
          var originalOffset;

          // Optional Classes
          var stickyClass = $attrs.stickyClass || '';
          var unstickyClass = $attrs.unstickyClass || '';
          var bodyClass = $attrs.bodyClass || '';

          // Find scrollbar
          var scrollbar = deriveScrollingViewport ($elem);

          // Define elements
          var windowElement = angular.element($window);
          var scrollbarElement = angular.element(scrollbar);
          var $body = angular.element(document.body);

          // Define options
          var usePlaceholder = ($attrs.usePlaceholder !== 'false');
          var anchor = $attrs.anchor === 'bottom' ? 'bottom' : 'top';
          var confine = ($attrs.confine === 'true');
          // flag: can react to recalculating the initial CSS dimensions later as link executes prematurely. defaults to immediate checking
          var isStickyLayoutDeferred = $attrs.isStickyLayoutDeferred !== undefined ? ($attrs.isStickyLayoutDeferred === 'true') : false;

          // flag: is sticky content constantly observed for changes. Should be true if content uses ngBind to show text that may vary in size over time
          var isStickyLayoutWatched = $attrs.isStickyLayoutWatched !== undefined ? ($attrs.isStickyLayoutWatched === 'true') : true;
          var preferredStickyPosition = $elem.css('position'); // needed when resetting state

          var offset = $attrs.offset ? parseInt ($attrs.offset.replace(/px;?/, '')) : 0;
          var onStickyContentLayoutHeightWatchUnbind;

          // initial style
          var initialStyle = $elem.attr('style') || '';
          var initialCSS;

          /**
           * Initialize Sticky
           */
          var initSticky = function() {
            // Listeners
            scrollbarElement.on('scroll', checkIfShouldStick);
            windowElement.on('resize', $scope.$apply.bind($scope, onResize));

            memorizeDimensions (); // remember sticky's layout dimensions

            // Clean up
            $scope.$on('$destroy', onDestroy);
          };

          /**
           * need to recall sticky's DOM attributes ( make sure layout has occured)
           */
          function memorizeDimensions() {
            // immediate assignment, but there is the potential for wrong values if content not ready
            calculateStickyContentInitialDimensions ();

            // option to calculate the dimensions when layout is "ready"
            if (isStickyLayoutDeferred) {

              // logic: when this directive link() runs before the content has had a chance to layout on browser, height could be 0
              if (!$elem[0].getBoundingClientRect().height) {

                onStickyContentLayoutHeightWatchUnbind = $scope.$watch(
                    function() {
                      return $elem.height();
                    },

                    // state change: sticky content's height set
                    function onStickyContentLayoutInitialHeightSet(newValue, oldValue) {
                      if (newValue > 0) {
                        // now can memorize
                        calculateStickyContentInitialDimensions ();

                        if (!isStickyLayoutWatched) {
                          // preference was to do just a one-time async watch on the sticky's content; now stop watching
                          onStickyContentLayoutHeightWatchUnbind ();
                        }

                      }

                    }
                );
              }

              // any processing for when sticky layout is immediate
            } else {

            }

          }

          /**
           * set the dimensions for the defaults of the content block occupied by the sticky element
           */
          function calculateStickyContentInitialDimensions() {

            initialCSS = {
              zIndex: $elem.css('z-index'),
              top: $elem.css('top'),
              position: $elem.css('position'),
              marginTop: $elem.css('margin-top'),
              marginBottom: $elem.css('margin-bottom'),
              cssLeft: $elem.css('left'),
              height: $elem.css('height')
            };

          }

          /**
           * only change content box dimensions
           */
          function calculateStickyContentUpdateDimensions() {
            initialCSS.width = $elem.css('width');
            initialCSS.height = $elem.css('height');
          }

          /**
           * Determine if the element should be sticking or not.
           */
          var checkIfShouldStick = function() {

            // Check media query and disabled attribute
            if (($scope.disabled === true || mediaQueryMatches ()) && isSticking) {
              return unStickElement ();
            }

            // What's the document client top for?
            var scrollbarPosition = scrollbarYPos () - (document.documentElement.clientTop || 0);
            var shouldStick;

            if (anchor === 'top') {
              if (confine === true) {
                shouldStick = scrollbarPosition > stickyLine && scrollbarPosition <= stickyBottomLine;
              } else {
                shouldStick = scrollbarPosition > stickyLine;
              }
            } else {
              shouldStick = scrollbarPosition <= stickyLine;
            }

            // Switch the sticky mode if the element crosses the sticky line
            // $attrs.stickLimit - when it's equal to true it enables the user
            // to turn off the sticky function when the elem height is
            // bigger then the viewport
            var closestLine = getClosest (scrollbarPosition, stickyLine, stickyBottomLine);
            if (shouldStick && !shouldStickWithLimit ($attrs.stickLimit) && !isSticking) {
              stickElement (closestLine);
            } else if (!shouldStick && isSticking) {
              unStickElement (closestLine, scrollbarPosition);
            } else if (confine && !shouldStick && closestLine === 'bottom' && $elem.css('position') !== 'absolute') {
              // If we are confined to the parent, refresh, and past the stickyBottomLine
              // We should "remember" the original offset and unstick the element which places it at the stickyBottomLine
              originalOffset = elementsOffsetFromTop ($elem[0]);

              unStickElement (closestLine, scrollbarPosition);
            }
          };

          /**
           * determine the respective node that handles scrolling, defaulting to browser window
           */
          function deriveScrollingViewport(stickyNode) {
            // derive relevant scrolling by ascending the DOM tree
            var match = stickyNode.closest("sticky-scroll");
            return (match.length === 1) ? match.get(0) : $window;
          }

          /**
           * Seems to be undocumented functionality
           */
          function shouldStickWithLimit(shouldApplyWithLimit) {
            if (shouldApplyWithLimit === 'true') {
              return ($window.innerHeight - ($elem[0].offsetHeight + parseInt (offset)) < 0);
            } else {
              return false;
            }
          }

          /**
           * Finds the closest value from a set of numbers in an array.
           */
          function getClosest(scrollTop, stickyLine, stickyBottomLine) {
            var closest = 'top';
            var topDistance = Math.abs(scrollTop - stickyLine);
            var bottomDistance = Math.abs(scrollTop - stickyBottomLine);

            if (topDistance > bottomDistance) {
              closest = 'bottom';
            }

            return closest;
          }

          /**
           * Unsticks the element
           */
          function unStickElement(fromDirection) {
            $elem.attr('style', initialStyle);
            isSticking = false;

            $body.removeClass(bodyClass);
            $elem.removeClass(stickyClass);
            $elem.removeClass(stickyClass);
            $elem.addClass(unstickyClass);

            if (fromDirection === 'top') {
              $elem
                  .css('z-index', 10)
                  .css('width', $elem[0].offsetWidth)
                  .css('top', initialCSS.top)
                  .css('position', initialCSS.position)
                  .css('left', initialCSS.cssLeft)
                  .css('margin-top', initialCSS.marginTop)
                  .css('height', initialCSS.height);
            } else if (fromDirection === 'bottom' && confine === true) {
              $elem
                  .css('z-index', 10)
                  .css('width', $elem[0].offsetWidth)
                  .css('top', '')
                  .css('bottom', 0)
                  .css('position', 'absolute')
                  .css('left', initialCSS.cssLeft)
                  .css('margin-top', initialCSS.marginTop)
                  .css('margin-bottom', initialCSS.marginBottom)
                  .css('height', initialCSS.height);
            }

            if (placeholder && fromDirection === anchor) {
              placeholder.remove();
            }
          }

          /**
           * Sticks the element
           */
          function stickElement(closestLine) {
            // Set sticky state
            isSticking = true;

            initialCSS.offsetWidth = $elem[0].offsetWidth;

            $body.addClass(bodyClass);
            $elem.removeClass(unstickyClass);
            $elem.addClass(stickyClass);

            if (usePlaceholder && closestLine === anchor) {
              placeholder = angular.element('<div>');
              placeholder.css('height', $elem[0].offsetHeight + 'px');
              $elem.after(placeholder);
            }

            $elem
                .css('z-index', '10')
                .css('width', $elem[0].offsetWidth + 'px')
                .css('position', 'fixed')
                .css('left', $elem.css('left').replace('px', '') + 'px')
                .css(anchor, (offset + elementsOffsetFromTop (scrollbar)) + 'px')
                .css('margin-top', 0);

            if (anchor === 'bottom') {
              $elem.css('margin-bottom', 0);
            }
          }

          /**
           * Clean up directive
           */
          var onDestroy = function() {
            scrollbarElement.off('scroll', checkIfShouldStick);
            windowElement.off('resize', onResize);

            $body.removeClass(bodyClass);

            if (placeholder) {
              placeholder.remove();
            }
          };

          /**
           * Updates on resize.
           */
          var onResize = function() {
            unStickElement (anchor);
            checkIfShouldStick ();
          };

          /**
           * Triggered on load / digest cycle
           */
          var onDigest = function() {
            if ($scope.disabled === true) {
              return unStickElement ();
            }

            if (anchor === 'top') {
              return (originalOffset || elementsOffsetFromTop ($elem[0])) - elementsOffsetFromTop (scrollbar) + scrollbarYPos ();
            } else {
              return elementsOffsetFromTop ($elem[0]) - scrollbarHeight () + $elem[0].offsetHeight + scrollbarYPos ();
            }
          };

          /**
           * Triggered on change
           */
          var onChange = function(newVal, oldVal) {
            if (( newVal !== oldVal || typeof stickyLine === 'undefined' ) && !isSticking) {
              stickyLine = newVal - offset;

              // IF the sticky is confined, we want to make sure the parent is relatively positioned,
              // otherwise it won't bottom out properly

              if (confine) {
                $elem.parent().css({
                  'position': 'relative'
                });
              }

              // Get Parent height, so we know when to bottom out for confined stickies
              var parent = $elem.parent()[0];
              // Offset parent height by the elements height, if we're not using a placeholder
              var parentHeight = parseInt (parent.offsetHeight) - (usePlaceholder ? 0 : $elem[0].offsetHeight);

              // and now lets ensure we adhere to the bottom margins
              // TODO: make this an attribute? Maybe like ignore-margin?
              var marginBottom = parseInt ($elem.css('margin-bottom').replace(/px;?/, '')) || 0;

              // specify the bottom out line for the sticky to unstick
              var elementsDistanceFromTop = elementsOffsetFromTop ($elem[0]);
              var parentsDistanceFromTop = elementsOffsetFromTop (parent)
              var scrollbarDistanceFromTop = elementsOffsetFromTop (scrollbar);

              var elementsDistanceFromScrollbarStart = elementsDistanceFromTop - scrollbarDistanceFromTop;
              var elementsDistanceFromBottom = parentsDistanceFromTop + parentHeight - elementsDistanceFromTop;

              stickyBottomLine = elementsDistanceFromScrollbarStart + elementsDistanceFromBottom - $elem[0].offsetHeight - marginBottom - offset + +scrollbarYPos ();

              checkIfShouldStick ();
            }
          };

          /**
           * Helper Functions
           */

          /**
           * Fetch top offset of element
           */
          function elementsOffsetFromTop(element) {
            var offset = 0;

            if (element.getBoundingClientRect) {
              offset = element.getBoundingClientRect().top;
            }

            return offset;
          }

          /**
           * Retrieves top scroll distance
           */
          function scrollbarYPos() {
            var position;

            if (typeof scrollbar.scrollTop !== 'undefined') {
              position = scrollbar.scrollTop;
            } else if (typeof scrollbar.pageYOffset !== 'undefined') {
              position = scrollbar.pageYOffset;
            } else {
              position = document.documentElement.scrollTop;
            }

            return position;
          }

          /**
           * Determine scrollbar's height
           */
          function scrollbarHeight() {
            var height;

            if (scrollbarElement[0] instanceof HTMLElement) {
              // isn't bounding client rect cleaner than insane regex mess?
              height = $window.getComputedStyle(scrollbarElement[0], null)
                  .getPropertyValue('height')
                  .replace(/px;?/, '');
            } else {
              height = $window.innerHeight;
            }

            return parseInt (height) || 0;
          }

          /**
           * Checks if the media matches
           */
          function mediaQueryMatches() {
            var mediaQuery = $attrs.mediaQuery || false;
            var matchMedia = $window.matchMedia;

            return mediaQuery && !(matchMedia ('(' + mediaQuery + ')').matches || matchMedia (mediaQuery).matches);
          }

          // Setup watcher on digest and change
          $scope.$watch(onDigest, onChange);

          // Init the directive
          initSticky ();

          /**
           * +++++++++ public methods ( via parent ) +++++++++++++
           */

          /**
           * manually trigger a recalculation of the directive's private state of initial dimensions
           * Used when there are external factors that affect layout of the children DOM nodes of this element
           * Method exported into presumed parent scope, since this very directive uses isolate mode
           * long name chosen as to not collide with shared scope
           * Is this a common practice in Angular when battling isolate directives?
           */
            $scope.$parent.stickyUpdateModel = function() {
              calculateStickyContentUpdateDimensions();
            };

          /**
           * integration method allows for an outside client to reset the pinned state back to unpinned.
           * Useful for when refreshing the scrollable DIV content completely
           */

          /**
           * integration method allows for an outside client to reset the pinned state back to unpinned.
           * Useful for when refreshing the scrollable DIV content completely
           */
          $scope.$parent.stickyResetLayout = function() {

            function _resetScrollPosition() {

              // reset means content is scrolled to anchor position
              if (anchor === "top") {
                // window based scroller
                if (scrollbar === $window) {
                  $window.scrollTo(0, 0);
                  // DIV based sticky scroller
                } else {
                  if (scrollbar.scrollTop > 0) {
                    scrollbar.scrollTop = 0;
                  }
                }
              }
            }

            // only if pinned, force unpinning, otherwise height is inadvertently reset to 0
            if (isSticking) {
              unStickElement (anchor);
            }
            // remove hardcoded height
            $elem.css({"width": "", "height": "", "position": "", "top": ""});
            initialCSS.position = preferredStickyPosition; // revert

            calculateStickyContentUpdateDimensions ();
            _resetScrollPosition ();
          };

        }
      };
    }]
  );

  // Shiv: matchMedia
  //
  window.matchMedia = window.matchMedia || (function () {
      var warning = 'angular-sticky: This browser does not support ' +
        'matchMedia, therefore the minWidth option will not work on ' +
        'this browser. Polyfill matchMedia to fix this issue.';

      if (window.console && console.warn) {
        console.warn(warning);
      }

      return function () {
        return {
          matches: true
        };
      };
    }());
}());
<|endoftext|>


<commit_before>var proxyquire =  require('proxyquire');
var foo = proxyquire('../../app/controllers/Account.js');

exports.Register = {
	testValid :
		function(test){
		    var request = {
		    	body : {
		    		emailAddress : 'example@valid.com'
		    	}
		    };

		},
	testAlreadyExists :
		function(test) {
    test.ok(false, "this assertion should fail");
		},
	testInvalidEmailAddress :
		function (test) {
    test.ok(false, "this assertion should fail");
		},
	testPropertyExists :
		function (test) {
    test.ok(false, "this assertion should fail");
		},
}

exports.testSomethingElse = function(test){
    test.ok(false, "this assertion should fail");
    test.done();
};<commit_msg>failing tests<commit_after>var proxyquire =  require('proxyquire');
var foo = proxyquire('../../app/controllers/Account.js', {});

exports.Register = {
	testValid :
		function(test){
		    var request = {
		    	body : {
		    		emailAddress : 'example@valid.com'
		    	}
		    };
    test.ok(false, "this assertion should fail");
    test.done();

		},
	testAlreadyExists :
		function(test) {
    test.ok(false, "this assertion should fail");
    test.done();
		},
	testInvalidEmailAddress :
		function (test) {
    test.ok(false, "this assertion should fail");
    test.done();
		},
	testPropertyExists :
		function (test) {
    test.ok(false, "this assertion should fail");
    test.done();
		},
}

exports.testSomethingElse = function(test){
    test.ok(false, "this assertion should fail");
    test.done();
};<|endoftext|>


<commit_before>
var gulp = require('gulp');
var mocha = require('gulp-mocha');

gulp.task('mocha', function() {
  return  gulp.src(['test/cs1a.test.js', 'test/cs2a.test.js', 'test/cs3a.test.js', 'test/e3x.test.js'], { read: false })
              .pipe(mocha({ reporter: 'list' }))
              .on('error', function(){
              })
              .on('end', function(){

              });
});

gulp.task('dev', ['mocha'], function() {

})
<commit_msg>add unitTests and srcfiles to watching mocha and chext<commit_after>
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var watch = require('gulp-watch')
var chext = require("chext")

var unitTests =  ['test/cs1a.test.js', 'test/cs2a.test.js', 'test/cs3a.test.js', 'test/e3x.test.js'];
var srcFiles = ['ciphers/**/*.js', "e3x.js"]

gulp.task('mocha', function() {
  return  gulp.src( unitTests, { read: false })
              .pipe(mocha({ reporter: 'list' }))
              .on('error', function(){
              })
              .on('end', function(){

              });
});

gulp.task('dev', ['mocha'], function() {
  var ch = new chext()

  ch.watchify(unitTests)

  ch.on("testing_complete",function(results){
    console.log("tests complete", results)
  })

  gulp.watch(unitTests.concat(srcFiles), ["mocha"])
})
<|endoftext|>


<commit_before>var utilities = require('./utilities');

// argv[2] (required): the name of the active file
// argv[3] (required): the ipv4 address of the server to contact first

var activeFileName = process.argv[2];

var fileContents = "";
var tmpFileContents = fileContents;

var otherServerUri = "http://" + process.argv[3] + ':' +
  utilities.SERVER_HTTP_PORT;

var p = new utilities.p2p.peer(otherServerUri, utilities.SERVER_HTTP_PORT);

// TODO: make proxy solution for network with firewall which blocks all ports

utilities.fs.writeFileSync(activeFileName, fileContents);
utilities.fs.writeFileSync(
  activeFileName + utilities.TMP_FILENAME_SUFFIX,
  tmpFileContents);

loadEmacsLisp(utilities.LISP_FILE_PATH, function() {
  openFileInEmacs(activeFileName, function() {
    p.start(
      // client init function
      function() {
        console.log("speaking on " + utilities.os.hostname() + ':' +
          utilities.SERVER_HTTP_PORT);
      },

      // client socket function
      function(socket) {
        // get user id, filename, and file contents; write to file
        socket.on('connection_info', function(
          connectionInfo) {
          activeFileName = connectionInfo.activeFileName;
          fileContents = connectionInfo.fileContents;
          tmpFileContents = fileContents;
          utilities.fs.writeFile(
            activeFileName,
            fileContents,
            function(error) {
              if (error) {
                console.log(error);
              }
              updateBufferInEmacs(activeFileName);
              console.log("connection info received");

              socket.on('file_send', function(sentFileBuffer) {
                // if not self socket
                if ("http://127.0.0.1:" + utilities.SERVER_HTTP_PORT !=
                  utilities.p2p.client.getUriOfSocket(
                    socket)) {
                  utilities.fs.writeFile(
                    activeFileName + utilities.TMP_FILENAME_SUFFIX,
                    sentFileBuffer,
                    function(error) {
                      if (error) {
                        console.log(error);
                      }
                      updateBufferInEmacs(activeFileName +
                        utilities.TMP_FILENAME_SUFFIX);
                      console.log("file received");
                    });
                }
              });

              socket.on('file_diff', function(sentFilePatch) {
                if ("http://127.0.0.1:" + utilities.SERVER_HTTP_PORT !=
                  utilities.p2p.client.getUriOfSocket(
                    socket)) {
                  utilities.fs.writeFile(
                    activeFileName +
                    utilities.DIFF_FILENAME_SUFFIX,
                    JSON.stringify(sentFilePatch),
                    function(error) {
                      if (error) {
                        console.log(error);
                      }
                      console.log(
                        JSON.stringify(
                          sentFilePatch));
                      performPatchFromFile(
                        activeFileName,
                        activeFileName +
                        utilities.DIFF_FILENAME_SUFFIX
                      );
                      console.log("diff received");
                    });
                }
              });
            });
        });
      },

      // server init function
      function() {
        console.log("listening on " + utilities.os.hostname() + ':' +
          utilities.SERVER_HTTP_PORT);
        // if (process.argv[3] == "127.0.0.1") {
        setInterval(broadcastDiff, utilities.DIFF_SYNC_TIME);
        setInterval(broadcastBuffer, utilities.FILE_SYNC_TIME);
        // }
      },

      // server socket function
      function(socket) {
        socket.emit('connection_info', {
          activeFileName: activeFileName,
          fileContents: fileContents
        });
      });
  });
});

// requires emacs to be open and server to be on
function openFileInEmacs(filename, callback) {
  var emacsOpenFile = utilities.spawn('emacsclient', ['-n', filename]);
  setupEmacsSpawn(
    emacsOpenFile,
    "error: file could not be loaded",
    "file loaded",
    function() {
      console.log("FILE OPENED :DDDDDDD");
      callback();
    });
}

function broadcastBuffer() {
  var emacsWriteFile = spawnEmacsCommand(
    "send-buffer-to-file", "\"" + activeFileName + "\"",
    "\"" + activeFileName + utilities.TMP_FILENAME_SUFFIX + "\"");
  setupEmacsSpawn(
    emacsWriteFile,
    "error: buffer could not be saved",
    "file broadcasted",
    function() {
      utilities.fs.readFile(
        activeFileName + utilities.TMP_FILENAME_SUFFIX,
        function(error, fileContents) {
          if (error) {
            console.log(error);
          }
          if (34 == error.errno && 'ENOENT' == error.code){
            fileContents = "";
          }
          p.emit('file_send', fileContents.toString());
        });
    });
}

function writeBufferToFile(callback) {
  var emacsWriteFile = spawnEmacsCommand(
    "send-buffer-to-file", "\"" + activeFileName + "\"",
    "\"" + activeFileName + "\"");
  setupEmacsSpawn(
    emacsWriteFile,
    "error: buffer could not be saved",
    "file broadcasted",
    function() {
      utilities.fs.readFile(
        activeFileName + utilities.TMP_FILENAME_SUFFIX,
        function(error, fileContents) {
          if (error) {
            console.log(error);
          }
          if ("function" == typeof(callback)) {
            callback();
          }
        });
    });
}

function broadcastDiff() {
  var emacsWriteFile = spawnEmacsCommand(
    "send-buffer-to-file", "\"" + activeFileName + "\"",
    "\"" + activeFileName + utilities.TMP_FILENAME_SUFFIX + "\"");
  setupEmacsSpawn(
    emacsWriteFile,
    "error: buffer could not be loaded",
    "diff broadcasted",
    function() {
      utilities.fs.readFile(
        activeFileName + utilities.TMP_FILENAME_SUFFIX,
        function(tmpError, tmpFileContents) {
          if (tmpError) {
            console.log(tmpError);
            tmpFileContents = "";
          }
          utilities.fs.readFile(
            activeFileName,
            function(curError, curFileContents) {
              if (curError) {
                console.log(curError);
              }
              utilities.fs.writeFile(
                activeFileName,
                tmpFileContents,
                function(error) {
                  if (error) {
                    console.log(error);
                  }
                  p.emit('file_diff',
                    utilities.diff_match_patch.patch_make(
                      curFileContents.toString(),
                      tmpFileContents.toString()));
                }
              );
            });
        });
    });
}

function updateBufferInEmacs(filename, callback) {
  var emacsReadFile = spawnEmacsCommand(
    "read-buffer-from-file", "\"" + filename + "\"");
  setupEmacsSpawn(
    emacsReadFile,
    "error: file could not be read",
    "file read",
    callback);
}

function loadEmacsLisp(filename, callback) {
  var emacsLoadFile = spawnEmacsCommand(
    "load-file", "\"" + filename + "\""
  );
  setupEmacsSpawn(
    emacsLoadFile,
    "error: file could not be loaded",
    "file loaded",
    callback);
}

function performPatchFromFile(filename, callback) {
  var emacsPerformPatch = spawnEmacsCommand(
    "perform-patch-from-file", "\"" + filename + "\"",
    "\"" + filename + utilities.DIFF_FILENAME_SUFFIX + "\""
  );
  setupEmacsSpawn(
    emacsPerformPatch,
    "error: patch could not be performed",
    "file loaded",
    callback);
}

// helper function
function setupEmacsSpawn(spawnProcess, errorText, successText, callback) {
  spawnProcess.stdout.on('data', function(data) {
    console.log("emacs stdout: " + data);
  });
  spawnProcess.stderr.on('data', function(data) {
    console.log("emacs stderr: " + data);
  });
  spawnProcess.on('exit', function(return_code, signal) {
    if (return_code != 0) {
      console.log(errorText);
    } else {
      console.log(successText);
    }
    if ("function" == typeof(callback)) {
      callback();
    }
  });
}

// helper function
// takes variable number of arguments
// returns spawn object
function spawnEmacsCommand() {
  var evalArg = "(";
  for (var i = 0; i < arguments.length; ++i) {
    evalArg += arguments[i] + " ";
  }
  evalArg += ")";
  return utilities.spawn('emacsclient', ['-e', evalArg]);
}
<commit_msg>fixed again<commit_after>var utilities = require('./utilities');

// argv[2] (required): the name of the active file
// argv[3] (required): the ipv4 address of the server to contact first

var activeFileName = process.argv[2];

var fileContents = "";
var tmpFileContents = fileContents;

var otherServerUri = "http://" + process.argv[3] + ':' +
  utilities.SERVER_HTTP_PORT;

var p = new utilities.p2p.peer(otherServerUri, utilities.SERVER_HTTP_PORT);

// TODO: make proxy solution for network with firewall which blocks all ports

utilities.fs.writeFileSync(activeFileName, fileContents);
utilities.fs.writeFileSync(
  activeFileName + utilities.TMP_FILENAME_SUFFIX,
  tmpFileContents);

loadEmacsLisp(utilities.LISP_FILE_PATH, function() {
  openFileInEmacs(activeFileName, function() {
    p.start(
      // client init function
      function() {
        console.log("speaking on " + utilities.os.hostname() + ':' +
          utilities.SERVER_HTTP_PORT);
      },

      // client socket function
      function(socket) {
        // get user id, filename, and file contents; write to file
        socket.on('connection_info', function(
          connectionInfo) {
          activeFileName = connectionInfo.activeFileName;
          fileContents = connectionInfo.fileContents;
          tmpFileContents = fileContents;
          utilities.fs.writeFile(
            activeFileName,
            fileContents,
            function(error) {
              if (error) {
                console.log(error);
              }
              updateBufferInEmacs(activeFileName);
              console.log("connection info received");

              socket.on('file_send', function(sentFileBuffer) {
                // if not self socket
                if ("http://127.0.0.1:" + utilities.SERVER_HTTP_PORT !=
                  utilities.p2p.client.getUriOfSocket(
                    socket)) {
                  utilities.fs.writeFile(
                    activeFileName + utilities.TMP_FILENAME_SUFFIX,
                    sentFileBuffer,
                    function(error) {
                      if (error) {
                        console.log(error);
                      }
                      updateBufferInEmacs(activeFileName +
                        utilities.TMP_FILENAME_SUFFIX);
                      console.log("file received");
                    });
                }
              });

              socket.on('file_diff', function(sentFilePatch) {
                if ("http://127.0.0.1:" + utilities.SERVER_HTTP_PORT !=
                  utilities.p2p.client.getUriOfSocket(
                    socket)) {
                  utilities.fs.writeFile(
                    activeFileName +
                    utilities.DIFF_FILENAME_SUFFIX,
                    JSON.stringify(sentFilePatch),
                    function(error) {
                      if (error) {
                        console.log(error);
                      }
                      console.log(
                        JSON.stringify(
                          sentFilePatch));
                      performPatchFromFile(
                        activeFileName,
                        activeFileName +
                        utilities.DIFF_FILENAME_SUFFIX
                      );
                      console.log("diff received");
                    });
                }
              });
            });
        });
      },

      // server init function
      function() {
        console.log("listening on " + utilities.os.hostname() + ':' +
          utilities.SERVER_HTTP_PORT);
        // if (process.argv[3] == "127.0.0.1") {
        setInterval(broadcastDiff, utilities.DIFF_SYNC_TIME);
        setInterval(broadcastBuffer, utilities.FILE_SYNC_TIME);
        // }
      },

      // server socket function
      function(socket) {
        socket.emit('connection_info', {
          activeFileName: activeFileName,
          fileContents: fileContents
        });
      });
  });
});

// requires emacs to be open and server to be on
function openFileInEmacs(filename, callback) {
  var emacsOpenFile = utilities.spawn('emacsclient', ['-n', filename]);
  setupEmacsSpawn(
    emacsOpenFile,
    "error: file could not be loaded",
    "file loaded",
    function() {
      console.log("FILE OPENED :DDDDDDD");
      callback();
    });
}

function broadcastBuffer() {
  var emacsWriteFile = spawnEmacsCommand(
    "send-buffer-to-file", "\"" + activeFileName + "\"",
    "\"" + activeFileName + utilities.TMP_FILENAME_SUFFIX + "\"");
  setupEmacsSpawn(
    emacsWriteFile,
    "error: buffer could not be saved",
    "file broadcasted",
    function() {
      utilities.fs.readFile(
        activeFileName + utilities.TMP_FILENAME_SUFFIX,
        function(error, fileContents) {
          if (error) {
            console.log(error);
            if (34 == error.errno && 'ENOENT' == error.code) {
              fileContents = "";
            }
          }
          p.emit('file_send', fileContents.toString());
        });
    });
}

function writeBufferToFile(callback) {
  var emacsWriteFile = spawnEmacsCommand(
    "send-buffer-to-file", "\"" + activeFileName + "\"",
    "\"" + activeFileName + "\"");
  setupEmacsSpawn(
    emacsWriteFile,
    "error: buffer could not be saved",
    "file broadcasted",
    function() {
      utilities.fs.readFile(
        activeFileName + utilities.TMP_FILENAME_SUFFIX,
        function(error, fileContents) {
          if (error) {
            console.log(error);
          }
          if ("function" == typeof(callback)) {
            callback();
          }
        });
    });
}

function broadcastDiff() {
  var emacsWriteFile = spawnEmacsCommand(
    "send-buffer-to-file", "\"" + activeFileName + "\"",
    "\"" + activeFileName + utilities.TMP_FILENAME_SUFFIX + "\"");
  setupEmacsSpawn(
    emacsWriteFile,
    "error: buffer could not be loaded",
    "diff broadcasted",
    function() {
      utilities.fs.readFile(
        activeFileName + utilities.TMP_FILENAME_SUFFIX,
        function(tmpError, tmpFileContents) {
          if (tmpError) {
            console.log(tmpError);
            tmpFileContents = "";
          }
          utilities.fs.readFile(
            activeFileName,
            function(curError, curFileContents) {
              if (curError) {
                console.log(curError);
              }
              utilities.fs.writeFile(
                activeFileName,
                tmpFileContents,
                function(error) {
                  if (error) {
                    console.log(error);
                  }
                  p.emit('file_diff',
                    utilities.diff_match_patch.patch_make(
                      curFileContents.toString(),
                      tmpFileContents.toString()));
                }
              );
            });
        });
    });
}

function updateBufferInEmacs(filename, callback) {
  var emacsReadFile = spawnEmacsCommand(
    "read-buffer-from-file", "\"" + filename + "\"");
  setupEmacsSpawn(
    emacsReadFile,
    "error: file could not be read",
    "file read",
    callback);
}

function loadEmacsLisp(filename, callback) {
  var emacsLoadFile = spawnEmacsCommand(
    "load-file", "\"" + filename + "\""
  );
  setupEmacsSpawn(
    emacsLoadFile,
    "error: file could not be loaded",
    "file loaded",
    callback);
}

function performPatchFromFile(filename, callback) {
  var emacsPerformPatch = spawnEmacsCommand(
    "perform-patch-from-file", "\"" + filename + "\"",
    "\"" + filename + utilities.DIFF_FILENAME_SUFFIX + "\""
  );
  setupEmacsSpawn(
    emacsPerformPatch,
    "error: patch could not be performed",
    "file loaded",
    callback);
}

// helper function
function setupEmacsSpawn(spawnProcess, errorText, successText, callback) {
  spawnProcess.stdout.on('data', function(data) {
    console.log("emacs stdout: " + data);
  });
  spawnProcess.stderr.on('data', function(data) {
    console.log("emacs stderr: " + data);
  });
  spawnProcess.on('exit', function(return_code, signal) {
    if (return_code != 0) {
      console.log(errorText);
    } else {
      console.log(successText);
    }
    if ("function" == typeof(callback)) {
      callback();
    }
  });
}

// helper function
// takes variable number of arguments
// returns spawn object
function spawnEmacsCommand() {
  var evalArg = "(";
  for (var i = 0; i < arguments.length; ++i) {
    evalArg += arguments[i] + " ";
  }
  evalArg += ")";
  return utilities.spawn('emacsclient', ['-e', evalArg]);
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

somospnt.util.ui.places = (function() {
    var placeListTemplate, placeInfoTemplate;
    var placeClass = "myplaces-establecimiento-";
    var placesChangeCallback, clickPlaceCallback;

    function init(listTemplate, infoTemplate, placesChange, clickPlace) {
        placeListTemplate = $.templates(listTemplate);
        placeInfoTemplate = $.templates(infoTemplate);
        placesChangeCallback = placesChange;
        clickPlaceCallback = clickPlace;
        $('.myplaces-placesList ul').on('click', 'li', showInformationOfPlace);
        $('.myplaces-infoContenido').append('
To see the details of a place please click on it.
');
    }

    function showInformationOfPlace() {
        var placeLi = $(this);
        var location = placeLi.data("location");
        $('.myplaces-selectedPlaces').removeClass('myplaces-selectedPlaces');
        placeLi.addClass('myplaces-selectedPlaces');
        $('.myplaces-infoContenido').empty().append(placeInfoTemplate.render(location.place));
        somospnt.util.ui.map.highlightPlace(location);

        clickPlaceCallback();
    }

    function showLocations(locations) {

        var selectedLocation = $('.myplaces-selectedPlaces').data("location");

        var placeUl = $('.myplaces-placesList ul');

        placeUl.empty();

        if (locations.length) {
            for (var i = 0; i < locations.length; i++) {

                placeUl.append(
                        $(placeListTemplate.render(locations[i].place))
                        .addClass(placeClass + locations[i].place.id)
                        .data("location", locations[i])
                        );
            }
        } else {
            placeUl.append('
No results to display in this area
');
        }

        if (selectedLocation) {
            $("." + placeClass + selectedLocation.place.id).addClass('myplaces-selectedPlaces');
        }

        placesChangeCallback();
    }

    function selecteById(id) {
        $("." + placeClass + id).click();
    }

    function getSelectedLocation() {
        return $('.myplaces-selectedPlaces').data("location");
    }

    function unselect() {
        $('.myplaces-selectedPlaces').removeClass("myplaces-selectedPlaces");
        $('.myplaces-infoContenido').empty().append('
To see the details of a place please click on it.
');
    }

    return {
        init: init,
        showLocations: showLocations,
        selecteById: selecteById,
        getSelectedLocation: getSelectedLocation,
        unselect: unselect
    };

})();<commit_msg>Cambié una palabra que había quedado en inglés.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

somospnt.util.ui.places = (function() {
    var placeListTemplate, placeInfoTemplate;
    var placeClass = "myplaces-place-";
    var placesChangeCallback, clickPlaceCallback;

    function init(listTemplate, infoTemplate, placesChange, clickPlace) {
        placeListTemplate = $.templates(listTemplate);
        placeInfoTemplate = $.templates(infoTemplate);
        placesChangeCallback = placesChange;
        clickPlaceCallback = clickPlace;
        $('.myplaces-placesList ul').on('click', 'li', showInformationOfPlace);
        $('.myplaces-infoContenido').append('
To see the details of a place please click on it.
');
    }

    function showInformationOfPlace() {
        var placeLi = $(this);
        var location = placeLi.data("location");
        $('.myplaces-selectedPlaces').removeClass('myplaces-selectedPlaces');
        placeLi.addClass('myplaces-selectedPlaces');
        $('.myplaces-infoContenido').empty().append(placeInfoTemplate.render(location.place));
        somospnt.util.ui.map.highlightPlace(location);

        clickPlaceCallback();
    }

    function showLocations(locations) {

        var selectedLocation = $('.myplaces-selectedPlaces').data("location");

        var placeUl = $('.myplaces-placesList ul');

        placeUl.empty();

        if (locations.length) {
            for (var i = 0; i < locations.length; i++) {

                placeUl.append(
                        $(placeListTemplate.render(locations[i].place))
                        .addClass(placeClass + locations[i].place.id)
                        .data("location", locations[i])
                        );
            }
        } else {
            placeUl.append('
No results to display in this area
');
        }

        if (selectedLocation) {
            $("." + placeClass + selectedLocation.place.id).addClass('myplaces-selectedPlaces');
        }

        placesChangeCallback();
    }

    function selecteById(id) {
        $("." + placeClass + id).click();
    }

    function getSelectedLocation() {
        return $('.myplaces-selectedPlaces').data("location");
    }

    function unselect() {
        $('.myplaces-selectedPlaces').removeClass("myplaces-selectedPlaces");
        $('.myplaces-infoContenido').empty().append('
To see the details of a place please click on it.
');
    }

    return {
        init: init,
        showLocations: showLocations,
        selecteById: selecteById,
        getSelectedLocation: getSelectedLocation,
        unselect: unselect
    };

})();<|endoftext|>


<commit_before>/*global define*/
/*jslint nomen: true*/
/*jshint browser: true, devel: true*/
define(function (require) {
    'use strict';

    var $ = require('jquery');
    var _ = require('underscore');
    var bootstrap = require('bootstrap');

    var scrollspy = require('oroui/js/scrollspy');
    var widgetControlInitializer = require('oroui/js/widget-control-initializer');
    var mediator = require('oroui/js/mediator');

    var pageRenderedCbPool = [];
    var layout = {};

    require('jquery-ui');
    require('jquery-ui-timepicker');

    layout.init = function (container) {
        container = $(container || document.body);
        this.styleForm(container);

        scrollspy.init(container);

        container.find('[data-toggle="tooltip"]').tooltip();

        this.initPopover($('form label'));
        widgetControlInitializer.init(container);

//        @todo: BAP-3374
//        layout.onPageRendered(function () {
//            scrollspy.top();
//        });
    };

    layout.initPopover = function (container) {
        var handlePopoverMouseout = function (e, popover) {
            var popoverHandler = $(e.relatedTarget).closest('.popover');
            if (!popoverHandler.length) {
                popover.data('popover-timer',
                    setTimeout(function () {
                        popover.popover('hide');
                        popover.data('popover-active', false);
                    }, 500));
            } else {
                popoverHandler.one('mouseout', function (evt) {
                    handlePopoverMouseout(evt, popover);
                });
            }
        };
        container.find('[data-toggle="popover"]')
            .popover({
                animation: true,
                delay: { show: 0, hide: 0 },
                html: true,
                trigger: 'manual'
            })
            .mouseover(function () {
                var popoverEl = $(this);
                clearTimeout(popoverEl.data('popover-timer'));
                if (!popoverEl.data('popover-active')) {
                    popoverEl.data('popover-active', true);
                    $(this).popover('show');
                }
            })
            .mouseout(function (e) {
                var popover = $(this);
                setTimeout(function () {
                    handlePopoverMouseout(e, popover);
                }, 500);
            });
    };

    layout.hideProgressBar = function () {
        var $bar = $('#progressbar');
        if ($bar.is(':visible')) {
            $bar.hide();
            $('#page').show();
        }
    };

    layout.styleForm = function (container) {
        if ($.isPlainObject($.uniform)) {
            var elements = $(container).find('input:file, select:not(.select2)');
            elements.uniform();
            elements.trigger('uniformInit');
        }
    };

    layout.onPageRendered = function (cb) {
        if (document.pageReady) {
            setTimeout(cb, 0);
        } else {
            pageRenderedCbPool.push(cb);
        }
    };

    layout.pageRendering = function () {
        document.pageReady = false;

        pageRenderedCbPool = [];
    };

    layout.pageRendered = function () {
        document.pageReady = true;

        _.each(pageRenderedCbPool, function (cb) {
            try {
                cb();
            } catch (ex) {
                if (console && (typeof console.log === 'function')) {
                    console.log(ex);
                }
            }
        });

        pageRenderedCbPool = [];
    };

    mediator.on('layout.init', function(element) {
        layout.init(element);
    });

    mediator.on('grid_load:complete', function(collection, element) {
        widgetControlInitializer.init(element);
    });

    mediator.on('grid_render:complete', function(element) {
        widgetControlInitializer.init(element);
    });

    return layout;
});
<commit_msg>BAP-3735: Open tooltip on mouse click, not on mouse over, and without animation - should work onclick and remove all animation     - change appearence behavior<commit_after>/*global define*/
/*jslint nomen: true*/
/*jshint browser: true, devel: true*/
define(function (require) {
    'use strict';

    var $ = require('jquery');
    var _ = require('underscore');
    var bootstrap = require('bootstrap');

    var scrollspy = require('oroui/js/scrollspy');
    var widgetControlInitializer = require('oroui/js/widget-control-initializer');
    var mediator = require('oroui/js/mediator');

    var pageRenderedCbPool = [];
    var layout = {};

    require('jquery-ui');
    require('jquery-ui-timepicker');

    layout.init = function (container) {
        container = $(container || document.body);
        this.styleForm(container);

        scrollspy.init(container);

        container.find('[data-toggle="tooltip"]').tooltip();

        this.initPopover($('form label'));
        widgetControlInitializer.init(container);

//        @todo: BAP-3374
//        layout.onPageRendered(function () {
//            scrollspy.top();
//        });
    };

    layout.initPopover = function (container) {
        var handlePopoverMouseout = function (e, popover) {
            var popoverHandler = $(e.relatedTarget).closest('.popover');
            if (!popoverHandler.length) {
                popover.data('popover-timer',
                    setTimeout(function () {
                        popover.popover('hide');
                        popover.data('popover-active', false);
                    }, 500));
            } else {
                popoverHandler.one('mouseout', function (evt) {
                    handlePopoverMouseout(evt, popover);
                });
            }
        };
        container.find('[data-toggle="popover"]')
            .popover({
                animation: false,
                delay: { show: 0, hide: 0 },
                html: true,
                trigger: 'manual'
            })
            .click(function () {
                var popoverEl = $(this);
                clearTimeout(popoverEl.data('popover-timer'));
                if (!popoverEl.data('popover-active')) {
                    popoverEl.data('popover-active', true);
                    $(this).popover('show');
                }
            })
            .mouseout(function (e) {
                var popover = $(this);
                setTimeout(function () {
                    handlePopoverMouseout(e, popover);
                }, 500);
            });
    };

    layout.hideProgressBar = function () {
        var $bar = $('#progressbar');
        if ($bar.is(':visible')) {
            $bar.hide();
            $('#page').show();
        }
    };

    layout.styleForm = function (container) {
        if ($.isPlainObject($.uniform)) {
            var elements = $(container).find('input:file, select:not(.select2)');
            elements.uniform();
            elements.trigger('uniformInit');
        }
    };

    layout.onPageRendered = function (cb) {
        if (document.pageReady) {
            setTimeout(cb, 0);
        } else {
            pageRenderedCbPool.push(cb);
        }
    };

    layout.pageRendering = function () {
        document.pageReady = false;

        pageRenderedCbPool = [];
    };

    layout.pageRendered = function () {
        document.pageReady = true;

        _.each(pageRenderedCbPool, function (cb) {
            try {
                cb();
            } catch (ex) {
                if (console && (typeof console.log === 'function')) {
                    console.log(ex);
                }
            }
        });

        pageRenderedCbPool = [];
    };

    mediator.on('layout.init', function(element) {
        layout.init(element);
    });

    mediator.on('grid_load:complete', function(collection, element) {
        widgetControlInitializer.init(element);
    });

    mediator.on('grid_render:complete', function(element) {
        widgetControlInitializer.init(element);
    });

    return layout;
});
<|endoftext|>