<commit_before>;(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['knockout', 'jquery', 'knockoutpunches', 'History', 'osfutils'], factory);
    } else {
        global.Search  = factory(ko, jQuery, History);
    }
}(this, function(ko, $, History) {
    // Enable knockout punches
    ko.punches.enableAll();

    //https://stackoverflow.com/questions/7731778/jquery-get-query-string-parameters

    var Category = function(name, count, display){
        var self = this;

        self.name = name;
        self.count = count;
        self.display = display;

        self.url = ko.computed(function() {
            if (self.name === 'total') {
                return '';
            }
            return self.name + '/';
        });
    };

    var Tag = function(tagInfo){
        var self = this;
        self.name = tagInfo.key;
        self.count = tagInfo.doc_count;
    };

    var User = function(result){
        var self = this;
        self.category = result.category;
        self.gravatarUrl = ko.observable('');
        self.social = result.social;
        self.job_title = result.job_title;
        self.job = result.job;
        self.degree = result.degree;
        self.school = result.school;
        self.url = result.url;
        self.wikiUrl = result.url+'wiki/';
        self.filesUrl = result.url+'files/';
        self.user = result.user;

        $.ajax('/api/v1'+ result.url).success(function(data){
            if (typeof data.profile !== 'undefined') {
                self.gravatarUrl(data.profile.gravatar_url);
            }
        });

    };

    var ViewModel = function(params) {
        var self = this;
        self.params = params || {};
        self.queryUrl = self.params.url;
        self.appURL = self.params.appURL;

        self.tag = ko.observable('');
        self.stateJustPushed = false;
        self.query = ko.observable('');
        self.category = ko.observable({});
        self.tags = ko.observableArray([]);
        self.tagMaxCount = ko.observable(1);
        self.currentPage = ko.observable(1);
        self.totalResults = ko.observable(0);
        self.results = ko.observableArray([]);
        self.searching = ko.observable(false);
        self.resultsPerPage = ko.observable(10);
        self.categories = ko.observableArray([]);
        self.searchStarted = ko.observable(false);

        self.totalCount = ko.computed(function() {
            if (self.categories().length === 0 || self.categories()[0] === undefined) {
                return 0;
            }

            return self.categories()[0].count;
        });

        self.totalPages = ko.computed(function() {
            var resultsCount = Math.max(self.resultsPerPage(),1); // No Divide by Zero
            countOfPages = Math.ceil(self.totalResults() / resultsCount);
            return countOfPages;
        });

        self.nextPageExists = ko.computed(function() {
            return ((self.totalPages() > 1) && (self.currentPage() < self.totalPages()));
        });

        self.prevPageExists = ko.computed(function() {
            return self.totalPages() > 1 && self.currentPage() > 1;
        });

        self.currentIndex = ko.computed(function() {
            return Math.max(self.resultsPerPage() * (self.currentPage()-1),0);
        });

        self.navLocation = ko.computed(function() {
            return 'Page ' + self.currentPage() + ' of ' + self.totalPages();
        });

        self.queryObject = ko.computed(function(){
            return {
                'query_string': {
                    'default_field': '_all',
                    'query': self.query(),
                    'analyze_wildcard': true,
                    'lenient': true
                }
            };
        });

        self.fullQuery = ko.computed(function() {
            return {
                'filtered': {
                    'query': self.queryObject()
                }
            };
        });

        self.sortCategories = function(a, b) {
            if(a.name === 'Total') {
                return -1;
            } else if (b.name === 'Total') {
                return 1;
            }
            return a.count >  b.count ? -1 : 1;
        };

        self.claim = function(mid) {
            claimURL = self.appURL + 'metadata/' + mid + '/promote/';
            $.osf.postJSON(claimURL, {category: 'project'}).success(function(data) {
                window.location = data.url;
            });
        };

        self.help = function() {
            bootbox.dialog({
                title: 'Search help',
                message: '
Queries
'+
                    '
Search uses the Lucene search syntax. ' +
                    'This gives you many options, but can be very simple as well. ' +
                    'Examples of valid searches include:' +
                    '

repro*
' +
                    '
brian AND title:many
' +
                    '
tags:(psychology)

' +
                    '
'
            });
        };

        self.filter = function(alias) {
            self.searchStarted(false);
            self.currentPage(1);
            self.category(alias);
            self.search();
        };

        self.addTag = function(name) {
            // To handle passing from template vs. in main html
            var tag = name;

            if(typeof name.name !== 'undefined') {
                tag = name.name;
            }

            self.currentPage(1);
            self.query(self.query() + ' AND tags:("' + tag + '")');
            self.search();
        };

        self.submit = function() {
            self.searchStarted(false);
            self.totalResults(0);
            self.currentPage(1);
            self.search();
        };

        self.search = function(noPush, validate) {
            self.tagMaxCount(1);
            var jsonData = {'query': self.fullQuery(), 'from': self.currentIndex(), 'size': self.resultsPerPage()};
            var url = self.queryUrl + self.category().url();

            $.osf.postJSON(url, jsonData).success(function(data) {

                //Clear out our variables
                self.tags([]);
                self.results.removeAll();
                self.categories.removeAll();

                data.results.forEach(function(result){
                    if(result.category === 'user'){
                        self.results.push(new User(result));
                    }
                    else {
                        if(typeof result.url !== 'undefined'){
                            result.wikiUrl = result.url+'wiki/';
                            result.filesUrl = result.url+'files/';
                        }
                        self.results.push(result);
                    }
                });

                //Load our categories
                var categories = data.counts;
                $.each(categories, function(key, value){
                    if (value === null) {
                        value = 0;
                    }
                    self.categories.push(new Category(key, value, data.typeAliases[key]));
                });
                self.categories(self.categories().sort(self.sortCategories));

                // If our category is named attempt to load its total else set it to the total total
                if (self.category().name !== undefined) {
                    self.totalResults(data.counts[self.category().name] || 0);
                } else {
                    self.totalResults(self.self.categories()[0].count);
                }

                // Load up our tags
                $.each(data.tags, function(key, value){
                    self.tags.push(new Tag(value));
                    self.tagMaxCount(Math.max(self.tagMaxCount(), value.doc_count));
                });

                self.searchStarted(true);

                if (validate) {
                    self.validateSearch();
                }

                if (!noPush) {
                    self.pushState();
                }

            }).fail(function(response){
                self.totalResults(0);
                self.currentPage(0);
                self.results([]);
                self.tags([]);
                self.categories([]);
                self.searchStarted(false);
                $.osf.handleJSONError(response);
            });

        };

        self.paginate = function(val) {
            window.scrollTo(0, 0);
            self.currentPage(self.currentPage()+val);
            self.search();
        };

        self.pagePrev = self.paginate.bind(self, -1);
        self.pageNext = self.paginate.bind(self, 1);

        //History JS callback
        self.pageChange = function() {
            if (self.stateJustPushed) {
                self.stateJustPushed = false;
                return;
            }

            self.loadState();

            self.search(true);
        };

        //Ensure that the first url displays properly
        self.validateSearch = function() {
            if (self.category().name !== undefined) {
                possibleCategories = $.map(self.categories().filter(function(category) {
                    return category.count > 0;
                }), function(category) {
                    return category.name;
                });

                if (possibleCategories.indexOf(self.category().name) === -1) {
                    self.filter(self.categories()[0]);
                    return self.search(true);
                }
            }
            if (self.currentPage() > self.totalPages()) {
                self.currentPage(self.totalPages());
                return self.search(true);
            }
        };

        //Load state from History JS
        self.loadState = function() {
            var state = History.getState().data;
            self.currentPage(state.page || 1);
            self.setCategory(state.filter);
            self.query(state.query || '');
        };

        //Push a new state to History
        self.pushState = function() {
            var state = {
                filter: '',
                query: self.query(),
                page: self.currentPage(),
                scrollTop: $(window).scrollTop()
            };

            var url = '?q=' + self.query();

            if (self.category().name !== undefined && self.category().url() !== '') {
                state.filter = self.category().name;
                url += ('&filter=' + self.category().name);
            }

            url += ('&page=' + self.currentPage());

            //Indicate that we've just pushed a state so the
            //Call back does not process this push as a state change
            self.stateJustPushed = true;
            History.pushState(state, 'OSF | Search', url);
        };

        self.setCategory = function(cat) {
            if (cat !== undefined && cat !== null && cat !== '') {
                self.category(new Category(cat, 0, cat.charAt(0).toUpperCase() + cat.slice(1) + 's'));
            } else {
                self.category(new Category('total', 0, 'Total'));
            }
        };

    };

    function Search(selector, url, appURL) {
        // Initialization code
        var self = this;

        self.viewModel = new ViewModel({'url': url, 'appURL': appURL});
        History.Adapter.bind(window, 'statechange', self.viewModel.pageChange);

        var data = {
            query: $.osf.urlParams().q,
            page: Number($.osf.urlParams().page),
            scrollTop: 0,
            filter: $.osf.urlParams().filter
        };
        //Ensure our state keeps its URL paramaters
        History.replaceState(data, 'OSF | Search', location.search);
        //Set out observables from the newly replaced state
        self.viewModel.loadState();
        //Preform search from url params
        self.viewModel.search(true, true);

        $.osf.applyBindings(self.viewModel, selector);
    }

    return Search;

}));
<commit_msg>Eliminate the tag flash by moving the clearing of the tag max count to after the clearing of the tags.<commit_after>;(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['knockout', 'jquery', 'knockoutpunches', 'History', 'osfutils'], factory);
    } else {
        global.Search  = factory(ko, jQuery, History);
    }
}(this, function(ko, $, History) {
    // Enable knockout punches
    ko.punches.enableAll();

    //https://stackoverflow.com/questions/7731778/jquery-get-query-string-parameters

    var Category = function(name, count, display){
        var self = this;

        self.name = name;
        self.count = count;
        self.display = display;

        self.url = ko.computed(function() {
            if (self.name === 'total') {
                return '';
            }
            return self.name + '/';
        });
    };

    var Tag = function(tagInfo){
        var self = this;
        self.name = tagInfo.key;
        self.count = tagInfo.doc_count;
    };

    var User = function(result){
        var self = this;
        self.category = result.category;
        self.gravatarUrl = ko.observable('');
        self.social = result.social;
        self.job_title = result.job_title;
        self.job = result.job;
        self.degree = result.degree;
        self.school = result.school;
        self.url = result.url;
        self.wikiUrl = result.url+'wiki/';
        self.filesUrl = result.url+'files/';
        self.user = result.user;

        $.ajax('/api/v1'+ result.url).success(function(data){
            if (typeof data.profile !== 'undefined') {
                self.gravatarUrl(data.profile.gravatar_url);
            }
        });

    };

    var ViewModel = function(params) {
        var self = this;
        self.params = params || {};
        self.queryUrl = self.params.url;
        self.appURL = self.params.appURL;

        self.tag = ko.observable('');
        self.stateJustPushed = false;
        self.query = ko.observable('');
        self.category = ko.observable({});
        self.tags = ko.observableArray([]);
        self.tagMaxCount = ko.observable(1);
        self.currentPage = ko.observable(1);
        self.totalResults = ko.observable(0);
        self.results = ko.observableArray([]);
        self.searching = ko.observable(false);
        self.resultsPerPage = ko.observable(10);
        self.categories = ko.observableArray([]);
        self.searchStarted = ko.observable(false);

        self.totalCount = ko.computed(function() {
            if (self.categories().length === 0 || self.categories()[0] === undefined) {
                return 0;
            }

            return self.categories()[0].count;
        });

        self.totalPages = ko.computed(function() {
            var resultsCount = Math.max(self.resultsPerPage(),1); // No Divide by Zero
            countOfPages = Math.ceil(self.totalResults() / resultsCount);
            return countOfPages;
        });

        self.nextPageExists = ko.computed(function() {
            return ((self.totalPages() > 1) && (self.currentPage() < self.totalPages()));
        });

        self.prevPageExists = ko.computed(function() {
            return self.totalPages() > 1 && self.currentPage() > 1;
        });

        self.currentIndex = ko.computed(function() {
            return Math.max(self.resultsPerPage() * (self.currentPage()-1),0);
        });

        self.navLocation = ko.computed(function() {
            return 'Page ' + self.currentPage() + ' of ' + self.totalPages();
        });

        self.queryObject = ko.computed(function(){
            return {
                'query_string': {
                    'default_field': '_all',
                    'query': self.query(),
                    'analyze_wildcard': true,
                    'lenient': true
                }
            };
        });

        self.fullQuery = ko.computed(function() {
            return {
                'filtered': {
                    'query': self.queryObject()
                }
            };
        });

        self.sortCategories = function(a, b) {
            if(a.name === 'Total') {
                return -1;
            } else if (b.name === 'Total') {
                return 1;
            }
            return a.count >  b.count ? -1 : 1;
        };

        self.claim = function(mid) {
            claimURL = self.appURL + 'metadata/' + mid + '/promote/';
            $.osf.postJSON(claimURL, {category: 'project'}).success(function(data) {
                window.location = data.url;
            });
        };

        self.help = function() {
            bootbox.dialog({
                title: 'Search help',
                message: '
Queries
'+
                    '
Search uses the Lucene search syntax. ' +
                    'This gives you many options, but can be very simple as well. ' +
                    'Examples of valid searches include:' +
                    '

repro*
' +
                    '
brian AND title:many
' +
                    '
tags:(psychology)

' +
                    '
'
            });
        };

        self.filter = function(alias) {
            self.searchStarted(false);
            self.currentPage(1);
            self.category(alias);
            self.search();
        };

        self.addTag = function(name) {
            // To handle passing from template vs. in main html
            var tag = name;

            if(typeof name.name !== 'undefined') {
                tag = name.name;
            }

            self.currentPage(1);
            self.query(self.query() + ' AND tags:("' + tag + '")');
            self.search();
        };

        self.submit = function() {
            self.searchStarted(false);
            self.totalResults(0);
            self.currentPage(1);
            self.search();
        };

        self.search = function(noPush, validate) {

            var jsonData = {'query': self.fullQuery(), 'from': self.currentIndex(), 'size': self.resultsPerPage()};
            var url = self.queryUrl + self.category().url();

            $.osf.postJSON(url, jsonData).success(function(data) {

                //Clear out our variables
                self.tags([]);
                self.tagMaxCount(1);
                self.results.removeAll();
                self.categories.removeAll();

                data.results.forEach(function(result){
                    if(result.category === 'user'){
                        self.results.push(new User(result));
                    }
                    else {
                        if(typeof result.url !== 'undefined'){
                            result.wikiUrl = result.url+'wiki/';
                            result.filesUrl = result.url+'files/';
                        }
                        self.results.push(result);
                    }
                });

                //Load our categories
                var categories = data.counts;
                $.each(categories, function(key, value){
                    if (value === null) {
                        value = 0;
                    }
                    self.categories.push(new Category(key, value, data.typeAliases[key]));
                });
                self.categories(self.categories().sort(self.sortCategories));

                // If our category is named attempt to load its total else set it to the total total
                if (self.category().name !== undefined) {
                    self.totalResults(data.counts[self.category().name] || 0);
                } else {
                    self.totalResults(self.self.categories()[0].count);
                }

                // Load up our tags
                $.each(data.tags, function(key, value){
                    self.tags.push(new Tag(value));
                    self.tagMaxCount(Math.max(self.tagMaxCount(), value.doc_count));
                });

                self.searchStarted(true);

                if (validate) {
                    self.validateSearch();
                }

                if (!noPush) {
                    self.pushState();
                }

            }).fail(function(response){
                self.totalResults(0);
                self.currentPage(0);
                self.results([]);
                self.tags([]);
                self.categories([]);
                self.searchStarted(false);
                $.osf.handleJSONError(response);
            });

        };

        self.paginate = function(val) {
            window.scrollTo(0, 0);
            self.currentPage(self.currentPage()+val);
            self.search();
        };

        self.pagePrev = self.paginate.bind(self, -1);
        self.pageNext = self.paginate.bind(self, 1);

        //History JS callback
        self.pageChange = function() {
            if (self.stateJustPushed) {
                self.stateJustPushed = false;
                return;
            }

            self.loadState();

            self.search(true);
        };

        //Ensure that the first url displays properly
        self.validateSearch = function() {
            if (self.category().name !== undefined) {
                possibleCategories = $.map(self.categories().filter(function(category) {
                    return category.count > 0;
                }), function(category) {
                    return category.name;
                });

                if (possibleCategories.indexOf(self.category().name) === -1) {
                    self.filter(self.categories()[0]);
                    return self.search(true);
                }
            }
            if (self.currentPage() > self.totalPages()) {
                self.currentPage(self.totalPages());
                return self.search(true);
            }
        };

        //Load state from History JS
        self.loadState = function() {
            var state = History.getState().data;
            self.currentPage(state.page || 1);
            self.setCategory(state.filter);
            self.query(state.query || '');
        };

        //Push a new state to History
        self.pushState = function() {
            var state = {
                filter: '',
                query: self.query(),
                page: self.currentPage(),
                scrollTop: $(window).scrollTop()
            };

            var url = '?q=' + self.query();

            if (self.category().name !== undefined && self.category().url() !== '') {
                state.filter = self.category().name;
                url += ('&filter=' + self.category().name);
            }

            url += ('&page=' + self.currentPage());

            //Indicate that we've just pushed a state so the
            //Call back does not process this push as a state change
            self.stateJustPushed = true;
            History.pushState(state, 'OSF | Search', url);
        };

        self.setCategory = function(cat) {
            if (cat !== undefined && cat !== null && cat !== '') {
                self.category(new Category(cat, 0, cat.charAt(0).toUpperCase() + cat.slice(1) + 's'));
            } else {
                self.category(new Category('total', 0, 'Total'));
            }
        };

    };

    function Search(selector, url, appURL) {
        // Initialization code
        var self = this;

        self.viewModel = new ViewModel({'url': url, 'appURL': appURL});
        History.Adapter.bind(window, 'statechange', self.viewModel.pageChange);

        var data = {
            query: $.osf.urlParams().q,
            page: Number($.osf.urlParams().page),
            scrollTop: 0,
            filter: $.osf.urlParams().filter
        };
        //Ensure our state keeps its URL paramaters
        History.replaceState(data, 'OSF | Search', location.search);
        //Set out observables from the newly replaced state
        self.viewModel.loadState();
        //Preform search from url params
        self.viewModel.search(true, true);

        $.osf.applyBindings(self.viewModel, selector);
    }

    return Search;

}));
<|endoftext|>


<commit_before>sitemaps.add('/mw_AllPages_sitemap.xml', function() {
	var homePosts = Posts.find({
		published: true,
		home: true
	}).fetch();

	var homePhotosArray = [];

	_.each(homePosts, function(post) {
		var photos = Photos.find({postId: post._id}).fetch();

		_.each(photos, function (photo) {
			var photoData = {};
			photoData.loc = photo.urlThumb,
			photoData.caption = photo.title,
			photoData.title = photo.title
			homePhotosArray.push(photoData);
		});
	});

	var out = [
	{ page: '/', images: homePhotosArray},
	{ page: '/contact'},
	{ page: '/about'},
	{ page: '/posts'}
	];

	var posts = Posts.find({
		published: true,
		home: { '$ne': true }
	}).fetch();

	_.each(posts, function(post) {
		var photos = Photos.find({postId: post._id}).fetch();
		var photosArray = [];

		_.each(photos, function (photo) {
			var photoData = {};
			photoData.loc = photo.urlThumb,
			photoData.caption = photo.title,
			photoData.title = photo.title
			photosArray.push(photoData);
		});

		out.push({
			page: 'posts/' + post._id,
			lastmod: post.updatedAt,
			images: photosArray
		});
	});

	return out;
});
<commit_msg>fixes sitemaps url<commit_after>sitemaps.add('/sitemaps.xml', function() {
	var homePosts = Posts.find({
		published: true,
		home: true
	}).fetch();

	var homePhotosArray = [];

	_.each(homePosts, function(post) {
		var photos = Photos.find({postId: post._id}).fetch();

		_.each(photos, function (photo) {
			var photoData = {};
			photoData.loc = photo.urlThumb,
			photoData.caption = photo.title,
			photoData.title = photo.title
			homePhotosArray.push(photoData);
		});
	});

	var out = [
	{ page: '/', images: homePhotosArray},
	{ page: '/contact'},
	{ page: '/about'},
	{ page: '/posts'}
	];

	var posts = Posts.find({
		published: true,
		home: { '$ne': true }
	}).fetch();

	_.each(posts, function(post) {
		var photos = Photos.find({postId: post._id}).fetch();
		var photosArray = [];

		_.each(photos, function (photo) {
			var photoData = {};
			photoData.loc = photo.urlThumb,
			photoData.caption = photo.title,
			photoData.title = photo.title
			photosArray.push(photoData);
		});

		out.push({
			page: 'posts/' + post._id,
			lastmod: post.updatedAt,
			images: photosArray
		});
	});

	return out;
});
<|endoftext|>


<commit_before>/*
 * jQuery UI Depends:
 *        jquery.ui.autocomplete.js
 *        jquery.ui.button.js
 *        jquery.ui.core.js
 *        jquery.ui.widget.js
 *        jquery.ui.position.js
 *        jquery.ui.menu.js
 */

nb.define('select', {
    events: {
        'init': 'onInit'
        //'open' { event, ui}
        //'close' { event, ui}
    },

    /**
     * Init select
     * @fires 'nb-select_inited'
     */

    onInit: function () {
        nb.init(this);
        this.$node = $(this.node)
        this.data = this.data();

        // find elements and values
        this.button = this.children()[0];

        this.$fallback = this.$node.find('.nb-select__fallback');
        this.$selected = this.$fallback.children(':selected');

        that.value = that.$selected.val();
        that.text = that.value ? that.$selected.text() : '';

        this.button.setText(this.text)

        // preparing control depending on configuration and content
        this.controlPrepare();
        this.trigger('nb-select_inited');
    },

    /**
     * preparing control depending on configuration and content
     */
    controlPrepare: function () {
        var that = this;
        // preparing position parameters for popup from direction data
        var position = {};
        position.collision = 'flip';

        if (that.data.within) {
            position.within = that.data.within;
        }

        if (that.data.direction == 'top') {
            position.my = "left bottom";
            position.at = "left top";

        } else {
            position.my = "left top";
            position.at = "left bottom";
        }

        // select JUI control init
        this.$node.autocomplete({
            delay: 0,
            minLength: 0,
            autoFocus: false,
            position: position,
            appendTo: that.node,
            source: function (request, response) {
                response(that.$fallback.children('option').map(function () {
                    return {
                        label: $(this).text(),
                        value: $(this).val(),
                        option: this
                    };
                }));
            },
            select: function (event, ui) {
                ui.item.option.selected = true;

                that.$jUI._trigger('selected', event, {
                    item: ui.item.option
                });
            },
            // delegate handler on 'outer' click on open
            open: function (event, ui) {
                that.$jUI._on(that.$jUI.document, {
                    // on 'outer' mousedown close control
                    mousedown: function (e) {
                        if (e.which == 1 && !$.contains(that.$jUI.element.get(0), e.target)) {
                            this.close();
                        }
                    }
                })
                that.trigger('open', {
                    event: event,
                    ui: ui
                });
            },

            close: function (event, ui) {
                that.$jUI._off(that.$jUI.document, 'mousedown');
                that.trigger('close', {
                    event: event,
                    ui: ui
                });
            }
        }).addClass('ui-widget ui-widget-content');

        that.$jUI = that.$node.data('uiAutocomplete')

        // redefine one menu item rendering method, fires every time, then popup opening
        that.$jUI._renderItem = function (ul, item) {
            var $itemNode = $('

');

            if (item.option.selected) {
                $itemNode.addClass('nb-select__item_selected_yes');
            }

            $itemNode.data('ui-autocomplete-item', item);
            $itemNode.append('' + item.label + '');
            $itemNode.appendTo(ul);

            return $itemNode;
        };

        // redefine valueMethod, extend with button text changing and fallback select value changing
        // if value not provided, return current value of fallback select
        that.$jUI.valueMethod = function (value) {
            if (value) {
                var text = that.$fallback.children('[value="' + value + '"]').text()
                that.setState({
                    value: value,
                    text: text
                });
            }
            return that.$selected.val();
        };

        // add click event for button
        $(this.button.node).on('click', function (evt) {
            // иначе сабмитит форму при клике
            evt.preventDefault();
            // close if already visible
            if (that.$node.autocomplete('widget').css('display') == 'block') {
                that.$node.autocomplete('close');
                return;
            }
            // pass empty string as value to search for, displaying all results
            that.$node.autocomplete('search', '');
            that.$node.focus();
        });
    },

    /**
     * Changes a value of control, text on the button and select value it the fallback
     *
     * @param name — event id that caused the change
     * @param params — {
         *     text: '..'
         *     value: '..'
         * }
     * @fires 'nb-select_changed'
     */
    setState: function (params) {
        this.value = params.value;
        this.text = params.text;
        this.$selected.removeAttr('selected');

        this.$selected = this.$fallback.children('[value="' + this.value + '"]').attr('selected', 'selected');
        this.button.setText(this.text);

        this.trigger('nb-select_changed');

        this.$fallback.val(params.value);
        return this
    },

    /**
     * Returns state of the select
     *
     * @return {Object} -
     * {
         *     value: '..'
         *     text: '..'
         * }
     */
    getState: function () {
        return {
            value: this.value,
            text: this.text
        }
    },

    /**
     * Disables the select
     * @fires 'nb-select_disabled'
     * @returns {nb.block}
     */
    disable: function () {
        if (this.isEnabled()) {
            this.button.disable();
            this.trigger('nb-select_disabled');
        }
        return this;
    },

    /**
     * Enables the select
     * @fires 'nb-select_enabled'
     * @returns {nb.block}
     */
    enable: function () {
        if (!this.isEnabled()) {
            this.button.enable();
            this.trigger('nb-select_enabled');
        }
        return this;
    },

    /**
     * Return state of the select
     * @returns {Boolean}
     */
    isEnabled: function () {
        return this.button.isEnabled();
    },

    /**
     * Focus the select
     * @fires 'nb-select_focused'
     * @returns {nb.block}
     */
    focus: function () {
        if (this.isEnabled()) {
            this.button.focus();
        }
        this.trigger('nb-select_focused');
        return this;
    },

    /**
     * Blur the select
     * @fires 'nb-select_blured'
     * @returns {nb.block}
     */
    blur: function () {
        if (this.isEnabled()) {
            this.button.blur();
        }
        this.trigger('nb-select_blured');
        return this;
    },

    /**
     * Destroy the select
     * @fires 'nb-select_destroyed'
     */
    destroy: function () {
        if (this.$node && this.$node.data('uiAutocomplete')) {
            this.button.destroy();
            $(this.button.node).off('click');
            this.$node.autocomplete('destroy');
        }

        this.trigger('nb-select_destroyed');
        nb.destroy(this.node.getAttribute('id'));
    }
});

<commit_msg>nb.select add setSource method<commit_after>/*
 * jQuery UI Depends:
 *        jquery.ui.autocomplete.js
 *        jquery.ui.button.js
 *        jquery.ui.core.js
 *        jquery.ui.widget.js
 *        jquery.ui.position.js
 *        jquery.ui.menu.js
 */

nb.define('select', {
    events: {
        'init': 'onInit'
        //'open' { event, ui}
        //'close' { event, ui}
    },

    /**
     * Init select
     * @fires 'nb-select_inited'
     */

    onInit: function () {
        nb.init(this);
        this.$node = $(this.node)
        this.data = this.data();

        // find elements and values
        this.button = this.children()[0];

        this.$fallback = this.$node.find('.nb-select__fallback');

        this._updateFromSelect();

        // preparing control depending on configuration and content
        this.controlPrepare();
        this.trigger('nb-select_inited');
    },

    /**
     * preparing control depending on configuration and content
     */
    controlPrepare: function () {
        var that = this;
        // preparing position parameters for popup from direction data
        var position = {};
        position.collision = 'flip';

        if (that.data.within) {
            position.within = that.data.within;
        }

        if (that.data.direction == 'top') {
            position.my = "left bottom";
            position.at = "left top";

        } else {
            position.my = "left top";
            position.at = "left bottom";
        }

        // select JUI control init
        this.$node.autocomplete({
            delay: 0,
            minLength: 0,
            autoFocus: false,
            position: position,
            appendTo: that.node,
            source: function (request, response) {
                response(that.$fallback.children('option').map(function () {
                    return {
                        label: $(this).text(),
                        value: $(this).val(),
                        option: this
                    };
                }));
            },
            select: function (event, ui) {
                ui.item.option.selected = true;

                that.$jUI._trigger('selected', event, {
                    item: ui.item.option
                });
            },
            // delegate handler on 'outer' click on open
            open: function (event, ui) {
                that.$jUI._on(that.$jUI.document, {
                    // on 'outer' mousedown close control
                    mousedown: function (e) {
                        if (e.which == 1 && !$.contains(that.$jUI.element.get(0), e.target)) {
                            this.close();
                        }
                    }
                })
                that.trigger('open', {
                    event: event,
                    ui: ui
                });
            },

            close: function (event, ui) {
                that.$jUI._off(that.$jUI.document, 'mousedown');
                that.trigger('close', {
                    event: event,
                    ui: ui
                });
            }
        }).addClass('ui-widget ui-widget-content');

        that.$jUI = that.$node.data('uiAutocomplete')

        // redefine one menu item rendering method, fires every time, then popup opening
        that.$jUI._renderItem = function (ul, item) {
            var $itemNode = $('

');

            if (item.option.selected) {
                $itemNode.addClass('nb-select__item_selected_yes');
            }

            $itemNode.data('ui-autocomplete-item', item);
            $itemNode.append('' + item.label + '');
            $itemNode.appendTo(ul);

            return $itemNode;
        };

        // redefine valueMethod, extend with button text changing and fallback select value changing
        // if value not provided, return current value of fallback select
        that.$jUI.valueMethod = function (value) {
            if (value) {
                var text = that.$fallback.children('[value="' + value + '"]').text()
                that.setState({
                    value: value,
                    text: text
                });
            }
            return that.$selected.val();
        };

        // add click event for button
        $(this.button.node).on('click', function (evt) {
            // иначе сабмитит форму при клике
            evt.preventDefault();
            // close if already visible
            if (that.$node.autocomplete('widget').css('display') == 'block') {
                that.$node.autocomplete('close');
                return;
            }
            // pass empty string as value to search for, displaying all results
            that.$node.autocomplete('search', '');
            that.$node.focus();
        });
    },

    /**
     * Changes a value of control, text on the button and select value it the fallback
     *
     * @param name — event id that caused the change
     * @param params — {
         *     text: '..'
         *     value: '..'
         * }
     * @fires 'nb-select_changed'
     */
    setState: function (params) {
        this.value = params.value;
        this.text = params.text;
        this.$selected.removeAttr('selected');

        this.$selected = this.$fallback.children('[value="' + this.value + '"]').attr('selected', 'selected');
        this.button.setText(this.text);

        this.trigger('nb-select_changed');

        this.$fallback.val(params.value);
        return this
    },

    /**
     * Returns state of the select
     *
     * @return {Object} -
     * {
         *     value: '..'
         *     text: '..'
         * }
     */
    getState: function () {
        return {
            value: this.value,
            text: this.text
        }
    },

    /**
     * Disables the select
     * @fires 'nb-select_disabled'
     * @returns {nb.block}
     */
    disable: function () {
        if (this.isEnabled()) {
            this.button.disable();
            this.trigger('nb-select_disabled');
        }
        return this;
    },

    /**
     * Enables the select
     * @fires 'nb-select_enabled'
     * @returns {nb.block}
     */
    enable: function () {
        if (!this.isEnabled()) {
            this.button.enable();
            this.trigger('nb-select_enabled');
        }
        return this;
    },

    /**
     * Return state of the select
     * @returns {Boolean}
     */
    isEnabled: function () {
        return this.button.isEnabled();
    },

    /*
     * Set new items for select
     * @params {Array} source New source
     */
    setSource: function(source) {
        var html = [];
        for (var i = 0, j = source.length; i < j; i++) {
            var item = source[i];
            html.push(
                '<option' +
                    ' label="' + item.text + '"' +
                    ' value="' + item.value + '"' +
                    (item.selected ? ' selected="selected"' : '') +
                '>' + item.text + '</option>'
            );
        }

        // set new source for select
        this.$fallback.empty().append(html);

        this._updateFromSelect();
    },

    /**
     * Save value and text from <select> node.
     * @private
     */
    _updateFromSelect: function() {
        // get selected <option/>
        this.$selected = this.$fallback.children(':selected');

        this.value = this.$selected.val();
        //   - to prevent button from collapse if no text on <option/>
        this.text = this.$selected.text() || ' ';

        this.button.setText(this.text)
    }

    /**
     * Focus the select
     * @fires 'nb-select_focused'
     * @returns {nb.block}
     */
    focus: function () {
        if (this.isEnabled()) {
            this.button.focus();
        }
        this.trigger('nb-select_focused');
        return this;
    },

    /**
     * Blur the select
     * @fires 'nb-select_blured'
     * @returns {nb.block}
     */
    blur: function () {
        if (this.isEnabled()) {
            this.button.blur();
        }
        this.trigger('nb-select_blured');
        return this;
    },

    /**
     * Destroy the select
     * @fires 'nb-select_destroyed'
     */
    destroy: function () {
        if (this.$node && this.$node.data('uiAutocomplete')) {
            this.button.destroy();
            $(this.button.node).off('click');
            this.$node.autocomplete('destroy');
        }

        this.trigger('nb-select_destroyed');
        nb.destroy(this.node.getAttribute('id'));
    }
});

<|endoftext|>


<commit_before>/*
 * jQuery UI Depends:
 *        jquery.ui.autocomplete.js
 *        jquery.ui.button.js
 *        jquery.ui.core.js
 *        jquery.ui.widget.js
 *        jquery.ui.position.js
 *        jquery.ui.menu.js
 */

nb.define('select', {
    events: {
        'init': 'onInit'
        //'open' { event, ui}
        //'close' { event, ui}
    },

    /**
     * Init select
     * @fires 'nb-select_inited'
     */

    onInit: function() {
        nb.init(this);
        this.$node = $(this.node);
        this.data = this.data();

        // find elements and values
        this.button = this.children()[0];

        this.$fallback = this.$node.find('.nb-select__fallback');

        this._updateFromSelect();

        // preparing control depending on configuration and content
        this.controlPrepare();
        this.trigger('nb-select_inited');
    },

    /**
     * preparing control depending on configuration and content
     */
    controlPrepare: function() {
        var that = this;
        // preparing position parameters for popup from direction data
        var position = {};
        position.collision = 'flip';

        if (that.data.within) {
            position.within = that.data.within;
        }

        if (that.data.direction == 'top') {
            position.my = "left bottom";
            position.at = "left top";

        } else {
            position.my = "left top";
            position.at = "left bottom";
        }

        // select JUI control init
        this.$node.autocomplete({
            delay: 0,
            minLength: 0,
            autoFocus: false,
            position: position,
            appendTo: that.node,
            source: function(request, response) {
                response(that.$fallback.children('option').map(function() {
                    return {
                        label: $(this).text(),
                        value: $(this).val(),
                        option: this
                    };
                }));
            },
            select: function(event, ui) {
                ui.item.option.selected = true;

                that.$jUI._trigger('selected', event, {
                    item: ui.item.option
                });
            },
            // delegate handler on 'outer' click on open
            open: function(event, ui) {
                that.$jUI._on(that.$jUI.document, {
                    // on 'outer' mousedown close control
                    mousedown: function(e) {
                        if (e.which == 1 && !$.contains(that.$jUI.element.get(0), e.target)) {
                            this.close();
                        }
                    }
                });
                that.trigger('open', {
                    event: event,
                    ui: ui
                });
            },

            close: function(event, ui) {
                that.$jUI._off(that.$jUI.document, 'mousedown');
                that.trigger('close', {
                    event: event,
                    ui: ui
                });
            }
        }).addClass('ui-widget ui-widget-content');

        that.$jUI = that.$node.data('uiAutocomplete');

        // redefine one menu item rendering method, fires every time, then popup opening
        that.$jUI._renderItem = function(ul, item) {
            var $itemNode = $('

');

            if (item.option.selected) {
                $itemNode.addClass('nb-select__item_selected_yes');
            }

            $itemNode.data('ui-autocomplete-item', item);
            $itemNode.append('' + item.label + '');
            $itemNode.appendTo(ul);

            return $itemNode;
        };

        // redefine valueMethod, extend with button text changing and fallback select value changing
        // if value not provided, return current value of fallback select
        that.$jUI.valueMethod = function(value) {
            if (value) {
                var text = that.$fallback.children('[value="' + value + '"]').text();
                that.setState({
                    value: value,
                    text: text
                });
            }
            return that.$selected.val();
        };

        // add click event for button
        $(this.button.node).on('click', function(evt) {
            // иначе сабмитит форму при клике
            evt.preventDefault();
            // close if already visible
            if (that.$node.autocomplete('widget').css('display') == 'block') {
                that.$node.autocomplete('close');
                return;
            }
            // pass empty string as value to search for, displaying all results
            that.$node.autocomplete('search', '');
            that.$node.focus();
        });
    },

    /**
     * Save value and text from <select> node.
     * @private
     */
    _updateFromSelect: function() {
        // get selected <option/>
        this.$selected = this.$fallback.children(':selected');

        this.value = this.$selected.val();
        //   - to prevent button from collapse if no text on <option/>
        this.text = this.$selected.text() || ' ';

        this.button.setText(this.text);
    },

    /**
     * Changes a value of control, text on the button and select value it the fallback
     * @param {Object} params — {
         *     text: '..'
         *     value: '..'
         * }
     * @fires 'nb-select_changed'
     */
    setState: function(params) {
        this.value = params.value;
        this.text = params.text;
        this.$selected.removeAttr('selected');

        this.$selected = this.$fallback.children('[value="' + this.value + '"]').attr('selected', 'selected');
        this.button.setText(this.text);

        this.trigger('nb-select_changed');

        this.$fallback.val(params.value);
        return this;
    },

    /**
     * Returns state of the select
     *
     * @return {Object} -
     * {
         *     value: '..'
         *     text: '..'
         * }
     */
    getState: function() {
        return {
            value: this.value,
            text: this.text
        };
    },

    /**
     * Disables the select
     * @fires 'nb-select_disabled'
     * @returns {nb.block}
     */
    disable: function() {
        if (this.isEnabled()) {
            this.button.disable();
            this.trigger('nb-select_disabled');
        }
        return this;
    },

    /**
     * Enables the select
     * @fires 'nb-select_enabled'
     * @returns {nb.block}
     */
    enable: function() {
        if (!this.isEnabled()) {
            this.button.enable();
            this.trigger('nb-select_enabled');
        }
        return this;
    },

    /**
     * Return state of the select
     * @returns {Boolean}
     */
    isEnabled: function() {
        return this.button.isEnabled();
    },

    /*
     * Set new items for select
     * @params {Array} source New source
     * @fires 'nb-select_enabled'
     * @returns {nb.block}
     */
    setSource: function(source) {
        var html = [];
        for (var i = 0, j = source.length; i < j; i++) {
            var item = source[i];
            html.push(
                '<option' +
                    ' label="' + item.text + '"' +
                    ' value="' + item.value + '"' +
                    (item.selected ? ' selected="selected"' : '') +
                    '>' + item.text + '</option>'
            );
        }

        // set new source for select
        this.$fallback.empty().append(html);

        this._updateFromSelect();
        this.trigger('nb-select_source-setted');
        return this;
    },

    /*
     * Get items from select
     * @returns {Array} source
     */
    getSource: function() {
        return this.$fallback.children('option').map(function() {
            return {
                text: $(this).text(),
                value: $(this).val()
            };
        });
    },

    /**
     * Focus the select
     * @fires 'nb-select_focused'
     * @returns {nb.block}
     */
    focus: function() {
        if (this.isEnabled()) {
            this.button.focus();
        }
        this.trigger('nb-select_focused');
        return this;
    },

    /**
     * Blur the select
     * @fires 'nb-select_blured'
     * @returns {nb.block}
     */
    blur: function() {
        if (this.isEnabled()) {
            this.button.blur();
        }
        this.trigger('nb-select_blured');
        return this;
    },

    /**
     * Destroy the select
     * @fires 'nb-select_destroyed'
     */
    destroy: function() {
        if (this.$node && this.$node.data('uiAutocomplete')) {
            this.button.destroy();
            $(this.button.node).off('click');
            this.$node.autocomplete('destroy');
        }

        this.trigger('nb-select_destroyed');
        nb.destroy(this.node.getAttribute('id'));
    }
});
<commit_msg>nb.select method  have to return common js Array, not jQuery Object<commit_after>/*
 * jQuery UI Depends:
 *        jquery.ui.autocomplete.js
 *        jquery.ui.button.js
 *        jquery.ui.core.js
 *        jquery.ui.widget.js
 *        jquery.ui.position.js
 *        jquery.ui.menu.js
 */

nb.define('select', {
    events: {
        'init': 'onInit'
        //'open' { event, ui}
        //'close' { event, ui}
    },

    /**
     * Init select
     * @fires 'nb-select_inited'
     */

    onInit: function() {
        nb.init(this);
        this.$node = $(this.node);
        this.data = this.data();

        // find elements and values
        this.button = this.children()[0];

        this.$fallback = this.$node.find('.nb-select__fallback');

        this._updateFromSelect();

        // preparing control depending on configuration and content
        this.controlPrepare();
        this.trigger('nb-select_inited');
    },

    /**
     * preparing control depending on configuration and content
     */
    controlPrepare: function() {
        var that = this;
        // preparing position parameters for popup from direction data
        var position = {};
        position.collision = 'flip';

        if (that.data.within) {
            position.within = that.data.within;
        }

        if (that.data.direction == 'top') {
            position.my = "left bottom";
            position.at = "left top";

        } else {
            position.my = "left top";
            position.at = "left bottom";
        }

        // select JUI control init
        this.$node.autocomplete({
            delay: 0,
            minLength: 0,
            autoFocus: false,
            position: position,
            appendTo: that.node,
            source: function(request, response) {
                response(that.$fallback.children('option').map(function() {
                    return {
                        label: $(this).text(),
                        value: $(this).val(),
                        option: this
                    };
                }));
            },
            select: function(event, ui) {
                ui.item.option.selected = true;

                that.$jUI._trigger('selected', event, {
                    item: ui.item.option
                });
            },
            // delegate handler on 'outer' click on open
            open: function(event, ui) {
                that.$jUI._on(that.$jUI.document, {
                    // on 'outer' mousedown close control
                    mousedown: function(e) {
                        if (e.which == 1 && !$.contains(that.$jUI.element.get(0), e.target)) {
                            this.close();
                        }
                    }
                });
                that.trigger('open', {
                    event: event,
                    ui: ui
                });
            },

            close: function(event, ui) {
                that.$jUI._off(that.$jUI.document, 'mousedown');
                that.trigger('close', {
                    event: event,
                    ui: ui
                });
            }
        }).addClass('ui-widget ui-widget-content');

        that.$jUI = that.$node.data('uiAutocomplete');

        // redefine one menu item rendering method, fires every time, then popup opening
        that.$jUI._renderItem = function(ul, item) {
            var $itemNode = $('

');

            if (item.option.selected) {
                $itemNode.addClass('nb-select__item_selected_yes');
            }

            $itemNode.data('ui-autocomplete-item', item);
            $itemNode.append('' + item.label + '');
            $itemNode.appendTo(ul);

            return $itemNode;
        };

        // redefine valueMethod, extend with button text changing and fallback select value changing
        // if value not provided, return current value of fallback select
        that.$jUI.valueMethod = function(value) {
            if (value) {
                var text = that.$fallback.children('[value="' + value + '"]').text();
                that.setState({
                    value: value,
                    text: text
                });
            }
            return that.$selected.val();
        };

        // add click event for button
        $(this.button.node).on('click', function(evt) {
            // иначе сабмитит форму при клике
            evt.preventDefault();
            // close if already visible
            if (that.$node.autocomplete('widget').css('display') == 'block') {
                that.$node.autocomplete('close');
                return;
            }
            // pass empty string as value to search for, displaying all results
            that.$node.autocomplete('search', '');
            that.$node.focus();
        });
    },

    /**
     * Save value and text from <select> node.
     * @private
     */
    _updateFromSelect: function() {
        // get selected <option/>
        this.$selected = this.$fallback.children(':selected');

        this.value = this.$selected.val();
        //   - to prevent button from collapse if no text on <option/>
        this.text = this.$selected.text() || ' ';

        this.button.setText(this.text);
    },

    /**
     * Changes a value of control, text on the button and select value it the fallback
     * @param {Object} params — {
         *     text: '..'
         *     value: '..'
         * }
     * @fires 'nb-select_changed'
     */
    setState: function(params) {
        this.value = params.value;
        this.text = params.text;
        this.$selected.removeAttr('selected');

        this.$selected = this.$fallback.children('[value="' + this.value + '"]').attr('selected', 'selected');
        this.button.setText(this.text);

        this.trigger('nb-select_changed');

        this.$fallback.val(params.value);
        return this;
    },

    /**
     * Returns state of the select
     *
     * @return {Object} -
     * {
         *     value: '..'
         *     text: '..'
         * }
     */
    getState: function() {
        return {
            value: this.value,
            text: this.text
        };
    },

    /**
     * Disables the select
     * @fires 'nb-select_disabled'
     * @returns {nb.block}
     */
    disable: function() {
        if (this.isEnabled()) {
            this.button.disable();
            this.trigger('nb-select_disabled');
        }
        return this;
    },

    /**
     * Enables the select
     * @fires 'nb-select_enabled'
     * @returns {nb.block}
     */
    enable: function() {
        if (!this.isEnabled()) {
            this.button.enable();
            this.trigger('nb-select_enabled');
        }
        return this;
    },

    /**
     * Return state of the select
     * @returns {Boolean}
     */
    isEnabled: function() {
        return this.button.isEnabled();
    },

    /*
     * Set new items for select
     * @params {Array} source New source
     * @fires 'nb-select_enabled'
     * @returns {nb.block}
     */
    setSource: function(source) {
        var html = [];
        for (var i = 0, j = source.length; i < j; i++) {
            var item = source[i];
            html.push(
                '<option' +
                    ' label="' + item.text + '"' +
                    ' value="' + item.value + '"' +
                    (item.selected ? ' selected="selected"' : '') +
                    '>' + item.text + '</option>'
            );
        }

        // set new source for select
        this.$fallback.empty().append(html);

        this._updateFromSelect();
        this.trigger('nb-select_source-setted');
        return this;
    },

    /*
     * Get items from select
     * @returns {Array} source
     */
    getSource: function() {
        return $.map(this.$fallback.children('option'), function(node) {
            return {
                text: $(node).text(),
                value: $(node).val()
            }
        });
    },

    /**
     * Focus the select
     * @fires 'nb-select_focused'
     * @returns {nb.block}
     */
    focus: function() {
        if (this.isEnabled()) {
            this.button.focus();
        }
        this.trigger('nb-select_focused');
        return this;
    },

    /**
     * Blur the select
     * @fires 'nb-select_blured'
     * @returns {nb.block}
     */
    blur: function() {
        if (this.isEnabled()) {
            this.button.blur();
        }
        this.trigger('nb-select_blured');
        return this;
    },

    /**
     * Destroy the select
     * @fires 'nb-select_destroyed'
     */
    destroy: function() {
        if (this.$node && this.$node.data('uiAutocomplete')) {
            this.button.destroy();
            $(this.button.node).off('click');
            this.$node.autocomplete('destroy');
        }

        this.trigger('nb-select_destroyed');
        nb.destroy(this.node.getAttribute('id'));
    }
});
<|endoftext|>


<commit_before>'use strict';

module.exports = function(kbox) {

  kbox.install.registerStep(function(step) {
    step.name = 'kalabox-services';
    step.description = step.name;
    step.deps = [];
    step.all = function(state, done) {
      console.log(step.name);
      done();
    };
  });

};
<commit_msg>Added services install, install step.<commit_after>'use strict';

module.exports = function(kbox) {

  // Install services.
  kbox.install.registerStep(function(step) {
    step.name = 'kalabox-services-kalabox';
    step.description = 'Install kalabox-services-kalabox plugin services.';
    step.deps = ['init-engine'];
    step.all = function(state, done) {
      kbox.services.install(function(err) {
        if (err) {
          state.log(state.status.notOk);
          done(err);
        } else {
          state.log(state.status.ok);
          done();
        }
      });
    };
  });

};
<|endoftext|>


<commit_before>// Copyright 2012 The Obvious Corporation.

/*
 * This simply fetches the right version of phantom for the current platform.
 */

'use strict'

var AdmZip = require('adm-zip')
var cp = require('child_process')
var fs = require('fs')
var helper = require('./lib/phantomjs')
var http = require('http')
var kew = require('kew')
var ncp = require('ncp')
var npmconf = require('npmconf')
var mkdirp = require('mkdirp')
var path = require('path')
var rimraf = require('rimraf').sync
var url = require('url')
var which = require('which')

var downloadUrl = 'http://phantomjs.googlecode.com/files/phantomjs-' + helper.version + '-'

var originalPath = process.env.PATH

// NPM adds bin directories to the path, which will cause `which` to find the
// bin for this package not the actual phantomjs bin.  Also help out people who
// put ./bin on their path
process.env.PATH = helper.cleanPath(originalPath)

var libPath = path.join(__dirname, 'lib', 'phantom')
var phantomPath = null
var tmpPath = null

var whichDeferred = kew.defer()
which('phantomjs', whichDeferred.makeNodeResolver())
whichDeferred.promise
  .then(function (path) {
    phantomPath = path

    // Horrible hack to avoid problems during global install. We check to see if
    // the file `which` found is our own bin script.
    // See: https://github.com/Obvious/phantomjs/issues/85
    if (/NPM_INSTALL_MARKER/.test(fs.readFileSync(phantomPath, 'utf8'))) {
      console.log('Looks like an `npm install -g`; unable to check for already installed version.')
      throw new Error('Global install')

    } else {
      var checkVersionDeferred = kew.defer()
      cp.execFile(phantomPath, ['--version'], checkVersionDeferred.makeNodeResolver())
      return checkVersionDeferred.promise
    }
  })
  .then(function (stdout) {
    var version = stdout.trim()
    if (helper.version == version) {
      writeLocationFile(phantomPath)
      console.log('PhantomJS is already installed at', phantomPath + '.')
      exit(0)

    } else {
      console.log('PhantomJS detected, but wrong version', stdout.trim(), '@', phantomPath + '.')
      throw new Error('Wrong version')
    }
  })
  .fail(function (err) {
    // Trying to use a local file failed, so initiate download and install
    // steps instead.
    var npmconfDeferred = kew.defer()
    npmconf.load(npmconfDeferred.makeNodeResolver())
    return npmconfDeferred.promise
  })
  .then(function (conf) {
    tmpPath = findSuitableTempDirectory(conf)

    // Can't use a global version so start a download.
    if (process.platform === 'linux' && process.arch === 'x64') {
      downloadUrl += 'linux-x86_64.tar.bz2'
    } else if (process.platform === 'linux') {
      downloadUrl += 'linux-i686.tar.bz2'
    } else if (process.platform === 'darwin') {
      downloadUrl += 'macosx.zip'
    } else if (process.platform === 'win32') {
      downloadUrl += 'windows.zip'
    } else {
      console.log('Unexpected platform or architecture:', process.platform, process.arch)
      exit(1)
    }

    var fileName = downloadUrl.split('/').pop()
    var downloadedFile = path.join(tmpPath, fileName)

    // Start the install.
    if (!fs.existsSync(downloadedFile)) {
      console.log('Downloading', downloadUrl)
      console.log('Saving to', downloadedFile)
      return requestBinary(getRequestOptions(conf.get('proxy')), downloadedFile)
    } else {
      console.log('Download already available at', downloadedFile)
      return downloadedFile
    }
  })
  .then(function (downloadedFile) {
    return extractDownload(downloadedFile, tmpPath)
  })
  .then(function () {
    return copyIntoPlace(tmpPath, libPath)
  })
  .then(function () {
    var location = process.platform === 'win32' ?
        path.join(libPath, 'phantomjs.exe') :
        path.join(libPath, 'bin' ,'phantomjs')
    writeLocationFile(location)
    console.log('Done. Phantomjs binary available at', location)
    exit(0)
  })
  .fail(function (err) {
    console.error('Phantom installation failed', err.stack)
    exit(1)
  })

function writeLocationFile(location) {
  console.log('Writing location.js file')
  if (process.platform === 'win32') {
    location = location.replace(/\\/g, '\\\\')
  }
  fs.writeFileSync(path.join(__dirname, 'lib', 'location.js'),
      'module.exports.location = "' + location + '"')
}

function exit(code) {
  process.env.PATH = originalPath
  process.exit(code || 0)
}

function findSuitableTempDirectory(npmConf) {
  var now = Date.now()
  var candidateTmpDirs = [
    process.env.TMPDIR || '/tmp',
    npmConf.get('tmp'),
    path.join(process.cwd(), 'tmp')
  ]

  for (var i = 0; i < candidateTmpDirs.length; i++) {
    var candidatePath = path.join(candidateTmpDirs[i], 'phantomjs')

    try {
      mkdirp.sync(candidatePath, '0777')
      var testFile = path.join(candidatePath, now + '.tmp')
      fs.writeFileSync(testFile, 'test')
      fs.unlinkSync(testFile)
      return candidatePath
    } catch (e) {
      console.log(candidatePath, 'is not writable:', e.message)
    }
  }

  console.error('Can not find a writable tmp directory, please report issue ' +
      'on https://github.com/Obvious/phantomjs/issues/59 with as much ' +
      'information as possible.')
  exit(1)
}

function getRequestOptions(proxyUrl) {
  if (proxyUrl) {
    var options = url.parse(proxyUrl)
    options.path = downloadUrl
    options.headers = { Host: url.parse(downloadUrl).host }
    // If going through proxy, spoof the User-Agent, since may commerical proxies block blank or unknown agents in headers
    options.headers['User-Agent'] = 'curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5'
    // Turn basic authorization into proxy-authorization.
    if (options.auth) {
      options.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(options.auth).toString('base64')
      delete options.auth
    }

    return options
  } else {
    return url.parse(downloadUrl)
  }
}

function requestBinary(requestOptions, filePath) {
  var deferred = kew.defer()

  var count = 0
  var notifiedCount = 0
  var outFile = fs.openSync(filePath, 'w')

  var client = http.get(requestOptions, function (response) {
    var status = response.statusCode
    console.log('Receiving...')

    if (status === 200) {
      response.addListener('data',   function (data) {
        fs.writeSync(outFile, data, 0, data.length, null)
        count += data.length
        if ((count - notifiedCount) > 800000) {
          console.log('Received ' + Math.floor(count / 1024) + 'K...')
          notifiedCount = count
        }
      })

      response.addListener('end',   function () {
        console.log('Received ' + Math.floor(count / 1024) + 'K total.')
        fs.closeSync(outFile)
        deferred.resolve(filePath)
      })

    } else {
      client.abort()
      deferred.reject('Error with http request: ' + util.inspect(response.headers))
    }
  })

  return deferred.promise
}

function extractDownload(filePath, tmpPath) {
  var deferred = kew.defer()
  var options = {cwd: tmpPath}

  if (filePath.substr(-4) === '.zip') {
    console.log('Extracting zip contents')

    try {
      var zip = new AdmZip(filePath)
      zip.extractAllTo(tmpPath, true)
      deferred.resolve(true)
    } catch (err) {
      deferred.reject('Error extracting archive ' + err.stack)
    }

  } else {
    console.log('Extracting tar contents (via spawned process)')
    cp.execFile('tar', ['jxf', filePath], options, function (err, stdout, stderr) {
      if (err) {
        deferred.reject('Error extracting archive ' + err.stack)
      } else {
        deferred.resolve(true)
      }
    })
  }
  return deferred.promise
}

function copyIntoPlace(tmpPath, targetPath) {
  rimraf(targetPath)

  var deferred = kew.defer()
  // Look for the extracted directory, so we can rename it.
  var files = fs.readdirSync(tmpPath)
  for (var i = 0; i < files.length; i++) {
    var file = path.join(tmpPath, files[i])
    if (fs.statSync(file).isDirectory()) {
      console.log('Renaming extracted folder', file, '->', targetPath)
      ncp(file, targetPath, deferred.makeNodeResolver())
      break
    }
  }

  return deferred.promise
}
<commit_msg>Explicitly set mode of tmp/phantomjs directory<commit_after>// Copyright 2012 The Obvious Corporation.

/*
 * This simply fetches the right version of phantom for the current platform.
 */

'use strict'

var AdmZip = require('adm-zip')
var cp = require('child_process')
var fs = require('fs')
var helper = require('./lib/phantomjs')
var http = require('http')
var kew = require('kew')
var ncp = require('ncp')
var npmconf = require('npmconf')
var mkdirp = require('mkdirp')
var path = require('path')
var rimraf = require('rimraf').sync
var url = require('url')
var which = require('which')

var downloadUrl = 'http://phantomjs.googlecode.com/files/phantomjs-' + helper.version + '-'

var originalPath = process.env.PATH

// NPM adds bin directories to the path, which will cause `which` to find the
// bin for this package not the actual phantomjs bin.  Also help out people who
// put ./bin on their path
process.env.PATH = helper.cleanPath(originalPath)

var libPath = path.join(__dirname, 'lib', 'phantom')
var phantomPath = null
var tmpPath = null

var whichDeferred = kew.defer()
which('phantomjs', whichDeferred.makeNodeResolver())
whichDeferred.promise
  .then(function (path) {
    phantomPath = path

    // Horrible hack to avoid problems during global install. We check to see if
    // the file `which` found is our own bin script.
    // See: https://github.com/Obvious/phantomjs/issues/85
    if (/NPM_INSTALL_MARKER/.test(fs.readFileSync(phantomPath, 'utf8'))) {
      console.log('Looks like an `npm install -g`; unable to check for already installed version.')
      throw new Error('Global install')

    } else {
      var checkVersionDeferred = kew.defer()
      cp.execFile(phantomPath, ['--version'], checkVersionDeferred.makeNodeResolver())
      return checkVersionDeferred.promise
    }
  })
  .then(function (stdout) {
    var version = stdout.trim()
    if (helper.version == version) {
      writeLocationFile(phantomPath)
      console.log('PhantomJS is already installed at', phantomPath + '.')
      exit(0)

    } else {
      console.log('PhantomJS detected, but wrong version', stdout.trim(), '@', phantomPath + '.')
      throw new Error('Wrong version')
    }
  })
  .fail(function (err) {
    // Trying to use a local file failed, so initiate download and install
    // steps instead.
    var npmconfDeferred = kew.defer()
    npmconf.load(npmconfDeferred.makeNodeResolver())
    return npmconfDeferred.promise
  })
  .then(function (conf) {
    tmpPath = findSuitableTempDirectory(conf)

    // Can't use a global version so start a download.
    if (process.platform === 'linux' && process.arch === 'x64') {
      downloadUrl += 'linux-x86_64.tar.bz2'
    } else if (process.platform === 'linux') {
      downloadUrl += 'linux-i686.tar.bz2'
    } else if (process.platform === 'darwin') {
      downloadUrl += 'macosx.zip'
    } else if (process.platform === 'win32') {
      downloadUrl += 'windows.zip'
    } else {
      console.log('Unexpected platform or architecture:', process.platform, process.arch)
      exit(1)
    }

    var fileName = downloadUrl.split('/').pop()
    var downloadedFile = path.join(tmpPath, fileName)

    // Start the install.
    if (!fs.existsSync(downloadedFile)) {
      console.log('Downloading', downloadUrl)
      console.log('Saving to', downloadedFile)
      return requestBinary(getRequestOptions(conf.get('proxy')), downloadedFile)
    } else {
      console.log('Download already available at', downloadedFile)
      return downloadedFile
    }
  })
  .then(function (downloadedFile) {
    return extractDownload(downloadedFile, tmpPath)
  })
  .then(function () {
    return copyIntoPlace(tmpPath, libPath)
  })
  .then(function () {
    var location = process.platform === 'win32' ?
        path.join(libPath, 'phantomjs.exe') :
        path.join(libPath, 'bin' ,'phantomjs')
    writeLocationFile(location)
    console.log('Done. Phantomjs binary available at', location)
    exit(0)
  })
  .fail(function (err) {
    console.error('Phantom installation failed', err.stack)
    exit(1)
  })

function writeLocationFile(location) {
  console.log('Writing location.js file')
  if (process.platform === 'win32') {
    location = location.replace(/\\/g, '\\\\')
  }
  fs.writeFileSync(path.join(__dirname, 'lib', 'location.js'),
      'module.exports.location = "' + location + '"')
}

function exit(code) {
  process.env.PATH = originalPath
  process.exit(code || 0)
}

function findSuitableTempDirectory(npmConf) {
  var now = Date.now()
  var candidateTmpDirs = [
    process.env.TMPDIR || '/tmp',
    npmConf.get('tmp'),
    path.join(process.cwd(), 'tmp')
  ]

  for (var i = 0; i < candidateTmpDirs.length; i++) {
    var candidatePath = path.join(candidateTmpDirs[i], 'phantomjs')

    try {
      mkdirp.sync(candidatePath, '0777')
      // Make double sure we have 0777 permissions; some operating systems
      // default umask does not allow write by default.
      fs.chmodSync(candidatePath, '0777')
      var testFile = path.join(candidatePath, now + '.tmp')
      fs.writeFileSync(testFile, 'test')
      fs.unlinkSync(testFile)
      return candidatePath
    } catch (e) {
      console.log(candidatePath, 'is not writable:', e.message)
    }
  }

  console.error('Can not find a writable tmp directory, please report issue ' +
      'on https://github.com/Obvious/phantomjs/issues/59 with as much ' +
      'information as possible.')
  exit(1)
}

function getRequestOptions(proxyUrl) {
  if (proxyUrl) {
    var options = url.parse(proxyUrl)
    options.path = downloadUrl
    options.headers = { Host: url.parse(downloadUrl).host }
    // If going through proxy, spoof the User-Agent, since may commerical proxies block blank or unknown agents in headers
    options.headers['User-Agent'] = 'curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5'
    // Turn basic authorization into proxy-authorization.
    if (options.auth) {
      options.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(options.auth).toString('base64')
      delete options.auth
    }

    return options
  } else {
    return url.parse(downloadUrl)
  }
}

function requestBinary(requestOptions, filePath) {
  var deferred = kew.defer()

  var count = 0
  var notifiedCount = 0
  var outFile = fs.openSync(filePath, 'w')

  var client = http.get(requestOptions, function (response) {
    var status = response.statusCode
    console.log('Receiving...')

    if (status === 200) {
      response.addListener('data',   function (data) {
        fs.writeSync(outFile, data, 0, data.length, null)
        count += data.length
        if ((count - notifiedCount) > 800000) {
          console.log('Received ' + Math.floor(count / 1024) + 'K...')
          notifiedCount = count
        }
      })

      response.addListener('end',   function () {
        console.log('Received ' + Math.floor(count / 1024) + 'K total.')
        fs.closeSync(outFile)
        deferred.resolve(filePath)
      })

    } else {
      client.abort()
      deferred.reject('Error with http request: ' + util.inspect(response.headers))
    }
  })

  return deferred.promise
}

function extractDownload(filePath, tmpPath) {
  var deferred = kew.defer()
  var options = {cwd: tmpPath}

  if (filePath.substr(-4) === '.zip') {
    console.log('Extracting zip contents')

    try {
      var zip = new AdmZip(filePath)
      zip.extractAllTo(tmpPath, true)
      deferred.resolve(true)
    } catch (err) {
      deferred.reject('Error extracting archive ' + err.stack)
    }

  } else {
    console.log('Extracting tar contents (via spawned process)')
    cp.execFile('tar', ['jxf', filePath], options, function (err, stdout, stderr) {
      if (err) {
        deferred.reject('Error extracting archive ' + err.stack)
      } else {
        deferred.resolve(true)
      }
    })
  }
  return deferred.promise
}

function copyIntoPlace(tmpPath, targetPath) {
  rimraf(targetPath)

  var deferred = kew.defer()
  // Look for the extracted directory, so we can rename it.
  var files = fs.readdirSync(tmpPath)
  for (var i = 0; i < files.length; i++) {
    var file = path.join(tmpPath, files[i])
    if (fs.statSync(file).isDirectory()) {
      console.log('Renaming extracted folder', file, '->', targetPath)
      ncp(file, targetPath, deferred.makeNodeResolver())
      break
    }
  }

  return deferred.promise
}
<|endoftext|>


<commit_before>require('./src/createDataReader.test.js')
require('./src/loader/createVerge1MapLoader.test.js')
require('./src/loader/createVerge1VspLoader.test.js')
require('./src/converter/createVerge1VspConverter.test.js')
require('./src/loader/createVerge1PalLoader.test.js')
require('./src/loader/createVerge1ChrLoader.test.js')
require('./src/converter/createVerge1ChrConverter.test.js')
require('./src/converter/createTileGridConverter.test.js')
require('./src/loader/createVerge1SmallFntLoader.test.js')
require('./src/loader/createVerge1MainFntLoader.test.js')
require('./src/loader/createVerge1BoxRawLoader.test.js')
require('./src/converter/createVerge1SmallFntConverter.test.js')
require('./src/converter/createVerge1MainFntConverter.test.js')
require('./src/converter/createVerge1BoxRawConverter.test.js')
require('./src/loader/createVerge1SpeechSpcLoader.test.js')
require('./src/converter/createVerge1SpeechSpcConverter.test.js')
require('./src/loader/createPcxLoader.test.js')
require('./src/converter/createPcxConverter.test.js')<commit_msg>sort tests<commit_after>require('./src/converter/createPcxConverter.test.js')
require('./src/converter/createTileGridConverter.test.js')
require('./src/converter/createVerge1BoxRawConverter.test.js')
require('./src/converter/createVerge1ChrConverter.test.js')
require('./src/converter/createVerge1MainFntConverter.test.js')
require('./src/converter/createVerge1SmallFntConverter.test.js')
require('./src/converter/createVerge1SpeechSpcConverter.test.js')
require('./src/converter/createVerge1VspConverter.test.js')
require('./src/createDataReader.test.js')
require('./src/loader/createPcxLoader.test.js')
require('./src/loader/createVerge1BoxRawLoader.test.js')
require('./src/loader/createVerge1ChrLoader.test.js')
require('./src/loader/createVerge1MainFntLoader.test.js')
require('./src/loader/createVerge1MapLoader.test.js')
require('./src/loader/createVerge1PalLoader.test.js')
require('./src/loader/createVerge1SmallFntLoader.test.js')
require('./src/loader/createVerge1SpeechSpcLoader.test.js')
require('./src/loader/createVerge1VspLoader.test.js')<|endoftext|>


<commit_before>define(function(require, exports, module) {
module.exports = '\n\
import jedi\n\
import json\n\
import sys\n\
\n\
row = int(sys.argv[1])\n\
column = int(sys.argv[2])\n\
script = jedi.Script(sys.stdin.read(), row, column, "name.py")\n\
\n\
def to_json(d):\n\
    return {\n\
        "path": d.module_path,\n\
        "row": d.line,\n\
        "column": d.column,\n\
    }\n\
\n\
print json.dumps(script.goto_definitions(), default = to_json)\n\
';
});<commit_msg>Jump to python library files outside of VFS dir<commit_after>define(function(require, exports, module) {
module.exports = '\n\
import jedi\n\
import json\n\
import sys\n\
\n\
row = int(sys.argv[1])\n\
column = int(sys.argv[2])\n\
script = jedi.Script(sys.stdin.read(), row, column, "name.py")\n\
\n\
def to_json(d):\n\
    return {\n\
        "path": "/" + d.module_path,\n\
        "row": d.line,\n\
        "column": d.column,\n\
    }\n\
\n\
print json.dumps(script.goto_definitions(), default = to_json)\n\
';
});<|endoftext|>


<commit_before>angular.module('app.services').factory('favorite',
  function ($http, serverConfig) {
    var _bookmarks = []
    return {
      load: function(){
        return $http.get(serverConfig.url + '/api/bookmarks/list/all/1').then(function(response){
          _bookmarks = response.data.items
          return(response.data.items)
        })
      },

      isBookmarked: function(activity){
        var bookmarkedIDs = _bookmarks.map(function(b){
          return(b.item_id)
        })
        var aID = activity.get('entity').id
        return bookmarkedIDs.includes(aID)
      },
      addBookmark: function(activity){
        var aID = activity.get('entity').id
        var aType = activity.get('entity').type
        if(aType == 'micro-petition'){
          var hasTitle = activity.get('title') && activity.get('title').length > 0
          if(hasTitle)
            aType = 'petition'
          else
            aType = 'post'
        }
        var that = this

        $http.post(serverConfig.url + '/api/bookmarks/add/'+aType+'/'+aID).then(function(){
          that.load()
        })
      },

      removeBookmark: function(activity){
        var aID = activity.get('entity').id
        $http.delete(serverConfig.url + '/api/bookmarks/remove/'+aID).then(function(){
          that.load()
        })
      }
    }
  });
<commit_msg>#125: fix remove bookmark API call id<commit_after>angular.module('app.services').factory('favorite',
  function ($http, serverConfig) {
    var _bookmarks = []
    return {
      load: function(){
        return $http.get(serverConfig.url + '/api/bookmarks/list/all/1').then(function(response){
          _bookmarks = response.data.items
          return(response.data.items)
        })
      },

      isBookmarked: function(activity){
        var bookmarkedIDs = _bookmarks.map(function(b){
          return(b.item_id)
        })
        var aID = activity.get('entity').id
        return bookmarkedIDs.includes(aID)
      },
      addBookmark: function(activity){
        var aID = activity.get('entity').id
        var aType = activity.get('entity').type
        if(aType == 'micro-petition'){
          var hasTitle = activity.get('title') && activity.get('title').length > 0
          if(hasTitle)
            aType = 'petition'
          else
            aType = 'post'
        }
        var that = this

        $http.post(serverConfig.url + '/api/bookmarks/add/'+aType+'/'+aID).then(function(){
          that.load()
        })
      },

      removeBookmark: function(activity){
        var that = this
        var aID = activity.get('entity').id
        var bookmark =  _bookmarks.find(function(b){
          return(b.item_id = aID)
        })
        var bID = bookmark.id

        $http.delete(serverConfig.url + '/api/bookmarks/remove/'+bID).then(function(){
          that.load()
        })
      }
    }
  });
<|endoftext|>


<commit_before>angular.module('emission.splash.pushnotify', ['ionic.cloud', 'emission.plugin.logger',
                                              'angularLocalStorage'])
.factory('PushNotify', function($window, $state, $rootScope, $ionicPush, $ionicPlatform,        $ionicPopup, storage, Logger) {

    var pushnotify = {};
    var nativeNotifyNames = {
        "ios": "TRANSITION_NOTIFY_NAME",
        "android": "TRANSITION_NOTIFY_NAME"
    }

    var push = null;

    pushnotify.startupInit = function() {
      var push = $window.PushNotification.init({
        "ios": {
          "badge": true,
          "sound": true,
          "vibration": true,
          "clearBadge": true
        },
        "android": {
          "senderID": "97387382925",
          "iconColor": "#343434",
          "clearNotifications": true
        }
      });
    }

    $ionicPlatform.ready().then(function() {
      $ionicPush.register().then(function(t) {
         alert("Token = "+JSON.stringify(t));
         console.log("Token = "+JSON.stringify(t));
         return $ionicPush.saveToken(t);
      }).then(function(t) {
         alert("Finished saving token = "+JSON.stringify(t.token));
         console.log("Finished saving token = "+JSON.stringify(t.token));
      }).catch(function(error) {
         $ionicPopup.alert({template: JSON.stringify(error)});
      });;
      var notifyEventName = nativeNotifyNames[ionic.Platform.platform()];
      $rootScope.$on('cloud:push:notification', function(event, data) {
        var msg = data.message;
        console.log("data = "+JSON.stringify(data));

        if (data.raw.additionalData["content-available"] == 1) {
          console.log("Found silent push notification, for platform "+ionic.Platform.platform());
          $window.cordova.plugins.BEMDataCollection.handleSilentPush()
            .then(function() {
               $ionicPush.plugin.finish(function(result) {
                 console.log("Finish successful with result " + result);
               }, function(error) {
                 console.log("Finish unsuccessful with result "+error);
               });
            });
        };
     });
      $window.broadcaster.addEventListener(notifyEventName, function(e) {
          console.log("Event = "+JSON.stringify(e));
          /*
          push.finish(function() {
              console.log("processing of push data is finished");
          }, function() {
              console.log("something went wrong with push.finish for ID = " + data.additionalData.notId)
          }, data.additionalData.notId);
          */
      });

      Logger.log("pushnotify startup done");
    });

    return pushnotify;
});
<commit_msg>Change the push notify code to update our profile<commit_after>angular.module('emission.splash.pushnotify', ['ionic.cloud', 'emission.plugin.logger',
                                              'emission.services',
                                              'angularLocalStorage'])
.factory('PushNotify', function($window, $state, $rootScope, $ionicPush, $ionicPlatform,        $ionicPopup, storage, Logger, CommHelper) {

    var pushnotify = {};
    var push = null;

    pushnotify.startupInit = function() {
      var push = $window.PushNotification.init({
        "ios": {
          "badge": true,
          "sound": true,
          "vibration": true,
          "clearBadge": true
        },
        "android": {
          "senderID": "97387382925",
          "iconColor": "#343434",
          "clearNotifications": true
        }
      });
    }

    pushnotify.registerPush = function() {
      $ionicPush.register().then(function(t) {
         // alert("Token = "+JSON.stringify(t));
         Logger.log("Token = "+JSON.stringify(t));
         return $window.cordova.plugins.BEMServerSync.getConfig().then(function(config) {
            return config.sync_interval;
         }, function(error) {
            console.log("Got error "+error+" while reading config, returning default = 3600");
            return 3600;
         }).then(function(sync_interval) {
             CommHelper.updateUser({
                device_token: t.token,
                curr_platform: ionic.Platform.platform(),
                curr_sync_interval: sync_interval
             });
             return t;
         }).then(function(t) {
            // TODO: Figure out if we need this if we are going to invoke manually with tokens...
            return $ionicPush.saveToken(t);
         });
      }).then(function(t) {
         // alert("Finished saving token = "+JSON.stringify(t.token));
         Logger.log("Finished saving token = "+JSON.stringify(t.token));
      }).catch(function(error) {
         $ionicPopup.alert({template: JSON.stringify(error)});
      });
    }

    var redirectSilentPush = function(event, data) {
        Logger.log("Found silent push notification, for platform "+ionic.Platform.platform());
        if (!$ionicPlatform.is('ios')) {
          Logger.log("Platform is not ios, handleSilentPush is not implemented or needed");
          return;
        }
        Logger.log("Platform is ios, calling handleSilentPush on DataCollection");

        pushnotify.datacollect.handleSilentPush()
        .then(function() {
           Logger.log("silent push finished successfully, calling push.finish");
           showDebugLocalNotification("silent push finished, calling push.finish");
           $ionicPush.plugin.finish(function(result) {
             Logger.log("Finish successful with result " + result);
           }, function(error) {
             Logger.log("Finish unsuccessful with result "+error);
           });
        })
        .catch(function(error) {
            $ionicPopup.alert({template: JSON.stringify(error)});
        });
    }

    var showDebugLocalNotification = function(message) {
        pushnotify.datacollect.getConfig().then(function(config) {
            if(config.simulate_user_interaction) {
              var actions = [ {
                    identifier: 'SIGN_IN',
                    title: 'Yes',
                    icon: 'res://ic_signin',
                    activationMode: 'background',
                    destructive: false,
                    authenticationRequired: true
                },
                {
                   identifier: 'MORE_SIGNIN_OPTIONS',
                   title: 'More Options',
                   icon: 'res://ic_moreoptions',
                   activationMode: 'foreground',
                   destructive: false,
                   authenticationRequired: false
                },
                {
                   identifier: 'PROVIDE_INPUT',
                   title: 'Provide Input',
                   icon: 'ic_input',
                   activationMode: 'background',
                   destructive: false,
                   authenticationRequired: false,
                   behavior: 'textInput',
                   textInputSendTitle: 'Reply'
                }];

              cordova.plugins.notification.local.schedule({
                  id: 1,
                  title: "Debug javascript notification",
                  text: message,
                  actions: [actions[0], actions[1]],
                  category: 'SIGN_IN_TO_CLASS'
              });
            }
        });
    }

    pushnotify.registerNotificationHandler = function() {
      $rootScope.$on('cloud:push:notification', function(event, data) {
        var msg = data.message;
        Logger.log("data = "+JSON.stringify(data));
        if (data.raw.additionalData["content-available"] == 1) {
           redirectSilentPush(event, data);
        };
      });
    };

    $ionicPlatform.ready().then(function() {
      pushnotify.datacollect = $window.cordova.plugins.BEMDataCollection;
      pushnotify.registerPush();
      pushnotify.registerNotificationHandler();

      Logger.log("pushnotify startup done");
    });

    return pushnotify;
});
<|endoftext|>