<commit_before>Ext.namespace('Vpc.Paragraphs');
Vpc.Paragraphs.Panel = Ext.extend(Vps.Binding.AbstractPanel,
{
    layout:'fit',
    cls: 'vpc-paragraphs',
    initComponent : function()
    {
        this.addEvents('editcomponent');

        if (this.autoLoad !== false) {
            this.autoLoad = true;
        } else {
            delete this.autoLoad;
        }

        this.dataView = new Vpc.Paragraphs.DataView({
            components: this.components,
            componentIcons: this.componentIcons,
            width: this.previewWidth,
            listeners: {
                scope: this,
                'delete': this.onDelete,
                edit: this.onEdit,
                changeVisible: this.onChangeVisible,
                changePos: this.onChangePos,
                addParagraphMenuShow: this.onAddParagraphMenuShow,
                addParagraph: this.onParagraphAdd
            }
        });

        this.items = [ this.dataView ];

        this.actions.showVisible = new Ext.Action({
            text : trlVps('Show'),
            icon : '/assets/silkicons/monitor.png',
            cls  : 'x-btn-text-icon',
            menu : [{
                text: trlVps('all paragraphs'),
                group: 'showVisible',
                checked: true,
                handler: function() {
                    this.applyBaseParams({
                        filter_visible: null
                    });
                    this.load();
                },
                scope: this
            }, {
                text: trlVps('visible paragraphs'),
                group: 'showVisible',
                checked: false,
                handler: function() {
                    this.applyBaseParams({
                        filter_visible: 1
                    });
                    this.load();
                },
                scope: this
            }]
        });
        this.actions.addparagraph = new Vpc.Paragraphs.AddParagraphButton({
            components: this.components,
            componentIcons: this.componentIcons,
            listeners: {
                scope: this,
                menushow: function() {
                    this.addParagraphPos = this.store.getAt(this.store.getCount()-1).get('pos')+1;
                },
                addParagraph: function(component) {
                    this.onParagraphAdd(component);
                }
            }
        });

        this.tbar = [ this.actions.showVisible, '-', this.actions.addparagraph ];

        Vpc.Paragraphs.Panel.superclass.initComponent.call(this);
    },

    doAutoLoad : function()
    {
        //autoLoad kann in der zwischenzeit abgeschaltet werden, zB wenn
        //wir in einem Binding sind
        if (!this.autoLoad) return;
        this.load();
    },

    load: function(params, options) {
        if (!params) params = {};
        if (!this.store) {
            Ext.applyIf(params, Ext.apply({ meta: true }, this.baseParams));
            Ext.Ajax.request({
                mask: true,
                url: this.controllerUrl+'/json-data',
                params: params,
                success: function(response, options, r) {
                    this.onMetaLoad(r);
                },
                scope: this
            });
        } else {
            if (this.pagingType && this.pagingType != 'Date' && !params.start) {
                params.start = 0;
            }
            this.store.load({
                params: params
            });
        }
    },

    onMetaLoad : function(result)
    {
        var meta = result.metaData;
        this.metaData = meta;

        var storeConfig = {
            proxy: new Ext.data.HttpProxy({ url: this.controllerUrl + '/json-data' }),
            reader: new Ext.data.JsonReader({
                totalProperty: meta.totalProperty,
                root: meta.root,
                id: meta.id,
                sucessProperty: meta.successProperty,
                fields: meta.fields
            }),
            sortInfo: meta.sortInfo
        };
        this.store = new Ext.data.Store(storeConfig);
        if (this.baseParams) {
            this.setBaseParams(this.baseParams);
            delete this.baseParams;
        }
        this.dataView.setStore(this.store);
        this.loadMask = new Ext.LoadMask(this.bwrap,
                Ext.apply({store:this.store}, this.loadMask));

        if (result.rows) {
            this.store.loadData(result);
        }
    },
    getStore : function() {
        return this.store;
    },
    getBaseParams : function() {
        if (this.getStore()) {
            return this.getStore().baseParams;
        } else {
            return this.baseParams || {};
        }
    },
    setBaseParams : function(baseParams) {
        if (this.getStore()) {
            this.getStore().baseParams = baseParams;
        } else {
            //no store yet, apply them later
            this.baseParams = baseParams;
        }
    },
    applyBaseParams : function(baseParams) {
        if (this.getStore()) {
            Ext.apply(this.getStore().baseParams, baseParams);
        } else {
            //no store yet, apply them later
            if (!this.baseParams) this.baseParams = {};
            Ext.apply(this.baseParams, baseParams);
        }
    },

    //protected, zum überschreiben in unterklassen um zusäztliche daten zu speichern
    getSaveParams : function()
    {
        var data = [];
        var modified = this.store.getModifiedRecords();
        if (!modified.length) return {};
        modified.each(function(r) {
            data.push(r.data);
        }, this);
        var params = this.getBaseParams() || {};
        params.data = Ext.util.JSON.encode(data);
        return params;
    },

    submit : function()
    {
        var params = this.getSaveParams();

        //gibts da keine bessere l�sung?
        var empty = true;
        for (var i in params) {
            empty = false;
            break;
        }
        if (empty) return;

        this.el.mask(trlVps('Saving...'));

        Ext.Ajax.request({
            url: this.controllerUrl+'/json-save',
            params: params,
            success: function(response, options, r) {
                //geänderte und neue zurücksetzen, damit isDirty false ist
                this.store.modified = [];
                this.reload();
                this.fireEvent('datachange', r);
            },
            callback: function() {
                this.el.unmask();
            },
            scope  : this
        });
    },

    onChangeVisible: function(record) {
        record.set('visible', !record.get('visible'));
        this.submit();
    },

    onChangePos: function(record, pos) {
        record.set('pos', pos);
        this.submit();
    },

    onDelete : function(record) {
        Ext.Msg.show({
            title: trlVps('Delete'),
            msg: trlVps('Do you really wish to remove this paragraph?'),
            buttons: Ext.Msg.YESNO,
            scope: this,
            fn: function(button) {
                if (button == 'yes') {
                    this.el.mask(trlVps('Deleting...'));
                    var params = this.getBaseParams();
                    params.id = record.get('id');
                    Ext.Ajax.request({
                        url: this.controllerUrl+'/json-delete',
                        params: params,
                        success: function(response, options, r) {
                            this.reload();
                        },
                        callback: function() {
                            this.el.unmask();
                        },
                        scope : this
                    });
                }
            }
        });
    },

    onEdit : function(record) {
        var bp = this.getBaseParams();
        this.fireEvent('editcomponent', {
            componentClass: record.get('component_class'),
            componentId: bp.componentId + '-' + record.get('id'),
            text: record.get('component_name')
        });
    },

    onAddParagraphMenuShow: function(record) {
        this.addParagraphPos = record.get('pos')+1;
    },

    onParagraphAdd : function(component)
    {
        var params = this.getBaseParams();
        params.pos = this.addParagraphPos;
        params.component = component;
        Ext.Ajax.request({
            url: this.controllerUrl + '/json-add-paragraph',
            params: params,
            success: function(r) {
                response = Ext.decode(r.responseText);
                if (response.hasController) {
                    this.fireEvent('editcomponent', {
                        componentClass: response.data.component_class,
                        componentId: this.getBaseParams().componentId + '-' + response.data.id,
                        text: response.data.component_name
                    });
                } else {
                    this.reload();
                }
            },
            scope: this
        });
    }

});

Ext.reg('vpc.paragraphs', Vpc.Paragraphs.Panel);
<commit_msg>wenn > 10 eintraege korrekt sortieren<commit_after>Ext.namespace('Vpc.Paragraphs');
Vpc.Paragraphs.Panel = Ext.extend(Vps.Binding.AbstractPanel,
{
    layout:'fit',
    cls: 'vpc-paragraphs',
    initComponent : function()
    {
        this.addEvents('editcomponent');

        if (this.autoLoad !== false) {
            this.autoLoad = true;
        } else {
            delete this.autoLoad;
        }

        this.dataView = new Vpc.Paragraphs.DataView({
            components: this.components,
            componentIcons: this.componentIcons,
            width: this.previewWidth,
            listeners: {
                scope: this,
                'delete': this.onDelete,
                edit: this.onEdit,
                changeVisible: this.onChangeVisible,
                changePos: this.onChangePos,
                addParagraphMenuShow: this.onAddParagraphMenuShow,
                addParagraph: this.onParagraphAdd
            }
        });

        this.items = [ this.dataView ];

        this.actions.showVisible = new Ext.Action({
            text : trlVps('Show'),
            icon : '/assets/silkicons/monitor.png',
            cls  : 'x-btn-text-icon',
            menu : [{
                text: trlVps('all paragraphs'),
                group: 'showVisible',
                checked: true,
                handler: function() {
                    this.applyBaseParams({
                        filter_visible: null
                    });
                    this.load();
                },
                scope: this
            }, {
                text: trlVps('visible paragraphs'),
                group: 'showVisible',
                checked: false,
                handler: function() {
                    this.applyBaseParams({
                        filter_visible: 1
                    });
                    this.load();
                },
                scope: this
            }]
        });
        this.actions.addparagraph = new Vpc.Paragraphs.AddParagraphButton({
            components: this.components,
            componentIcons: this.componentIcons,
            listeners: {
                scope: this,
                menushow: function() {
                    this.addParagraphPos = this.store.getAt(this.store.getCount()-1).get('pos')+1;
                },
                addParagraph: function(component) {
                    this.onParagraphAdd(component);
                }
            }
        });

        this.tbar = [ this.actions.showVisible, '-', this.actions.addparagraph ];

        Vpc.Paragraphs.Panel.superclass.initComponent.call(this);
    },

    doAutoLoad : function()
    {
        //autoLoad kann in der zwischenzeit abgeschaltet werden, zB wenn
        //wir in einem Binding sind
        if (!this.autoLoad) return;
        this.load();
    },

    load: function(params, options) {
        if (!params) params = {};
        if (!this.store) {
            Ext.applyIf(params, Ext.apply({ meta: true }, this.baseParams));
            Ext.Ajax.request({
                mask: true,
                url: this.controllerUrl+'/json-data',
                params: params,
                success: function(response, options, r) {
                    this.onMetaLoad(r);
                },
                scope: this
            });
        } else {
            if (this.pagingType && this.pagingType != 'Date' && !params.start) {
                params.start = 0;
            }
            this.store.load({
                params: params
            });
        }
    },

    onMetaLoad : function(result)
    {
        var meta = result.metaData;
        this.metaData = meta;

        var storeConfig = {
            proxy: new Ext.data.HttpProxy({ url: this.controllerUrl + '/json-data' }),
            reader: new Ext.data.JsonReader({
                totalProperty: meta.totalProperty,
                root: meta.root,
                id: meta.id,
                sucessProperty: meta.successProperty,
                fields: meta.fields
            }),
            sortInfo: meta.sortInfo,
            remoteSort: true
        };
        this.store = new Ext.data.Store(storeConfig);
        if (this.baseParams) {
            this.setBaseParams(this.baseParams);
            delete this.baseParams;
        }
        this.dataView.setStore(this.store);
        this.loadMask = new Ext.LoadMask(this.bwrap,
                Ext.apply({store:this.store}, this.loadMask));

        if (result.rows) {
            this.store.loadData(result);
        }
    },
    getStore : function() {
        return this.store;
    },
    getBaseParams : function() {
        if (this.getStore()) {
            return this.getStore().baseParams;
        } else {
            return this.baseParams || {};
        }
    },
    setBaseParams : function(baseParams) {
        if (this.getStore()) {
            this.getStore().baseParams = baseParams;
        } else {
            //no store yet, apply them later
            this.baseParams = baseParams;
        }
    },
    applyBaseParams : function(baseParams) {
        if (this.getStore()) {
            Ext.apply(this.getStore().baseParams, baseParams);
        } else {
            //no store yet, apply them later
            if (!this.baseParams) this.baseParams = {};
            Ext.apply(this.baseParams, baseParams);
        }
    },

    //protected, zum überschreiben in unterklassen um zusäztliche daten zu speichern
    getSaveParams : function()
    {
        var data = [];
        var modified = this.store.getModifiedRecords();
        if (!modified.length) return {};
        modified.each(function(r) {
            data.push(r.data);
        }, this);
        var params = this.getBaseParams() || {};
        params.data = Ext.util.JSON.encode(data);
        return params;
    },

    submit : function()
    {
        var params = this.getSaveParams();

        //gibts da keine bessere l�sung?
        var empty = true;
        for (var i in params) {
            empty = false;
            break;
        }
        if (empty) return;

        this.el.mask(trlVps('Saving...'));

        Ext.Ajax.request({
            url: this.controllerUrl+'/json-save',
            params: params,
            success: function(response, options, r) {
                //geänderte und neue zurücksetzen, damit isDirty false ist
                this.store.modified = [];
                this.reload();
                this.fireEvent('datachange', r);
            },
            callback: function() {
                this.el.unmask();
            },
            scope  : this
        });
    },

    onChangeVisible: function(record) {
        record.set('visible', !record.get('visible'));
        this.submit();
    },

    onChangePos: function(record, pos) {
        record.set('pos', pos);
        this.submit();
    },

    onDelete : function(record) {
        Ext.Msg.show({
            title: trlVps('Delete'),
            msg: trlVps('Do you really wish to remove this paragraph?'),
            buttons: Ext.Msg.YESNO,
            scope: this,
            fn: function(button) {
                if (button == 'yes') {
                    this.el.mask(trlVps('Deleting...'));
                    var params = this.getBaseParams();
                    params.id = record.get('id');
                    Ext.Ajax.request({
                        url: this.controllerUrl+'/json-delete',
                        params: params,
                        success: function(response, options, r) {
                            this.reload();
                        },
                        callback: function() {
                            this.el.unmask();
                        },
                        scope : this
                    });
                }
            }
        });
    },

    onEdit : function(record) {
        var bp = this.getBaseParams();
        this.fireEvent('editcomponent', {
            componentClass: record.get('component_class'),
            componentId: bp.componentId + '-' + record.get('id'),
            text: record.get('component_name')
        });
    },

    onAddParagraphMenuShow: function(record) {
        this.addParagraphPos = record.get('pos')+1;
    },

    onParagraphAdd : function(component)
    {
        var params = this.getBaseParams();
        params.pos = this.addParagraphPos;
        params.component = component;
        Ext.Ajax.request({
            url: this.controllerUrl + '/json-add-paragraph',
            params: params,
            success: function(r) {
                response = Ext.decode(r.responseText);
                if (response.hasController) {
                    this.fireEvent('editcomponent', {
                        componentClass: response.data.component_class,
                        componentId: this.getBaseParams().componentId + '-' + response.data.id,
                        text: response.data.component_name
                    });
                } else {
                    this.reload();
                }
            },
            scope: this
        });
    }

});

Ext.reg('vpc.paragraphs', Vpc.Paragraphs.Panel);
<|endoftext|>


<commit_before>var jsonview = {};

(function() {

	var child, data;

	if (document.body && document.body.childNodes[0] && document.body.childNodes[0].tagName == "PRE" || document.body.children.length == 0) {
		child = document.body.children.length ? document.body.childNodes[0] : document.body;
		data = child.innerText.trim();
		if (data) {
			chrome.extension.sendRequest({
				init : true
			}, function(response) {
				if (response.init) {
					jsonview.data = data;
					jsonview.options = JSON.parse(response.options);
				}
			});
		}
	}

})();
<commit_msg>removed unused file<commit_after><|endoftext|>


<commit_before>var express = require("express");
var mongoose = require("mongoose");
var router = express.Router({mergeParams: true});
var Article = require("../models/article");
var Comment = require("../models/comment");
var User = require("../models/user");
var middleware = require("../middleware");
var moment = require("moment");

router.use(middleware.isLoggedIn);

// CREATE COMMENT LOGIC
router.post("/", (req, res) => {
    Article.findById(req.params.id).populate("comments").exec((err, article) => {
        if(err) {
            req.flash("error", `Error creating comment: ${err.message}`);
            return res.redirect("back");
        } else {
            var comment = req.body.comment;
            comment.createdAt = moment().format();
            comment.author = {
                id: req.user._id,
                username: req.user.username
            }
            Comment.create(comment, (err, comment) => {
                if(err) {
                    console.log(err);
                } else {
                    article.comments.push(comment);
                    article.save();

                    var commentIds = article.comments.map((el) => {return el.author.id});

                    // send notif to everyone who commented
                    User.find().where('_id').in(commentIds).exec((err, commenters) => {
                        for (var i = 0; i < commenters.length; i++) {
                            var commenter = commenters[i]
                            if (article.author.id.equals(commenter.id)) {
                                commenter.notifications.push({
                                    message: `${req.user.username} commented on your post`,
                                    link: `/articles/${req.params.id}`,
                                    isRead: false
                                });
                            } else if (!commenter._id.equals(req.user.id)) {
                                commenter.notifications.push({
                                    message: `${req.user.username} commented on a post you're following`,
                                    link: `/articles/${req.params.id}`,
                                    isRead: false
                                });
                            }
                            commenter.save();
                        }
                        req.flash("success", "Posted comment");
                        return res.redirect(`/articles/${article._id}`);
                    });
                }
            });
        }
    })
});

// EDIT COMMENT FORM
router.get("/:comment_id/edit", middleware.checkCommentOwnership, (req, res) => {
    Comment.findById(req.params.comment_id, (err, comment) => {
        return res.render("comments/edit", { articleId: req.params.id, comment: comment });
    });
});

// UPDATE COMMENT
router.put("/:comment_id", middleware.checkCommentOwnership, (req, res) => {
    Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment, (err, comment) => {
        if (err) {
            req.flash("error", `Error updating comment: ${err.message}`);
            return res.redirect("back");
        } else {
            req.flash("success", "Updated comment!");
            return res.redirect(`/articles/${req.params.id}`);
        }
    });
});

// DESTROY COMMEMNT
router.delete("/:comment_id", middleware.checkCommentOwnership, (req, res) => {
    Comment.findByIdAndRemove(req.params.comment_id, (err) => {
        if (err) {
            req.flash("error", `Error deleting comment: ${err.message}`);
            return res.redirect("back");
        } else {
            // Remove comment from article's comment array (there's probably a better way to do this)
            Article.findById(req.params.id, (err, article) => {
                var newComments = []
                var objectId = mongoose.Types.ObjectId(req.params.comment_id);
                var numComments = article.comments.length;
                var counter = 0;
                article.comments.forEach((comment) => {
                    if (!comment.id.equals(objectId.id)) {
                        newComments.push(comment);
                    }
                    counter++;
                    if (numComments === counter) { // iterated through all comments
                        article.comments = newComments;
                        article.save();
                        req.flash("success", "Deleted comment");
                        return res.redirect(`/articles/${article._id}`);
                    }
                });
            });
        }
    });
});

module.exports = router;<commit_msg>Fix notifications on article activity<commit_after>var express = require("express");
var mongoose = require("mongoose");
var router = express.Router({ mergeParams: true });
var Article = require("../models/article");
var Comment = require("../models/comment");
var User = require("../models/user");
var middleware = require("../middleware");
var moment = require("moment");

router.use(middleware.isLoggedIn);

// CREATE COMMENT LOGIC
router.post("/", (req, res) => {
    Article.findById(req.params.id).populate("comments").exec((err, article) => {
        if (err) {
            req.flash("error", `Error creating comment: ${err.message}`);
            return res.redirect("back");
        } else {
            var comment = req.body.comment;
            comment.createdAt = moment().format();
            comment.author = {
                id: req.user._id,
                username: req.user.username
            }
            Comment.create(comment, (err, comment) => {
                if (err) {
                    console.log(err);
                } else {
                    article.comments.push(comment);
                    article.save();

                    // send notif to author
                    User.findById(article.author.id, (err, author) => {
                        author.notifications.push({
                            message: `${req.user.username} commented on your post`,
                            link: `/articles/${req.params.id}`,
                            isRead: false
                        });
                        author.save();
                        var commentIds = article.comments.map((el) => { return el.author.id });

                        // send notif to everyone who commented, who isn't the author or comment poster
                        User.find().where('_id').in(commentIds).exec((err, commenters) => {
                            for (var i = 0; i < commenters.length; i++) {
                                var commenter = commenters[i]
                                if ((!req.user._id.equals(commenter.id)) && (!article.author.id.equals(commenter.id))) {
                                    commenter.notifications.push({
                                        message: `${req.user.username} commented on a post you're following`,
                                        link: `/articles/${req.params.id}`,
                                        isRead: false
                                    });
                                }
                                commenter.save();
                            }
                            req.flash("success", "Posted comment");
                            return res.redirect(`/articles/${article._id}`);
                        });
                    });
                }
            });
        }
    })
});

// EDIT COMMENT FORM
router.get("/:comment_id/edit", middleware.checkCommentOwnership, (req, res) => {
    Comment.findById(req.params.comment_id, (err, comment) => {
        return res.render("comments/edit", { articleId: req.params.id, comment: comment });
    });
});

// UPDATE COMMENT
router.put("/:comment_id", middleware.checkCommentOwnership, (req, res) => {
    Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment, (err, comment) => {
        if (err) {
            req.flash("error", `Error updating comment: ${err.message}`);
            return res.redirect("back");
        } else {
            req.flash("success", "Updated comment!");
            return res.redirect(`/articles/${req.params.id}`);
        }
    });
});

// DESTROY COMMEMNT
router.delete("/:comment_id", middleware.checkCommentOwnership, (req, res) => {
    Comment.findByIdAndRemove(req.params.comment_id, (err) => {
        if (err) {
            req.flash("error", `Error deleting comment: ${err.message}`);
            return res.redirect("back");
        } else {
            // Remove comment from article's comment array (there's probably a better way to do this)
            Article.findById(req.params.id, (err, article) => {
                var newComments = []
                var objectId = mongoose.Types.ObjectId(req.params.comment_id);
                var numComments = article.comments.length;
                var counter = 0;
                article.comments.forEach((comment) => {
                    if (!comment.id.equals(objectId.id)) {
                        newComments.push(comment);
                    }
                    counter++;
                    if (numComments === counter) { // iterated through all comments
                        article.comments = newComments;
                        article.save();
                        req.flash("success", "Deleted comment");
                        return res.redirect(`/articles/${article._id}`);
                    }
                });
            });
        }
    });
});

module.exports = router;<|endoftext|>


<commit_before>
var pow = Math.pow;
var sqrt = Math.sqrt;
var fabs = Math.abs;
var exp = Math.exp;
var log = Math.log;

var VERBOSE = false;

var NULL = null;
var PI = Math.PI;
var TRUE = true;
var FALSE = false;
var ECCENTRICITY_COEFF = (0.077);	/* Dole's was 0.077 */
var PROTOPLANET_MASS = (1.0E-15);	/* Units of solar masses */
var SOLAR_MASS_IN_GRAMS = (1.989E33);	/* Units of grams */
var EARTH_MASS_IN_GRAMS = (5.977E27);	/* Units of grams */
var EARTH_RADIUS = (6.378E6);	/* Units of cm */
var EARTH_RADIUS_IN_KM = (6378.0);	/* Units of km */
var EARTH_ACCELERATION = (981.0);	/* Units of cm/sec2 */
var EARTH_AXIAL_TILT = (23.4);	/* Units of degrees */
var EARTH_EXOSPHERE_TEMP = (1273.0);	/* Units of degrees Kelvin */
var EARTH_MASSES_PER_SOLAR_MASS = (332775.64);
var EARTH_EFFECTIVE_TEMP = (255.0);	/* Units of degrees Kelvin */
var EARTH_ALBEDO = (0.39);
var CLOUD_COVERAGE_FACTOR = (1.839E-8);	/* Km2/kg */
var EARTH_WATER_MASS_PER_AREA = (3.83E15);	/* grams per square km */
var EARTH_SURF_PRES_IN_MILLIBARS = (1000.0);
var EARTH_CONVECTION_FACTOR = (0.43);	/* from Hart, eq.20 */
var FREEZING_POINT_OF_WATER = (273.0);	/* Units of degrees Kelvin */
var DAYS_IN_A_YEAR = (365.256);	/* Earth days per Earth year */

/* gas_retention_threshold = 6.0; *//* ratio of esc vel to RMS vel */

var GAS_RETENTION_THRESHOLD = (5.0);	/* ratio of esc vel to RMS vel */
var GAS_GIANT_ALBEDO = (0.5);	/* albedo of a gas giant */
var CLOUD_ALBEDO = (0.52);
var AIRLESS_ROCKY_ALBEDO = (0.07);
var ROCKY_ALBEDO = (0.15);
var WATER_ALBEDO = (0.04);
var AIRLESS_ICE_ALBEDO = (0.5);
var ICE_ALBEDO = (0.7);
var SECONDS_PER_HOUR = (3600.0);
var CM_PER_AU = (1.495978707E13);	/* number of cm in an AU */
var CM_PER_KM = (1.0E5);	/* number of cm in a km */
var CM_PER_METER = (100.0);
var MILLIBARS_PER_BAR = (1000.0);
var KELVIN_CELCIUS_DIFFERENCE = (273.0);
var GRAV_CONSTANT = (6.672E-8);	/* units of dyne cm2/gram2 */
var GREENHOUSE_EFFECT_CONST = (0.93);	/* affects inner radius.. */
var MOLAR_GAS_CONST = (8314.41);	/* units: g*m2/=(sec2*K*mol); */
var K = (50.0);	/* K = gas/dust ratio */
var B = (1.2E-5);	/* Used in Crit_mass calc */
var DUST_DENSITY_COEFF = (2.0E-3);	/* A in Dole's paper */
var ALPHA = (5.0);	/* Used in density calcs */
var N = (3.0);	/* Used in density calcs */
var J = (1.46E-19);	/* Used in day-length calcs =(cm2/sec2 g); */
var INCREDIBLY_LARGE_NUMBER = (9.9999E37);

/* Now for a few molecular weights =(used for RMS velocity calcs);: */
/* This table is from Dole's book "Habitable Planets for Man", p. 38 */
var ATOMIC_HYDROGEN = (1.0);	/* H */
var MOLECULAR_HYDROGEN = (2.0);	/* H2 */
var HELIUM = (4.0);	/* He */
var ATOMIC_NITROGEN = (14.0);	/* N */
var ATOMIC_OXYGEN = (16.0);	/* O */
var METHANE = (16.0);	/* CH4 */
var AMMONIA = (17.0);	/* NH3 */
var WATER_VAPOR = (18.0);	/* H2O */
var NEON = (20.2);	/* Ne */
var MOLECULAR_NITROGEN = (28.0);	/* N2 */
var CARBON_MONOXIDE = (28.0);	/* CO */
var NITRIC_OXIDE = (30.0);	/* NO */
var MOLECULAR_OXYGEN = (32.0);	/* O2 */
var HYDROGEN_SULPHIDE = (34.1);	/* H2S */
var ARGON = (39.9);	/* Ar */
var CARBON_DIOXIDE = (44.0);	/* CO2 */
var NITROUS_OXIDE = (44.0);	/* N2O */
var NITROGEN_DIOXIDE = (46.0);	/* NO2 */
var OZONE = (48.0);	/* O3 */
var SULPHUR_DIOXIDE = (64.1);	/* SO2 */
var SULPHUR_TRIOXIDE = (80.1);	/* SO3 */
var KRYPTON = (83.8);	/* Kr */
var XENON = (131.3);	/* Xe */

/* The following defines are used in the kothari_radius function in */
/* file enviro.c. */
var A1_20 = (6.485E12);	/* All units are in cgs system. */
var A2_20 = (4.0032E-8);	/* ie: cm, g, dynes, etc. */
var BETA_20 = (5.71E12);

/* The following defines are used in determining the fraction of a planet */
/* covered with clouds in function cloud_fraction in file enviro.c. */
var Q1_36 = (1.258E19);	/* grams */
var Q2_36 = (0.0698);	/* 1/Kelvin */

<commit_msg>Removed the Math function remaps, all instances of log,exp,sqrt,fabs,pow are replaced by their Math.*** counterparts in the source.<commit_after>var VERBOSE = false;

var NULL = null;
var PI = Math.PI;
var TRUE = true;
var FALSE = false;
var ECCENTRICITY_COEFF = (0.077); /* Dole's was 0.077 */
var PROTOPLANET_MASS = (1.0E-15); /* Units of solar masses */
var SOLAR_MASS_IN_GRAMS = (1.989E33); /* Units of grams */
var EARTH_MASS_IN_GRAMS = (5.977E27); /* Units of grams */
var EARTH_RADIUS = (6.378E6); /* Units of cm */
var EARTH_RADIUS_IN_KM = (6378.0); /* Units of km */
var EARTH_ACCELERATION = (981.0); /* Units of cm/sec2 */
var EARTH_AXIAL_TILT = (23.4); /* Units of degrees */
var EARTH_EXOSPHERE_TEMP = (1273.0); /* Units of degrees Kelvin */
var EARTH_MASSES_PER_SOLAR_MASS = (332775.64);
var EARTH_EFFECTIVE_TEMP = (255.0); /* Units of degrees Kelvin */
var EARTH_ALBEDO = (0.39);
var CLOUD_COVERAGE_FACTOR = (1.839E-8); /* Km2/kg */
var EARTH_WATER_MASS_PER_AREA = (3.83E15); /* grams per square km */
var EARTH_SURF_PRES_IN_MILLIBARS = (1000.0);
var EARTH_CONVECTION_FACTOR = (0.43); /* from Hart, eq.20 */
var FREEZING_POINT_OF_WATER = (273.0); /* Units of degrees Kelvin */
var DAYS_IN_A_YEAR = (365.256); /* Earth days per Earth year */

/* gas_retention_threshold = 6.0; *//* ratio of esc vel to RMS vel */

var GAS_RETENTION_THRESHOLD = (5.0); /* ratio of esc vel to RMS vel */
var GAS_GIANT_ALBEDO = (0.5); /* albedo of a gas giant */
var CLOUD_ALBEDO = (0.52);
var AIRLESS_ROCKY_ALBEDO = (0.07);
var ROCKY_ALBEDO = (0.15);
var WATER_ALBEDO = (0.04);
var AIRLESS_ICE_ALBEDO = (0.5);
var ICE_ALBEDO = (0.7);
var SECONDS_PER_HOUR = (3600.0);
var CM_PER_AU = (1.495978707E13); /* number of cm in an AU */
var CM_PER_KM = (1.0E5); /* number of cm in a km */
var CM_PER_METER = (100.0);
var MILLIBARS_PER_BAR = (1000.0);
var KELVIN_CELCIUS_DIFFERENCE = (273.0);
var GRAV_CONSTANT = (6.672E-8); /* units of dyne cm2/gram2 */
var GREENHOUSE_EFFECT_CONST = (0.93); /* affects inner radius.. */
var MOLAR_GAS_CONST = (8314.41); /* units: g*m2/=(sec2*K*mol); */
var K = (50.0); /* K = gas/dust ratio */
var B = (1.2E-5); /* Used in Crit_mass calc */
var DUST_DENSITY_COEFF = (2.0E-3); /* A in Dole's paper */
var ALPHA = (5.0); /* Used in density calcs */
var N = (3.0); /* Used in density calcs */
var J = (1.46E-19); /* Used in day-length calcs =(cm2/sec2 g); */
var INCREDIBLY_LARGE_NUMBER = (9.9999E37);

/* Now for a few molecular weights =(used for RMS velocity calcs);: */
/* This table is from Dole's book "Habitable Planets for Man", p. 38 */
var ATOMIC_HYDROGEN = (1.0); /* H */
var MOLECULAR_HYDROGEN = (2.0); /* H2 */
var HELIUM = (4.0); /* He */
var ATOMIC_NITROGEN = (14.0); /* N */
var ATOMIC_OXYGEN = (16.0); /* O */
var METHANE = (16.0); /* CH4 */
var AMMONIA = (17.0); /* NH3 */
var WATER_VAPOR = (18.0); /* H2O */
var NEON = (20.2); /* Ne */
var MOLECULAR_NITROGEN = (28.0); /* N2 */
var CARBON_MONOXIDE = (28.0); /* CO */
var NITRIC_OXIDE = (30.0); /* NO */
var MOLECULAR_OXYGEN = (32.0); /* O2 */
var HYDROGEN_SULPHIDE = (34.1); /* H2S */
var ARGON = (39.9); /* Ar */
var CARBON_DIOXIDE = (44.0); /* CO2 */
var NITROUS_OXIDE = (44.0); /* N2O */
var NITROGEN_DIOXIDE = (46.0); /* NO2 */
var OZONE = (48.0); /* O3 */
var SULPHUR_DIOXIDE = (64.1); /* SO2 */
var SULPHUR_TRIOXIDE = (80.1); /* SO3 */
var KRYPTON = (83.8); /* Kr */
var XENON = (131.3); /* Xe */

/* The following defines are used in the kothari_radius function in */
/* file enviro.c. */
var A1_20 = (6.485E12); /* All units are in cgs system. */
var A2_20 = (4.0032E-8); /* ie: cm, g, dynes, etc. */
var BETA_20 = (5.71E12);

/* The following defines are used in determining the fraction of a planet */
/* covered with clouds in function cloud_fraction in file enviro.c. */
var Q1_36 = (1.258E19); /* grams */
var Q2_36 = (0.0698); /* 1/Kelvin */

<|endoftext|>


<commit_before>"use strict";

// old /upcomingLectures is now /lectures/upcoming !!!
// old /lecturesForGroups is now /lectures/groups !!!

// import the express router
var router = require("express").Router();

var moment = require("moment");

// create model
var Lecture = require("../models/model_lecture");

// on routes that end in /lectures
router.route("/")

    // get all lectures (GET /$apiBaseUrl/lectures)
    .get(function(req, res) {
        Lecture.find({}).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
            if (err) { res.status(500).send(err); }
            res.status(200).json(lectures);
            res.end();
        });
    });

// on routes that end in /lectures/upcoming
// this returns all lectures since monday of the current week
router.route("/upcoming")

    // get upcoming lectures (GET /$apiBaseUrl/lectures/upcoming)
    .post(function(req, res) {
        var mon = moment().day(1);
        mon.hour(0);
        mon.minute(0);
        mon.seconds(0);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "startTime": {"$gte": mon}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/groups
router.route("/groups")

    // get lectures for specific groups (POST /$apiBaseUrl/lectures/groups)
    .post(function(req, res) {

        // today at 0:00
        var today = new Date();
        today.setHours(0,0,0,0);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "endTime": {"$gte": today}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/weekly
router.route("/weekly")

    // get lectures for specific groups (POST /$apiBaseUrl/lectures/groups)
    .post(function(req, res) {

        var mon = moment().day(1);
        mon.hour(0);
        mon.minute(0);
        mon.seconds(0);
        var sun = moment().day(7);
        sun.hour(23);
        sun.minute(59);
        sun.seconds(59);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "startTime": {"$gte": mon}, "endTime": {"$lte": sun}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/:lecture_id
router.route("/:lecture_id")

    // get lecture with that id (GET /$apiBaseUrl/lectures/:lecture_id)
    .get(function(req, res) {
        Lecture.findById(req.params.lecture_id, function(err, lecture) {
            if (err) { res.status(500).send(err); }
            res.status(200).json(lecture);
            res.end();
        });
    });

module.exports = router;
<commit_msg>lectures: get deadlines per user<commit_after>"use strict";

// old /upcomingLectures is now /lectures/upcoming !!!
// old /lecturesForGroups is now /lectures/groups !!!

// import the express router
var router = require("express").Router();

var moment = require("moment");

// create model
var Lecture = require("../models/model_lecture");
var User = require("../models/model_user");

// on routes that end in /lectures
router.route("/")

    // get all lectures (GET /$apiBaseUrl/lectures)
    .get(function(req, res) {
        Lecture.find({}).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
            if (err) { res.status(500).send(err); }
            res.status(200).json(lectures);
            res.end();
        });
    });

// on routes that end in /lectures/user/:user_id
router.route("/user/:user_id")

    // get all lectures (GET /$apiBaseUrl/lectures)
    .get(function(req, res) {

        // get monday of the current week
        var mon = moment().day(1);
        mon.hour(0);
        mon.minute(0);
        mon.seconds(0);

        // get the users selected lectures
        User.findOne({'deviceId': req.params.user_id}, function(err, user) {
            if (err) { res.status(500).send(err); }
            if (user === null) { res.status(500).send("deviceId not found"); return;}

            var selectedLectures = user.selectedLectures.toObject();
            var selectedGroupsArr = [];
            var selectedLecturesArr = [];

            for (var i = 0; i < selectedLectures.length; i++) {
                selectedGroupsArr.push(selectedLectures[i].groupName);
                selectedLecturesArr.push(selectedLectures[i].lectureName);
            }

            var query = {groups: {$in: selectedGroupsArr},
                         lectureName: {$in: selectedLecturesArr},
                         startTime: {"$gte": mon}};

            Lecture.find(query).exec(function(err, lectures) {
                if (err) { res.status(500).send(err); }
                res.status(200).json(lectures);
                res.end();
            });
        });
    });

// on routes that end in /lectures/upcoming
// this returns all lectures since monday of the current week
router.route("/upcoming")

    // get upcoming lectures (GET /$apiBaseUrl/lectures/upcoming)
    .post(function(req, res) {
        var mon = moment().day(1);
        mon.hour(0);
        mon.minute(0);
        mon.seconds(0);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "startTime": {"$gte": mon}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/groups
router.route("/groups")

    // get lectures for specific groups (POST /$apiBaseUrl/lectures/groups)
    .post(function(req, res) {

        // today at 0:00
        var today = new Date();
        today.setHours(0,0,0,0);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "endTime": {"$gte": today}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/weekly
router.route("/weekly")

    // get lectures for specific groups (POST /$apiBaseUrl/lectures/groups)
    .post(function(req, res) {

        var mon = moment().day(1);
        mon.hour(0);
        mon.minute(0);
        mon.seconds(0);
        var sun = moment().day(7);
        sun.hour(23);
        sun.minute(59);
        sun.seconds(59);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "startTime": {"$gte": mon}, "endTime": {"$lte": sun}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/:lecture_id
router.route("/:lecture_id")

    // get lecture with that id (GET /$apiBaseUrl/lectures/:lecture_id)
    .get(function(req, res) {
        Lecture.findById(req.params.lecture_id, function(err, lecture) {
            if (err) { res.status(500).send(err); }
            res.status(200).json(lecture);
            res.end();
        });
    });

module.exports = router;
<|endoftext|>


<commit_before>var   server = require('http').createServer(),
 express = require('express')
 app = express(),
 WebSocketServer = require('ws').Server,
 wss = new WebSocketServer({ server:server }),
 port = '8080';

app.use(express.static(__dirname + '/www'));

wss.on('connection', function connection(ws) {
  var interv;
  ws.on('message', function incoming(message) {
    var counter = 0;
    console.log('received: %s', message);

    interv = setInterval(function(){
      ws.send('polo '+counter++);
    }, 3000);
  });
  ws.on('close',function(){
    console.log('connections closed');
    clearInterval(interv);
  });
  ws.send('connected');
});

server.on('request', app);
server.listen(port, function () { console.log('Listening on ' + server.address().port) });

<commit_msg>added comma in var simple websocket<commit_after>var   server = require('http').createServer(),
 express = require('express'),
 app = express(),
 WebSocketServer = require('ws').Server,
 wss = new WebSocketServer({ server:server }),
 port = '8080';

app.use(express.static(__dirname + '/www'));

wss.on('connection', function connection(ws) {
  var interv;
  ws.on('message', function incoming(message) {
    var counter = 0;
    console.log('received: %s', message);

    interv = setInterval(function(){
      ws.send('polo '+counter++);
    }, 3000);
  });
  ws.on('close',function(){
    console.log('connections closed');
    clearInterval(interv);
  });
  ws.send('connected');
});

server.on('request', app);
server.listen(port, function () { console.log('Listening on ' + server.address().port) });

<|endoftext|>


<commit_before>var express = require('express');
var passport = require('passport');
var connectRouter = express.Router();
var router = express.Router();
var dealRouter = express.Router();

var Merchant = require('../model/merchant');
var Deal = require('../model/deal');

connectRouter.get('/test', function (req, res) {
  res.status(200).json({
    message: 'hahahaha'
  });
});

connectRouter.post('/reg', function (req, res) {
  Merchant.findOneAndUpdate({
    phone: req.body.phone
  }, {
      phone: req.body.phone,
      address: req.body.address,
      token: Merchant.genACTK()
    }, {
      upsert: true,
      new: true
    }, function (error, Merchant) {
      if (error) {
        console.error(error);
        return res.status(500).json({
          message: 'internal error'
        });
      }
      return res.status(200).json(Merchant);
    });
});

dealRouter.get('/', passport.authenticate('bearer', {
  session: false
}), function (req, res, next) {
  Deal.find()
})

router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

router.use('/connect', connectRouter);

module.exports = router;
<commit_msg>change something to try password<commit_after>var express = require('express');
var passport = require('passport');
var connectRouter = express.Router();
var router = express.Router();
var dealRouter = express.Router();

var Merchant = require('../model/merchant');
var Deal = require('../model/deal');

connectRouter.get('/test', function (req, res) {
  res.status(200).json({
    message: 'hahahaha'
  });
});

connectRouter.post('/reg', function (req, res) {
  Merchant.findOneAndUpdate({
    phone: req.body.phone
  }, {
      phone: req.body.phone,
      address: req.body.address,
      token: Merchant.genACTK()
    }, {
      upsert: true,
      new: true
    }, function (error, Merchant) {
      if (error) {
        console.error(error);
        return res.status(500).json({
          message: 'internal error'
        });
      }
      return res.status(200).json(Merchant);
    });
});

dealRouter.get('/', passport.authenticate('bearer', {
  session: false
}), function (req, res, next) {
  Deal.find()
})

router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

router.use('/connect', connectRouter);
router.use('/deal', dealRouter);

module.exports = router;
<|endoftext|>


<commit_before>/*
 * GET home page
 */

 exports.addBuddy= function(req,res){
 	res.render('newBuddy');
 }<commit_msg>forgot semi colon<commit_after>/*
 * GET home page
 */

 exports.addBuddy= function(req,res){
 	res.render('newBuddy');
 };<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  name: 'DocDiagramTrait',
  package: 'foam.documentation',
  // enhances BaseDetailView to add diagram support

  properties: [
    {
      name: 'diagramItem',
      documentation: "The diagram item we create and are managing.",
      type: 'diagram.DiagramItemTrait'
    }
  ],

  methods: {
    // destroy: function() {
    //   if ( this.diagramItem ) {
    //     this.diagramItem.destroy();
    //     this.diagramItem.parent = undefined;
    //
    //     this.diagramItem = undefined;
    //   }
    //   this.SUPER();
    // }
  }
});

CLASS({
  name: 'DocDiagramView',
  extendsModel: 'CViewView',
  package: 'foam.documentation',

  traits: [ 'foam.views.ChildTreeTrait',
            'foam.views.DataConsumerTrait'],

  requires: ['foam.documentation.ModelDocDiagram',
             'diagram.LinearLayout'],

  documentation: function() {/*
    A view that renders one model's diagram.
  */},

  properties: [
    {
      name: 'mainLayout',
      type: 'diagram.LinearLayout',
      factory: function() {
        return this.LinearLayout.create();
      }
    },
    {
      name: 'modelDiagram',
      factory: function() {
        var modelDiagram = this.ModelDocDiagram.create();
        this.mainLayout.addChild(modelDiagram.diagramItem);
        return modelDiagram;
      }
    }
  ],

  methods: {
    init: function() {
      this.SUPER();
      this.cview = this.mainLayout;
      this.mainLayout.x = 0;
      this.mainLayout.y = 0;
      this.mainLayout.width = 300;
      this.mainLayout.height = 250;
    },

    toHTML: function() {
      this.destroy();
      ret = this.SUPER();
      this.construct();
      return ret;
    },

    destroy: function() {
      //if ( this.modelDiagram && this.modelDiagram.diagramItem ) this.mainLayout.removeChild(this.modelDiagram.diagramItem);
      //this.modelDiagram = undefined;
      this.SUPER();
    }
  }
});

CLASS({
  name: 'ModelDocDiagram',
  extendsModel: 'foam.views.BaseDetailView',
  package: 'foam.documentation',
  traits: ['foam.documentation.DocDiagramTrait',
           'foam.documentation.DocModelFeatureDAOTrait'],

  requires: ['diagram.Block',
             'diagram.Section',
             'foam.documentation.FeatureListDiagram'],

  documentation: function() {/*
    A diagram block documenting one $$DOC{ref:'Model'}.
  */},

  properties: [
    {
      name: 'modelName',
      type: 'String'
    },
    {
      name: 'diagramItem',
      factory: function() {
        var diagramItem = this.Block.create({}, this.childX);
        diagramItem.addChild(
          this.Section.create({
            title$: this.modelName$, titleFont: 'bold 16px Roboto',
            background: 'rgba(64,64,255,255)',
            color: 'white'
          }, this.childX)
        );
        return diagramItem;
      }
    }
  ],

  methods: {

    construct: function() {
      this.SUPER();
      this.createTemplateView('properties', { model_: 'foam.documentation.FeatureListDiagram',
            model: this.X.Property, featureType:'properties' });
      //this.addChild(this.FeatureListDiagram.create({ model: this.X.Property, featureType:'properties' }, this.childX));
    },

    onValueChange_: function() {
      if (this.data) this.modelName = this.data.name;
      this.processModelChange();
    },

    processModelChange: function() {
      // abort if it's too early //TODO: (we import data and run its postSet before the rest is set up)
      if (!this.featureDAO || !this.modelDAO) return;
      this.generateFeatureDAO(this.data);
    },

    addChild: function(child) {
      this.SUPER(child);
      // add diagram node of the child to ours (child is a PropertyView in our case)
      // TODO(jacksonic): make a digram specific PropertyView trait to pass through diagramItem
      if ( this.diagramItem && child.view && child.view.diagramItem ) this.diagramItem.addChild(child.view.diagramItem);
    },
    removeChild: function(child) {
      if ( this.diagramItem && child.view && child.view.diagramItem ) this.diagramItem.removeChild(child.view.diagramItem);
      this.SUPER(child);
    }

  }
});

CLASS({
  name: 'FeatureListDiagram',
  package: 'foam.documentation',

  requires: ['foam.documentation.FeatureDiagram',
             'diagram.SectionGroup'],

  traits: [ 'foam.views.ChildTreeTrait',
            'foam.views.DataConsumerTrait',
            'foam.views.DataProviderTrait',
            'foam.documentation.DocDiagramTrait',
            'foam.documentation.FeatureListLoaderTrait'],

  documentation: function() {/*
    Renders a feature list (such as $$DOC{ref:'Model.properties'}, $$DOC{ref:'Model.methods'}, etc.) into
    a diagram.
  */},

  properties: [
    {
      name: 'diagramItem',
      factory: function() {
        return this.SectionGroup.create({ title: this.featureType.capitalize(), titleBackground: 'rgba(200,200,200,255)' });
      }
    }
  ],

  methods: {
    construct: function() {
      this.SUPER();
      this.diagramItem.title = this.featureType.capitalize();
      console.log("constructing FeatureListDiagram, already have children: ", this.children, this.diagramItem.children);
      this.selfFeaturesDAO.limit(5).select({ put: function(item) {
        var X = this.childX.sub({ data$: this.childX.SimpleValue.create(item, this.childX) });
        this.addChild(this.FeatureDiagram.create({ model: item.model_ }, X));
      }.bind(this)});
    },

    addChild: function(child) {
      this.SUPER(child);
      // add diagram node of the child to ours
      if ( this.diagramItem && child.diagramItem ) this.diagramItem.addChild(child.diagramItem);
    },
    removeChild: function(child) {
      if ( this.diagramItem &&  child.diagramItem ) this.diagramItem.removeChild(child.diagramItem);
      this.SUPER(child);
    }
  }

});

CLASS({
  name: 'FeatureDiagram',
  package: 'foam.documentation',

  traits: [ 'foam.views.ChildTreeTrait',
            'foam.views.DataConsumerTrait',
            'foam.views.DataProviderTrait',
            'foam.documentation.DocDiagramTrait'],

  requires: ['diagram.Section'],

  documentation: function() {/*
    The base model for feature-specific diagrams. Use PropertyFeatureDiagram,
    MethodFeatureDiagram, etc. as needed to diagram a feature.
  */},

  properties: [
    {
      name: 'data',
      postSet: function() {
        this.diagramItem.title = this.data.name;
      }
    },
    {
      name: 'diagramItem',
      factory: function() {
        return this.Section.create({ title: ( this.data ? this.data.name : "" ), titleFont: '10px' });
      }
    }
  ],
});

<commit_msg>DocBrowser diagrams: new layouts for extendsModel<commit_after>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  name: 'DocDiagramTrait',
  package: 'foam.documentation',
  // enhances BaseDetailView to add diagram support

  properties: [
    {
      name: 'diagramItem',
      documentation: "The diagram item we create and are managing.",
      type: 'diagram.DiagramItemTrait'
    }
  ],

  methods: {
    // destroy: function() {
    //   if ( this.diagramItem ) {
    //     this.diagramItem.destroy();
    //     this.diagramItem.parent = undefined;
    //
    //     this.diagramItem = undefined;
    //   }
    //   this.SUPER();
    // }
  }
});

CLASS({
  name: 'DocDiagramView',
  extendsModel: 'CViewView',
  package: 'foam.documentation',

  traits: [ 'foam.views.ChildTreeTrait',
            'foam.views.DataConsumerTrait'],

  requires: ['foam.documentation.ModelDocDiagram',
             'diagram.LinearLayout',
             'foam.graphics.Spacer'],

  documentation: function() {/*
    A view that renders one model's diagram.
  */},

  properties: [
    {
      name: 'outerLayout',
      type: 'diagram.LinearLayout',
      factory: function() {
        return this.LinearLayout.create({orientation:'vertical'});
      }
    },
    {
      name: 'mainLayout',
      type: 'diagram.LinearLayout',
      factory: function() {
        return this.LinearLayout.create({orientation:'horizontal'});
      }
    },
    {
      name: 'extendsModelLayout',
      type: 'diagram.LinearLayout',
      factory: function() {
        return this.LinearLayout.create({orientation:'vertical'});
      }
    },
    {
      name: 'modelDiagram',
      factory: function() {
        var modelDiagram = this.ModelDocDiagram.create();
        this.mainLayout.addChild(this.Spacer.create());
        this.mainLayout.addChild(modelDiagram.diagramItem);
        this.mainLayout.addChild(this.Spacer.create());
        return modelDiagram;
      }
    }
  ],

  methods: {
    init: function() {
      this.SUPER();
      this.cview = this.outerLayout;
      this.outerLayout.x = 0;
      this.outerLayout.y = 0;
      this.outerLayout.width = 300;
      this.outerLayout.height = 250;
      this.outerLayout.addChild(this.extendsModelLayout);
      this.outerLayout.addChild(this.mainLayout);

    },

    toHTML: function() {
      this.destroy();
      ret = this.SUPER();
      this.construct();
      return ret;
    },

    destroy: function() {
      //if ( this.modelDiagram && this.modelDiagram.diagramItem ) this.mainLayout.removeChild(this.modelDiagram.diagramItem);
      //this.modelDiagram = undefined;
      this.SUPER();
    }
  }
});

CLASS({
  name: 'ModelDocDiagram',
  extendsModel: 'foam.views.BaseDetailView',
  package: 'foam.documentation',
  traits: ['foam.documentation.DocDiagramTrait',
           'foam.documentation.DocModelFeatureDAOTrait'],

  requires: ['diagram.Block',
             'diagram.Section',
             'foam.documentation.FeatureListDiagram'],

  documentation: function() {/*
    A diagram block documenting one $$DOC{ref:'Model'}.
  */},

  properties: [
    {
      name: 'modelName',
      type: 'String'
    },
    {
      name: 'diagramItem',
      factory: function() {
        var diagramItem = this.Block.create({}, this.childX);
        diagramItem.addChild(
          this.Section.create({
            title$: this.modelName$, titleFont: 'bold 16px Roboto',
            background: 'rgba(64,64,255,255)',
            color: 'white'
          }, this.childX)
        );
        return diagramItem;
      }
    }
  ],

  methods: {

    construct: function() {
      this.SUPER();
      this.createTemplateView('properties', { model_: 'foam.documentation.FeatureListDiagram',
            model: this.X.Property, featureType:'properties' });
      //this.addChild(this.FeatureListDiagram.create({ model: this.X.Property, featureType:'properties' }, this.childX));
    },

    onValueChange_: function() {
      if (this.data) this.modelName = this.data.id;
      this.processModelChange();
    },

    processModelChange: function() {
      // abort if it's too early //TODO: (we import data and run its postSet before the rest is set up)
      if (!this.featureDAO || !this.modelDAO) return;
      this.generateFeatureDAO(this.data);
    },

    addChild: function(child) {
      this.SUPER(child);
      // add diagram node of the child to ours (child is a PropertyView in our case)
      // TODO(jacksonic): make a digram specific PropertyView trait to pass through diagramItem
      if ( this.diagramItem && child.view && child.view.diagramItem ) this.diagramItem.addChild(child.view.diagramItem);
    },
    removeChild: function(child) {
      if ( this.diagramItem && child.view && child.view.diagramItem ) this.diagramItem.removeChild(child.view.diagramItem);
      this.SUPER(child);
    }

  }
});

CLASS({
  name: 'FeatureListDiagram',
  package: 'foam.documentation',

  requires: ['foam.documentation.FeatureDiagram',
             'diagram.SectionGroup'],

  traits: [ 'foam.views.ChildTreeTrait',
            'foam.views.DataConsumerTrait',
            'foam.views.DataProviderTrait',
            'foam.documentation.DocDiagramTrait',
            'foam.documentation.FeatureListLoaderTrait'],

  documentation: function() {/*
    Renders a feature list (such as $$DOC{ref:'Model.properties'}, $$DOC{ref:'Model.methods'}, etc.) into
    a diagram.
  */},

  properties: [
    {
      name: 'diagramItem',
      factory: function() {
        return this.SectionGroup.create({ title: this.featureType.capitalize(), titleBackground: 'rgba(200,200,200,255)' });
      }
    }
  ],

  methods: {
    construct: function() {
      this.SUPER();
      this.diagramItem.title = this.featureType.capitalize();
      console.log("constructing FeatureListDiagram, already have children: ", this.children, this.diagramItem.children);
      this.selfFeaturesDAO.limit(5).select({ put: function(item) {
        var X = this.childX.sub({ data$: this.childX.SimpleValue.create(item, this.childX) });
        this.addChild(this.FeatureDiagram.create({ model: item.model_ }, X));
      }.bind(this)});
    },

    addChild: function(child) {
      this.SUPER(child);
      // add diagram node of the child to ours
      if ( this.diagramItem && child.diagramItem ) this.diagramItem.addChild(child.diagramItem);
    },
    removeChild: function(child) {
      if ( this.diagramItem &&  child.diagramItem ) this.diagramItem.removeChild(child.diagramItem);
      this.SUPER(child);
    }
  }

});

CLASS({
  name: 'FeatureDiagram',
  package: 'foam.documentation',

  traits: [ 'foam.views.ChildTreeTrait',
            'foam.views.DataConsumerTrait',
            'foam.views.DataProviderTrait',
            'foam.documentation.DocDiagramTrait'],

  requires: ['diagram.Section'],

  documentation: function() {/*
    The base model for feature-specific diagrams. Use PropertyFeatureDiagram,
    MethodFeatureDiagram, etc. as needed to diagram a feature.
  */},

  properties: [
    {
      name: 'data',
      postSet: function() {
        this.diagramItem.title = this.data.name;
      }
    },
    {
      name: 'diagramItem',
      factory: function() {
        return this.Section.create({ title: ( this.data ? this.data.name : "" ), titleFont: '10px' });
      }
    }
  ],
});

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */
(function() {

	/**
	 * Construct a new FileActions instance
	 * @constructs Files
	 */
	var Files = function() {
		this.initialize();
	};
	/**
	 * @memberof OCA.Search
	 */
	Files.prototype = {

		fileList: null,

		/**
		 * Initialize the file search
		 */
		initialize: function() {

			var self = this;

			this.fileAppLoaded = function() {
				return !!OCA.Files && !!OCA.Files.App;
			};
			function inFileList($row, result) {
				if (! self.fileAppLoaded()) {
					return false;
				}
				var dir = self.fileList.getCurrentDirectory().replace(/\/+$/,'');
				var resultDir = OC.dirname(result.path);
				return dir === resultDir && self.fileList.inList(result.name);
			}
			function updateLegacyMimetype(result) {
				// backward compatibility:
				if (!result.mime && result.mime_type) {
					result.mime = result.mime_type;
				}
			}
			function hideNoFilterResults() {
				var $nofilterresults = $('.nofilterresults');
				if ( ! $nofilterresults.hasClass('hidden') ) {
					$nofilterresults.addClass('hidden');
				}
			}

			this.renderFolderResult = function($row, result) {
				if (inFileList($row, result)) {
					return null;
				}
				hideNoFilterResults();
				/*render folder icon, show path beneath filename,
				 show size and last modified date on the right */
				this.updateLegacyMimetype(result);

				var $pathDiv = $('

').text(result.path);
				$row.find('td.info div.name').after($pathDiv).text(result.name);

				$row.find('td.result a').attr('href', result.link);
				$row.find('td.icon').css('background-image', 'url(' + OC.imagePath('core', 'filetypes/folder') + ')');
				return $row;
			};

			this.renderFileResult = function($row, result) {
				if (inFileList($row, result)) {
					return null;
				}
				hideNoFilterResults();
				/*render preview icon, show path beneath filename,
				 show size and last modified date on the right */
				this.updateLegacyMimetype(result);

				var $pathDiv = $('

').text(result.path);
				$row.find('td.info div.name').after($pathDiv).text(result.name);

				$row.find('td.result a').attr('href', result.link);

				if (self.fileAppLoaded()) {
					self.fileList.lazyLoadPreview({
						path: result.path,
						mime: result.mime,
						callback: function (url) {
							$row.find('td.icon').css('background-image', 'url(' + url + ')');
						}
					});
				} else {
					// FIXME how to get mime icon if not in files app
					var mimeicon = result.mime.replace('/', '-');
					$row.find('td.icon').css('background-image', 'url(' + OC.imagePath('core', 'filetypes/' + mimeicon) + ')');
					var dir = OC.dirname(result.path);
					if (dir === '') {
						dir = '/';
					}
					$row.find('td.info a').attr('href',
						OC.generateUrl('/apps/files/?dir={dir}&scrollto={scrollto}', {dir: dir, scrollto: result.name})
					);
				}
				return $row;
			};

			this.renderAudioResult = function($row, result) {
				/*render preview icon, show path beneath filename,
				 show size and last modified date on the right
				 show Artist and Album */
				$row = this.renderFileResult($row, result);
				if ($row) {
					$row.find('td.icon').css('background-image', 'url(' + OC.imagePath('core', 'filetypes/audio') + ')');
				}
				return $row;
			};

			this.renderImageResult = function($row, result) {
				/*render preview icon, show path beneath filename,
				 show size and last modified date on the right
				 show width and height */
				$row = this.renderFileResult($row, result);
				if ($row && !self.fileAppLoaded()) {
					$row.find('td.icon').css('background-image', 'url(' + OC.imagePath('core', 'filetypes/image') + ')');
				}
				return $row;
			};

			this.handleFolderClick = function($row, result, event) {
				// open folder
				if (self.fileAppLoaded() && self.fileList.id === 'files') {
					self.fileList.changeDirectory(result.path);
					return false;
				} else {
					return true;
				}
			};

			this.handleFileClick = function($row, result, event) {
				if (self.fileAppLoaded() && self.fileList.id === 'files') {
					self.fileList.changeDirectory(OC.dirname(result.path));
					self.fileList.scrollTo(result.name);
					return false;
				} else {
					return true;
				}
			};

			this.updateLegacyMimetype = function (result) {
				// backward compatibility:
				if (!result.mime && result.mime_type) {
					result.mime = result.mime_type;
				}
			};
			this.setFileList = function (fileList) {
				this.fileList = fileList;
			};

			OC.Plugins.register('OCA.Search', this);
		},
		attach: function(search) {
			var self = this;
			search.setFilter('files', function (query) {
				if (self.fileAppLoaded()) {
					self.fileList.setFilter(query);
					if (query.length > 2) {
						//search is not started until 500msec have passed
						window.setTimeout(function() {
							$('.nofilterresults').addClass('hidden');
						}, 500);
					}
				}
			});

			search.setRenderer('folder', this.renderFolderResult.bind(this));
			search.setRenderer('file',   this.renderFileResult.bind(this));
			search.setRenderer('audio',  this.renderAudioResult.bind(this));
			search.setRenderer('image',  this.renderImageResult.bind(this));

			search.setHandler('folder',  this.handleFolderClick.bind(this));
			search.setHandler(['file', 'audio', 'image'], this.handleFileClick.bind(this));
		}
	};
	OCA.Search.Files = Files;
	OCA.Search.files = new Files();
})();
<commit_msg>Hide search results after switching directory<commit_after>/*
 * Copyright (c) 2014
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */
(function() {

	/**
	 * Construct a new FileActions instance
	 * @constructs Files
	 */
	var Files = function() {
		this.initialize();
	};
	/**
	 * @memberof OCA.Search
	 */
	Files.prototype = {

		fileList: null,

		/**
		 * Initialize the file search
		 */
		initialize: function() {

			var self = this;

			this.fileAppLoaded = function() {
				return !!OCA.Files && !!OCA.Files.App;
			};
			function inFileList($row, result) {
				if (! self.fileAppLoaded()) {
					return false;
				}
				var dir = self.fileList.getCurrentDirectory().replace(/\/+$/,'');
				var resultDir = OC.dirname(result.path);
				return dir === resultDir && self.fileList.inList(result.name);
			}
			function updateLegacyMimetype(result) {
				// backward compatibility:
				if (!result.mime && result.mime_type) {
					result.mime = result.mime_type;
				}
			}
			function hideNoFilterResults() {
				var $nofilterresults = $('.nofilterresults');
				if ( ! $nofilterresults.hasClass('hidden') ) {
					$nofilterresults.addClass('hidden');
				}
			}

			this.renderFolderResult = function($row, result) {
				if (inFileList($row, result)) {
					return null;
				}
				hideNoFilterResults();
				/*render folder icon, show path beneath filename,
				 show size and last modified date on the right */
				this.updateLegacyMimetype(result);

				var $pathDiv = $('

').text(result.path);
				$row.find('td.info div.name').after($pathDiv).text(result.name);

				$row.find('td.result a').attr('href', result.link);
				$row.find('td.icon').css('background-image', 'url(' + OC.imagePath('core', 'filetypes/folder') + ')');
				return $row;
			};

			this.renderFileResult = function($row, result) {
				if (inFileList($row, result)) {
					return null;
				}
				hideNoFilterResults();
				/*render preview icon, show path beneath filename,
				 show size and last modified date on the right */
				this.updateLegacyMimetype(result);

				var $pathDiv = $('

').text(result.path);
				$row.find('td.info div.name').after($pathDiv).text(result.name);

				$row.find('td.result a').attr('href', result.link);

				if (self.fileAppLoaded()) {
					self.fileList.lazyLoadPreview({
						path: result.path,
						mime: result.mime,
						callback: function (url) {
							$row.find('td.icon').css('background-image', 'url(' + url + ')');
						}
					});
				} else {
					// FIXME how to get mime icon if not in files app
					var mimeicon = result.mime.replace('/', '-');
					$row.find('td.icon').css('background-image', 'url(' + OC.imagePath('core', 'filetypes/' + mimeicon) + ')');
					var dir = OC.dirname(result.path);
					if (dir === '') {
						dir = '/';
					}
					$row.find('td.info a').attr('href',
						OC.generateUrl('/apps/files/?dir={dir}&scrollto={scrollto}', {dir: dir, scrollto: result.name})
					);
				}
				return $row;
			};

			this.renderAudioResult = function($row, result) {
				/*render preview icon, show path beneath filename,
				 show size and last modified date on the right
				 show Artist and Album */
				$row = this.renderFileResult($row, result);
				if ($row) {
					$row.find('td.icon').css('background-image', 'url(' + OC.imagePath('core', 'filetypes/audio') + ')');
				}
				return $row;
			};

			this.renderImageResult = function($row, result) {
				/*render preview icon, show path beneath filename,
				 show size and last modified date on the right
				 show width and height */
				$row = this.renderFileResult($row, result);
				if ($row && !self.fileAppLoaded()) {
					$row.find('td.icon').css('background-image', 'url(' + OC.imagePath('core', 'filetypes/image') + ')');
				}
				return $row;
			};

			this.handleFolderClick = function($row, result, event) {
				// open folder
				if (self.fileAppLoaded() && self.fileList.id === 'files') {
					self.fileList.changeDirectory(result.path);
					return false;
				} else {
					return true;
				}
			};

			this.handleFileClick = function($row, result, event) {
				if (self.fileAppLoaded() && self.fileList.id === 'files') {
					self.fileList.changeDirectory(OC.dirname(result.path));
					self.fileList.scrollTo(result.name);
					return false;
				} else {
					return true;
				}
			};

			this.updateLegacyMimetype = function (result) {
				// backward compatibility:
				if (!result.mime && result.mime_type) {
					result.mime = result.mime_type;
				}
			};
			this.setFileList = function (fileList) {
				this.fileList = fileList;
			};

			OC.Plugins.register('OCA.Search', this);
		},
		attach: function(search) {
			var self = this;
			search.setFilter('files', function (query) {
				if (self.fileAppLoaded()) {
					self.fileList.setFilter(query);
					if (query.length > 2) {
						//search is not started until 500msec have passed
						window.setTimeout(function() {
							$('.nofilterresults').addClass('hidden');
						}, 500);
					}
				}
			});

			search.setRenderer('folder', this.renderFolderResult.bind(this));
			search.setRenderer('file',   this.renderFileResult.bind(this));
			search.setRenderer('audio',  this.renderAudioResult.bind(this));
			search.setRenderer('image',  this.renderImageResult.bind(this));

			search.setHandler('folder',  this.handleFolderClick.bind(this));
			search.setHandler(['file', 'audio', 'image'], this.handleFileClick.bind(this));

			if (self.fileAppLoaded()) {
				// hide results when switching directory outside of search results
				$('#app-content').delegate('>div', 'changeDirectory', function() {
					search.clear();
				});
			}
		}
	};
	OCA.Search.Files = Files;
	OCA.Search.files = new Files();
})();
<|endoftext|>


<commit_before>/* global moment, google */
(function (doc, win, $) {

  var
    eventTags = ['wizard'],
    autocomplete,
    event = {},
    environment = 'dev',
    eventsAPI = {
      dev: 'http://localhost:1989/events',
      staging: 'https://events-api.mofostaging.net/events',
      production: 'https://events-api.webmaker.org/events'
    },
    formFields = {},
    eventsFrontEnd = {
      dev: 'http://localhost:1981/events/',
      staging: 'https://events.mofostaging.net/events/',
      production: 'https://events.webmaker.org/events/'
    };

  switch (win.location.host) {
  case 'welcome.webmaker.org':
    environment = 'production';
    break;
  case 'welcome.mofostaging.net':
    environment = 'staging';
    break;
  default:
    environment = 'dev';
  }

  function findaPlace() {
    autocomplete = new win.google.maps.places.Autocomplete((doc.getElementById('address')), {
      types: ['geocode']
    });
    geolocate();
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
      updateEventAddress();
    });
  }

  function geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
        var geolocation = new win.google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
        autocomplete.setBounds(new google.maps.LatLngBounds(geolocation,
          geolocation));
      });
    }
  }

  function updateEventAddress() {

    var place = autocomplete.getPlace();

    event.address = place.formatted_address;
    event.latitude = place.geometry.location.B;
    event.longitude = place.geometry.location.k;
  }

  function submitForm(event) {
    event.preventDefault();

    var
      $estimatedAttendees = $('select[name="estimatedAttendees"]'),
      $address = $('#address'),
      webmakerLogin = function safeGetWebmakerLogin() {
        try {
          return JSON.parse(localStorage['webmaker-login']);
        } catch (e) {
          return null;
        }
      },
      $context = $(this);

    $('#submit-event').prop('disabled', true);

    $('input[name="beginDate"]').val(moment($('#datepicker').val(), 'MM/DD/YYYY h:mm A'));

    if ($address.val() === '') {
      handleErrors();
      return false;
    }

    if ($estimatedAttendees.find('option:selected').val() === '0') {
      handleErrors();
      return false;
    }

    $context.append('<input type="hidden" name="organizer" value="' + webmakerLogin().email + '" />');
    $context.append('<input type="hidden" name="organizerID" value="' + webmakerLogin().username + '" />');

    function compileInputs() {
      formFields[$(this).prop('name')] = $(this).val();
    }

    $('input[type="text"]').each(compileInputs);
    $('input[type="hidden"]').each(compileInputs);
    $('input[type="number"]').each(compileInputs);

    formFields.isEventPublic = false;
    formFields.estimatedAttendees = $estimatedAttendees.find('option:selected').val();
    formFields.tags = eventTags;

    deployPayload(JSON.stringify(formFields));
  }

  function handleErrors() {
    var
      $estimatedAttendees = $('select[name="estimatedAttendees"]'),
      $address = $('#address');

    if ($address.val() === '') {
      $address.addClass('error');
    }

    if ($estimatedAttendees.find('option:selected').val() === '0') {
      $estimatedAttendees.addClass('error');
    }
    $('#submit-event').prop('disabled', false);
  }

  function updateStep3(eventID) {
    var eventURL = eventsFrontEnd[environment] + eventID;

    $('#event-url').prop('href', eventURL).text(eventURL);

    $('#share-twitter').attr('href', 'https://twitter.com/intent/tweet?text=Check%20out%20this%20event!&url=' + encodeURIComponent(eventURL) + '&via=webmaker&related=mozilla,webmaker');
    $('#share-facebook').attr('href', 'https://www.facebook.com/sharer.php?u=' + encodeURIComponent(eventURL));

    $('#confirmed-event-location').text(formFields.address);
    $('#confirmed-event-date').text(moment(formFields.beginDate).format('LLL'));
    $('#confirmed-event-size').text($('#estimatedAttendees').find('option:selected').text());
  }

  function deployPayload(payload) {
    $.ajax(eventsAPI[environment], {
      data: payload,
      contentType: 'application/json',
      error: function () {
        $('#start-event-submission').prepend(
          '
Something went wrong with the form submission. Please wait a moment and try again.
'
        );
        $('#submit-event').prop('disabled', false);
      },
      type: 'POST',
      xhrFields: {
        withCredentials: true
      },
      success: function (data) {
        $('#step-2').fadeOut('slow').next().delay(500).fadeIn('slow');
        updateStep3(data.id);
      }
    });
  }

  function showStep2(target, isDeepLink) {
    var
      $fieldset = $('fieldset.hidden.' + target),
      eventName = $fieldset.find('.event')[0].innerHTML,
      eventIcon = $fieldset.find('.icon')[0].innerHTML,
      eventDescription = $fieldset.find('.description')[0].innerHTML;

    eventTags.push(target);

    if (isDeepLink) {
      $('#step-1').hide().next().show();
    } else {
      $('#step-1').fadeOut('slow').next().delay(500).fadeIn('slow');
    }

    $('#submit-event').prop('disabled', false);
    $fieldset.appendTo('#start-event-submission');
    $('.event-title').text(eventName);
    $('.event-description').text(eventDescription);
    $('.event-icon').addClass(eventIcon);
  }

  function setUpWizard() {
    $('#datepicker').datetimepicker({
      icons: {
        time: "fa fa-clock-o",
        date: "fa fa-calendar",
        up: "fa fa-arrow-up",
        down: "fa fa-arrow-down"
      },
      minuteStepping: 15,
      defaultDate: moment().add(1, 'months').minutes(60)
    });

    $('a[href="/auth/login"]').on('click', function (e) {
      e.preventDefault();
      win.webmaker.auth.login();
    });

    $('.eventBtn').on('click', function () {
      showStep2(this.id);
    });

    $('#submit-event').on('click', submitForm);
  }

  function init() {
    if ($('.start-page').length > 0) {
      setUpWizard();
      findaPlace();
      $('#submit.event').prop('disabled', false);
      win.webmaker.auth.on('login', function () {
        $('#sign-in-form').hide();
        $('#start-event-submission').removeClass('hidden');
      });
    }

    // Check for deep links
    var hash = window.location.hash;

    // If there's a deep link jump to step 2, otherwise show step 1
    if (hash) {
      showStep2(hash.split('#/')[1], true);
    } else {
      $('#step-1').show();
    }
  }

  init();
})(document, window, jQuery);
<commit_msg>Bug 1093748 - Remove localStorage access<commit_after>/* global moment, google */
(function (doc, win, $) {

  var
    eventTags = ['wizard'],
    autocomplete,
    event = {},
    environment = 'dev',
    eventsAPI = {
      dev: 'http://localhost:1989/events',
      staging: 'https://events-api.mofostaging.net/events',
      production: 'https://events-api.webmaker.org/events'
    },
    formFields = {},
    eventsFrontEnd = {
      dev: 'http://localhost:1981/events/',
      staging: 'https://events.mofostaging.net/events/',
      production: 'https://events.webmaker.org/events/'
    };

  switch (win.location.host) {
  case 'welcome.webmaker.org':
    environment = 'production';
    break;
  case 'welcome.mofostaging.net':
    environment = 'staging';
    break;
  default:
    environment = 'dev';
  }

  function findaPlace() {
    autocomplete = new win.google.maps.places.Autocomplete((doc.getElementById('address')), {
      types: ['geocode']
    });
    geolocate();
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
      updateEventAddress();
    });
  }

  function geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
        var geolocation = new win.google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
        autocomplete.setBounds(new google.maps.LatLngBounds(geolocation,
          geolocation));
      });
    }
  }

  function updateEventAddress() {

    var place = autocomplete.getPlace();

    event.address = place.formatted_address;
    event.latitude = place.geometry.location.B;
    event.longitude = place.geometry.location.k;
  }

  function submitForm(event) {
    event.preventDefault();

    var
      $estimatedAttendees = $('select[name="estimatedAttendees"]'),
      $address = $('#address'),
      $context = $(this);

    $('#submit-event').prop('disabled', true);

    $('input[name="beginDate"]').val(moment($('#datepicker').val(), 'MM/DD/YYYY h:mm A'));

    if ($address.val() === '') {
      handleErrors();
      return false;
    }

    if ($estimatedAttendees.find('option:selected').val() === '0') {
      handleErrors();
      return false;
    }

    $context.append('<input type="hidden" name="organizer" value="' + win.webmaker.person.email + '" />');
    $context.append('<input type="hidden" name="organizerID" value="' + win.webmaker.person.username + '" />');

    function compileInputs() {
      formFields[$(this).prop('name')] = $(this).val();
    }

    $('input[type="text"]').each(compileInputs);
    $('input[type="hidden"]').each(compileInputs);
    $('input[type="number"]').each(compileInputs);

    formFields.isEventPublic = false;
    formFields.estimatedAttendees = $estimatedAttendees.find('option:selected').val();
    formFields.tags = eventTags;

    deployPayload(JSON.stringify(formFields));
  }

  function handleErrors() {
    var
      $estimatedAttendees = $('select[name="estimatedAttendees"]'),
      $address = $('#address');

    if ($address.val() === '') {
      $address.addClass('error');
    }

    if ($estimatedAttendees.find('option:selected').val() === '0') {
      $estimatedAttendees.addClass('error');
    }
    $('#submit-event').prop('disabled', false);
  }

  function updateStep3(eventID) {
    var eventURL = eventsFrontEnd[environment] + eventID;

    $('#event-url').prop('href', eventURL).text(eventURL);

    $('#share-twitter').attr('href', 'https://twitter.com/intent/tweet?text=Check%20out%20this%20event!&url=' + encodeURIComponent(eventURL) + '&via=webmaker&related=mozilla,webmaker');
    $('#share-facebook').attr('href', 'https://www.facebook.com/sharer.php?u=' + encodeURIComponent(eventURL));

    $('#confirmed-event-location').text(formFields.address);
    $('#confirmed-event-date').text(moment(formFields.beginDate).format('LLL'));
    $('#confirmed-event-size').text($('#estimatedAttendees').find('option:selected').text());
  }

  function deployPayload(payload) {
    $.ajax(eventsAPI[environment], {
      data: payload,
      contentType: 'application/json',
      error: function () {
        $('#start-event-submission').prepend(
          '
Something went wrong with the form submission. Please wait a moment and try again.
'
        );
        $('#submit-event').prop('disabled', false);
      },
      type: 'POST',
      xhrFields: {
        withCredentials: true
      },
      success: function (data) {
        $('#step-2').fadeOut('slow').next().delay(500).fadeIn('slow');
        updateStep3(data.id);
      }
    });
  }

  function showStep2(target, isDeepLink) {
    var
      $fieldset = $('fieldset.hidden.' + target),
      eventName = $fieldset.find('.event')[0].innerHTML,
      eventIcon = $fieldset.find('.icon')[0].innerHTML,
      eventDescription = $fieldset.find('.description')[0].innerHTML;

    eventTags.push(target);

    if (isDeepLink) {
      $('#step-1').hide().next().show();
    } else {
      $('#step-1').fadeOut('slow').next().delay(500).fadeIn('slow');
    }

    $('#submit-event').prop('disabled', false);
    $fieldset.appendTo('#start-event-submission');
    $('.event-title').text(eventName);
    $('.event-description').text(eventDescription);
    $('.event-icon').addClass(eventIcon);
  }

  function setUpWizard() {
    $('#datepicker').datetimepicker({
      icons: {
        time: "fa fa-clock-o",
        date: "fa fa-calendar",
        up: "fa fa-arrow-up",
        down: "fa fa-arrow-down"
      },
      minuteStepping: 15,
      defaultDate: moment().add(1, 'months').minutes(60)
    });

    $('a[href="/auth/login"]').on('click', function (e) {
      e.preventDefault();
      win.webmaker.auth.login();
    });

    $('.eventBtn').on('click', function () {
      showStep2(this.id);
    });

    $('#submit-event').on('click', submitForm);
  }

  function init() {
    if ($('.start-page').length > 0) {
      setUpWizard();
      findaPlace();
      $('#submit.event').prop('disabled', false);
      win.webmaker.auth.on('login', function () {
        $('#sign-in-form').hide();
        $('#start-event-submission').removeClass('hidden');
      });
    }

    // Check for deep links
    var hash = window.location.hash;

    // If there's a deep link jump to step 2, otherwise show step 1
    if (hash) {
      showStep2(hash.split('#/')[1], true);
    } else {
      $('#step-1').show();
    }
  }

  init();
})(document, window, jQuery);
<|endoftext|>