<commit_before>/*jshint multistr: true, unused: false*/

'use strict';

var $ = require('jquery'),
    NavMainComponent = require('../../../js/NavMainComponent');

$.fx.off = !$.fx.off

describe('NavMain component', function() {

    beforeEach(function() {
        this.$html = $('

').appendTo('html');
        this.$body = $('

').appendTo(this.$html);
        this.$markup = $('\
\

\
    Jadu\
\

\

\
          1\

\

\
          2\

\

\
          3\

\

\

\
\
    x\
\
    <form>\
      <input type="search" placeholder="search" />\
      <button>Go</button>\
    </form>\
\

\

\

\
            1.1\

\

\

\
\

\

\

\
            2.1\

\

\

\
\

\
\

\
').appendTo(this.$html);

        this.$navMain = this.$html.find('.nav-main');
        this.$closeLink = this.$html.find('[data-nav-action="close"]');
        this.$contentMain = this.$html.find('.content-main');

        this.$linkOne = this.$html.find('[href="#one"]');
        this.$linkTwo = this.$html.find('[href="#two"]');
        this.$linkThree = this.$html.find('[href="#three"]');
        this.$secondaryLinkOne = this.$html.find('[href="#one_one"]');
        this.$secondaryLinkTwo = this.$html.find('[href="#two_one"]');

        this.navMainComponent = new NavMainComponent(this.$html);

    });

    describe('clicking on the first primary nav link', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
        });

        it('should add the is-active class to the first link', function() {
            expect(this.$linkOne.hasClass('is-active')).to.be.true;
        });

        it('should open the secondary nav', function() {
            expect(this.$html.find('.nav-main').hasClass('is-open')).to.be.true;
        });

        it('should add the is-active class to the secondary sub navigation menu', function() {
            expect(this.$html.find('[data-nav="#one"]').hasClass('is-active')).to.be.true;
        });

        it('should not add the is-active class to the other sub navigation menus', function() {
            expect(this.$html.find('[data-nav="#two"]').hasClass('is-active')).to.be.false;
        });

    });

    describe('clicking the first, then the second primary nav link', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$linkTwo.click();
        });

        it('should add the is-active class to the second link', function() {
            expect(this.$linkTwo.hasClass('is-active')).to.be.true;
        });

        it('should remove the is-active class from the first link', function() {
            expect(this.$linkOne.hasClass('is-active')).to.be.false;
        });

        it('should add the is-active class to the second sub navigation menu', function() {
            expect(this.$html.find('[data-nav="#two"]').hasClass('is-active')).to.be.true;
        });

        it('should remove the is-active class from the first sub navigation menu', function() {
            expect(this.$html.find('[data-nav="#one"]').hasClass('is-active')).to.be.false;
        });

    });

    describe('clicking a secondary nav link', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$secondaryLinkOne.click();
        });

        it('should add the is-active class to the clicked link', function() {
            expect(this.$secondaryLinkOne.hasClass('is-active')).to.be.true;
        });

    });

    describe('clicking a second secondary nav link', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$secondaryLinkOne.click();
            this.$secondaryLinkTwo.click();
        });

        it('should add the is-active class to the clicked link', function() {
            expect(this.$secondaryLinkTwo.hasClass('is-active')).to.be.true;
        });

    });

    describe('clicking a primary nav link that has no sub navigation', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkThree.click();
        });

        it('should not open the secondary nav', function() {
            expect(this.$html.find('.nav-main').hasClass('is-open')).to.be.false;
        });
    });

    describe('clicking a primary nav link that has no sub navigation when the subnavigation is open', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$linkThree.click();
        });

        it('should close the secondary nav', function() {
            expect(this.$html.find('.nav-main').hasClass('nav-main--open')).to.be.false;
        });
    });

    describe('clicking the close icon, when the sub navigation is closed', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$closeLink.click();
        });

        it('should have no effect on the subnavigation', function() {
            expect(this.$html.find('.nav-main').hasClass('is-active')).to.be.false;
        });

    });

    describe('clicking the close icon, when the sub navigation is open', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$closeLink.click();
        });

        it('should close the sub navigation', function() {
            expect(this.$html.find('.nav-main').hasClass('is-open')).to.be.false;
        });

    });

    describe('clicking outside of the navigation, when the sub navigation is open', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$contentMain.click();
        });

        it('should close the sub navigation', function() {
            expect(this.$html.find('.nav-main').hasClass('is-open')).to.be.false;
        });

    });

});
<commit_msg>Add missing semicolon<commit_after>/*jshint multistr: true, unused: false*/

'use strict';

var $ = require('jquery'),
    NavMainComponent = require('../../../js/NavMainComponent');

$.fx.off = !$.fx.off;

describe('NavMain component', function() {

    beforeEach(function() {
        this.$html = $('

').appendTo('html');
        this.$body = $('

').appendTo(this.$html);
        this.$markup = $('\
\

\
    Jadu\
\

\

\
          1\

\

\
          2\

\

\
          3\

\

\

\
\
    x\
\
    <form>\
      <input type="search" placeholder="search" />\
      <button>Go</button>\
    </form>\
\

\

\

\
            1.1\

\

\

\
\

\

\

\
            2.1\

\

\

\
\

\
\

\
').appendTo(this.$html);

        this.$navMain = this.$html.find('.nav-main');
        this.$closeLink = this.$html.find('[data-nav-action="close"]');
        this.$contentMain = this.$html.find('.content-main');

        this.$linkOne = this.$html.find('[href="#one"]');
        this.$linkTwo = this.$html.find('[href="#two"]');
        this.$linkThree = this.$html.find('[href="#three"]');
        this.$secondaryLinkOne = this.$html.find('[href="#one_one"]');
        this.$secondaryLinkTwo = this.$html.find('[href="#two_one"]');

        this.navMainComponent = new NavMainComponent(this.$html);

    });

    describe('clicking on the first primary nav link', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
        });

        it('should add the is-active class to the first link', function() {
            expect(this.$linkOne.hasClass('is-active')).to.be.true;
        });

        it('should open the secondary nav', function() {
            expect(this.$html.find('.nav-main').hasClass('is-open')).to.be.true;
        });

        it('should add the is-active class to the secondary sub navigation menu', function() {
            expect(this.$html.find('[data-nav="#one"]').hasClass('is-active')).to.be.true;
        });

        it('should not add the is-active class to the other sub navigation menus', function() {
            expect(this.$html.find('[data-nav="#two"]').hasClass('is-active')).to.be.false;
        });

    });

    describe('clicking the first, then the second primary nav link', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$linkTwo.click();
        });

        it('should add the is-active class to the second link', function() {
            expect(this.$linkTwo.hasClass('is-active')).to.be.true;
        });

        it('should remove the is-active class from the first link', function() {
            expect(this.$linkOne.hasClass('is-active')).to.be.false;
        });

        it('should add the is-active class to the second sub navigation menu', function() {
            expect(this.$html.find('[data-nav="#two"]').hasClass('is-active')).to.be.true;
        });

        it('should remove the is-active class from the first sub navigation menu', function() {
            expect(this.$html.find('[data-nav="#one"]').hasClass('is-active')).to.be.false;
        });

    });

    describe('clicking a secondary nav link', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$secondaryLinkOne.click();
        });

        it('should add the is-active class to the clicked link', function() {
            expect(this.$secondaryLinkOne.hasClass('is-active')).to.be.true;
        });

    });

    describe('clicking a second secondary nav link', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$secondaryLinkOne.click();
            this.$secondaryLinkTwo.click();
        });

        it('should add the is-active class to the clicked link', function() {
            expect(this.$secondaryLinkTwo.hasClass('is-active')).to.be.true;
        });

    });

    describe('clicking a primary nav link that has no sub navigation', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkThree.click();
        });

        it('should not open the secondary nav', function() {
            expect(this.$html.find('.nav-main').hasClass('is-open')).to.be.false;
        });
    });

    describe('clicking a primary nav link that has no sub navigation when the subnavigation is open', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$linkThree.click();
        });

        it('should close the secondary nav', function() {
            expect(this.$html.find('.nav-main').hasClass('nav-main--open')).to.be.false;
        });
    });

    describe('clicking the close icon, when the sub navigation is closed', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$closeLink.click();
        });

        it('should have no effect on the subnavigation', function() {
            expect(this.$html.find('.nav-main').hasClass('is-active')).to.be.false;
        });

    });

    describe('clicking the close icon, when the sub navigation is open', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$closeLink.click();
        });

        it('should close the sub navigation', function() {
            expect(this.$html.find('.nav-main').hasClass('is-open')).to.be.false;
        });

    });

    describe('clicking outside of the navigation, when the sub navigation is open', function() {

        beforeEach(function() {
            this.navMainComponent.init();
            this.$linkOne.click();
            this.$contentMain.click();
        });

        it('should close the sub navigation', function() {
            expect(this.$html.find('.nav-main').hasClass('is-open')).to.be.false;
        });

    });

});
<|endoftext|>


<commit_before>var through = require('through2')
var D = require('../../../lib/dombii.js')

module.exports = function ($) {

  var t // template
  var s = through.obj()

  $.on('data', function (d) {
    if (d.nimoy) t = new D(d)
    else t.draw(d)
  })

  s.on('close', function () {t.erase()})

  return {s:s, $:$}
}
<commit_msg>rough in cat filter<commit_after>var through = require('through2')
var D = require('../../../lib/dombii.js')

module.exports = function ($) {

  var t // template
  var s = through.obj()

  $.on('data', function (d) {
    console.log('CAT',d)
    if (d.nimoy) t = new D(d)

    // grabs an array of data!

    // else t.draw(d)
  })

  $.write('?$*')

  s.on('close', function () {t.erase()})

  return {s:s, $:$}
}
<|endoftext|>


<commit_before>/**
 * @copyright 2009 - present by OpenGamma Inc
 * @license See distribution for license
 */
$.register_module({
    name: 'og.common.slickgrid.manager',
    dependencies: ['og.common.util.ui.message'],
    obj: function () {

        return function (obj) {
            var DEAFULT_PAGESIZE = 20,
                data = {length: 0},
                on_data_loading = new Slick.Event(),
                on_data_loaded = new Slick.Event(),
                timer;
            /**
             * Fetches the data and populates the data object required for SlickGrid
             */
            function ensure_data(args) {
                var from = args.from,
                    to = args.to,
                    from_page = Math.floor(from / DEAFULT_PAGESIZE),
                    to_page = Math.floor(to / DEAFULT_PAGESIZE),
                    request_page_size,
                    request_page_number,
                    data_already_cached = false,
                    ui = og.common.util.ui,
                    filters = args.filters,
                    is_new_filter = args.filter_being_applied || false;

                if (!is_new_filter) {
                    while (data[from_page * DEAFULT_PAGESIZE] !== undefined && from_page < to_page) from_page++;
                    while (data[to_page * DEAFULT_PAGESIZE] !== undefined && from_page < to_page) to_page--;
                } else for (var i = 0; i < data.length; i++) if (data[i]) delete data[i]; // Delete old data

                // Get page size/number
                request_page_size = (((to_page - from_page) * DEAFULT_PAGESIZE) + DEAFULT_PAGESIZE);
                request_page_number = Math.floor(from_page / (request_page_size / DEAFULT_PAGESIZE));

                (function () {
                    // The search is always different if filters is populated on keyup
                    // so only check if cached data exists if a new filter has not been applied
                    var from_num, to_num, i;
                    if (is_new_filter) {
                        from_page = 0;
                        $(obj.selector + ' .slick-viewport').scrollTop(0);
                    }
                    else {
                        from_num = request_page_number * request_page_size;
                        to_num = from_num + request_page_size;
                        for (i = from_num; i < to_num; i++) data_already_cached = data[i] !== undefined || false;
                    }
                }());

                // Rest handler
                function handle_data(r) {
                    var from, to, json_header;
                    if (r.error) {
                        ui.message({
                            location: '#OG-sr',
                            message: 'oops, something bad happened (' + r.message + ')'
                        });
                        return;
                    }
                    json_header = r.data.header;
                    from = from_page * DEAFULT_PAGESIZE;
                    to = from + json_header.count;
                    data.length = parseInt(json_header.total);
                    // Create Data Object for slickgrid
                    $.each(r.data.data, function (i, row) {
                        var field_values = row.split('|'),
                            field_names = json_header.dataFields,
                            tmp_val;
                        data[from + i] = {};
                        $.each(field_names, function (k, field_name) {
                            tmp_val = field_values[k];
                            if (field_names[k] === 'type') {
                                data[from + i][field_name] = tmp_val;
                            } else data[from + i][field_name] = tmp_val;
                        });
                        if (filters.type) data[from + i].type = filters.type.replace(/_/g, ' ');
                        data[from + i].index = from + i;
                    });
                    on_data_loaded.notify({from: from,to: to});
                    ui.message({location: '#OG-sr', destroy: true});
                    clearTimeout(timer);
                }
                /**
                 * Do rest request
                 */
                if (!data_already_cached) {
                    og.api.rest[obj.page_type].get($.extend({
                        handler: handle_data,
                        loading: function () {
                            ui.message({location: '#OG-sr', message: {0: 'loading...', 3000: 'still loading...'}});
                        },
                        page_size: request_page_size,
                        page: request_page_number + 1, // 0 and 1 are the same
                        search: true
                    }, (function () {
                        var fields = ['name', 'type', 'data_source', 'identifier', 'data_provider',
                            'data_field', 'ob_time', 'ob_date', 'observation_time', 'status', 'quantity'];
                        return fields.reduce(function (acc, val) {
                            if (!filters[val]) return acc;
                            if (val === 'type') return acc[val] = filters.type, acc;
                            if (val === 'quantity') {
                                acc.min_quantity = filters.min_quantity, acc.max_quantity = filters.max_quantity;
                                return acc;
                            }
                            if (val === 'ob_date')
                                if (/19|20[0-9]{2}-[01][0-9]-[0123][0-9]/.test(filters['ob_date']))
                                    return acc['observation_date'] = filters[val], acc;
                                else return acc;
                            if (val === 'ob_time') {
                                return acc['observation_time'] = ('*' + filters[val] + '*').replace(/\s/g, '*'), acc
                            }
                            return acc[val] = ('*' + filters[val] + '*').replace(/\s/g, '*'), acc;
                        }, {});
                    }())));
                }
            }
            return {
                "data": data,                                  // properties
                "on_data_loading": on_data_loading,            // events
                "on_data_loaded": on_data_loaded,              // events
                "ensure_data": ensure_data                     // methods
            };
        }
    }
});<commit_msg>bugfix for scrolling at the bottom of search results<commit_after>/**
 * @copyright 2009 - present by OpenGamma Inc
 * @license See distribution for license
 */
$.register_module({
    name: 'og.common.slickgrid.manager',
    dependencies: ['og.common.util.ui.message'],
    obj: function () {

        return function (obj) {
            var DEFAULT_PAGESIZE = 20,
                data = {length: 0},
                on_data_loading = new Slick.Event(),
                on_data_loaded = new Slick.Event(),
                timer, ensure_data;
            /**
             * Fetches the data and populates the data object required for SlickGrid
             */
            ensure_data = function (args) {
                var from = args.from,
                    to = args.to,
                    from_page = Math.floor(from / DEFAULT_PAGESIZE),
                    to_page = Math.floor(to / DEFAULT_PAGESIZE),
                    request_page_size,
                    request_page_number,
                    data_already_cached = false,
                    ui = og.common.util.ui,
                    filters = args.filters,
                    is_new_filter = args.filter_being_applied || false,
                    handle_data;

                if (!is_new_filter) {
                    while (data[from_page * DEFAULT_PAGESIZE] !== undefined && from_page < to_page) from_page++;
                    while (data[to_page * DEFAULT_PAGESIZE] !== undefined && from_page < to_page) to_page--;
                } else for (var i = 0; i < data.length; i++) if (data[i]) delete data[i]; // Delete old data

                // Get page size/number
                request_page_size = (((to_page - from_page) * DEFAULT_PAGESIZE) + DEFAULT_PAGESIZE);
                request_page_number = Math.floor(from_page / (request_page_size / DEFAULT_PAGESIZE));

                (function () {
                    // The search is always different if filters is populated on keyup
                    // so only check if cached data exists if a new filter has not been applied
                    var from_num, to_num, i;
                    if (is_new_filter) {
                        from_page = 0;
                        $(obj.selector + ' .slick-viewport').scrollTop(0);
                    }
                    else {
                        from_num = request_page_number * request_page_size;
                        to_num = 'total' in data ? Math.min(from_num + request_page_size, data.total)
                            : from_num + request_page_size;
                        for (i = from_num; i < to_num; i++) data_already_cached = data[i] !== undefined || false;
                    }
                }());

                // Rest handler
                handle_data = function (r) {
                    var from, to, json_header;
                    if (r.error) {
                        ui.message({
                            location: '#OG-sr',
                            message: 'oops, something bad happened (' + r.message + ')'
                        });
                        return;
                    }
                    json_header = r.data.header;
                    from = from_page * DEFAULT_PAGESIZE;
                    to = from + json_header.count;
                    data.length = parseInt(json_header.total);
                    // Create Data Object for slickgrid
                    data.total = r.data.header.total;
                    $.each(r.data.data, function (i, row) {
                        var field_values = row.split('|'),
                            field_names = json_header.dataFields,
                            tmp_val;
                        data[from + i] = {};
                        $.each(field_names, function (k, field_name) {
                            tmp_val = field_values[k];
                            if (field_names[k] === 'type') {
                                data[from + i][field_name] = tmp_val;
                            } else data[from + i][field_name] = tmp_val;
                        });
                        if (filters.type) data[from + i].type = filters.type.replace(/_/g, ' ');
                        data[from + i].index = from + i;
                    });
                    on_data_loaded.notify({from: from,to: to});
                    ui.message({location: '#OG-sr', destroy: true});
                    clearTimeout(timer);
                }
                /**
                 * Do rest request
                 */
                if (!data_already_cached) {
                    og.api.rest[obj.page_type].get($.extend({
                        handler: handle_data,
                        loading: function () {
                            ui.message({location: '#OG-sr', message: {0: 'loading...', 3000: 'still loading...'}});
                        },
                        page_size: request_page_size,
                        page: request_page_number + 1, // 0 and 1 are the same
                        search: true
                    }, (function () {
                        var fields = ['name', 'type', 'data_source', 'identifier', 'data_provider',
                            'data_field', 'ob_time', 'ob_date', 'observation_time', 'status', 'quantity'];
                        return fields.reduce(function (acc, val) {
                            if (!filters[val]) return acc;
                            if (val === 'type') return acc[val] = filters.type, acc;
                            if (val === 'quantity') {
                                acc.min_quantity = filters.min_quantity, acc.max_quantity = filters.max_quantity;
                                return acc;
                            }
                            if (val === 'ob_date')
                                if (/19|20[0-9]{2}-[01][0-9]-[0123][0-9]/.test(filters['ob_date']))
                                    return acc['observation_date'] = filters[val], acc;
                                else return acc;
                            if (val === 'ob_time') {
                                return acc['observation_time'] = ('*' + filters[val] + '*').replace(/\s/g, '*'), acc
                            }
                            return acc[val] = ('*' + filters[val] + '*').replace(/\s/g, '*'), acc;
                        }, {});
                    }())));
                }
            }
            return {
                data: data,                                  // properties
                on_data_loading: on_data_loading,            // events
                on_data_loaded: on_data_loaded,              // events
                ensure_data: ensure_data                     // methods
            };
        }
    }
});<|endoftext|>


<commit_before>//inject umbracos assetsServce and dialog service
function MarkdownEditorController($scope, $element, assetsService, dialogService, angularHelper, $timeout) {

    //tell the assets service to load the markdown.editor libs from the markdown editors
    //plugin folder

    if ($scope.model.value === null || $scope.model.value === "") {
        $scope.model.value = $scope.model.config.defaultValue;
    }

    function openMediaPicker(callback) {

      $scope.mediaPickerOverlay = {};
      $scope.mediaPickerOverlay.view = "mediaPicker";
      $scope.mediaPickerOverlay.show = true;
      $scope.mediaPickerOverlay.disableFolderSelect = true;

      $scope.mediaPickerOverlay.submit = function(model) {

          var selectedImagePath = model.selectedImages[0].image;
          callback(selectedImagePath);

          $scope.mediaPickerOverlay.show = false;
          $scope.mediaPickerOverlay = null;
      };

      $scope.mediaPickerOverlay.close = function(model) {
          $scope.mediaPickerOverlay.show = false;
          $scope.mediaPickerOverlay = null;
      };

    }

    assetsService
        .load([
            "lib/markdown/markdown.converter.js",
            "lib/markdown/markdown.sanitizer.js",
            "lib/markdown/markdown.editor.js"
        ])
        .then(function () {

            // we need a short delay to wait for the textbox to appear.
            setTimeout(function () {
                //this function will execute when all dependencies have loaded
                // but in the case that they've been previously loaded, we can only
                // init the md editor after this digest because the DOM needs to be ready first
                // so run the init on a timeout
                $timeout(function () {
                    var converter2 = new Markdown.Converter();
                    var editor2 = new Markdown.Editor(converter2, "-" + $scope.model.alias);
                    editor2.run();

                    //subscribe to the image dialog clicks
                    editor2.hooks.set("insertImageDialog", function (callback) {
                        openMediaPicker(callback);
                        return true; // tell the editor that we'll take care of getting the image url
                    });

                    editor2.hooks.set("onPreviewRefresh", function () {
                        // We must manually update the model as there is no way to hook into the markdown editor events without exstensive edits to the library.
                        if ($scope.model.value !== $("textarea", $element).val()) {
                            angularHelper.getCurrentForm($scope).$setDirty();
                            $scope.model.value = $("textarea", $element).val();
                        }
                    });

                }, 200);
            });

            //load the seperat css for the editor to avoid it blocking our js loading TEMP HACK
            assetsService.loadCss("lib/markdown/markdown.css");
        })
}

angular.module("umbraco").controller("Umbraco.PropertyEditors.MarkdownEditorController", MarkdownEditorController);
<commit_msg>Prevent "unsaved" warning when no changes on MarkDown Editor<commit_after>//inject umbracos assetsServce and dialog service
function MarkdownEditorController($scope, $element, assetsService, dialogService, angularHelper, $timeout) {

    //tell the assets service to load the markdown.editor libs from the markdown editors
    //plugin folder

    if ($scope.model.value === null || $scope.model.value === "") {
        $scope.model.value = $scope.model.config.defaultValue;
    }

    function openMediaPicker(callback) {

      $scope.mediaPickerOverlay = {};
      $scope.mediaPickerOverlay.view = "mediaPicker";
      $scope.mediaPickerOverlay.show = true;
      $scope.mediaPickerOverlay.disableFolderSelect = true;

      $scope.mediaPickerOverlay.submit = function(model) {

          var selectedImagePath = model.selectedImages[0].image;
          callback(selectedImagePath);

          $scope.mediaPickerOverlay.show = false;
          $scope.mediaPickerOverlay = null;
      };

      $scope.mediaPickerOverlay.close = function(model) {
          $scope.mediaPickerOverlay.show = false;
          $scope.mediaPickerOverlay = null;
      };

    }

    assetsService
        .load([
            "lib/markdown/markdown.converter.js",
            "lib/markdown/markdown.sanitizer.js",
            "lib/markdown/markdown.editor.js"
        ])
        .then(function () {

            // we need a short delay to wait for the textbox to appear.
            setTimeout(function () {
                //this function will execute when all dependencies have loaded
                // but in the case that they've been previously loaded, we can only
                // init the md editor after this digest because the DOM needs to be ready first
                // so run the init on a timeout
                $timeout(function () {
                    $scope.markdownEditorInitComplete = false;
                    var converter2 = new Markdown.Converter();
                    var editor2 = new Markdown.Editor(converter2, "-" + $scope.model.alias);
                    editor2.run();

                    //subscribe to the image dialog clicks
                    editor2.hooks.set("insertImageDialog", function (callback) {
                        openMediaPicker(callback);
                        return true; // tell the editor that we'll take care of getting the image url
                    });

                    editor2.hooks.set("onPreviewRefresh", function () {
                        // We must manually update the model as there is no way to hook into the markdown editor events without exstensive edits to the library.
                        if ($scope.model.value !== $("textarea", $element).val()) {
                            if ($scope.markdownEditorInitComplete) {
                                //only set dirty after init load to avoid "unsaved" dialogue when we don't want it
                                angularHelper.getCurrentForm($scope).$setDirty();
                            } else {
                                $scope.markdownEditorInitComplete = true;
                            }
                            $scope.model.value = $("textarea", $element).val();
                        }
                    });

                }, 200);
            });

            //load the seperat css for the editor to avoid it blocking our js loading TEMP HACK
            assetsService.loadCss("lib/markdown/markdown.css");
        })
}

angular.module("umbraco").controller("Umbraco.PropertyEditors.MarkdownEditorController", MarkdownEditorController);
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var fs = require('fs');
var assert = require('assert');
var csvWriter = require('csv-write-stream');
var nodePath = process.env.NODE_PATH;
var demo = require(nodePath + '/demofile/demo');
const emptyCell = 0;

function parseDemoFile(path) {
  fs.readFile(path, function (err, buffer) {
    assert.ifError(err);
    var csgoDataFile = 'csgo_data.csv';

    if (!fs.existsSync(csgoDataFile)) {
      var writer = csvWriter({headers: ["eventType", "map", "attacker",
                                        "victim", "weapon", "attackerHealth",
                                        "headshot", "remainingHealth",
                                        "remainingArmor", "hitgroup",
                                        "winningTeam", "winReason"]});
      writer.pipe(fs.createWriteStream(csgoDataFile));
    }
    else {
      var writer = csvWriter({sendHeaders: false});
      writer.pipe(fs.createWriteStream(csgoDataFile, {flags: 'a'}));
    }

    var demoFile = new demo.DemoFile();
    var mapName;

    demoFile.on('start', () => {
      mapName = demoFile.header.mapName;
    });

    demoFile.on('end', () => {
      writer.end();
    });

    demoFile.gameEvents.on('player_hurt', e => {
      let victim = demoFile.entities.getByUserId(e.userid);
      let attacker = demoFile.entities.getByUserId(e.attacker);

      if (e.hitgroup == 1) {
        var headshot = true
      }
      else {
        var headshot = false
      }

      var hitgroup = determineHitGroup(e.hitgroup);
      if (victim && attacker) {
        writer.write({eventType: "player_hurt", map: mapName,
                      attacker: attacker.name, victim: victim.name,
                      weapon: e.weapon, attackerHealth: attacker.health,
                      headshot: headshot, remainingHealth: victim.health,
                      remainingArmor: victim.armor, hitgroup: hitgroup,
                      winningTeam: emptyCell, winReason: emptyCell});
      }
    });

    demoFile.gameEvents.on('player_death', e => {
      let victim = demoFile.entities.getByUserId(e.userid);
      let attacker = demoFile.entities.getByUserId(e.attacker);

      if (e.headshot) {
        var hitgroup = "Head"
      }
      else {
        var hitgroup = "None"
      }

      if (victim && attacker) {
        writer.write({eventType: "player_death", map: mapName,
                      attacker: attacker.name, victim: victim.name,
                      weapon: e.weapon, attackerHealth: attacker.health,
                      headshot: e.headshot, remainingHealth: victim.health,
                      remainingArmor: victim.armor, hitgroup: hitgroup,
                      winningTeam: emptyCell, winReason: emptyCell});
      }
    });

    demoFile.gameEvents.on('round_end', e => {
      if (e.winner == 2) {
        var winningTeam = "Terrorists"
      }
      else if (e.winner == 3) {
        var winningTeam = "Counter-Terrorists"
      }
      writer.write({eventType: "round_end", map: mapName,
                    attacker: emptyCell, victim: emptyCell,
                    weapon: emptyCell, attackerHealth: emptyCell,
                    headshot: emptyCell, remainingHealth: emptyCell,
                    remainingArmor: emptyCell, hitgroup: emptyCell,
                    winningTeam: winningTeam, winReason: e.message.substring(13)});
    });

    demoFile.parse(buffer);
  });
}

function determineHitGroup(hitgroup){
  var finalHitGroup = "None";

  switch(hitgroup) {
    case 1:
      finalHitGroup = "Head";
      break;
    case 2:
      finalHitGroup = "Upper Torso";
      break;
    case 3:
      finalHitGroup = "Lower Torso";
      break;
    case 4:
      finalHitGroup = "Left Arm";
      break;
    case 5:
      finalHitGroup = "Right Arm";
      break;
    case 6:
      finalHitGroup = "Left Leg";
      break;
    case 7:
      finalHitGroup = "Right Leg";
      break;
  }

  return finalHitGroup;
}

parseDemoFile(process.argv[2]);
<commit_msg>Change emptyCell value from 0 to ''<commit_after>#!/usr/bin/env node

'use strict';

var fs = require('fs');
var assert = require('assert');
var csvWriter = require('csv-write-stream');
var nodePath = process.env.NODE_PATH;
var demo = require(nodePath + '/demofile/demo');
const emptyCell = "";

function parseDemoFile(path) {
  fs.readFile(path, function (err, buffer) {
    assert.ifError(err);
    var csgoDataFile = 'csgo_data.csv';

    if (!fs.existsSync(csgoDataFile)) {
      var writer = csvWriter({headers: ["eventType", "map", "attacker",
                                        "victim", "weapon", "attackerHealth",
                                        "headshot", "remainingHealth",
                                        "remainingArmor", "hitgroup",
                                        "winningTeam", "winReason"]});
      writer.pipe(fs.createWriteStream(csgoDataFile));
    }
    else {
      var writer = csvWriter({sendHeaders: false});
      writer.pipe(fs.createWriteStream(csgoDataFile, {flags: 'a'}));
    }

    var demoFile = new demo.DemoFile();
    var mapName;

    demoFile.on('start', () => {
      mapName = demoFile.header.mapName;
    });

    demoFile.on('end', () => {
      writer.end();
    });

    demoFile.gameEvents.on('player_hurt', e => {
      let victim = demoFile.entities.getByUserId(e.userid);
      let attacker = demoFile.entities.getByUserId(e.attacker);

      if (e.hitgroup == 1) {
        var headshot = true
      }
      else {
        var headshot = false
      }

      var hitgroup = determineHitGroup(e.hitgroup);
      if (victim && attacker) {
        writer.write({eventType: "player_hurt", map: mapName,
                      attacker: attacker.name, victim: victim.name,
                      weapon: e.weapon, attackerHealth: attacker.health,
                      headshot: headshot, remainingHealth: victim.health,
                      remainingArmor: victim.armor, hitgroup: hitgroup,
                      winningTeam: emptyCell, winReason: emptyCell});
      }
    });

    demoFile.gameEvents.on('player_death', e => {
      let victim = demoFile.entities.getByUserId(e.userid);
      let attacker = demoFile.entities.getByUserId(e.attacker);

      if (e.headshot) {
        var hitgroup = "Head"
      }
      else {
        var hitgroup = "None"
      }

      if (victim && attacker) {
        writer.write({eventType: "player_death", map: mapName,
                      attacker: attacker.name, victim: victim.name,
                      weapon: e.weapon, attackerHealth: attacker.health,
                      headshot: e.headshot, remainingHealth: victim.health,
                      remainingArmor: victim.armor, hitgroup: hitgroup,
                      winningTeam: emptyCell, winReason: emptyCell});
      }
    });

    demoFile.gameEvents.on('round_end', e => {
      if (e.winner == 2) {
        var winningTeam = "Terrorists"
      }
      else if (e.winner == 3) {
        var winningTeam = "Counter-Terrorists"
      }
      writer.write({eventType: "round_end", map: mapName,
                    attacker: emptyCell, victim: emptyCell,
                    weapon: emptyCell, attackerHealth: emptyCell,
                    headshot: emptyCell, remainingHealth: emptyCell,
                    remainingArmor: emptyCell, hitgroup: emptyCell,
                    winningTeam: winningTeam, winReason: e.message.substring(13)});
    });

    demoFile.parse(buffer);
  });
}

function determineHitGroup(hitgroup){
  var finalHitGroup = "None";

  switch(hitgroup) {
    case 1:
      finalHitGroup = "Head";
      break;
    case 2:
      finalHitGroup = "Upper Torso";
      break;
    case 3:
      finalHitGroup = "Lower Torso";
      break;
    case 4:
      finalHitGroup = "Left Arm";
      break;
    case 5:
      finalHitGroup = "Right Arm";
      break;
    case 6:
      finalHitGroup = "Left Leg";
      break;
    case 7:
      finalHitGroup = "Right Leg";
      break;
  }

  return finalHitGroup;
}

parseDemoFile(process.argv[2]);
<|endoftext|>


<commit_before>$(document).ready(function() {

  // init foundation for offcanvas menu
  $(document).foundation();

  // custom theme js for sidebar links
  var allClosed;

  // close all accordions, besides the menu containing the page that you've clicked on.
  $('.toctree-l1').each(function(){
    if($(this).children('a').attr('state') == 'open') {
      $(this).children('ul').show();
      allClosed = false;
      return false;
    } else {
      allClosed = true;
    }
  });

  if (allClosed == true) { }

  // if menu is closed when clicked, expand it
  $('.toctree-l1 > a').click(function() {

    //Make the titles of open accordions dead links
    if ($(this).attr('state') == 'open') {return false;}

    //Clicking on a title of a closed accordion
    if($(this).attr('state') != 'open' && $(this).siblings().size() > 0) {
      $('.toctree-l1 > ul').hide();
      $('.toctree-l1 > a').attr('state', '');
      $(this).attr('state', 'open');
      $(this).next().slideDown(function(){});
      return false;
    }
  });

  // insert urls into markdown
  $(function(){
    $('a#AWS').attr('href', documentationBaseURL + '/quickstart/provider/aws/boot/')
    $('a#GKE').attr('href', documentationBaseURL + '/quickstart/provider/gke/boot/')
    $('a#Vagrant').attr('href', documentationBaseURL + '/quickstart/provider/vagrant/boot/')
  });

});

// use headroom.js for sticky topbar
(function() {
  var searchBar = document.querySelector(".top-bar");
  new Headroom(searchBar, {
    offset: 50,
    classes: {
      "initial": "headroom",
      "pinned": "headroom--pinned",
      "unpinned": "headroom--unpinned",
      "top" : "headroom--top",
      "notTop" : "headroom--not-top"
    }
  }).init();
}());
<commit_msg>bug(azure/quickstart): fix Azure link in the menu<commit_after>$(document).ready(function() {

  // init foundation for offcanvas menu
  $(document).foundation();

  // custom theme js for sidebar links
  var allClosed;

  // close all accordions, besides the menu containing the page that you've clicked on.
  $('.toctree-l1').each(function(){
    if($(this).children('a').attr('state') == 'open') {
      $(this).children('ul').show();
      allClosed = false;
      return false;
    } else {
      allClosed = true;
    }
  });

  if (allClosed == true) { }

  // if menu is closed when clicked, expand it
  $('.toctree-l1 > a').click(function() {

    //Make the titles of open accordions dead links
    if ($(this).attr('state') == 'open') {return false;}

    //Clicking on a title of a closed accordion
    if($(this).attr('state') != 'open' && $(this).siblings().size() > 0) {
      $('.toctree-l1 > ul').hide();
      $('.toctree-l1 > a').attr('state', '');
      $(this).attr('state', 'open');
      $(this).next().slideDown(function(){});
      return false;
    }
  });

  // insert urls into markdown
  $(function(){
    $('a#AWS').attr('href', documentationBaseURL + '/quickstart/provider/aws/boot/')
    $('a#GKE').attr('href', documentationBaseURL + '/quickstart/provider/gke/boot/')
    $('a#Vagrant').attr('href', documentationBaseURL + '/quickstart/provider/vagrant/boot/')
    $('a#Azure').attr('href', documentationBaseURL + '/quickstart/provider/azure-acs/boot/')
  });

});

// use headroom.js for sticky topbar
(function() {
  var searchBar = document.querySelector(".top-bar");
  new Headroom(searchBar, {
    offset: 50,
    classes: {
      "initial": "headroom",
      "pinned": "headroom--pinned",
      "unpinned": "headroom--unpinned",
      "top" : "headroom--top",
      "notTop" : "headroom--not-top"
    }
  }).init();
}());
<|endoftext|>


<commit_before>var fs = require('fs');
var inquirer = require('inquirer');
var _ = require('underscore');
var M = require('mstring')

inquirer.prompt({
  type: 'list',
  name: 'category',
  message: '☂  Hackathon Starter',
  choices: ['Authentication', 'API Examples', 'Exit'],
  filter: function(val) {
    return val.toLowerCase();
  }
}, function(answer) {
  if (answer.category === 'authentication') {
    inquirer.prompt({
      type: 'checkbox',
      message: 'Select Authentication Providers:',
      name: 'auth',
      choices: [
        { name: 'Facebook', checked: true },
        { name: 'GitHub', checked: true },
        { name: 'Google', checked: true },
        { name: 'Twitter', checked: true },
        { name: 'Local', checked: true },
        { name: 'LinkedIn' },
        { name: 'Instagram' }
      ],
      validate: function(answer) {
        if (answer.length < 1) {
          return "You must choose at least one authentication method.";
        }
        return true;
      },
      filter: function(val) {
        return _.map(val, function(auth) {
          return auth.toLowerCase();
        });
      }
    }, function(answer) {
      var passportFile = 'config/passport.js';
      if (_.contains(answer.auth, 'facebook')) {
        var search = "var FacebookStrategy = require('passport-facebook').Strategy;";
        var strategy = M(function() {
          /***
          // Sign in with Facebook.

          passport.use(new FacebookStrategy(secrets.facebook, function(req, accessToken, refreshToken, profile, done) {
            if (req.user) {
              User.findOne({ $or: [{ facebook: profile.id }, { email: profile.email }] }, function(err, existingUser) {
                if (existingUser) {
                  req.flash('errors', { msg: 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
                  done(err);
                } else {
                  User.findById(req.user.id, function(err, user) {
                    user.facebook = profile.id;
                    user.tokens.push({ kind: 'facebook', accessToken: accessToken });
                    user.profile.name = user.profile.name || profile.displayName;
                    user.profile.gender = user.profile.gender || profile._json.gender;
                    user.profile.picture = user.profile.picture || 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
                    user.save(function(err) {
                      req.flash('info', { msg: 'Facebook account has been linked.' });
                      done(err, user);
                    });
                  });
                }
              });
            } else {
              User.findOne({ facebook: profile.id }, function(err, existingUser) {
                if (existingUser) return done(null, existingUser);
                User.findOne({ email: profile._json.email }, function(err, existingEmailUser) {
                  if (existingEmailUser) {
                    req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.' });
                    done(err);
                  } else {
                    var user = new User();
                    user.email = profile._json.email;
                    user.facebook = profile.id;
                    user.tokens.push({ kind: 'facebook', accessToken: accessToken });
                    user.profile.name = profile.displayName;
                    user.profile.gender = profile._json.gender;
                    user.profile.picture = 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
                    user.profile.location = (profile._json.location) ? profile._json.location.name : '';
                    user.save(function(err) {
                      done(err, user);
                    });
                  }
                });
              });
            }
          }));

          ***/
        });
        var body = fs.readFileSync(passportFile).toString();
        if (body.indexOf(search) < 0) {
          body = body.split('\n');
          var idx = body.lastIndexOf("var passport = require('passport');");
          body.splice(idx + 1, 0, search);
          var idx2 = body.lastIndexOf("passport.deserializeUser(function(id, done) {");
          body.splice(idx2 + 6, 0, strategy);

          var output = body.join('\n');
          fs.writeFileSync(passportFile, output);
        }
      }
    });
  } else if (answer.category === 'api examples') {
    console.log('selected api examples');
  }
});
<commit_msg>Added Facebook auth remover<commit_after>var _ = require('underscore');
var colors = require('colors');
var fs = require('fs');
var inquirer = require('inquirer');
var M = require('mstring')

inquirer.prompt({
  type: 'list',
  name: 'category',
  message: 'Hackathon Starter Generator:',
  choices: ['Authentication', 'API Examples', 'Exit'],
  filter: function(val) {
    return val.toLowerCase();
  }
}, function(answer) {
  if (answer.category === 'authentication') {
    inquirer.prompt({
      type: 'checkbox',
      message: 'Select Authentication Providers:',
      name: 'auth',
      choices: [
        { name: 'Facebook', checked: true },
        { name: 'GitHub', checked: true },
        { name: 'Google', checked: true },
        { name: 'Twitter', checked: true },
        { name: 'Local', checked: true },
        { name: 'LinkedIn' },
        { name: 'Instagram' }
      ],
      validate: function(answer) {
        if (answer.length < 1) {
          return "You must choose at least one authentication method.";
        }
        return true;
      },
      filter: function(val) {
        return _.map(val, function(auth) {
          return auth.toLowerCase();
        });
      }
    }, function(answer) {
      var passportConfig = 'config/passport.js';
      var userModel  = 'models/User.js';
      var profileTemplate = 'views/account/profile.jade';
      var loginTemplate = 'views/account/login.jade';

      var facebookStrategyRequire = "var FacebookStrategy = require('passport-facebook').Strategy;";
      var facebookStrategy = M(function() {
        /***
         // Sign in with Facebook.

         passport.use(new FacebookStrategy(secrets.facebook, function(req, accessToken, refreshToken, profile, done) {
            if (req.user) {
              User.findOne({ $or: [{ facebook: profile.id }, { email: profile.email }] }, function(err, existingUser) {
                if (existingUser) {
                  req.flash('errors', { msg: 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
                  done(err);
                } else {
                  User.findById(req.user.id, function(err, user) {
                    user.facebook = profile.id;
                    user.tokens.push({ kind: 'facebook', accessToken: accessToken });
                    user.profile.name = user.profile.name || profile.displayName;
                    user.profile.gender = user.profile.gender || profile._json.gender;
                    user.profile.picture = user.profile.picture || 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
                    user.save(function(err) {
                      req.flash('info', { msg: 'Facebook account has been linked.' });
                      done(err, user);
                    });
                  });
                }
              });
            } else {
              User.findOne({ facebook: profile.id }, function(err, existingUser) {
                if (existingUser) return done(null, existingUser);
                User.findOne({ email: profile._json.email }, function(err, existingEmailUser) {
                  if (existingEmailUser) {
                    req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.' });
                    done(err);
                  } else {
                    var user = new User();
                    user.email = profile._json.email;
                    user.facebook = profile.id;
                    user.tokens.push({ kind: 'facebook', accessToken: accessToken });
                    user.profile.name = profile.displayName;
                    user.profile.gender = profile._json.gender;
                    user.profile.picture = 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
                    user.profile.location = (profile._json.location) ? profile._json.location.name : '';
                    user.save(function(err) {
                      done(err, user);
                    });
                  }
                });
              });
            }
          }));

         ***/
      });

      var body = fs.readFileSync(passportConfig).toString();

      if (_.contains(answer.auth, 'facebook')) {

        if (body.indexOf(facebookStrategyRequire) < 0) {
          body = body.split('\n');
          var idx = body.lastIndexOf("var passport = require('passport');");
          body.splice(idx + 1, 0, facebookStrategyRequire);
          var idx2 = body.lastIndexOf("passport.deserializeUser(function(id, done) {");
          body.splice(idx2 + 6, 0, facebookStrategy);
          var output = body.join('\n');
          fs.writeFileSync(passportConfig, output);
          console.log('Facebook authentication has been added.');
        } else {
          console.log('Facebook authentication is already active.');
        }
      } else {
        // If unchecked, delete Facebook auth completely.
        body = body.split('\n');
        var idx = body.lastIndexOf(facebookStrategyRequire);
        body.splice(idx, 1);
        var idx2 = body.lastIndexOf('// Sign in with Facebook.');
        body.splice(idx2, 47);
        var output = body.join('\n');
        fs.writeFileSync(passportConfig, output);
        console.log('Facebook authentication has been deleted.');
      }
    });
  } else if (answer.category === 'api examples') {
    console.log('selected api examples');
  }
});
<|endoftext|>


<commit_before>;(function (angular, contentUpdate, undefined) {

    "use strict";

    /**
     * Module to handle general navigation in the app
     */
    angular.module('cqAppNavigation', ['cqContentSyncUpdate'])
        .controller('AppNavigationController', ['$scope', '$window', '$location', 'cqContentSyncUpdate',
            function ($scope, $window, $location, cqContentSyncUpdate) {
                $scope.transition = '';
                var contentUpdater = contentUpdate();

                /**
                 * Handle back button
                 */
                $scope.back = function() {
                    $scope.transition = 'transition-right';
                    $window.history.back();
                    console.log('[nav] handled back event.');
                };

                /**
                 * Handle navigation to app pages
                 */
                $scope.go = function(path){
                    if ($scope.wcmMode) {
                        // WCMMode is not disabled; head to the page itself
                        navigateToPageInAuthorMode(path);
                    }
                    else {
                        navigateToPageInApp(path);
                    }

                    console.log('[nav] app navigated to: [' + path + '].');
                };

                /**
                 * Toggle the menu
                 */
                $scope.toggleMenu = function() {
                    $scope.navigationMenuStatus = !$scope.navigationMenuStatus;
                };

                /**
                 * Trigger an app update
                 */
                $scope.updateApp = function() {
                    // If update is in progress, NOOP
                    if($scope.updating) return;

                    // Check if an update is available
                    contentUpdater.isContentPackageUpdateAvailable($scope.contentPackageName,
                        function callback(error, isUpdateAvailable) {
                            if (error) {
                                // Alert the error details.
                                return navigator.notification.alert(error, null, 'ContentSync Error');
                            }

                            if (isUpdateAvailable) {
                                // Confirm if the user would like to update now
                                navigator.notification.confirm('Update is available, would you like to install it now?',
                                    function onConfirm(buttonIndex) {
                                        if (buttonIndex == 1) {
                                            // user selected 'Update'
                                            $scope.updating = true;
                                            contentUpdater.updateContentPackageByName($scope.contentPackageName,
                                                function callback(error, pathToContent) {
                                                    if (error) {
                                                        return navigator.notification.alert(error, null, 'Error');
                                                    }
                                                    // else
                                                    console.log('Update complete; reloading app.');
                                                    window.location.reload( true );
                                                });
                                        }
                                        else {
                                            // user selected Later
                                            // no-op
                                        }
                                    },
                                    'ContentSync Update',       // title
                                    ['Update', 'Later'] // button labels
                                );
                            }
                            else {
                                navigator.notification.alert('App is up to date.', null, 'ContentSync Update', 'Done');
                            }
                        }
                    );
                };

                /*
                 * Private helpers
                 */
                function navigateToPageInAuthorMode(path) {
                    $window.location.href = path + '.html';
                }

                function navigateToPageInApp(path) {
                    // SPA hash navigation
                    $scope.transition = 'transition-left';
                    $location.url(path);
                    $scope.navigationMenuStatus = false;
                }
            }
        ]);
})(angular, CQ.mobile.contentUpdate);<commit_msg>fixes #13 - Use nativepagetransitions plugin for navigation between pages<commit_after>;(function (angular, contentUpdate, undefined) {

    "use strict";

    /**
     * Module to handle general navigation in the app
     */
    angular.module('cqAppNavigation', ['btford.phonegap.ready'])
        .controller('AppNavigationController', ['$scope', '$window', '$location', '$timeout', 'phonegapReady',
            function ($scope, $window, $location, $timeout, phonegapReady) {

                $scope.updating = false;
                var contentUpdater = contentUpdate();

                // Counter to indicate how far we've travelled from the root of the app
                var numberOfPagesFromRoot = 0;
                $scope.atRootPage = true;

                // Page dimensions for consistent transitions
                var headerHeight = 0;
                var footerHeight = 0;

                // Page transition constants
                var pageTransitions = {
                    direction: {
                        right:  'right',
                        left:   'left',
                        up:     'up',
                        down:   'down',
                        none:   'none'
                    },
                    effect: {
                        slide: function(){
                            // NOOP
                        },
                        flip: function(){
                            // NOOP
                        }
                    }
                };

                // Initialize pageTransition effect options once deviceready has fired
                var initializeTransitions = phonegapReady(function() {
                    if (($scope.wcmMode === false) &&
                        (window.plugins && window.plugins.nativepagetransitions)) {
                        pageTransitions.effect = {
                            slide: window.plugins.nativepagetransitions.slide.bind(window.plugins.nativepagetransitions),
                            flip: window.plugins.nativepagetransitions.flip.bind(window.plugins.nativepagetransitions)
                        }
                    }
                });
                initializeTransitions();

                /**
                 * Handle back button
                 */
                $scope.back = function() {
                    numberOfPagesFromRoot--;
                    navigateBack( pageTransitions.effect.slide, pageTransitions.direction.right );

                    console.log( '[nav] handled back event.' );
                };

                /**
                 * Handle navigation from menu items to pages in the app
                 */
                $scope.goMenuItem = function( path, trackingTitle ) {
                    numberOfPagesFromRoot++;
                    $scope.atRootPage = false;
                    // Navigate to the given path with a fixed header & footer size of 0
                    navigateToPage( path, trackingTitle,
                        pageTransitions.effect.slide, pageTransitions.direction.left, 0, 0 );
                    console.log( '[nav] app navigated to menu item: [' + (trackingTitle || path) + '].' );
                };

                /**
                 * Handle navigation to app pages
                 */
                $scope.go = function( path, trackingTitle, transitionDirection ) {
                    numberOfPagesFromRoot++;
                    $scope.atRootPage = false;
                    transitionDirection = transitionDirection || pageTransitions.direction.left;
                    navigateToPage( path, trackingTitle,
                        pageTransitions.effect.slide, transitionDirection );
                    console.log( '[nav] app navigated to: [' + (trackingTitle || path) + '].' );
                };

                /**
                 * Toggle the menu
                 */
                $scope.toggleMenu = function() {
                    if( window.ADB && !$scope.navigationMenuStatus ) {
                        ADB.trackState( 'menu', {} );
                    }

                    $scope.navigationMenuStatus = !$scope.navigationMenuStatus;
                };

                /**
                 * Trigger an app update
                 */
                $scope.updateApp = function() {
                    // don't start updating again if we're already updating.
                    if($scope.updating) return;

                    // Check if an update is available
                    contentUpdater.isContentPackageUpdateAvailable($scope.contentPackageName,
                        function callback(error, isUpdateAvailable) {
                            if (error) {
                                // Alert the error details.
                                //return navigator.notification.alert(error, null, 'Content Update Error');
                                console.log(error);
                                return
                            }

                            if (isUpdateAvailable) {
                                // Confirm if the user would like to update now
                                navigator.notification.confirm('Update is available, would you like to install it now?',
                                    function onConfirm(buttonIndex) {
                                        if (buttonIndex == 1) {
                                            // user selected 'Update'
                                            $scope.updating = true;
                                            contentUpdater.updateContentPackageByName($scope.contentPackageName,
                                                function callback(error, pathToContent) {
                                                    if (error) {
                                                        //return navigator.notification.alert(error, null, 'Error');
                                                        console.log(error);
                                                        $scope.updating = false;
                                                        return;
                                                    }
                                                    // else
                                                    console.log('Update complete; reloading app.');
                                                    window.location.reload( true );
                                                });
                                        }
                                        else {
                                            // user selected Later
                                            // no-op
                                        }
                                    },
                                    'Content Update',       // title
                                    ['Update', 'Later'] // button labels
                                );
                            } else {
                                console.log("no update is currently available");
                            }
                        }
                    );
                };

                /*
                 * Private helpers
                 */
                function navigateToPage( path, trackingTitle, transition, transitionDirection,
                                         fixedHeaderHeight, fixedFooterHeight) {

                    if( $scope.wcmMode ) {
                        // WCMMode is enabled; head to the page itself
                        $window.location.href = path + '.html';
                    }
                    else {
                        if (window.ADB) {
                            // Track using trackingTitle, falling back to path if unavailable
                            ADB.trackState(trackingTitle || path, {});
                        }

                        // Set to default values if parameters are undefined (0 is OK)
                        if (fixedHeaderHeight === undefined) {
                            fixedHeaderHeight = headerHeight;
                        }
                        if (fixedFooterHeight === undefined) {
                            fixedFooterHeight = footerHeight;
                        }

                        // Configure transition options
                        var transitionConfig = {
                            // Change $location below after a brief $timeout
                            'href': null,
                            'direction': transitionDirection
                        };

                        // Set the fixed pixels properties *only* if they are > 0
                        if (fixedHeaderHeight > 0) {
                            transitionConfig.fixedPixelsTop = fixedHeaderHeight;
                        }
                        if (fixedFooterHeight > 0) {
                            transitionConfig.fixedPixelsBottom = fixedFooterHeight;
                        }

                        if (transition && (transitionDirection !== pageTransitions.direction.none)) {
                            // Invoke transition
                            transition(
                                transitionConfig,
                                function success(msg) {
                                    // NOOP
                                },
                                function error(msg) {
                                    console.error('[native transitions][ERROR] msg: ' + msg);
                                }
                            );
                        }

                        // Manually change the $location
                        $timeout(function () {
                            $location.url(path);
                            $scope.navigationMenuStatus = false;
                        }, 10);
                    }
                }

                function navigateBack(transition, transitionDirection) {
                    if( $scope.wcmMode ) {
                        $window.history.back();
                    }
                    else {
                        if (numberOfPagesFromRoot < 0) {
                            // Don't allow user to navigate further back than the first page
                            return;
                        }

                        transition(
                            {
                                'direction': transitionDirection,
                                // Change $location below after a brief $timeout
                                'href': null,
                                'fixedPixelsTop': headerHeight,
                                'fixedPixelsBottom': footerHeight
                            },
                            function success(msg) {
                                // NOOP
                            },
                            function error(msg) {
                                console.error('[native transitions][ERROR] msg: ' + msg);
                            }
                        );

                        $scope.navigationMenuStatus = false;

                        $timeout(function() {
                            $window.history.back();
                            if (numberOfPagesFromRoot === 0) {
                                $scope.atRootPage = true;
                            }
                        }, 10);
                    }
                }
            }
        ]);
})(angular, CQ.mobile.contentUpdate);<|endoftext|>


<commit_before>define([
    'jquery',
    'underscore',
    'oroui/js/tools',
    'chaplin'
], function($, _, tools, Chaplin) {
    'use strict';

    var original = {};
    var utils = Chaplin.utils;
    var location = window.location;
    original.viewDispose = Chaplin.View.prototype.dispose;
    original.collectionViewRender = Chaplin.CollectionView.prototype.render;

    /**
     * Added raw argument. Removed Internet Explorer < 9 workaround
     *
     * @param {string} subtitle
     * @param {boolean=} raw
     * @returns {string}
     */
    Chaplin.Layout.prototype.adjustTitle = function(subtitle, raw) {
        var title;
        if (!raw) {
            if (!subtitle) {
                subtitle = '';
            }
            title = this.settings.titleTemplate({
                title: this.title,
                subtitle: subtitle
            });
        } else {
            title = subtitle;
        }
        // removed Internet Explorer < 9 workaround
        document.title = title;
        return title;
    };

    Chaplin.View.prototype.dispose = function() {
        if (this.disposed) {
            return;
        }
        this.disposePageComponents();
        this.trigger('dispose', this);
        original.viewDispose.call(this, arguments);
    };

    /**
     * Detach all item view elements before render of collection to preserve DOM event handlers bound
     */
    Chaplin.CollectionView.prototype.render = function() {
        _.each(this.getItemViews(), function(itemView) {
            itemView.$el.detach();
        });
        return original.collectionViewRender.call(this, arguments);
    };

    /**
     * Fixes issue where path '/' was converted to boolean false value
     * @override
     */
    Chaplin.Router.prototype.route = function(pathDesc, params, options) {
        var handler;
        var path;
        if (typeof pathDesc === 'object') {
            path = pathDesc.url;
            if (!params && pathDesc.params) {
                params = pathDesc.params;
            }
        }
        params = params ? _.isArray(params) ? params.slice() : _.extend({}, params) : {};
        if (path !== null && path !== void 0) {
            path = path.replace(this.removeRoot, '');
            handler = this.findHandler(function(handler) {
                return handler.route.test(path);
            });
            options = params;
            params = null;
        } else {
            options = options ? _.extend({}, options) : {};
            handler = this.findHandler(function(handler) {
                if (handler.route.matches(pathDesc)) {
                    params = handler.route.normalizeParams(params);
                    if (params) {
                        return true;
                    }
                }
                return false;
            });
        }
        if (handler) {
            _.defaults(options, {
                changeURL: true
            });
            handler.callback(path !== null && path !== void 0 ? path : params, options);
            return true;
        } else {
            throw new Error('Router#route: request was not routed');
        }
    };

    /**
     * Added force flag that allows to retrieve even stale composition
     *
     * @param {string} name
     * @param {boolean=} force
     * @returns {*}
     * @override
     */
    Chaplin.Composer.prototype.retrieve = function(name, force) {
        var active;
        active = this.compositions[name];
        if (active && (force || !active.stale())) {
            return active.item;
        } else {
            return void 0;
        }
    };

    /**
     * Fixes issue when correspondent over options regions are not taken into account
     * @override
     */
    Chaplin.Layout.prototype.registerGlobalRegions = function(instance) {
        var name;
        var selector;
        var version;
        var _i;
        var _len;
        var _ref = utils.getAllPropertyVersions(instance, 'regions');

        if (instance.hasOwnProperty('regions')) {
            _ref.push(instance.regions);
        }

        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            version = _ref[_i];
            for (name in version) {
                if (!version.hasOwnProperty(name)) {
                    continue;
                }
                selector = version[name];
                this.registerGlobalRegion(instance, name, selector);
            }
        }
    };

    /**
     * Fixes issues
     *  - empty hashes (like '#')
     *  - routing full url (containing protocol and host)
     *  - stops application's navigation if it's an error page
     *  - process links with redirect options
     * @override
     */
    // jshint -W071
    Chaplin.Layout.prototype.openLink = _.wrap(Chaplin.Layout.prototype.openLink, function(func, event) {
        var href;
        var options;
        var payload;
        var external;
        var isAnchor;
        var skipRouting;
        var type;
        var el = event.currentTarget;
        var $el = $(el);

        if (event.isDefaultPrevented() || $el.parents('.sf-toolbar').length || tools.isErrorPage()) {
            return;
        }

        if (el.nodeName === 'A' && el.getAttribute('href')) {
            href = el.getAttribute('href');
            // prevent click by empty hashes
            if (href === '#') {
                event.preventDefault();
                return;
            }
            // fixes issue of routing full url
            if (href.indexOf(':\/\/') !== -1 && el.host === location.host) {
                el.setAttribute('href', el.pathname + el.search + el.hash);
            }
        }

        payload = {prevented: false, target: el};

        // jshint -W107
        // not link to same page and not javascript code link
        if (href && !Chaplin.mediator.execute('compareUrl', href) && href.substr(0, 11) !== 'javascript:') {
            Chaplin.mediator.publish('openLink:before', payload);
        }

        if (payload.prevented !== false) {
            event.preventDefault();
            return;
        }

        /* original Chaplin's openLink code: start */
        if (utils.modifierKeyPressed(event)) {
            return;
        }
        el = $ ? event.currentTarget : event.delegateTarget;
        isAnchor = el.nodeName === 'A';
        href = el.getAttribute('href') || el.getAttribute('data-href') || null;
        if (!(href !== null && href !== void 0) || href === '' || href.charAt(0) === '#') {
            return;
        }
        skipRouting = this.settings.skipRouting;
        type = typeof skipRouting;
        if (type === 'function' && !skipRouting(href, el) ||
                type === 'string' && ($ ? $(el).is(skipRouting) : $.find.matchesSelector(el, skipRouting))) {
            return;
        }
        external = isAnchor && this.isExternalLink(el);
        if (external) {
            if (this.settings.openExternalToBlank) {
                event.preventDefault();
                window.open(href);
            }
            return;
        }
        /* original Chaplin's openLink code:end */

        // now it's possible to pass redirect options over elements data-options attribute
        options = $el.data('options') || {};
        utils.redirectTo({url: href}, options);
        event.preventDefault();
    });

    /**
     * Since IE removes content form child elements when parent node is emptied
     * we need re-render item subviews manually
     * (see https://jsfiddle.net/3hrfhppe/)
     */

    if (/(MSIE\s|Trident\/|Edge\/)/.test(window.navigator.userAgent)) {
        Chaplin.CollectionView.prototype.insertView = _.wrap(
            Chaplin.CollectionView.prototype.insertView, function(func, item, view) {
                if (view.el.childNodes.length === 0) {
                    view.render();
                }
                return func.apply(this, _.rest(arguments));
            }
        );
    }

    /**
     * In case it's an error page blocks application's navigation and turns on full redirect
     * @override
     */
    utils.redirectTo = _.wrap(utils.redirectTo, function(func, pathDesc, params, options) {
        if (typeof pathDesc === 'object' && pathDesc.url !== null && pathDesc.url !== void 0 && tools.isErrorPage()) {
            options = params || {};
            options.fullRedirect = true;
            Chaplin.mediator.execute('redirectTo', pathDesc, options);
        } else {
            func.apply(this, _.rest(arguments));
        }
    });

    return Chaplin;
});
<commit_msg>BAP-9955: Recent emails widget doesn't work properly after refreshing/updating<commit_after>define([
    'jquery',
    'underscore',
    'oroui/js/tools',
    'chaplin'
], function($, _, tools, Chaplin) {
    'use strict';

    var original = {};
    var utils = Chaplin.utils;
    var location = window.location;
    original.viewDispose = Chaplin.View.prototype.dispose;
    original.collectionViewRender = Chaplin.CollectionView.prototype.render;

    /**
     * Added raw argument. Removed Internet Explorer < 9 workaround
     *
     * @param {string} subtitle
     * @param {boolean=} raw
     * @returns {string}
     */
    Chaplin.Layout.prototype.adjustTitle = function(subtitle, raw) {
        var title;
        if (!raw) {
            if (!subtitle) {
                subtitle = '';
            }
            title = this.settings.titleTemplate({
                title: this.title,
                subtitle: subtitle
            });
        } else {
            title = subtitle;
        }
        // removed Internet Explorer < 9 workaround
        document.title = title;
        return title;
    };

    Chaplin.View.prototype.dispose = function() {
        if (this.disposed) {
            return;
        }
        this.disposePageComponents();
        this.trigger('dispose', this);
        original.viewDispose.call(this);
    };

    /**
     * Detach all item view elements before render of collection to preserve DOM event handlers bound
     */
    Chaplin.CollectionView.prototype.render = function() {
        _.each(this.getItemViews(), function(itemView) {
            itemView.$el.detach();
        });
        return original.collectionViewRender.call(this);
    };

    /**
     * Fixes issue where path '/' was converted to boolean false value
     * @override
     */
    Chaplin.Router.prototype.route = function(pathDesc, params, options) {
        var handler;
        var path;
        if (typeof pathDesc === 'object') {
            path = pathDesc.url;
            if (!params && pathDesc.params) {
                params = pathDesc.params;
            }
        }
        params = params ? _.isArray(params) ? params.slice() : _.extend({}, params) : {};
        if (path !== null && path !== void 0) {
            path = path.replace(this.removeRoot, '');
            handler = this.findHandler(function(handler) {
                return handler.route.test(path);
            });
            options = params;
            params = null;
        } else {
            options = options ? _.extend({}, options) : {};
            handler = this.findHandler(function(handler) {
                if (handler.route.matches(pathDesc)) {
                    params = handler.route.normalizeParams(params);
                    if (params) {
                        return true;
                    }
                }
                return false;
            });
        }
        if (handler) {
            _.defaults(options, {
                changeURL: true
            });
            handler.callback(path !== null && path !== void 0 ? path : params, options);
            return true;
        } else {
            throw new Error('Router#route: request was not routed');
        }
    };

    /**
     * Added force flag that allows to retrieve even stale composition
     *
     * @param {string} name
     * @param {boolean=} force
     * @returns {*}
     * @override
     */
    Chaplin.Composer.prototype.retrieve = function(name, force) {
        var active;
        active = this.compositions[name];
        if (active && (force || !active.stale())) {
            return active.item;
        } else {
            return void 0;
        }
    };

    /**
     * Fixes issue when correspondent over options regions are not taken into account
     * @override
     */
    Chaplin.Layout.prototype.registerGlobalRegions = function(instance) {
        var name;
        var selector;
        var version;
        var _i;
        var _len;
        var _ref = utils.getAllPropertyVersions(instance, 'regions');

        if (instance.hasOwnProperty('regions')) {
            _ref.push(instance.regions);
        }

        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            version = _ref[_i];
            for (name in version) {
                if (!version.hasOwnProperty(name)) {
                    continue;
                }
                selector = version[name];
                this.registerGlobalRegion(instance, name, selector);
            }
        }
    };

    /**
     * Fixes issues
     *  - empty hashes (like '#')
     *  - routing full url (containing protocol and host)
     *  - stops application's navigation if it's an error page
     *  - process links with redirect options
     * @override
     */
    // jshint -W071
    Chaplin.Layout.prototype.openLink = _.wrap(Chaplin.Layout.prototype.openLink, function(func, event) {
        var href;
        var options;
        var payload;
        var external;
        var isAnchor;
        var skipRouting;
        var type;
        var el = event.currentTarget;
        var $el = $(el);

        if (event.isDefaultPrevented() || $el.parents('.sf-toolbar').length || tools.isErrorPage()) {
            return;
        }

        if (el.nodeName === 'A' && el.getAttribute('href')) {
            href = el.getAttribute('href');
            // prevent click by empty hashes
            if (href === '#') {
                event.preventDefault();
                return;
            }
            // fixes issue of routing full url
            if (href.indexOf(':\/\/') !== -1 && el.host === location.host) {
                el.setAttribute('href', el.pathname + el.search + el.hash);
            }
        }

        payload = {prevented: false, target: el};

        // jshint -W107
        // not link to same page and not javascript code link
        if (href && !Chaplin.mediator.execute('compareUrl', href) && href.substr(0, 11) !== 'javascript:') {
            Chaplin.mediator.publish('openLink:before', payload);
        }

        if (payload.prevented !== false) {
            event.preventDefault();
            return;
        }

        /* original Chaplin's openLink code: start */
        if (utils.modifierKeyPressed(event)) {
            return;
        }
        el = $ ? event.currentTarget : event.delegateTarget;
        isAnchor = el.nodeName === 'A';
        href = el.getAttribute('href') || el.getAttribute('data-href') || null;
        if (!(href !== null && href !== void 0) || href === '' || href.charAt(0) === '#') {
            return;
        }
        skipRouting = this.settings.skipRouting;
        type = typeof skipRouting;
        if (type === 'function' && !skipRouting(href, el) ||
                type === 'string' && ($ ? $(el).is(skipRouting) : $.find.matchesSelector(el, skipRouting))) {
            return;
        }
        external = isAnchor && this.isExternalLink(el);
        if (external) {
            if (this.settings.openExternalToBlank) {
                event.preventDefault();
                window.open(href);
            }
            return;
        }
        /* original Chaplin's openLink code:end */

        // now it's possible to pass redirect options over elements data-options attribute
        options = $el.data('options') || {};
        utils.redirectTo({url: href}, options);
        event.preventDefault();
    });

    /**
     * Since IE removes content form child elements when parent node is emptied
     * we need re-render item subviews manually
     * (see https://jsfiddle.net/3hrfhppe/)
     */

    if (/(MSIE\s|Trident\/|Edge\/)/.test(window.navigator.userAgent)) {
        Chaplin.CollectionView.prototype.insertView = _.wrap(
            Chaplin.CollectionView.prototype.insertView, function(func, item, view) {
                if (view.el.childNodes.length === 0) {
                    view.render();
                }
                return func.apply(this, _.rest(arguments));
            }
        );
    }

    /**
     * In case it's an error page blocks application's navigation and turns on full redirect
     * @override
     */
    utils.redirectTo = _.wrap(utils.redirectTo, function(func, pathDesc, params, options) {
        if (typeof pathDesc === 'object' && pathDesc.url !== null && pathDesc.url !== void 0 && tools.isErrorPage()) {
            options = params || {};
            options.fullRedirect = true;
            Chaplin.mediator.execute('redirectTo', pathDesc, options);
        } else {
            func.apply(this, _.rest(arguments));
        }
    });

    return Chaplin;
});
<|endoftext|>


<commit_before>/*global window Processing console*/
(function (module) {
	/**
	 * Used to build the attach options.
	 * @param object $ Contains a reference to thorny
	 * @param object options Contains the attachment specific options
	 * @return object Containing the attached options
	 */
	var attachOptions = function ($, options) {
		if (typeof options !== 'object') {
			options = {};
		}
		return $._.extend((function () {
			return {
				system: false
			};
		}()), options);
	};

	module.exports = function ($) {
		$.onInit(module, function () {
			$.data(module, 'draw', {});
			$.es().registerComponent('renderer', function () {
				return {
					/**
					 * Used to attach a renderer to an entity
					 * @param object entity Contains the entity we're adding
					 * a renderer to.
					 * @param string file Contains the file to load
					 * @return void
					 */
					attach: function (entity, options) {
						options = attachOptions($, options);

						$.data(module, 'draw')[entity.id] =
							$('thorny renderer ' + options.system)
								.attach(options);
					},

					/**
					 * Used to execute the renderer
					 * @param void
					 * @return void
					 */
					execute: function (entity) {
						$.data(module, 'draw')[entity.id]();
					}
				};
			});
		});
	};
}((typeof window === 'undefined') ? module : window.thorny_path('./thorny/browser/component/renderer')));<commit_msg>Fixed one of the components that snuck through the net when I made changes to the component system<commit_after>/*global window Processing console*/
(function (module) {
	/**
	 * Used to build the attach options.
	 * @param object $ Contains a reference to thorny
	 * @param object options Contains the attachment specific options
	 * @return object Containing the attached options
	 */
	var attachOptions = function ($, options) {
		if (typeof options !== 'object') {
			options = {};
		}
		return $._.extend((function () {
			return {
				system: false
			};
		}()), options);
	};

	module.exports = function ($) {
		$.onInit(module, function () {
			$.data(module, 'draw', {});
			$.es().registerComponent('renderer', function (entity) {
				return {
					/**
					 * Used to attach a renderer to an entity
					 * @param object entity Contains the entity we're adding
					 * a renderer to.
					 * @param string file Contains the file to load
					 * @return void
					 */
					attach: function (options) {
						options = attachOptions($, options);

						$.data(module, 'draw')[entity.id] =
							$('thorny renderer ' + options.system)
								.attach(options);
					},

					/**
					 * Used to execute the renderer
					 * @param void
					 * @return void
					 */
					execute: function () {
						$.data(module, 'draw')[entity.id]();
					}
				};
			});
		});
	};
}((typeof window === 'undefined') ? module : window.thorny_path('./thorny/browser/component/renderer')));<|endoftext|>