<commit_before>// The Post Settings Menu available in the content preview screen, as well as the post editor.

/*global window, document, $, _, Backbone, Ghost, moment */

(function () {
    "use strict";

    Ghost.View.PostSettings = Ghost.View.extend({

        events: {
            'blur  .post-setting-slug' : 'editSlug',
            'click .post-setting-slug' : 'selectSlug',
            'blur  .post-setting-date' : 'editDate',
            'click .post-setting-static-page' : 'toggleStaticPage',
            'click .delete' : 'deletePost'
        },

        initialize: function () {
            if (this.model) {
                this.listenTo(this.model, 'change:id', this.render);
                this.listenTo(this.model, 'change:status', this.render);
                this.listenTo(this.model, 'change:published_at', this.render);
                this.listenTo(this.model, 'change:page', this.render);
                this.listenTo(this.model, 'change:title', this.updateSlugPlaceholder);
            }
        },

        render: function () {
            var slug = this.model ? this.model.get('slug') : '',
                pubDate = this.model ? this.model.get('published_at') : 'Not Published',
                $pubDateEl = this.$('.post-setting-date'),
                $postSettingSlugEl = this.$('.post-setting-slug'),
                publishedDateFormat = 'DD MMM YY @ HH:mm';

            $postSettingSlugEl.val(slug);

            // Update page status test if already a page.
            if (this.model && this.model.get('page')) {
                $('.post-setting-static-page').prop('checked', this.model.get('page'));
            }

            // Insert the published date, and make it editable if it exists.
            if (this.model && this.model.get('published_at')) {
                pubDate = moment(pubDate).format(publishedDateFormat);
                $pubDateEl.attr('placeholder', '');
            } else {
                $pubDateEl.attr('placeholder', moment().format(publishedDateFormat));
            }

            if (this.model && this.model.get('id')) {
                this.$('.post-setting-page').removeClass('hidden');
                this.$('.delete').removeClass('hidden');
            }

            // Apply different style for model's that aren't
            // yet persisted to the server.
            // Mostly we're hiding the delete post UI
            if (this.model.id === undefined) {
                this.$el.addClass('unsaved');
            } else {
                this.$el.removeClass('unsaved');
            }

            $pubDateEl.val(pubDate);
        },

        // Requests a new slug when the title was changed
        updateSlugPlaceholder: function () {
            var title = this.model.get('title'),
                $postSettingSlugEl = this.$('.post-setting-slug');

            // If there's a title present we want to
            // validate it against existing slugs in the db
            // and then update the placeholder value.
            if (title) {
                $.ajax({
                    url: Ghost.paths.apiRoot + '/posts/getSlug/' + encodeURIComponent(title) + '/',
                    success: function (result) {
                        $postSettingSlugEl.attr('placeholder', result);
                    }
                });
            } else {
                // If there's no title set placeholder to blank
                // and don't make an ajax request to server
                // for a proper slug (as there won't be any).
                $postSettingSlugEl.attr('placeholder', '');
                return;
            }
        },

        selectSlug: function (e) {
            e.currentTarget.select();
        },

        editSlug: _.debounce(function (e) {
            e.preventDefault();
            var self = this,
                slug = self.model.get('slug'),
                slugEl = e.currentTarget,
                newSlug = slugEl.value;

            // If the model doesn't currently
            // exist on the server (aka has no id)
            // then just update the model's value
            if (self.model.id === undefined) {
                this.model.set({
                    slug: newSlug
                });
                return;
            }

            // Ignore unchanged slugs
            if (slug === newSlug) {
                slugEl.value = slug === undefined ? '' : slug;
                return;
            }

            this.model.save({
                slug: newSlug
            }, {
                success : function (model, response, options) {
                    /*jslint unparam:true*/
                    // Repopulate slug in case it changed on the server (e.g. 'new-slug-2')
                    slugEl.value = model.get('slug');
                    Ghost.notifications.addItem({
                        type: 'success',
                        message: "Permalink successfully changed to " + model.get('slug') + '.',
                        status: 'passive'
                    });
                },
                error : function (model, xhr) {
                    /*jslint unparam:true*/
                    Ghost.notifications.addItem({
                        type: 'error',
                        message: Ghost.Views.Utils.getRequestErrorMessage(xhr),
                        status: 'passive'
                    });
                }
            });
        }, 500),

        editDate: _.debounce(function (e) {
            e.preventDefault();
            var self = this,
                parseDateFormats = ['DD MMM YY HH:mm', 'DD MMM YYYY HH:mm', 'DD/MM/YY HH:mm', 'DD/MM/YYYY HH:mm', 'DD-MM-YY HH:mm', 'DD-MM-YYYY HH:mm'],
                displayDateFormat = 'DD MMM YY @ HH:mm',
                errMessage = '',
                pubDate = self.model.get('published_at'),
                pubDateEl = e.currentTarget,
                newPubDate = pubDateEl.value,
                pubDateMoment,
                newPubDateMoment;

            // if there is no new pub date do nothing
            if (!newPubDate) {
                return;
            }

            // Check for missing time stamp on new data
            // If no time specified, add a 12:00
            if (newPubDate && !newPubDate.slice(-5).match(/\d+:\d\d/)) {
                newPubDate += " 12:00";
            }

            newPubDateMoment = moment(newPubDate, parseDateFormats);

            // If there was a published date already set
            if (pubDate) {
                 // Check for missing time stamp on current model
                // If no time specified, add a 12:00
                if (!pubDate.slice(-5).match(/\d+:\d\d/)) {
                    pubDate += " 12:00";
                }

                pubDateMoment = moment(pubDate, parseDateFormats);

                 // Ensure the published date has changed
                if (newPubDate.length === 0 || pubDateMoment.isSame(newPubDateMoment)) {
                    // If it wasn't, reset it and return
                    pubDateEl.value = pubDateMoment.format(displayDateFormat);
                    return;
                }
            }

            // Validate new Published date
            if (!newPubDateMoment.isValid()) {
                errMessage = 'Published Date must be a valid date with format: DD MMM YY @ HH:mm (e.g. 6 Dec 14 @ 15:00)';
            }

            if (newPubDateMoment.diff(new Date(), 'h') > 0) {
                errMessage = 'Published Date cannot currently be in the future.';
            }

            if (errMessage.length) {
                // Show error message
                Ghost.notifications.addItem({
                    type: 'error',
                    message: errMessage,
                    status: 'passive'
                });

                // Reset back to original value and return
                pubDateEl.value = pubDateMoment ? pubDateMoment.format(displayDateFormat) : '';
                return;
            }

            // If the model doesn't currently
            // exist on the server (aka has no id)
            // then just update the model's value
            if (self.model.id === undefined) {
                this.model.set({
                    published_at: newPubDateMoment.toDate()
                });
                return;
            }

            // Save new 'Published' date
            this.model.save({
                published_at: newPubDateMoment.toDate()
            }, {
                success : function (model) {
                    pubDateEl.value = moment(model.get('published_at')).format(displayDateFormat);
                    Ghost.notifications.addItem({
                        type: 'success',
                        message: 'Publish date successfully changed to ' + pubDateEl.value + '.',
                        status: 'passive'
                    });
                },
                error : function (model, xhr) {
                    /*jslint unparam:true*/
                    Ghost.notifications.addItem({
                        type: 'error',
                        message: Ghost.Views.Utils.getRequestErrorMessage(xhr),
                        status: 'passive'
                    });
                }
            });

        }, 500),

        toggleStaticPage: _.debounce(function (e) {
            var pageEl = $(e.currentTarget),
                page = pageEl.prop('checked');

            // Don't try to save
            // if the model doesn't currently
            // exist on the server
            if (this.model.id === undefined) {
                this.model.set({
                    page: page
                });
                return;
            }

            this.model.save({
                page: page
            }, {
                success : function (model, response, options) {
                    /*jslint unparam:true*/
                    pageEl.prop('checked', page);
                    Ghost.notifications.addItem({
                        type: 'success',
                        message: "Successfully converted " + (page ? "to static page" : "to post") + '.',
                        status: 'passive'
                    });
                },
                error : function (model, xhr) {
                    /*jslint unparam:true*/
                    Ghost.notifications.addItem({
                        type: 'error',
                        message: Ghost.Views.Utils.getRequestErrorMessage(xhr),
                        status: 'passive'
                    });
                }
            });
        }, 500),

        deletePost: function (e) {
            e.preventDefault();
            var self = this;
            // You can't delete a post
            // that hasn't yet been saved
            if (this.model.id === undefined) {
                return;
            }
            this.addSubview(new Ghost.Views.Modal({
                model: {
                    options: {
                        close: false,
                        confirm: {
                            accept: {
                                func: function () {
                                    self.model.destroy({
                                        wait: true
                                    }).then(function () {
                                        // Redirect to content screen if deleting post from editor.
                                        if (window.location.pathname.indexOf('editor') > -1) {
                                            window.location = Ghost.paths.subdir + '/ghost/content/';
                                        }
                                        Ghost.notifications.addItem({
                                            type: 'success',
                                            message: 'Your post has been deleted.',
                                            status: 'passive'
                                        });
                                    }, function () {
                                        Ghost.notifications.addItem({
                                            type: 'error',
                                            message: 'Your post could not be deleted. Please try again.',
                                            status: 'passive'
                                        });
                                    });
                                },
                                text: "Yes"
                            },
                            reject: {
                                func: function () {
                                    return true;
                                },
                                text: "No"
                            }
                        },
                        type: "action",
                        style: ["wide", "centered"],
                        animation: 'fade'
                    },
                    content: {
                        template: 'blank',
                        title: 'Are you sure you want to delete this post?',
                        text: '
This is permanent! No backups, no restores, no magic undo button.
 We warned you, ok?
'
                    }
                }
            }));
        }

    });

}());
<commit_msg>Post settings don't render on change<commit_after>// The Post Settings Menu available in the content preview screen, as well as the post editor.

/*global window, document, $, _, Backbone, Ghost, moment */

(function () {
    "use strict";

    var parseDateFormats = ['DD MMM YY  HH:mm', 'DD MMM YYYY HH:mm', 'DD/MM/YY HH:mm', 'DD/MM/YYYY HH:mm',
            'DD-MM-YY HH:mm', 'DD-MM-YYYY HH:mm'],
        displayDateFormat = 'DD MMM YY @ HH:mm';

    Ghost.View.PostSettings = Ghost.View.extend({

        events: {
            'blur  .post-setting-slug' : 'editSlug',
            'click .post-setting-slug' : 'selectSlug',
            'blur  .post-setting-date' : 'editDate',
            'click .post-setting-static-page' : 'toggleStaticPage',
            'click .delete' : 'deletePost'
        },

        initialize: function () {
            if (this.model) {
                // These three items can be updated outside of the post settings menu, so have to be listened to.
                this.listenTo(this.model, 'change:id', this.render);
                this.listenTo(this.model, 'change:title', this.updateSlugPlaceholder);
                this.listenTo(this.model, 'change:published_at', this.updatePublishedDate);
            }
        },

        render: function () {
            var slug = this.model ? this.model.get('slug') : '',
                pubDate = this.model ? this.model.get('published_at') : 'Not Published',
                $pubDateEl = this.$('.post-setting-date'),
                $postSettingSlugEl = this.$('.post-setting-slug');

            $postSettingSlugEl.val(slug);

            // Update page status test if already a page.
            if (this.model && this.model.get('page')) {
                $('.post-setting-static-page').prop('checked', this.model.get('page'));
            }

            // Insert the published date, and make it editable if it exists.
            if (this.model && this.model.get('published_at')) {
                pubDate = moment(pubDate).format(displayDateFormat);
                $pubDateEl.attr('placeholder', '');
            } else {
                $pubDateEl.attr('placeholder', moment().format(displayDateFormat));
            }

            if (this.model && this.model.get('id')) {
                this.$('.post-setting-page').removeClass('hidden');
                this.$('.delete').removeClass('hidden');
            }

            // Apply different style for model's that aren't
            // yet persisted to the server.
            // Mostly we're hiding the delete post UI
            if (this.model.id === undefined) {
                this.$el.addClass('unsaved');
            } else {
                this.$el.removeClass('unsaved');
            }

            $pubDateEl.val(pubDate);
        },

        // Requests a new slug when the title was changed
        updateSlugPlaceholder: function () {
            var title = this.model.get('title'),
                $postSettingSlugEl = this.$('.post-setting-slug');

            // If there's a title present we want to
            // validate it against existing slugs in the db
            // and then update the placeholder value.
            if (title) {
                $.ajax({
                    url: Ghost.paths.apiRoot + '/posts/getSlug/' + encodeURIComponent(title) + '/',
                    success: function (result) {
                        $postSettingSlugEl.attr('placeholder', result);
                    }
                });
            } else {
                // If there's no title set placeholder to blank
                // and don't make an ajax request to server
                // for a proper slug (as there won't be any).
                $postSettingSlugEl.attr('placeholder', '');
                return;
            }
        },

        selectSlug: function (e) {
            e.currentTarget.select();
        },

        editSlug: _.debounce(function (e) {
            e.preventDefault();
            var self = this,
                slug = self.model.get('slug'),
                slugEl = e.currentTarget,
                newSlug = slugEl.value;

            // If the model doesn't currently
            // exist on the server (aka has no id)
            // then just update the model's value
            if (self.model.id === undefined) {
                this.model.set({
                    slug: newSlug
                });
                return;
            }

            // Ignore unchanged slugs
            if (slug === newSlug) {
                slugEl.value = slug === undefined ? '' : slug;
                return;
            }

            this.model.save({
                slug: newSlug
            }, {
                success : function (model, response, options) {
                    /*jslint unparam:true*/
                    // Repopulate slug in case it changed on the server (e.g. 'new-slug-2')
                    slugEl.value = model.get('slug');
                    Ghost.notifications.addItem({
                        type: 'success',
                        message: "Permalink successfully changed to " + model.get('slug') + '.',
                        status: 'passive'
                    });
                },
                error : function (model, xhr) {
                    /*jslint unparam:true*/
                    slugEl.value = model.previous('slug');
                    Ghost.notifications.addItem({
                        type: 'error',
                        message: Ghost.Views.Utils.getRequestErrorMessage(xhr),
                        status: 'passive'
                    });
                }
            });
        }, 500),

        updatePublishedDate: function () {
            var pubDate = this.model.get('published_at') ? moment(this.model.get('published_at'))
                    .format(displayDateFormat) : '',
                $pubDateEl = this.$('.post-setting-date');

            // Only change the date if it's different
            if (pubDate && $pubDateEl.val() !== pubDate) {
                $pubDateEl.val(pubDate);
            }
        },

        editDate: _.debounce(function (e) {
            e.preventDefault();
            var self = this,
                errMessage = '',
                pubDate = moment(self.model.get('published_at')).format(displayDateFormat),
                pubDateEl = e.currentTarget,
                newPubDate = pubDateEl.value,
                pubDateMoment,
                newPubDateMoment;

            // if there is no new pub date do nothing
            if (!newPubDate) {
                return;
            }

            // Check for missing time stamp on new data
            // If no time specified, add a 12:00
            if (newPubDate && !newPubDate.slice(-5).match(/\d+:\d\d/)) {
                newPubDate += " 12:00";
            }

            newPubDateMoment = moment(newPubDate, parseDateFormats);

            // If there was a published date already set
            if (pubDate) {
                 // Check for missing time stamp on current model
                // If no time specified, add a 12:00
                if (!pubDate.slice(-5).match(/\d+:\d\d/)) {
                    pubDate += " 12:00";
                }

                pubDateMoment = moment(pubDate, parseDateFormats);

                 // Ensure the published date has changed
                if (newPubDate.length === 0 || pubDateMoment.isSame(newPubDateMoment)) {
                    // If it wasn't, reset it and return
                    pubDateEl.value = pubDateMoment.format(displayDateFormat);
                    return;
                }
            }

            // Validate new Published date
            if (!newPubDateMoment.isValid()) {
                errMessage = 'Published Date must be a valid date with format: DD MMM YY @ HH:mm (e.g. 6 Dec 14 @ 15:00)';
            }

            if (newPubDateMoment.diff(new Date(), 'h') > 0) {
                errMessage = 'Published Date cannot currently be in the future.';
            }

            if (errMessage.length) {
                // Show error message
                Ghost.notifications.addItem({
                    type: 'error',
                    message: errMessage,
                    status: 'passive'
                });

                // Reset back to original value and return
                pubDateEl.value = pubDateMoment ? pubDateMoment.format(displayDateFormat) : '';
                return;
            }

            // If the model doesn't currently
            // exist on the server (aka has no id)
            // then just update the model's value
            if (self.model.id === undefined) {
                this.model.set({
                    published_at: newPubDateMoment.toDate()
                });
                return;
            }

            // Save new 'Published' date
            this.model.save({
                published_at: newPubDateMoment.toDate()
            }, {
                success : function (model) {
                    pubDateEl.value = moment(model.get('published_at')).format(displayDateFormat);
                    Ghost.notifications.addItem({
                        type: 'success',
                        message: 'Publish date successfully changed to ' + pubDateEl.value + '.',
                        status: 'passive'
                    });
                },
                error : function (model, xhr) {
                    /*jslint unparam:true*/
                    //  Reset back to original value
                    pubDateEl.value = pubDateMoment ? pubDateMoment.format(displayDateFormat) : '';
                    Ghost.notifications.addItem({
                        type: 'error',
                        message: Ghost.Views.Utils.getRequestErrorMessage(xhr),
                        status: 'passive'
                    });
                }
            });

        }, 500),

        toggleStaticPage: _.debounce(function (e) {
            var pageEl = $(e.currentTarget),
                page = pageEl.prop('checked');

            // Don't try to save
            // if the model doesn't currently
            // exist on the server
            if (this.model.id === undefined) {
                this.model.set({
                    page: page
                });
                return;
            }

            this.model.save({
                page: page
            }, {
                success : function (model, response, options) {
                    /*jslint unparam:true*/
                    pageEl.prop('checked', page);
                    Ghost.notifications.addItem({
                        type: 'success',
                        message: "Successfully converted " + (page ? "to static page" : "to post") + '.',
                        status: 'passive'
                    });
                },
                error : function (model, xhr) {
                    /*jslint unparam:true*/
                    pageEl.prop('checked', model.previous('page'));
                    Ghost.notifications.addItem({
                        type: 'error',
                        message: Ghost.Views.Utils.getRequestErrorMessage(xhr),
                        status: 'passive'
                    });
                }
            });
        }, 500),

        deletePost: function (e) {
            e.preventDefault();
            var self = this;
            // You can't delete a post
            // that hasn't yet been saved
            if (this.model.id === undefined) {
                return;
            }
            this.addSubview(new Ghost.Views.Modal({
                model: {
                    options: {
                        close: false,
                        confirm: {
                            accept: {
                                func: function () {
                                    self.model.destroy({
                                        wait: true
                                    }).then(function () {
                                        // Redirect to content screen if deleting post from editor.
                                        if (window.location.pathname.indexOf('editor') > -1) {
                                            window.location = Ghost.paths.subdir + '/ghost/content/';
                                        }
                                        Ghost.notifications.addItem({
                                            type: 'success',
                                            message: 'Your post has been deleted.',
                                            status: 'passive'
                                        });
                                    }, function () {
                                        Ghost.notifications.addItem({
                                            type: 'error',
                                            message: 'Your post could not be deleted. Please try again.',
                                            status: 'passive'
                                        });
                                    });
                                },
                                text: "Yes"
                            },
                            reject: {
                                func: function () {
                                    return true;
                                },
                                text: "No"
                            }
                        },
                        type: "action",
                        style: ["wide", "centered"],
                        animation: 'fade'
                    },
                    content: {
                        template: 'blank',
                        title: 'Are you sure you want to delete this post?',
                        text: '
This is permanent! No backups, no restores, no magic undo button.
 We warned you, ok?
'
                    }
                }
            }));
        }

    });

}());
<|endoftext|>


<commit_before>/*  ============================================================================

 Copyright (C) 2006-2016 Talend Inc. - www.talend.com

 This source code is available under agreement available at
 https://github.com/Talend/data-prep/blob/master/LICENSE

 You should have received a copy of the agreement
 along with this program; if not, write to Talend SA
 9 rue Pages 92150 Suresnes, France

 ============================================================================*/

import _ from 'lodash';

/**
 * @ngdoc controller
 * @name data-prep.transformation-form.controller:TransformFormCtrl
 * @description Transformation parameters controller.
 */
export default class TransformFormCtrl {
	constructor(TransformationUtilsService) {
		this.TransformationUtilsService = TransformationUtilsService;
	}

	/**
	 * @ngdoc method
	 * @name getParams
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description [PRIVATE] Get item parameters into one object for REST call
	 * @returns {object} the parameters
	 */
	getParams() {
		return this.TransformationUtilsService.extractParams(
			{},
			this.transformation.parameters
		);
	}

	/**
	 * @ngdoc method
	 * @name getClusterParams
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description [PRIVATE] Get cluster choice and choice parameters into one object
	 * @returns {object} the parameters
	 */
	getClusterParams() {
		const params = {};
		if (this.transformation.cluster) {
			this.transformation.cluster.clusters
				.filter(cluster => cluster.active)
				.forEach((cluster) => {
					const replaceValue = cluster.replace.value;
					cluster.parameters
						.filter(param => param.value)
						.forEach((param) => {
							params[param.name] = replaceValue;
						});
				});
		}
		return params;
	}

	/**
	 * @ngdoc method
	 * @name gatherParams
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description [PRIVATE] Gather params into one unique object
	 * @returns {object} The entire parameter values
	 */
	gatherParams() {
		const params = this.getParams();
		const clusterParams = this.getClusterParams();
		return _.merge(params, clusterParams);
	}

	/**
	 * @ngdoc method
	 * @name transformWithParam
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description Gather params and perform a transformation on the column if the form is valid
	 */
	transformWithParam() {
		const transformationParams = this.gatherParams();
		this.onSubmit({ params: transformationParams });
	}

	/**
	 * @ngdoc method
	 * @name submitHoverOn
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description Gather params and perform the submit mouseenter action
	 */
	submitHoverOn() {
		this.paramForm.$commitViewValue();
		const params = this.gatherParams();
		this.onSubmitHoverOn({ params });
	}

	/**
	 * @ngdoc method
	 * @name submitHoverOff
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description Gather params and perform the submit mouseleave action
	 */
	submitHoverOff() {
		const params = this.gatherParams();
		this.onSubmitHoverOff({ params });
	}
}
<commit_msg>fix(TDP-3365) : fix js minified issue... TL;DR fix Charles' problem<commit_after>/*  ============================================================================

 Copyright (C) 2006-2016 Talend Inc. - www.talend.com

 This source code is available under agreement available at
 https://github.com/Talend/data-prep/blob/master/LICENSE

 You should have received a copy of the agreement
 along with this program; if not, write to Talend SA
 9 rue Pages 92150 Suresnes, France

 ============================================================================*/
import _ from "lodash";

/**
 * @ngdoc controller
 * @name data-prep.transformation-form.controller:TransformFormCtrl
 * @description Transformation parameters controller.
 */
export default class TransformFormCtrl {
	constructor(TransformationUtilsService) {
        'ngInject';
		this.TransformationUtilsService = TransformationUtilsService;
	}

	/**
	 * @ngdoc method
	 * @name getParams
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description [PRIVATE] Get item parameters into one object for REST call
	 * @returns {object} the parameters
	 */
	getParams() {
		return this.TransformationUtilsService.extractParams(
			{},
			this.transformation.parameters
		);
	}

	/**
	 * @ngdoc method
	 * @name getClusterParams
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description [PRIVATE] Get cluster choice and choice parameters into one object
	 * @returns {object} the parameters
	 */
	getClusterParams() {
		const params = {};
		if (this.transformation.cluster) {
			this.transformation.cluster.clusters
				.filter(cluster => cluster.active)
				.forEach((cluster) => {
					const replaceValue = cluster.replace.value;
					cluster.parameters
						.filter(param => param.value)
						.forEach((param) => {
							params[param.name] = replaceValue;
						});
				});
		}
		return params;
	}

	/**
	 * @ngdoc method
	 * @name gatherParams
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description [PRIVATE] Gather params into one unique object
	 * @returns {object} The entire parameter values
	 */
	gatherParams() {
		const params = this.getParams();
		const clusterParams = this.getClusterParams();
		return _.merge(params, clusterParams);
	}

	/**
	 * @ngdoc method
	 * @name transformWithParam
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description Gather params and perform a transformation on the column if the form is valid
	 */
	transformWithParam() {
		const transformationParams = this.gatherParams();
		this.onSubmit({ params: transformationParams });
	}

	/**
	 * @ngdoc method
	 * @name submitHoverOn
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description Gather params and perform the submit mouseenter action
	 */
	submitHoverOn() {
		this.paramForm.$commitViewValue();
		const params = this.gatherParams();
		this.onSubmitHoverOn({ params });
	}

	/**
	 * @ngdoc method
	 * @name submitHoverOff
	 * @methodOf data-prep.transformation-form.controller:TransformFormCtrl
	 * @description Gather params and perform the submit mouseleave action
	 */
	submitHoverOff() {
		const params = this.gatherParams();
		this.onSubmitHoverOff({ params });
	}
}
<|endoftext|>


<commit_before>/**
 * 404 (Not Found) Handler
 *
 * Usage:
 * return res.notFound();
 *
 * NOTE:
 * If no user-defined route, blueprint route, or static file matches
 * the requested URL, Sails will call `res.notFound()`.
 */

module.exports = function notFound() {

  // Get access to `req`, `res`, `sails`
  var req = this.req;
  var res = this.res;
  var sails = req._sails;

  var viewFilePath = '404';
  var statusCode = 404;
  var result = {
    status: statusCode
  };

  // If the user-agent wants a JSON response, send json
  if (req.wantsJSON) {
    return res.json(result, result.status);
  }

  res.status(result.status);
  res.render(viewFilePath, function(err) {
    // If the view doesn't exist, or an error occured, send json
    if (err) {
      return res.json(result, result.status);
    }

    // Otherwise, serve the `views/404.*` page
    res.render(viewFilePath);
  });
};
<commit_msg>API: json response on notFound (404)<commit_after>/**
 * 404 (Not Found) Handler
 *
 * Usage:
 * return res.notFound();
 *
 * NOTE:
 * If no user-defined route, blueprint route, or static file matches
 * the requested URL, Sails will call `res.notFound()`.
 */

module.exports = function notFound() {

  // Get access to `req`, `res`, `sails`
  var req = this.req;
  var res = this.res;
  var sails = req._sails;

  var viewFilePath = '404';
  var statusCode = 404;
  var result = {
    status: statusCode
  };

  // If the user-agent wants a JSON response, send json
  // if (req.wantsJSON) {
  //   return res.json(result, result.status);
  // }

  // res.status(result.status);
  // res.render(viewFilePath, function(err) {
  //   // If the view doesn't exist, or an error occured, send json
  //   if (err) {
  //     return res.json(result, result.status);
  //   }

  //   // Otherwise, serve the `views/404.*` page
  //   res.render(viewFilePath);
  // });

  // NOTE: Send json response (no http response)
  result.message = "Endpoint '" + req.path + "' does not exist";
  return res.json(result, result.status);
};
<|endoftext|>


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

var CartoDB = require('../');

var commandLineArgs = require('command-line-args');

var cli = commandLineArgs([
  { name: 'sql', alias: 's', type: String, defaultOption: true },
  { name: 'user', alias: 'u', type: String },
  { name: 'api_key', alias: 'a', type: String },
  { name: 'format', alias: 'f', type: String },
  { name: 'output', alias: 'o', type: String },
  { name: 'help', alias: 'h' }
])

var cli_opts = cli.parse();

if (cli_opts.help || !cli_opts.sql) {
  console.log(cli.getUsage());
  return;
}

console.log(cli_opts.api_key)

var sql = new CartoDB.SQL({
  user: cli_opts.user,
  api_key: cli_opts.api_key
});

var options = {};
if (cli_opts.format) options.format = cli_opts.format;

sql.execute(cli_opts.sql, options).done(function (data) {
  if (cli_opts.output) {
    var file = require('fs').createWriteStream(cli_opts.output);
    sql.pipe(file);
  } else {
    console.log(data)
  }
}).error(function (error) {
  console.log('ERROR')
  console.log(error)
})
<commit_msg>completed cartodb-sql cli<commit_after>#!/usr/bin/env node

var CartoDB = require('../');

var commandLineArgs = require('command-line-args');

var args = [
  { name: 'sql', alias: 's', type: String, defaultOption: true, description: 'A SQL query' },
  { name: 'user', alias: 'u', type: String, description: 'Your CartoDB username' },
  { name: 'api_key', alias: 'a', type: String, description: 'Your CartoDB API Key (only needed for write operations)' },
  { name: 'format', alias: 'f', type: String, description: 'Output format json|csv|geojson|shp|svg|kml|SpatiaLite' },
  { name: 'output', alias: 'o', type: String, description: 'Output file. If omitted will use stdout' },
  { name: 'config', alias: 'c', type: String, description: 'Config file.' },
  { name: 'help', alias: 'h' }
];

var cli = commandLineArgs(args);

var cli_opts = cli.parse();

if (cli_opts.help || !cli_opts.sql) {
  console.log(cli.getUsage(args));
  return;
}

var sql = new CartoDB.SQL({
  user: cli_opts.user,
  api_key: cli_opts.api_key
});

var options = {};

if (cli_opts.format) options.format = cli_opts.format;

if (cli_opts.output) {
  var file = require('fs').createWriteStream(cli_opts.output);
  sql.pipe(file);
}

sql.execute(cli_opts.sql, options).done(function (data) {
  if (!cli_opts.output) console.log(data)
}).error(function (error) {
  console.log(error)
})
<|endoftext|>


<commit_before>/**
 * The resizable unit main file
 *
 * Copyright (C) 2010-2011 Nikolay Nemshilov
 */
var Resizable = new Widget({
  extend: {
    version: '2.2.0',

    EVENTS: $w('resize start release'),

    Options: {
      direction:  null, // 'top', 'left', 'right', 'bottom', null for bidrectional

      minWidth:   null,
      maxWidth:   null,
      minHeight:  null,
      maxHeight:  null
    }
  },

  /**
   * Basic constructor
   *
   * @param Element reference
   * @param Object options
   * @return void
   */
  initialize: function(element, options) {
    this
      .$super('resizable', this.old_inst = $(element))
      .setOptions(options);

    if (this.options.direction) {
      this.addClass('rui-resizable-'+ this.options.direction);
    } else {
      this.addClass('rui-resizable');
    }

    // initializing the inner structure
    this.content = this.first('.rui-resizable-content') ||
      $E('div', {'class': 'rui-resizable-content'}).insert(this.children()).insertTo(this);
    this.handle  = this.first('.rui-resizable-handle')  ||
      $E('div', {'class': 'rui-resizable-handle'}).insertTo(this);

    // resizing the content block so it fully fit the resizable element
    var size = this.size();

    size.x -= parseInt(this.getStyle('borderLeftWidth'), 10) + parseInt(this.getStyle('borderRightWidth'), 10);
    size.y -= parseInt(this.getStyle('borderTopWidth'), 10) + parseInt(this.getStyle('borderBottomWidth'), 10);

    this.content.resize(size);
  },

  /**
   * destructor
   *
   * @return Resizable this
   */
  destroy: function() {
    this
      .removeClass('rui-resizable')
      .removeClass('rui-resizable-top')
      .removeClass('rui-resizable-left')
      .removeClass('rui-resizable-right')
      .removeClass('rui-resizable-bottom')
      .insert(this.content._.childNodes);

    this.content.remove();
    this.handle.remove();

    // swapping the old element back
    if (this.old_inst) {
      Wrapper.Cache[$uid(this._)] = this.old_inst;
    }

    return this;
  },

  /**
   * Overriding the method to recognize the direction
   * option from the element class-name
   *
   * @param Object options
   * @return Resizable this
   */
  setOptions: function(options, context) {
    options = options || {};

    // trying to recognize the direction
    $w('top left right bottom').each(function(direction) {
      if (this.hasClass('rui-resizable-'+ direction)) {
        options.direction = direction;
      }
    }, this);

    return this.$super(options, context);
  },

  /**
   * Starts the resizing process
   *
   * @param Event mouse event
   */
  start: function(event) {
    this.prevSizes = this.size();
    this.prevEvPos = event.position();

    // used later during the resize process
    this.contXDiff = this.size().x - this.content.size().x;
    this.contYDiff = this.size().y - this.content.size().y;

    // trying to recognize the boundaries
    $w('minWidth maxWidth minHeight maxHeight').each(function(dimension) {
      this[dimension] = this.findDim(dimension);
    }, this);

    return this.fire('start', {original: event});
  },

  /**
   * Tracks the event during the resize process
   *
   * @param Event mouse event
   */
  track: function(event) {
    var event_pos = event.position(), prev_pos = this.prevEvPos,
        handle    = this.handle.dimensions(),
        prev_size = this.prevSizes, width = prev_size.x, height = prev_size.y,
        x_diff    = prev_pos.x - event_pos.x,
        y_diff    = prev_pos.y - event_pos.y,
        min_x     = this.minWidth,
        max_x     = this.maxWidth,
        min_y     = this.minHeight,
        max_y     = this.maxHeight,
        options   = this.options,
        direction = options.direction;

    // calculating the new size
    width  += (direction === 'left' ? 1 : -1) * x_diff;
    height += (direction === 'top'  ? 1 : -1) * y_diff;

    // applying the boundaries
    if (width  < min_x) { width  = min_x; }
    if (width  > max_x) { width  = max_x; }
    if (height < min_y) { height = min_y; }
    if (height > max_y) { height = max_y; }

    // applying the sizes
    if (prev_size.x !== width && direction !== 'top' && direction !== 'bottom') {
      this.setWidth(width);
    }
    if (prev_size.y !== height && direction !== 'left' && direction !== 'right') {
      this.setHeight(height);
    }

    // adjusting the previous cursor position so that it didn't had a shift
    if (width == min_x || width == max_x) {
      event_pos.x = handle.left + handle.width / 2;
    }
    if (height == min_y || height == max_y) {
      event_pos.y = handle.top + handle.height / 2;
    }

    this.prevEvPos = event_pos;
    this.prevSizes = this.size();

    this.fire('resize', {original: event});
  },

  /**
   * Sets the width of the widget
   *
   * @param Number width
   * @return Resizable this
   */
  setWidth: function(width) {
    this.content.setWidth(width - this.contXDiff);
    return this.$super(width);
  },

  /**
   * Sets the height of the widget
   *
   * @param Number height
   * @return Resizable this
   */
  setHeight: function(height) {
    this.content.setHeight(height - this.contYDiff);
    return this.$super(height);
  },

  /**
   * Marks it the end of the action
   *
   * @return Resizable this
   */
  release: function(event) {
    return this.fire('release', {original: event});
  },

// protected

  // finds dimensions of the element
  findDim: function(dimension) {
    var style = this.options[dimension] || this.getStyle(dimension);

    if (style && /\d+/.test(style) && parseFloat(style) > 0) {
      var what  = R(dimension).include('Width') ? 'width' : 'height',
          dummy = (this._dummy || (this._dummy = $E('div', {
            style: 'visibility:hidden;z-index:-1'
          })))
          .setStyle(what, style)
          .insertTo(this, 'before');

      var size = dummy._['offset' + R(what).capitalize()];
      dummy.remove();

      return size;
    }
  }
});
<commit_msg>Resizable bumping up the version number<commit_after>/**
 * The resizable unit main file
 *
 * Copyright (C) 2010-2011 Nikolay Nemshilov
 */
var Resizable = new Widget({
  extend: {
    version: '2.2.1',

    EVENTS: $w('resize start release'),

    Options: {
      direction:  null, // 'top', 'left', 'right', 'bottom', null for bidrectional

      minWidth:   null,
      maxWidth:   null,
      minHeight:  null,
      maxHeight:  null
    }
  },

  /**
   * Basic constructor
   *
   * @param Element reference
   * @param Object options
   * @return void
   */
  initialize: function(element, options) {
    this
      .$super('resizable', this.old_inst = $(element))
      .setOptions(options);

    if (this.options.direction) {
      this.addClass('rui-resizable-'+ this.options.direction);
    } else {
      this.addClass('rui-resizable');
    }

    // initializing the inner structure
    this.content = this.first('.rui-resizable-content') ||
      $E('div', {'class': 'rui-resizable-content'}).insert(this.children()).insertTo(this);
    this.handle  = this.first('.rui-resizable-handle')  ||
      $E('div', {'class': 'rui-resizable-handle'}).insertTo(this);

    // resizing the content block so it fully fit the resizable element
    var size = this.size();

    size.x -= parseInt(this.getStyle('borderLeftWidth'), 10) + parseInt(this.getStyle('borderRightWidth'), 10);
    size.y -= parseInt(this.getStyle('borderTopWidth'), 10) + parseInt(this.getStyle('borderBottomWidth'), 10);

    this.content.resize(size);
  },

  /**
   * destructor
   *
   * @return Resizable this
   */
  destroy: function() {
    this
      .removeClass('rui-resizable')
      .removeClass('rui-resizable-top')
      .removeClass('rui-resizable-left')
      .removeClass('rui-resizable-right')
      .removeClass('rui-resizable-bottom')
      .insert(this.content._.childNodes);

    this.content.remove();
    this.handle.remove();

    // swapping the old element back
    if (this.old_inst) {
      Wrapper.Cache[$uid(this._)] = this.old_inst;
    }

    return this;
  },

  /**
   * Overriding the method to recognize the direction
   * option from the element class-name
   *
   * @param Object options
   * @return Resizable this
   */
  setOptions: function(options, context) {
    options = options || {};

    // trying to recognize the direction
    $w('top left right bottom').each(function(direction) {
      if (this.hasClass('rui-resizable-'+ direction)) {
        options.direction = direction;
      }
    }, this);

    return this.$super(options, context);
  },

  /**
   * Starts the resizing process
   *
   * @param Event mouse event
   */
  start: function(event) {
    this.prevSizes = this.size();
    this.prevEvPos = event.position();

    // used later during the resize process
    this.contXDiff = this.size().x - this.content.size().x;
    this.contYDiff = this.size().y - this.content.size().y;

    // trying to recognize the boundaries
    $w('minWidth maxWidth minHeight maxHeight').each(function(dimension) {
      this[dimension] = this.findDim(dimension);
    }, this);

    return this.fire('start', {original: event});
  },

  /**
   * Tracks the event during the resize process
   *
   * @param Event mouse event
   */
  track: function(event) {
    var event_pos = event.position(), prev_pos = this.prevEvPos,
        handle    = this.handle.dimensions(),
        prev_size = this.prevSizes, width = prev_size.x, height = prev_size.y,
        x_diff    = prev_pos.x - event_pos.x,
        y_diff    = prev_pos.y - event_pos.y,
        min_x     = this.minWidth,
        max_x     = this.maxWidth,
        min_y     = this.minHeight,
        max_y     = this.maxHeight,
        options   = this.options,
        direction = options.direction;

    // calculating the new size
    width  += (direction === 'left' ? 1 : -1) * x_diff;
    height += (direction === 'top'  ? 1 : -1) * y_diff;

    // applying the boundaries
    if (width  < min_x) { width  = min_x; }
    if (width  > max_x) { width  = max_x; }
    if (height < min_y) { height = min_y; }
    if (height > max_y) { height = max_y; }

    // applying the sizes
    if (prev_size.x !== width && direction !== 'top' && direction !== 'bottom') {
      this.setWidth(width);
    }
    if (prev_size.y !== height && direction !== 'left' && direction !== 'right') {
      this.setHeight(height);
    }

    // adjusting the previous cursor position so that it didn't had a shift
    if (width == min_x || width == max_x) {
      event_pos.x = handle.left + handle.width / 2;
    }
    if (height == min_y || height == max_y) {
      event_pos.y = handle.top + handle.height / 2;
    }

    this.prevEvPos = event_pos;
    this.prevSizes = this.size();

    this.fire('resize', {original: event});
  },

  /**
   * Sets the width of the widget
   *
   * @param Number width
   * @return Resizable this
   */
  setWidth: function(width) {
    this.content.setWidth(width - this.contXDiff);
    return this.$super(width);
  },

  /**
   * Sets the height of the widget
   *
   * @param Number height
   * @return Resizable this
   */
  setHeight: function(height) {
    this.content.setHeight(height - this.contYDiff);
    return this.$super(height);
  },

  /**
   * Marks it the end of the action
   *
   * @return Resizable this
   */
  release: function(event) {
    return this.fire('release', {original: event});
  },

// protected

  // finds dimensions of the element
  findDim: function(dimension) {
    var style = this.options[dimension] || this.getStyle(dimension);

    if (style && /\d+/.test(style) && parseFloat(style) > 0) {
      var what  = R(dimension).include('Width') ? 'width' : 'height',
          dummy = (this._dummy || (this._dummy = $E('div', {
            style: 'visibility:hidden;z-index:-1'
          })))
          .setStyle(what, style)
          .insertTo(this, 'before');

      var size = dummy._['offset' + R(what).capitalize()];
      dummy.remove();

      return size;
    }
  }
});
<|endoftext|>


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

	$('#setup').hide();
	$('#main').hide();
	$('#settings').hide();
	$('#add').hide();
	$('#save-trigger').hide();

	// Google Analytics

	(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
		(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
		m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

	ga('create', 'UA-60030229-2', 'auto');
	ga('send', 'pageview');

	// Test for browser features

	if (document.addEventListener && window.localStorage) {
    	console.log("Compatible web browser detected.");
	} else {
		$('#warning').openModal();
	}

	// If setup is marked as complete
	if (localStorage.getItem("setup") === "completed") {

		// Load todaylist from localStorage

		var todaylist = JSON.parse("[" + localStorage["todaylist"] + "]");
		var tomorrowlist = JSON.parse("[" + localStorage["tomorrowlist"] + "]");

		// Find date

		var d = new Date();
		var month = d.getMonth()+1;
		var day = d.getDate();
		var date = d.getFullYear() + (month<10 ? '0' : '') + month + (day<10 ? '0' : '') + day;
		if (localStorage.getItem("lastopened") === null || localStorage.getItem("lastopened") === "") {
			localStorage["lastopened"] = date;
		}
		if (localStorage.getItem("lastopened") != date) {
			todaylist = tomorrowlist;
			tomorrowlist = JSON.parse("[]");
			localStorage["lastopened"] = date;
		}

		// Weather forecast

		if (localStorage.getItem("weather") === "true") {

			$.simpleWeather({
			location: localStorage['zip'],
			woeid: '',
			unit: 'f',
			success: function(weather) {
				$("#today-weather").append("

It's currently " + weather.temp + "°" + weather.units.temp + " and " + weather.currently +  ".

Weather provided by Yahoo Weather.

");
				$("#tomorrow-weather").append("

It's going to be " + weather.forecast[1].low + "°" + weather.units.temp + "/" + weather.forecast[1].high + "°" + weather.units.temp + " and " + weather.forecast[1].text +  ".

Weather provided by Yahoo Weather.

");
			},
			error: function(error) {
				toast('Error fetching the weather.', 3000, 'rounded');
			}
			});

		}

		// Reload everything after changes

		function reloadData() {

			var todaytemp = "";
			for (var i = 0; i < todaylist.length; ++i) {
				todaytemp += '"' + todaylist[i] + '",';
			}
			var tomorrowtemp = "";
			for (var i = 0; i < tomorrowlist.length; ++i) {
				tomorrowtemp += '"' + tomorrowlist[i] + '",';
			}
			todaytemp = todaytemp.substring(0, todaytemp.length - 1); // Cut off last comma
			tomorrowtemp = tomorrowtemp.substring(0, tomorrowtemp.length - 1); // Cut off last comma
			localStorage["todaylist"] = todaytemp;
			localStorage["tomorrowlist"] = tomorrowtemp;
			var url = new RegExp(/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim);
			// Generate today list
			if($('#todaylist').length > 0) {
				$("#todaylist").empty();
				if(todaylist.length === 0){
					$("#todaylist").append('

Theres nothing here! Add an item by pressing the Add button in the lower-right corner of the screen.

');
				} else {
					for (var i = 0; i < todaylist.length; ++i) {
						$( "#todaylist" ).append('

' + todaylist[i] + '

DismissPush

');
						// Detect links in task
						var result;
						while((result = url.exec(todaylist[i])) !== null) {
							$( ".actions" + i ).append('Open Link');
						}
					}
				}
			}

			// Generate tomorrow list
			if($('#tomorrowlist').length > 0) {
				$("#tomorrowlist").empty();
				if(tomorrowlist.length === 0){
					$("#tomorrowlist").append('

This is where your items pushed to tomorrow appear.

');
				} else {
					for (var i = 0; i < tomorrowlist.length; ++i) {
						$( "#tomorrowlist" ).append('

' + tomorrowlist[i] + '

');
					}
				}
			}

			// Reload variables from updated localStorage sources
			todaylist = JSON.parse("[" + localStorage["todaylist"] + "]");
			tomorrowlist = JSON.parse("[" + localStorage["tomorrowlist"] + "]");

			// Fix for night mode not applying to reloaded cards
			if (localStorage.getItem("night") === "true") {
				$(".card").css("background", "#151515", 'important');
				$("a").css("color", "#FFFFFF", 'important');
			}
		}

		reloadData();

		// Read values of settings from localStorage

		$("#settings-firstname").val(localStorage['firstname']);
		$("#settings-lastname").val(localStorage['lastname']);
		$("#settings-zip").val(localStorage['zip']);
		$("#settings-weather").prop('checked', JSON.parse(localStorage['weather']));
		$("#settings-night").prop('checked', JSON.parse(localStorage['night']));

		// Actions for settings buttons

		$('#settings-trigger').click(function() {
			$('#add').fadeOut( "slow", function() {});
			$('#settings').fadeIn( "slow", function() {});
			$('#save-trigger').fadeIn( "slow", function() {});
		});

		// Actions for save button

		$('#save-trigger').click(function() {
			if( ($("#settings-firstname").val() == 0) || ($("#settings-lastname").val() == 0) || ($("#settings-zip").val() == 0) )
			{
				// Tell user to fill out everything
				toast('Fill out everything before saving!', 3000, 'rounded');
			} else {
				localStorage['firstname'] = $("#settings-firstname").val();
				localStorage['lastname'] = $("#settings-lastname").val();
				localStorage['zip'] = $("#settings-zip").val();
				if ($("#settings-weather").is(":checked")) {
					localStorage['weather'] = "true";
				} else {
					localStorage['weather'] = "false";
				}
				if ($("#settings-night").is(":checked")) {
					localStorage['night'] = "true";
				} else {
					localStorage['night'] = "false";
				}
				location.reload();
			}
		});

		// Actions for dismiss button

		$(document).on('click', ".delete", function() {
			var item = $(this).parent().parent().parent().attr('id');
			// Remove item from today list
			todaylist.splice(item,1);
			$( "#" + item ).fadeOut( 500, function() {
				reloadData();
				toast('Task completed.', 3000, 'rounded');
			});
		});

		// Actions for push button

		$(document).on('click', ".push", function() {
			var item = $(this).parent().parent().parent().attr('id');
			var task = $( ".task" + item ).text();
			console.log("item: " + item);
			console.log("task: " + task);
			todaylist.splice(item,1); // Remove item from today list
			tomorrowlist.unshift(task); // Add item to tomorrow list
			$( "#" + item ).fadeOut( 500, function() {
				$('#confirm').closeModal();
				reloadData();
				toast('Task pushed to tomorrow.', 3000, 'rounded');
			});
		});

		// Actions for floating add button

		$( "#add" ).click(function() {
			$('#new').openModal();
			$('#task').focus();
		});

		// Actions for ENTER keypress in add modal

		$('#task').keypress(function(event){
		 var keycode = (event.keyCode ? event.keyCode : event.which);
		 if(keycode == '13'){
		 	if(document.getElementById("task").value == 0) {
				toast('Enter a task!', 3000, 'rounded');
			} else {
				var task = document.getElementById("task").value;
				if ($('#new-toggle').is(':checked')) {
					// Add item to tomorrow list
					tomorrowlist.unshift(task);
					// Reset checkbox
					$("#new-toggle").prop('checked', false);
				} else {
					// Add item to today list
					todaylist.unshift(task);
				}
				reloadData();
				document.getElementById("task").value = "";
				$('#new').closeModal();
				toast('Task added.', 3000, 'rounded');
			}
		 }
		});

		// Actions to do after everything is finished loading

		$(window).load(function() {

			// Night mode
			if (localStorage.getItem("night") === "true") {
				$(".navbar").css("background", "#212121", 'important');
				$("#add").css("background", "#424242", 'important');
				$("#settings-trigger").css("background", "#212121", 'important');
				$("#save-trigger").css("background", "#424242", 'important');
				$("#settings").css("background", "#000000", 'important');
				$(".modal").css("background", "#424242", 'important');
				$(".settings-item").css("border-bottom", "#424242", 'important');
				$("#main").css("background", "#000000", 'important');
				$(".card").css("background", "#212121", 'important');
				$(".switch label input[type=checkbox]:first-child:checked+.lever").css("background", "#151515", 'important');
				$("body").css("color", "#FFFFFF", 'important');
				$("a").css("color", "#FFFFFF", 'important');
				$("input").css("color", "#FFFFFF", 'important');
			}

			// Show everything
			$('.preloader-wrapper').fadeOut( "slow", function() {});
			$('#main').fadeIn( "slow", function() {});
			$('#add').fadeIn( "slow", function() {});

		});

	// If setup is not marked as complete
	} else if (localStorage.getItem("setup") != "completed") {

		// Show setup because it's not complete
		$('#setup').show();

		// Actions when 'Get Started' button is pressed on setup
		$('#getstarted').click(function() {
				// Test if any of the text fields are empty
			if( ($("#setup-firstname").val() == 0) || ($("#setup-lastname").val() == 0) || ($("#setup-zip").val() == 0) )
			{
				// Tell user to fill out everything
				toast('Fill out everything and try again!', 3000, 'rounded');
			} else {
				// Save contents of text fields to localStorage
				localStorage['firstname'] = $("#setup-firstname").val();
				localStorage['lastname'] = $("#setup-lastname").val();
				localStorage['zip'] = $("#setup-zip").val();
				localStorage["weather"] = "true";
				localStorage['setup'] = "completed";
				localStorage["todaylist"] = '"This is a sample list item. You can delete these easily by tapping the Dismiss button.","Look what happens when you add a link! http://www.google.com/"';
				localStorage["tomorrowlist"] = "";
				localStorage['night'] = "false";
				location.reload();
			}
		});

	} else {

		localStorage["setup"] = "";
		location.reload();
	}

});
<commit_msg>fixed google analytics hanging app load<commit_after>$(document).ready(function(){

	$('#setup').hide();
	$('#main').hide();
	$('#settings').hide();
	$('#add').hide();
	$('#save-trigger').hide();

	// Google Analytics

	(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
		(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
		m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
		})(window,document,'script','http://www.google-analytics.com/analytics.js','ga');

		ga('create', 'UA-60030229-2', 'auto');
		ga('send', 'pageview');

	// Test for browser features

	if (document.addEventListener && window.localStorage) {
    	console.log("Compatible web browser detected.");
	} else {
		$('#warning').openModal();
	}

	// If setup is marked as complete
	if (localStorage.getItem("setup") === "completed") {

		// Load todaylist from localStorage

		var todaylist = JSON.parse("[" + localStorage["todaylist"] + "]");
		var tomorrowlist = JSON.parse("[" + localStorage["tomorrowlist"] + "]");

		// Find date

		var d = new Date();
		var month = d.getMonth()+1;
		var day = d.getDate();
		var date = d.getFullYear() + (month<10 ? '0' : '') + month + (day<10 ? '0' : '') + day;
		if (localStorage.getItem("lastopened") === null || localStorage.getItem("lastopened") === "") {
			localStorage["lastopened"] = date;
		}
		if (localStorage.getItem("lastopened") != date) {
			todaylist = tomorrowlist;
			tomorrowlist = JSON.parse("[]");
			localStorage["lastopened"] = date;
		}

		// Weather forecast

		if (localStorage.getItem("weather") === "true") {

			$.simpleWeather({
			location: localStorage['zip'],
			woeid: '',
			unit: 'f',
			success: function(weather) {
				$("#today-weather").append("

It's currently " + weather.temp + "°" + weather.units.temp + " and " + weather.currently +  ".

Weather provided by Yahoo Weather.

");
				$("#tomorrow-weather").append("

It's going to be " + weather.forecast[1].low + "°" + weather.units.temp + "/" + weather.forecast[1].high + "°" + weather.units.temp + " and " + weather.forecast[1].text +  ".

Weather provided by Yahoo Weather.

");
			},
			error: function(error) {
				toast('Error fetching the weather.', 3000, 'rounded');
			}
			});

		}

		// Reload everything after changes

		function reloadData() {

			var todaytemp = "";
			for (var i = 0; i < todaylist.length; ++i) {
				todaytemp += '"' + todaylist[i] + '",';
			}
			var tomorrowtemp = "";
			for (var i = 0; i < tomorrowlist.length; ++i) {
				tomorrowtemp += '"' + tomorrowlist[i] + '",';
			}
			todaytemp = todaytemp.substring(0, todaytemp.length - 1); // Cut off last comma
			tomorrowtemp = tomorrowtemp.substring(0, tomorrowtemp.length - 1); // Cut off last comma
			localStorage["todaylist"] = todaytemp;
			localStorage["tomorrowlist"] = tomorrowtemp;
			var url = new RegExp(/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim);
			// Generate today list
			if($('#todaylist').length > 0) {
				$("#todaylist").empty();
				if(todaylist.length === 0){
					$("#todaylist").append('

Theres nothing here! Add an item by pressing the Add button in the lower-right corner of the screen.

');
				} else {
					for (var i = 0; i < todaylist.length; ++i) {
						$( "#todaylist" ).append('

' + todaylist[i] + '

DismissPush

');
						// Detect links in task
						var result;
						while((result = url.exec(todaylist[i])) !== null) {
							$( ".actions" + i ).append('Open Link');
						}
					}
				}
			}

			// Generate tomorrow list
			if($('#tomorrowlist').length > 0) {
				$("#tomorrowlist").empty();
				if(tomorrowlist.length === 0){
					$("#tomorrowlist").append('

This is where your items pushed to tomorrow appear.

');
				} else {
					for (var i = 0; i < tomorrowlist.length; ++i) {
						$( "#tomorrowlist" ).append('

' + tomorrowlist[i] + '

');
					}
				}
			}

			// Reload variables from updated localStorage sources
			todaylist = JSON.parse("[" + localStorage["todaylist"] + "]");
			tomorrowlist = JSON.parse("[" + localStorage["tomorrowlist"] + "]");

			// Fix for night mode not applying to reloaded cards
			if (localStorage.getItem("night") === "true") {
				$(".card").css("background", "#151515", 'important');
				$("a").css("color", "#FFFFFF", 'important');
			}
		}

		reloadData();

		// Read values of settings from localStorage

		$("#settings-firstname").val(localStorage['firstname']);
		$("#settings-lastname").val(localStorage['lastname']);
		$("#settings-zip").val(localStorage['zip']);
		$("#settings-weather").prop('checked', JSON.parse(localStorage['weather']));
		$("#settings-night").prop('checked', JSON.parse(localStorage['night']));

		// Actions for settings buttons

		$('#settings-trigger').click(function() {
			$('#add').fadeOut( "slow", function() {});
			$('#settings').fadeIn( "slow", function() {});
			$('#save-trigger').fadeIn( "slow", function() {});
		});

		// Actions for save button

		$('#save-trigger').click(function() {
			if( ($("#settings-firstname").val() == 0) || ($("#settings-lastname").val() == 0) || ($("#settings-zip").val() == 0) )
			{
				// Tell user to fill out everything
				toast('Fill out everything before saving!', 3000, 'rounded');
			} else {
				localStorage['firstname'] = $("#settings-firstname").val();
				localStorage['lastname'] = $("#settings-lastname").val();
				localStorage['zip'] = $("#settings-zip").val();
				if ($("#settings-weather").is(":checked")) {
					localStorage['weather'] = "true";
				} else {
					localStorage['weather'] = "false";
				}
				if ($("#settings-night").is(":checked")) {
					localStorage['night'] = "true";
				} else {
					localStorage['night'] = "false";
				}
				location.reload();
			}
		});

		// Actions for dismiss button

		$(document).on('click', ".delete", function() {
			var item = $(this).parent().parent().parent().attr('id');
			// Remove item from today list
			todaylist.splice(item,1);
			$( "#" + item ).fadeOut( 500, function() {
				reloadData();
				toast('Task completed.', 3000, 'rounded');
			});
		});

		// Actions for push button

		$(document).on('click', ".push", function() {
			var item = $(this).parent().parent().parent().attr('id');
			var task = $( ".task" + item ).text();
			console.log("item: " + item);
			console.log("task: " + task);
			todaylist.splice(item,1); // Remove item from today list
			tomorrowlist.unshift(task); // Add item to tomorrow list
			$( "#" + item ).fadeOut( 500, function() {
				$('#confirm').closeModal();
				reloadData();
				toast('Task pushed to tomorrow.', 3000, 'rounded');
			});
		});

		// Actions for floating add button

		$( "#add" ).click(function() {
			$('#new').openModal();
			$('#task').focus();
		});

		// Actions for ENTER keypress in add modal

		$('#task').keypress(function(event){
		 var keycode = (event.keyCode ? event.keyCode : event.which);
		 if(keycode == '13'){
		 	if(document.getElementById("task").value == 0) {
				toast('Enter a task!', 3000, 'rounded');
			} else {
				var task = document.getElementById("task").value;
				if ($('#new-toggle').is(':checked')) {
					// Add item to tomorrow list
					tomorrowlist.unshift(task);
					// Reset checkbox
					$("#new-toggle").prop('checked', false);
				} else {
					// Add item to today list
					todaylist.unshift(task);
				}
				reloadData();
				document.getElementById("task").value = "";
				$('#new').closeModal();
				toast('Task added.', 3000, 'rounded');
			}
		 }
		});

		// Actions to do after everything is finished loading

		$(window).load(function() {

			// Night mode
			if (localStorage.getItem("night") === "true") {
				$(".navbar").css("background", "#212121", 'important');
				$("#add").css("background", "#424242", 'important');
				$("#settings-trigger").css("background", "#212121", 'important');
				$("#save-trigger").css("background", "#424242", 'important');
				$("#settings").css("background", "#000000", 'important');
				$(".modal").css("background", "#424242", 'important');
				$(".settings-item").css("border-bottom", "#424242", 'important');
				$("#main").css("background", "#000000", 'important');
				$(".card").css("background", "#212121", 'important');
				$(".switch label input[type=checkbox]:first-child:checked+.lever").css("background", "#151515", 'important');
				$("body").css("color", "#FFFFFF", 'important');
				$("a").css("color", "#FFFFFF", 'important');
				$("input").css("color", "#FFFFFF", 'important');
			}

			// Show everything
			$('.preloader-wrapper').fadeOut( "slow", function() {});
			$('#main').fadeIn( "slow", function() {});
			$('#add').fadeIn( "slow", function() {});

		});

	// If setup is not marked as complete
	} else if (localStorage.getItem("setup") != "completed") {

		// Show setup because it's not complete
		$('#setup').show();

		// Actions when 'Get Started' button is pressed on setup
		$('#getstarted').click(function() {
				// Test if any of the text fields are empty
			if( ($("#setup-firstname").val() == 0) || ($("#setup-lastname").val() == 0) || ($("#setup-zip").val() == 0) )
			{
				// Tell user to fill out everything
				toast('Fill out everything and try again!', 3000, 'rounded');
			} else {
				// Save contents of text fields to localStorage
				localStorage['firstname'] = $("#setup-firstname").val();
				localStorage['lastname'] = $("#setup-lastname").val();
				localStorage['zip'] = $("#setup-zip").val();
				localStorage["weather"] = "true";
				localStorage['setup'] = "completed";
				localStorage["todaylist"] = '"This is a sample list item. You can delete these easily by tapping the Dismiss button.","Look what happens when you add a link! http://www.google.com/"';
				localStorage["tomorrowlist"] = "";
				localStorage['night'] = "false";
				location.reload();
			}
		});

	} else {

		localStorage["setup"] = "";
		location.reload();
	}

});
<|endoftext|>


<commit_before>var get = Ember.get, set = Ember.set;

Ember.Handlebars.registerHelper('yield', function(options) {
  var view = options.data.view, template;

  while (view && !get(view, 'layout')) {
    view = get(view, 'parentView');
  }

  ember_assert("You called yield in a template that was not a layout", !!view);

  template = get(view, 'template');

  ember_assert("You called yield on " + view.toString() + " without supplying a template", !!template);
  template(this, options);
});
<commit_msg>Adds documentation for {{yield}} Ember.Handlebars helper<commit_after>var get = Ember.get, set = Ember.set;

/**
  @name Handlebars.helpers.yield

  When used in a Handlebars template that is assigned to an `Ember.View` instance's
  `layout` property Ember will render the layout template first, inserting the view's
  own rendered output at the `{{ yield }}` location.

  An empty `<body>` and the following application code:

        AView = Ember.View.extend({
          classNames: ['a-view-with-layout'],
          layout: Ember.Handlebars.compile('
{{ yield }}
'),
          template: Ember.Handlebars.compile('I am wrapped')
        })

        aView = AView.create()
        aView.appendTo('body')

  Will result in the following HTML output:

              I am wrapped

  The yield helper cannot be used outside of a template assigned to an `Ember.View`'s `layout` property
  and will throw an error if attempted.

      BView = Ember.View.extend({
        classNames: ['a-view-with-layout'],
        template: Ember.Handlebars.compile('{{yield}}')
      })

      bView = BView.create()
      bView.appendTo('body')

      // throws
      // Uncaught Error: assertion failed: You called yield in a template that was not a layout
*/
Ember.Handlebars.registerHelper('yield', function(options) {
  var view = options.data.view, template;

  while (view && !get(view, 'layout')) {
    view = get(view, 'parentView');
  }

  ember_assert("You called yield in a template that was not a layout", !!view);

  template = get(view, 'template');

  ember_assert("You called yield on " + view.toString() + " without supplying a template", !!template);
  template(this, options);
});
<|endoftext|>


<commit_before>var amounts, buildingFunc, buildings, buildnames, clickUpg, clickcosts, clickeffects, clicknames, clickupgs, costs, hoverFuncBuild, hoverFuncUpg, hoverRemove, idleInc, idlecheck, inc, incamount, money, mps, mpsadds, toggleDisplay, totalclicks, upgcosts, upgeffects, upgnames, upgradeFunc, upgs;

incamount = 1.0;

money = 0.0;

mps = 0.0;

amounts = [0, 0, 0, 0];

costs = [8.0, 120.0, 1337.0, 20160.0];

mpsadds = [0.1, 0.4, 3.0, 7.5];

buildings = ["ac", "mp", "cc", "sc"];

buildnames = ["Auto-Clicker", "Money Printer", "Counterfeit Company", "Sharemarket Crash"];

upgs = [[0, 0], [0], [0], [0]];

upgcosts = [[1000, 42000], [5000, 150000], [16900], [150000]];

upgeffects = [[1.5, 2.5], [2.0, 3.0], [2.0], [3.0]];

upgnames = [["Clicking Factories", "Iron-Clad Mice"], ["Skilled Fake Money Making", "Efficient Ink Cartridges"], ["Printing Templates"], ["Fire on Wall Street"]];

clickupgs = [0];

clickcosts = [2100];

clickeffects = [3];

clicknames = ["Flexible Fingers"];

idlecheck = 0;

totalclicks = 0;

inc = function() {
  money = parseFloat((money + incamount).toFixed(3));
  totalclicks += 1;
  $("#money").html("Balance: $" + money.toFixed(1));
  return $("#clicks").html("Total Clicks: " + totalclicks);
};

toggleDisplay = function(id) {
  if (id === "build") {
    $("#buildings").toggle();
    if ($("#buildings").css("display") !== "none") {
      $("#upgrades").hide();
      return $("#stats").hide();
    }
  } else if (id === "upg") {
    $("#upgrades").toggle();
    if ($("#upgrades").css("display") !== "none") {
      $("#buildings").hide();
      return $("#stats").hide();
    }
  } else {
    $("#stats").toggle();
    if ($("#stats").css("display") !== "none") {
      $("#buildings").hide();
      return $("#upgrades").hide();
    }
  }
};

idleInc = function() {
  money = (money + (mps / 100)).toFixed(3);
  $("#money").html("Balance: $" + parseFloat(money).toFixed(1));
  money = parseFloat(money);
  window.setTimeout(idleInc, 10);
};

buildingFunc = function(n) {
  if (money >= costs[n]) {
    money -= costs[n];
    costs[n] = parseFloat((costs[n] * 1.15).toFixed(3));
    amounts[n] += 1;
    $("#" + buildings[n] + "build").html(buildnames[n] + " ($" + costs[n].toFixed(1) + ")");
    mps = parseFloat((mps + mpsadds[n]).toFixed(1));
    $("#mps").html("$" + mps + "/second");
    if (idlecheck === 0) {
      idlecheck += 1;
      idleInc();
    }
  } else {
    window.alert("You do not have enough money.");
  }
};

upgradeFunc = function(n, step) {
  if (money >= upgcosts[n][step] && amounts[n] >= 1) {
    money -= upgcosts[n][step];
    upgs[n][step] += 1;
    mpsadds[n] *= upgeffects[n][step];
    $("#" + buildings[n] + "upg" + (step + 1)).hide();
    mpsadds[n] = parseFloat((mpsadds[n] * upgeffects[n][step]).toFixed(3));
  } else {
    window.alert("You do not have enough money.");
  }
};

clickUpg = function(n) {
  if (money >= clickcosts[n]) {
    money -= clickcost[n];
    clickupgs[n] += 1;
    incamount *= clickeffects[n];
    return $("#clickupg" + (n + 1)).hide();
  } else {
    return window.alert("You do not have enough money.");
  }
};

hoverFuncBuild = function(n) {
  var boughtupgs, upgcheck;
  boughtupgs = [];
  upgcheck = 0;
  while (upgcheck < upgs[n].length) {
    if (upgs[n][upgcheck] === 1) {
      boughtupgs.push(upgnames[n][upgcheck] + " (*" + upgeffects[n][upgcheck] + "MPS)");
    }
    upgcheck += 1;
  }
  if (boughtupgs.length === 0) {
    boughtupgs.push("None yet!");
  }
  boughtupgs = boughtupgs.join("
");
  return $("#hoverinfo").html(buildnames[n] + "
Amount: " + amounts[n] + "
Total MPS: " + (amounts[n] * mpsadds[n]).toFixed(1) + "
Upgrades unlocked:
" + boughtupgs);
};

hoverFuncUpg = function(n, step) {
  var hovertemp1, hovertemp2, hovertemp3;
  if (n === -1) {
    hovertemp1 = clicknames[step];
    hovertemp2 = "Main Button ";
    hovertemp3 = clickeffects[step];
  } else {
    hovertemp1 = upgnames[n][step];
    hovertemp2 = buildnames[n];
    hovertemp3 = upgeffects[n][step] + "MPS";
  }
  return $("#hoverinfo").html(hovertemp1 + "
Effects:
" + hovertemp2 + " * " + hovertemp3);
};

hoverRemove = function() {
  return $("#hoverinfo").html("Hover over something!");
};
<commit_msg>Update main.js<commit_after>var amounts, buildingFunc, buildings, buildnames, clickUpg, clickcosts, clickeffects, clicknames, clickupgs, convertCosts, costs, hoverFuncBuild, hoverFuncUpg, hoverRemove, idleInc, idlecheck, inc, incamount, money, moneynameacr, mps, mpsadds, toggleDisplay, totalclicks, totalearned, upgcosts, upgeffects, upgnames, upgradeFunc, upgs;

incamount = 1.0;

money = 0.0;

moneynameacr = ["", "million", "billion", "trillion", "quadrillion", "quintillion"];

mps = 0.0;

amounts = [0, 0, 0, 0];

costs = [8.0, 120.0, 1337.0, 20160.0, 123456.0];

mpsadds = [0.1, 0.4, 3.0, 7.5, 32.1];

buildings = ["ac", "mp", "cc", "sc", "bh"];

buildnames = ["Auto-Clicker", "Money Printer", "Counterfeit Company", "Sharemarket Crash", "Bank Heist"];

upgs = [[0, 0], [0], [0], [0]];

upgcosts = [[100, 4200], [500, 15000], [1690, 40000], [15000], [500000]];

upgeffects = [[1.5, 2.5], [2.0, 3.0], [2.0], [3.0]];

upgnames = [["Clicking Factories", "Iron-Clad Mice"], ["Printing Templates", "Efficient Ink Cartridges"], ["Skilled Fake Money Making", "Patented Products"], ["Fire on Wall Street"], ["Lockpicks"]];

clickupgs = [0];

clickcosts = [210, 70000];

clickeffects = [3, 10];

clicknames = ["Flexible Fingers", "More Clicks!"];

idlecheck = 0;

totalclicks = 0;

totalearned = 0;

convertCosts = function(n) {
  var b, check, i, ref;
  check = 0;
  for (b = i = 1, ref = moneynameacr.length - 1; 1 <= ref ? i <= ref : i >= ref; b = 1 <= ref ? ++i : --i) {
    if (n >= Math.pow(10, 6 + ((b - 1) * 3))) {
      check += 1;
    }
  }
  if (check === 0) {
    return n.toFixed(1);
  } else {
    return (n / Math.pow(10, 6 + ((check - 1) * 3))).toFixed(1) + " " + moneynameacr[check];
  }
};

inc = function() {
  money = parseFloat((money + incamount).toFixed(3));
  totalearned = parseFloat((totalearned + incamount).toFixed(3));
  totalclicks += 1;
  $("#money").html("Balance: $" + convertCosts(money));
  $("#earned").html("Total Money Earned: $" + convertCosts(totalearned));
  return $("#clicks").html("Total Clicks: " + totalclicks);
};

toggleDisplay = function(id) {
  if (id === "build") {
    $("#buildings").toggle();
    if ($("#buildings").css("display") !== "none") {
      $("#upgrades").hide();
      $("#upgbutton").css("background-color", "grey");
      $("#stats").hide();
      $("#statsbutton").css("background-color", "grey");
      return $("#buildbutton").css("background-color", "#5555cc");
    } else {
      return $("#buildbutton").css("background-color", "grey");
    }
  } else if (id === "upg") {
    $("#upgrades").toggle();
    if ($("#upgrades").css("display") !== "none") {
      $("#buildings").hide();
      $("#buildbutton").css("background-color", "grey");
      $("#stats").hide();
      $("#statsbutton").css("background-color", "grey");
      return $("#upgbutton").css("background-color", "#5555cc");
    } else {
      return $("#upgbutton").css("background-color", "grey");
    }
  } else {
    $("#stats").toggle();
    if ($("#stats").css("display") !== "none") {
      $("#buildings").hide();
      $("#buildbutton").css("background-color", "grey");
      $("#upgrades").hide();
      $("#upgbutton").css("background-color", "grey");
      return $("#statsbutton").css("background-color", "#5555cc");
    } else {
      return $("#statsbutton").css("background-color", "grey");
    }
  }
};

idleInc = function() {
  money = (money + (mps / 100)).toFixed(3);
  totalearned = (totalearned + (mps / 100)).toFixed(3);
  $("#money").html("Balance: $" + convertCosts(parseFloat(money)));
  $("#earned").html("Total Money Earned: $" + convertCosts(parseFloat(totalearned)));
  money = parseFloat(money);
  totalearned = parseFloat(totalearned);
  window.setTimeout(idleInc, 10);
};

buildingFunc = function(n) {
  if (money >= costs[n]) {
    money -= costs[n];
    costs[n] = parseFloat((costs[n] * 1.15).toFixed(3));
    amounts[n] += 1;
    $("#" + buildings[n] + "build").html(buildnames[n] + "
($" + convertCosts(costs[n]) + ")");
    mps = parseFloat((mps + mpsadds[n]).toFixed(1));
    $("#mps").html("$" + convertCosts(mps) + "/second");
    if (idlecheck === 0) {
      idlecheck += 1;
      idleInc();
      return;
    }
    return hoverFuncBuild(n);
  } else {
    window.alert("You do not have enough money.");
  }
};

upgradeFunc = function(n, step) {
  if (money >= upgcosts[n][step] && amounts[n] >= 1) {
    money -= upgcosts[n][step];
    upgs[n][step] += 1;
    $("#" + buildings[n] + "upg" + (step + 1)).hide();
    mps += amounts[n] * (mpsadds[n] * (upgeffects[n][step] - 1));
    mpsadds[n] = parseFloat((mpsadds[n] * upgeffects[n][step]).toFixed(3));
    $("#mps").html("$" + convertCosts(mps) + "/second");
  } else {
    window.alert("You do not have enough money.");
  }
};

clickUpg = function(n) {
  if (money >= clickcosts[n]) {
    money -= clickcosts[n];
    clickupgs[n] += 1;
    incamount *= clickeffects[n];
    return $("#clickupg" + (n + 1)).hide();
  } else {
    return window.alert("You do not have enough money.");
  }
};

hoverFuncBuild = function(n) {
  var boughtupgs, upgcheck;
  boughtupgs = [];
  upgcheck = 0;
  while (upgcheck < upgs[n].length) {
    if (upgs[n][upgcheck] === 1) {
      boughtupgs.push(upgnames[n][upgcheck] + " (*" + upgeffects[n][upgcheck] + "MPS)");
    }
    upgcheck += 1;
  }
  if (boughtupgs.length === 0) {
    boughtupgs.push("None yet!");
  }
  boughtupgs = boughtupgs.join("
");
  return $("#hoverinfo").html(buildnames[n] + "
Amount: " + amounts[n] + "
Total MPS: " + convertCosts(amounts[n] * mpsadds[n]) + "
Upgrades unlocked:
" + boughtupgs);
};

hoverFuncUpg = function(n, step) {
  var hovertemp1, hovertemp2, hovertemp3;
  if (n === -1) {
    hovertemp1 = clicknames[step];
    hovertemp2 = "Main Button ";
    hovertemp3 = clickeffects[step];
  } else {
    hovertemp1 = upgnames[n][step];
    hovertemp2 = buildnames[n];
    hovertemp3 = upgeffects[n][step] + "MPS";
  }
  return $("#hoverinfo").html(hovertemp1 + "
Effects:
" + hovertemp2 + " * " + hovertemp3);
};

hoverRemove = function() {
  return $("#hoverinfo").html("Hover over something!");
};
<|endoftext|>


<commit_before>'use strict'

const Hemera = require('./../../hemera')
const HemeraMongoStore = require('./../index')
const Nats = require('nats')
const Code = require('code')
const HemeraTestsuite = require('hemera-testsuite')

const expect = Code.expect

describe('Hemera-mongo-store', function () {
  let PORT = 6243
  let noAuthUrl = 'nats://localhost:' + PORT
  const topic = 'mongo-store'
  const testCollection = 'test'
  let server
  let hemera

  before(function (done) {
    server = HemeraTestsuite.start_server(PORT, {}, () => {
      const nats = Nats.connect(noAuthUrl)
      hemera = new Hemera(nats, {
        logLevel: 'info'
      })
      hemera.use(HemeraMongoStore, {
        mongo: {
          url: 'mongodb://localhost:27017/test'
        }
      })
      hemera.ready(() => {
        hemera.act({
          topic,
          cmd: 'dropCollection',
          collection: testCollection
        }, function (err, resp) {
          done()
        })
      })
    })
  })

  after(function (done) {
    hemera.close()
    server.kill()
    done()
  })

  it('create', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'peter'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()
      expect(resp._id).to.be.exists()

      done()
    })
  })

  it('create multiple documents', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: [
        { name: 'peter' }, { name: 'parker' }
      ]
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()
      expect(resp._ids).to.be.an.array().length(2)

      done()
    })
  })

  it('update', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'peter'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'update',
        collection: testCollection,
        data: {
          $set: {
            name: 'nadja'
          }
        },
        query: {
          name: 'peter'
        }
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp).to.be.an.object()
        expect(resp._id).to.be.exists()
        expect(resp.name).to.be.exists()

        done()
      })
    })
  })

  it('updatebyId', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'peter'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'updateById',
        collection: testCollection,
        data: {
          $set: {
            name: 'nadja'
          }
        },
        id: resp._id
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp).to.be.an.object()
        expect(resp._id).to.be.exists()
        expect(resp.name).to.be.exists()

        done()
      })
    })
  })

  it('remove', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'olaf'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'remove',
        collection: testCollection,
        query: {
          name: 'olaf'
        }
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp).to.be.an.object()
        expect(resp.deletedCount).to.be.equals(1)

        done()
      })
    })
  })

  it('removeById', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'olaf'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'removeById',
        collection: testCollection,
        id: resp._id
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp._id).to.be.exists()
        expect(resp.name).to.be.exists()

        done()
      })
    })
  })

  it('findById', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'jens'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'findById',
        collection: testCollection,
        id: resp._id
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp._id).to.be.exists()
        expect(resp.name).to.be.exists()

        done()
      })
    })
  })

  it('find', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'jens'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'find',
        collection: testCollection,
        query: {}
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp.result).to.be.an.array()
        expect(resp.result[0]._id).to.be.exists()
        expect(resp.result[0].name).to.be.exists()
        done()
      })
    })
  })

  it('find with pagination', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'jens'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'find',
        collection: testCollection,
        query: {},
        options: {
          limit: 10,
          offset: 2
        }
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp.result).to.be.an.array()
        expect(resp.result[0]._id).to.be.exists()
        expect(resp.result[0].name).to.be.exists()
        expect(resp.limit).to.be.equals(10)
        expect(resp.offset).to.be.equals(2)
        done()
      })
    })
  })

  it('replace', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'nadine'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'replace',
        collection: testCollection,
        data: {
          $set: {
            name: 'nadja'
          }
        },
        query: {}
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp).to.be.an.object()
        expect(resp.matchedCount).to.be.exists()
        expect(resp.modifiedCount).to.be.exists()
        expect(resp.upsertedCount).to.be.exists()

        done()
      })
    })
  })

  it('replaceById', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'nadja'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'replaceById',
        collection: testCollection,
        data: {
          name: 'nadja'
        },
        id: resp._id
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp._id).to.be.exists()
        expect(resp.name).to.be.exists()
        done()
      })
    })
  })
})
<commit_msg>set silent log level<commit_after>'use strict'

const Hemera = require('./../../hemera')
const HemeraMongoStore = require('./../index')
const Nats = require('nats')
const Code = require('code')
const HemeraTestsuite = require('hemera-testsuite')

const expect = Code.expect

describe('Hemera-mongo-store', function () {
  let PORT = 6243
  let noAuthUrl = 'nats://localhost:' + PORT
  const topic = 'mongo-store'
  const testCollection = 'test'
  let server
  let hemera

  before(function (done) {
    server = HemeraTestsuite.start_server(PORT, {}, () => {
      const nats = Nats.connect(noAuthUrl)
      hemera = new Hemera(nats, {
        logLevel: 'silent'
      })
      hemera.use(HemeraMongoStore, {
        mongo: {
          url: 'mongodb://localhost:27017/test'
        }
      })
      hemera.ready(() => {
        hemera.act({
          topic,
          cmd: 'dropCollection',
          collection: testCollection
        }, function (err, resp) {
          done()
        })
      })
    })
  })

  after(function (done) {
    hemera.close()
    server.kill()
    done()
  })

  it('create', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'peter'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()
      expect(resp._id).to.be.exists()

      done()
    })
  })

  it('create multiple documents', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: [
        { name: 'peter' }, { name: 'parker' }
      ]
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()
      expect(resp._ids).to.be.an.array().length(2)

      done()
    })
  })

  it('update', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'peter'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'update',
        collection: testCollection,
        data: {
          $set: {
            name: 'nadja'
          }
        },
        query: {
          name: 'peter'
        }
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp).to.be.an.object()
        expect(resp._id).to.be.exists()
        expect(resp.name).to.be.exists()

        done()
      })
    })
  })

  it('updatebyId', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'peter'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'updateById',
        collection: testCollection,
        data: {
          $set: {
            name: 'nadja'
          }
        },
        id: resp._id
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp).to.be.an.object()
        expect(resp._id).to.be.exists()
        expect(resp.name).to.be.exists()

        done()
      })
    })
  })

  it('remove', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'olaf'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'remove',
        collection: testCollection,
        query: {
          name: 'olaf'
        }
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp).to.be.an.object()
        expect(resp.deletedCount).to.be.equals(1)

        done()
      })
    })
  })

  it('removeById', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'olaf'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'removeById',
        collection: testCollection,
        id: resp._id
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp._id).to.be.exists()
        expect(resp.name).to.be.exists()

        done()
      })
    })
  })

  it('findById', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'jens'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'findById',
        collection: testCollection,
        id: resp._id
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp._id).to.be.exists()
        expect(resp.name).to.be.exists()

        done()
      })
    })
  })

  it('find', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'jens'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'find',
        collection: testCollection,
        query: {}
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp.result).to.be.an.array()
        expect(resp.result[0]._id).to.be.exists()
        expect(resp.result[0].name).to.be.exists()
        done()
      })
    })
  })

  it('find with pagination', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'jens'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'find',
        collection: testCollection,
        query: {},
        options: {
          limit: 10,
          offset: 2
        }
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp.result).to.be.an.array()
        expect(resp.result[0]._id).to.be.exists()
        expect(resp.result[0].name).to.be.exists()
        expect(resp.limit).to.be.equals(10)
        expect(resp.offset).to.be.equals(2)
        done()
      })
    })
  })

  it('replace', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'nadine'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'replace',
        collection: testCollection,
        data: {
          $set: {
            name: 'nadja'
          }
        },
        query: {}
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp).to.be.an.object()
        expect(resp.matchedCount).to.be.exists()
        expect(resp.modifiedCount).to.be.exists()
        expect(resp.upsertedCount).to.be.exists()

        done()
      })
    })
  })

  it('replaceById', function (done) {
    hemera.act({
      topic,
      cmd: 'create',
      collection: testCollection,
      data: {
        name: 'nadja'
      }
    }, function (err, resp) {
      expect(err).to.be.not.exists()
      expect(resp).to.be.an.object()

      hemera.act({
        topic,
        cmd: 'replaceById',
        collection: testCollection,
        data: {
          name: 'nadja'
        },
        id: resp._id
      }, function (err, resp) {
        expect(err).to.be.not.exists()
        expect(resp._id).to.be.exists()
        expect(resp.name).to.be.exists()
        done()
      })
    })
  })
})
<|endoftext|>