<commit_before>// replies-test.js
//
// Test adding and removing replies
//
// Copyright 2012, StatusNet Inc.
//
// 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.

var assert = require("assert"),
    vows = require("vows"),
    databank = require("databank"),
    _ = require("underscore"),
    Step = require("step"),
    schema = require("../lib/schema").schema,
    URLMaker = require("../lib/urlmaker").URLMaker,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

var suite = vows.describe("replies interface");

suite.addBatch({
    "When we initialize the environment": {
        topic: function() {

            var cb = this.callback;
            // Need this to make IDs

            URLMaker.hostname = "example.net";

            // Dummy databank

            var params = {schema: schema};

            var db = Databank.get("memory", params);

            db.connect({}, function(err) {
                if (err) {
                    cb(err);
                } else {
                    DatabankObject.bank = db;
                    cb(null);
                }
            });
        },
        "it works": function(err) {
            assert.ifError(err);
        },
        "and we create a new object": {
            topic: function() {
                var Note = require("../lib/model/note").Note;
                Note.create({content: "This sucks."}, this.callback);
            },
            "it works": function(err, note) {
                assert.ifError(err);
                assert.isObject(note);
            },
            "it has a getReplies() method": function(err, note) {
                assert.isFunction(note.getReplies);
            },
            "and we check its replies list": {
                topic: function(note) {
                    note.getReplies(0, 20, this.callback);
                },
                "it works": function(err, replies) {
                    assert.ifError(err);
                },
                "it is empty": function(err, replies) {
                    assert.isArray(replies);
                    assert.lengthOf(replies, 0);
                }
            }
        },
        "and we create a new object and post a reply": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    Comment = require("../lib/model/comment").Comment,
                    cb = this.callback;

                Step(
                    function() {
                        Note.create({content: "Testing testing 123."}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        note = result;
                        Comment.create({content: "Whatever.", inReplyTo: note}, this);
                    },
                    function(err, comment) {
                        if (err) {
                            cb(err, null, null);
                        } else {
                            cb(null, comment, note);
                        }
                    }
                );
            },
            "it works": function(err, comment, note) {
                assert.ifError(err);
            },
            "and we check the replies of the first object": {
                topic: function(comment, note) {
                    var cb = this.callback;
                    note.getReplies(0, 20, function(err, list) {
                        cb(err, list, comment);
                    });
                },
                "it works": function(err, list, comment) {
                    assert.ifError(err);
                },
                "it looks correct": function(err, list, comment) {
                    assert.isArray(list);
                    assert.lengthOf(list, 1);
                    assert.deepEqual(list[0], comment);
                }
            }
        },
        "and we create a new object and post a reply and remove the reply": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    Comment = require("../lib/model/comment").Comment,
                    cb = this.callback;

                Step(
                    function() {
                        Note.create({content: "Another test note."}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        note = result;
                        Comment.create({content: "Still bad.", inReplyTo: note}, this);
                    },
                    function(err, comment) {
                        if (err) throw err;
                        comment.del(this);
                    },
                    function(err) {
                        if (err) {
                            cb(err, null, null);
                        } else {
                            cb(null, note);
                        }
                    }
                );
            },
            "it works": function(err, comment, note) {
                assert.ifError(err);
            },
            "and we check the replies of the first object": {
                topic: function(comment, note) {
                    var cb = this.callback;
                    note.getReplies(0, 20, function(err, list) {
                        cb(err, list, comment);
                    });
                },
                "it works": function(err, list, comment) {
                    assert.ifError(err);
                },
                "it looks correct": function(err, list, comment) {
                    assert.isArray(list);
                    assert.lengthOf(list, 0);
                }
            }
        },
        "and we create a new object and post a reply and post a reply to that": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    Comment = require("../lib/model/comment").Comment,
                    cb = this.callback,
                    comment1 = null;

                Step(
                    function() {
                        Note.create({content: "Test again."}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        note = result;
                        Comment.create({content: "PLBBBBTTTTBBTT.", inReplyTo: note}, this);
                    },
                    function(err, comment) {
                        if (err) throw err;
                        comment1 = comment;
                        Comment.create({content: "Uncalled for!", inReplyTo: comment}, this);
                    },
                    function(err, comment2) {
                        if (err) {
                            cb(err, null, null, null);
                        } else {
                            cb(null, comment2, comment1, note);
                        }
                    }
                );
            },
            "it works": function(err, comment2, comment1, note) {
                assert.ifError(err);
            },
            "and we check the replies of the first object": {
                topic: function(comment2, comment1, note) {
                    var cb = this.callback;
                    note.getReplies(0, 20, function(err, list) {
                        cb(err, list, comment1, comment2);
                    });
                },
                "it works": function(err, list, comment1, comment2) {
                    assert.ifError(err);
                },
                "it looks correct": function(err, list, comment1, comment2) {
                    assert.isArray(list);
                    assert.lengthOf(list, 1);
                    assert.equal(list[0].id, comment1.id);
                    assert.include(list[0], 'replies');
                    assert.include(list[0].replies, 'items');
                    assert.lengthOf(list[0].replies.items, 1);
                    assert.equal(list[0].replies.items[0].id, comment2.id);
                }
            }
        },
        "and we create a new object and post a lot of replies": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    Comment = require("../lib/model/comment").Comment,
                    cb = this.callback,
                    comments = null;

                Step(
                    function() {
                        Note.create({content: "More testing."}, this);
                    },
                    function(err, result) {
                        var i, group = this.group();
                        if (err) throw err;
                        note = result;
                        for (i = 0; i < 100; i++) {
                            Comment.create({content: "YOU LIE.", inReplyTo: note}, group());
                        }
                    },
                    function(err, comments) {
                        if (err) {
                            cb(err, null, null);
                        } else {
                            cb(null, comments, note);
                        }
                    }
                );
            },
            "it works": function(err, comments, note) {
                assert.ifError(err);
            },
            "and we check the replies of the first object": {
                topic: function(comments, note) {
                    var cb = this.callback;
                    note.getReplies(0, 200, function(err, list) {
                        cb(err, list, comments, note);
                    });
                },
                "it works": function(err, list, comments, note) {
                    assert.ifError(err);
                },
                "it looks correct": function(err, list, comments, note) {
                    var i, listIDs = new Array(100), commentIDs = new Array(100);
                    assert.isArray(list);
                    assert.lengthOf(list, 100);
                    for (i = 0; i < 100; i++) {
                        listIDs[i] = list.items[i].id;
                        commentIDs[i] = comments[i].id;
                    }
                    for (i = 0; i < 100; i++) {
                        assert.include(listIDs, comments[i].id);
                        assert.include(commentIDs, list.items[i].id);
                    }
                }
            }
        },
        "and we create a new object and expand it": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    cb = this.callback;

                Step(
                    function() {
                        Note.create({content: "Blow face."}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        note = result;
                        note.expand(this);
                    },
                    function(err) {
                        if (err) {
                            cb(err, null);
                        } else {
                            cb(null, note);
                        }
                    }
                );
            },
            "it works": function(err, note) {
                assert.ifError(err);
            },
            "its replies element looks right": function(err, note) {
                assert.ifError(err);
                assert.isObject(note);
                assert.include(note, "replies");
                assert.isObject(note.replies);
                assert.include(note.replies, "totalItems");
                assert.equal(note.replies.totalItems, 0);
                assert.include(note.replies, "url");
                assert.isString(note.replies.url);
                assert.include(note.replies, "items");
                assert.isArray(note.replies.items);
                assert.lengthOf(note.replies.items, 0);
            }
        },
        "and we create a new object and post a reply and expand the object": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    Comment = require("../lib/model/comment").Comment,
                    cb = this.callback,
                    comment = null;

                Step(
                    function() {
                        Note.create({content: "Test your face."}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        note = result;
                        Comment.create({content: "UR FACE", inReplyTo: note}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        comment = result;
                        note.expand(this);
                    },
                    function(err) {
                        if (err) {
                            cb(err, null, null);
                        } else {
                            cb(null, comment, note);
                        }
                    }
                );
            },
            "it works": function(err, comment, note) {
                assert.ifError(err);
            },
            "its replies element looks right": function(err, comment, note) {
                assert.include(note, "replies");
                assert.isObject(note.replies);
                assert.include(note.replies, "totalItems");
                assert.equal(note.replies.totalItems, 1);
                assert.include(note.replies, "url");
                assert.isString(note.replies.url);
                assert.include(note.replies, "items");
                assert.isArray(note.replies.items);
                assert.lengthOf(note.replies.items, 1);
                assert.equal(note.replies.items[0].id, comment.id);
            }
        }
    }
});

suite["export"](module);
<commit_msg>Correct arguments for test<commit_after>// replies-test.js
//
// Test adding and removing replies
//
// Copyright 2012, StatusNet Inc.
//
// 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.

var assert = require("assert"),
    vows = require("vows"),
    databank = require("databank"),
    _ = require("underscore"),
    Step = require("step"),
    schema = require("../lib/schema").schema,
    URLMaker = require("../lib/urlmaker").URLMaker,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

var suite = vows.describe("replies interface");

suite.addBatch({
    "When we initialize the environment": {
        topic: function() {

            var cb = this.callback;
            // Need this to make IDs

            URLMaker.hostname = "example.net";

            // Dummy databank

            var params = {schema: schema};

            var db = Databank.get("memory", params);

            db.connect({}, function(err) {
                if (err) {
                    cb(err);
                } else {
                    DatabankObject.bank = db;
                    cb(null);
                }
            });
        },
        "it works": function(err) {
            assert.ifError(err);
        },
        "and we create a new object": {
            topic: function() {
                var Note = require("../lib/model/note").Note;
                Note.create({content: "This sucks."}, this.callback);
            },
            "it works": function(err, note) {
                assert.ifError(err);
                assert.isObject(note);
            },
            "it has a getReplies() method": function(err, note) {
                assert.isFunction(note.getReplies);
            },
            "and we check its replies list": {
                topic: function(note) {
                    note.getReplies(0, 20, this.callback);
                },
                "it works": function(err, replies) {
                    assert.ifError(err);
                },
                "it is empty": function(err, replies) {
                    assert.isArray(replies);
                    assert.lengthOf(replies, 0);
                }
            }
        },
        "and we create a new object and post a reply": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    Comment = require("../lib/model/comment").Comment,
                    cb = this.callback;

                Step(
                    function() {
                        Note.create({content: "Testing testing 123."}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        note = result;
                        Comment.create({content: "Whatever.", inReplyTo: note}, this);
                    },
                    function(err, comment) {
                        if (err) {
                            cb(err, null, null);
                        } else {
                            cb(null, comment, note);
                        }
                    }
                );
            },
            "it works": function(err, comment, note) {
                assert.ifError(err);
                assert.isObject(comment);
                assert.isObject(note);
            },
            "and we check the replies of the first object": {
                topic: function(comment, note) {
                    var cb = this.callback;
                    note.getReplies(0, 20, function(err, list) {
                        cb(err, list, comment);
                    });
                },
                "it works": function(err, list, comment) {
                    assert.ifError(err);
                },
                "it looks correct": function(err, list, comment) {
                    assert.isArray(list);
                    assert.lengthOf(list, 1);
                    assert.deepEqual(list[0], comment);
                }
            }
        },
        "and we create a new object and post a reply and remove the reply": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    Comment = require("../lib/model/comment").Comment,
                    cb = this.callback;

                Step(
                    function() {
                        Note.create({content: "Another test note."}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        note = result;
                        Comment.create({content: "Still bad.", inReplyTo: note}, this);
                    },
                    function(err, comment) {
                        if (err) throw err;
                        comment.del(this);
                    },
                    function(err) {
                        if (err) {
                            cb(err, null, null);
                        } else {
                            cb(null, note);
                        }
                    }
                );
            },
            "it works": function(err, note) {
                assert.ifError(err);
            },
            "and we check the replies of the first object": {
                topic: function(note) {
                    var cb = this.callback;
                    note.getReplies(0, 20, function(err, list) {
                        cb(err, list);
                    });
                },
                "it works": function(err, list, comment) {
                    assert.ifError(err);
                },
                "it looks correct": function(err, list, comment) {
                    assert.isArray(list);
                    assert.lengthOf(list, 0);
                }
            }
        },
        "and we create a new object and post a reply and post a reply to that": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    Comment = require("../lib/model/comment").Comment,
                    cb = this.callback,
                    comment1 = null;

                Step(
                    function() {
                        Note.create({content: "Test again."}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        note = result;
                        Comment.create({content: "PLBBBBTTTTBBTT.", inReplyTo: note}, this);
                    },
                    function(err, comment) {
                        if (err) throw err;
                        comment1 = comment;
                        Comment.create({content: "Uncalled for!", inReplyTo: comment}, this);
                    },
                    function(err, comment2) {
                        if (err) {
                            cb(err, null, null, null);
                        } else {
                            cb(null, comment2, comment1, note);
                        }
                    }
                );
            },
            "it works": function(err, comment2, comment1, note) {
                assert.ifError(err);
            },
            "and we check the replies of the first object": {
                topic: function(comment2, comment1, note) {
                    var cb = this.callback;
                    note.getReplies(0, 20, function(err, list) {
                        cb(err, list, comment1, comment2);
                    });
                },
                "it works": function(err, list, comment1, comment2) {
                    assert.ifError(err);
                },
                "it looks correct": function(err, list, comment1, comment2) {
                    assert.isArray(list);
                    assert.lengthOf(list, 1);
                    assert.equal(list[0].id, comment1.id);
                    assert.include(list[0], 'replies');
                    assert.include(list[0].replies, 'items');
                    assert.lengthOf(list[0].replies.items, 1);
                    assert.equal(list[0].replies.items[0].id, comment2.id);
                }
            }
        },
        "and we create a new object and post a lot of replies": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    Comment = require("../lib/model/comment").Comment,
                    cb = this.callback,
                    comments = null;

                Step(
                    function() {
                        Note.create({content: "More testing."}, this);
                    },
                    function(err, result) {
                        var i, group = this.group();
                        if (err) throw err;
                        note = result;
                        for (i = 0; i < 100; i++) {
                            Comment.create({content: "YOU LIE.", inReplyTo: note}, group());
                        }
                    },
                    function(err, comments) {
                        if (err) {
                            cb(err, null, null);
                        } else {
                            cb(null, comments, note);
                        }
                    }
                );
            },
            "it works": function(err, comments, note) {
                assert.ifError(err);
            },
            "and we check the replies of the first object": {
                topic: function(comments, note) {
                    var cb = this.callback;
                    note.getReplies(0, 200, function(err, list) {
                        cb(err, list, comments, note);
                    });
                },
                "it works": function(err, list, comments, note) {
                    assert.ifError(err);
                },
                "it looks correct": function(err, list, comments, note) {
                    var i, listIDs = new Array(100), commentIDs = new Array(100);
                    assert.isArray(list);
                    assert.lengthOf(list, 100);
                    for (i = 0; i < 100; i++) {
                        listIDs[i] = list.items[i].id;
                        commentIDs[i] = comments[i].id;
                    }
                    for (i = 0; i < 100; i++) {
                        assert.include(listIDs, comments[i].id);
                        assert.include(commentIDs, list.items[i].id);
                    }
                }
            }
        },
        "and we create a new object and expand it": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    cb = this.callback;

                Step(
                    function() {
                        Note.create({content: "Blow face."}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        note = result;
                        note.expand(this);
                    },
                    function(err) {
                        if (err) {
                            cb(err, null);
                        } else {
                            cb(null, note);
                        }
                    }
                );
            },
            "it works": function(err, note) {
                assert.ifError(err);
            },
            "its replies element looks right": function(err, note) {
                assert.ifError(err);
                assert.isObject(note);
                assert.include(note, "replies");
                assert.isObject(note.replies);
                assert.include(note.replies, "totalItems");
                assert.equal(note.replies.totalItems, 0);
                assert.include(note.replies, "url");
                assert.isString(note.replies.url);
                assert.include(note.replies, "items");
                assert.isArray(note.replies.items);
                assert.lengthOf(note.replies.items, 0);
            }
        },
        "and we create a new object and post a reply and expand the object": {
            topic: function() {
                var Note = require("../lib/model/note").Note,
                    note = null,
                    Comment = require("../lib/model/comment").Comment,
                    cb = this.callback,
                    comment = null;

                Step(
                    function() {
                        Note.create({content: "Test your face."}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        note = result;
                        Comment.create({content: "UR FACE", inReplyTo: note}, this);
                    },
                    function(err, result) {
                        if (err) throw err;
                        comment = result;
                        note.expand(this);
                    },
                    function(err) {
                        if (err) {
                            cb(err, null, null);
                        } else {
                            cb(null, comment, note);
                        }
                    }
                );
            },
            "it works": function(err, comment, note) {
                assert.ifError(err);
            },
            "its replies element looks right": function(err, comment, note) {
                assert.include(note, "replies");
                assert.isObject(note.replies);
                assert.include(note.replies, "totalItems");
                assert.equal(note.replies.totalItems, 1);
                assert.include(note.replies, "url");
                assert.isString(note.replies.url);
                assert.include(note.replies, "items");
                assert.isArray(note.replies.items);
                assert.lengthOf(note.replies.items, 1);
                assert.equal(note.replies.items[0].id, comment.id);
            }
        }
    }
});

suite["export"](module);
<|endoftext|>


<commit_before>
// Leaflet stuff
// leaflet.js
var map = L.map('map').setView([41.88, -87.62], 12);

L.tileLayer('http://a.tiles.mapbox.com/v3/azavea.map-3kktou80/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, Imagery © Mapbox',
    maxZoom: 18
}).addTo(map);

var homeIcon = L.icon({
    iconUrl: 'js/images/marker-home.png',
    shadowUrl: 'js/images/marker-shadow.png',

    iconSize:     [35, 45], // size of the icon
    shadowSize:   [41, 41], // size of the shadow
    iconAnchor:   [10, 60], // point of the icon which will correspond to marker's location
    shadowAnchor: [4, 62],  // the same for the shadow
    popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
});

L.marker([41.883852, -87.632061], {icon: homeIcon}).addTo(map);
var popup = L.popup();

// More/Less button toggle
$('.more-less-btn').click(function() {
	$(this).toggleClass("active");
	$(this).html($(this).html() == "More" ? "Less" : "More");
});

//Favorite star toggle
$("img.fave-star").click(function () {
   if ($(this).hasClass("checked")){
     $(this).attr("src","img/icons/star-empty.svg").removeClass("checked");
   } else {
     $(this).attr("src","img/icons/star.svg").addClass("checked");
   }
   var favCount = $('.fave-star.checked').length;
   $('.search-fav-count').html(favCount);
});

// Chevron change
$('#refineBtn').click(function() {
    $(this).find("i").toggleClass("icon-chevron-down icon-chevron-right");
});

//Slidepanel
$(document).ready(function(){
  var th = $("#filter-options").height();
  $(".locations-wrapper").css("top", th);

  $(window).on("resize", function(){
    th = $("#filter-options").height();
    $(".locations-wrapper").css("top", th);
  });

  $('[data-slidepanel]').slidepanel({
    orientation: 'right',
    mode: 'overlay'
  });

  $('#filter-options').on('shown', function () {
    th = $("#filter-options").height();
    $(".locations-wrapper").animate({
      top: th
    }, 175);
  });

  $('#filter-options').on('hidden', function () {
    th = $("#filter-options").height();
    $(".locations-wrapper").animate({
      top: th
    }, 0);
  });

    $('#refineSearch').on('shown', function () {
  $(".locations-wrapper").animate({
    top: th
  }, 175);
});

  $('#refineSearch').on('hidden', function () {
    $(".locations-wrapper").animate({
      top: 0
    }, 0);
  });

});
<commit_msg>Remove unused applications.js<commit_after><|endoftext|>


<commit_before>/*
* mvcView
* author: ronglin
* create date: 2014.6.26
*/

'use strict';

var fs = require('fs'),
    path = require('path'),
    utils = require('./utilities');

var mvcView = module.exports = function(viewName) {
    this.viewName = viewName;
};

mvcView.prototype = {

    viewName: null, engineExtname: null,

    constructor: mvcView, className: 'mvcView',

    render: function(viewContext, callback) {
        var areas = viewContext.app.areas;
        var engines = viewContext.app.engines;
        //
        var extname = this.engineExtname;
        if (!extname) { extname = engines.default(); }
        var ctrlName = viewContext.controller.name();
        //
        var ctrlViewsDir = path.join(viewContext.routeArea.viewsPath, ctrlName);
        var filePath = path.join(ctrlViewsDir, this.viewName + extname);
        if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
            callback(new Error('Failed to lookup view "' + this.viewName + '" in views directory "' + ctrlViewsDir + '"'));
            return;
        }
        //
        var engine = engines.get(extname);
        if (!engine) {
            callback(new Error('Failed to load view engine "' + this.engineExtname + '"'));
            return;
        }
        //
        var findPaths = [];
        findPaths.push(ctrlViewsDir);
        findPaths.push(viewContext.routeArea.viewsSharedPath);
        findPaths.push(areas.rootArea().viewsSharedPath);
        var findView = function(name) {
            for(var i = 0; i < findPaths.length; i++) {
                var file = path.join(findPaths[i], name + extname);
                if (fs.existsSync(file) && fs.statSync(file).isFile()) {
                    return file;
                }
            }
            throw new Error('Failed to lookup view "' + name + '" in the following directories "' + findPaths.join('
') + '"');
        };
        //
        try {
            var data = {
                model: viewContext.viewData,
                url: viewContext.controller.url,
                __RULEE_findView: findView
            };
            engine(filePath, data, function(err, str) {
                callback(err, str);
            });
        } catch (ex) {
            callback(ex);
        }
    }
};
<commit_msg>update<commit_after>/*
* mvcView
* author: ronglin
* create date: 2014.6.26
*/

'use strict';

var fs = require('fs'),
    path = require('path'),
    utils = require('./utilities');

var mvcView = module.exports = function(viewName) {
    this.viewName = viewName;
};

mvcView.prototype = {

    viewName: null, engineExtname: null,

    constructor: mvcView, className: 'mvcView',

    render: function(viewContext, callback) {
        var engines = viewContext.app.engines;
        //
        var extname = this.engineExtname;
        if (!extname) { extname = engines.default(); }
        //
        var engine = engines.get(extname);
        if (!engine) {
            callback(new Error('Failed to load view engine "' + this.engineExtname + '"'));
            return;
        }
        //
        var areas = viewContext.app.areas;
        var ctrlName = viewContext.controller.name();
        //
        var findDirs = [];
        findDirs.push(path.join(viewContext.routeArea.viewsPath, ctrlName));
        findDirs.push(viewContext.routeArea.viewsSharedPath);
        if (viewContext.routeArea !== areas.rootArea()) {
            findDirs.push(areas.rootArea().viewsSharedPath);
        }
        //
        var findView = function(name) {
            for (var i = 0; i < findDirs.length; i++) {
                var file = path.join(findDirs[i], name + extname);
                if (fs.existsSync(file) && fs.statSync(file).isFile()) {
                    return file;
                }
            }
            throw new Error('Failed to lookup view "' + name + '" in the following directories "' + findDirs.join('
') + '"');
        };
        //
        try {
            var data = {
                model: viewContext.viewData,
                url: viewContext.controller.url,
                __RULEE_findView: findView
            };
            engine(findView(this.viewName), data, function(err, str) {
                callback(err, str);
            });
        } catch (ex) {
            callback(ex);
        }
    }
};
<|endoftext|>


<commit_before>"use strict";

var helper = require('../test_helper'),
  chai = require('chai'),
  chaiHttp = require('chai-http'),
  expect = require('chai').expect,
  app = require('../../lib/app'),
  mongoose = require('mongoose'),
  User = mongoose.model('User');

chai.use(chaiHttp);

if (!global.Promise) {
  var q = require('q');
  chai.request.addPromises(q.Promise);
}

describe('user routes', function() {
  describe("#updateAll", function() {
    it("returns 400 if the data is missing", function(done) {
      chai.request(app)
        .post('/users/update')
        .send({
          signature: 'asdf'
        })
        .end(function(err, res) {
          expect(res).to.have.status(400);
          done();
        });
    });

    it("returns 400 if the data is missing", function(done) {
      chai.request(app)
        .post('/users/update')
        .send({
          data: [
            ['asdf']
          ]
        })
        .end(function(err, res) {
          expect(res).to.have.status(400);
          done();
        });
    });

    it("returns 401 if the data doesn't match the signature", function(done) {
      chai.request(app)
        .post('/users/update')
        .send({
          data: [
            ['asdf']
          ],
          signature: 'qwerty'
        })
        .end(function(err, res) {
          expect(res).to.have.status(401);
          done();
        });
    });

    it("is a success", function(done) {
      chai.request(app)
        .post('/users/update')
        .send({
          data: [
            ['TestUser1',
              'testUser@test.com',
              'D--',
              'Student',
              0.6,
              5000,
              6500,
              6500,
              4500,
              4200,
              8000,
              7000,
              1500,
              1,
              3,
              75
            ]
          ],
          signature: 'REGphBS+alcE0YOyG90pZxniV/zXnywIi4tHmTBWUco='
        })
        .end(function(err, res) {
          expect(res).to.have.status(200);
          done();
        });
    });

    it("creates the users and updates existing ones", function(done) {
      helper.clearDb(function() {
        helper.factories.create('Employee', {
            email: 'testUser@test.com'
          })
          .then(function(createdStudents) {
            chai.request(app)
              .post('/users/update')
              .send({
                data: [
                  ['TestUser1',
                    'testUser@test.com',
                    'D--',
                    'Student',
                    0.6,
                    5000,
                    6600,
                    6500,
                    4500,
                    4200,
                    8000,
                    7000,
                    1500,
                    1,
                    3,
                    75
                  ],
                  ['TestUser2',
                    'testUser2@test.com',
                    'D',
                    'Contractor',
                    0.6,
                    9000,
                    10000,
                    7500,
                    5500,
                    500,
                    9000,
                    8000,
                    1500,
                    3,
                    9,
                    100
                  ]
                ],
                signature: 'vEWVc4cZftpTr6qWo0aGSzOnp3AHg2D60lnd+n6ww14='
              })
              .end(function(err, res) {
                expect(res).to.have.status(200);
                User.find().sort('name').exec().then(function(users) {
                  expect(users[0].name).to.equal('TestUser1');
                  expect(users[0].email).to.equal('testUser@test.com');
                  expect(users[0].contract).to.equal('Student');
                  expect(users[0].employeeGrossSalary.full).to.equal(6600);
                  expect(users[0].employeeGrossSalary.reduced).to.equal(6500);
                  expect(users[0].numberOfShares).to.equal(3);
                  expect(users[1].name).to.equal('TestUser2');
                  expect(users[1].email).to.equal('testUser2@test.com');
                  expect(users[1].contract).to.equal('Contractor');
                  expect(users[1].employeeGrossSalary.full).to.equal(10000);
                  expect(users[1].employeeGrossSalary.reduced).to.equal(7500);
                  expect(users[1].numberOfShares).to.equal(9);
                  done();
                });
              });
          });
      });
    });
  });

  describe("#index", function() {
    var students, employees, contractors;

    before(function(done) {
      helper.clearDb()
        .then(function() {
          return helper.factories.createList('Student', 2);
        })
        .then(function(createdStudents) {
          students = createdStudents;
          return helper.factories.createList('Employee', 2);
        })
        .then(function(createdEmployees) {
          employees = createdEmployees;
          return helper.factories.createList('Contractor', 2)
        })
        .then(function(createdContractors) {
          contractors = createdContractors;
          done();
        });
    });

    it("returns 401 if the user is not logged in", function(done) {
      chai.request(app)
        .get('/users')
        .end(function(err, res) {
          expect(res).to.have.status(401);
          expect(res).to.be.json;
          expect(res.body.error).to.equal("You must be logged in to perform this action");
          done();
        });
    });

    it("is a success", function(done) {
      chai.request(app)
        .get('/users')
        .set('Cookie', helper.sessionCookies({
          'passport': {
            'user': students[0].id
          }
        }))
        .end(function(err, res) {
          expect(res).to.have.status(200);
          expect(res).to.be.json;
          done();
        });
    });

    it("it only shows yours and contractor salaries if you're not an admin", function(done) {
      chai.request(app)
        .get('/users')
        .set('Cookie', helper.sessionCookies({
          'passport': {
            'user': students[0].id
          }
        }))
        .end(function(err, res) {
          console.log(res.body);
          var i;
          expect(res.body.length).to.eq(6);
          for (i = 0; i < 2; i++) {
            expect(res.body[i].contract).to.eq('Student');
            expect(res.body[i].name).to.eq(students[i].name);
          }
          expect(res.body[0].employeeGrossSalary.full).to.eq(5000);
          expect(res.body[0].employeeGrossSalary.reduced).to.eq(4000);
          expect(res.body[0].numberOfShares).to.eq(0);
          expect(res.body[1].employeeGrossSalary.full).to.eq(-1);
          expect(res.body[1].employeeGrossSalary.reduced).to.eq(-1);
          expect(res.body[1].numberOfShares).to.eq(-1);
          for (i = 2; i < 4; i++) {
            expect(res.body[i].name).to.eq(employees[i%2].name);
            expect(res.body[i].contract).to.eq('Employee');
            expect(res.body[i].employeeGrossSalary.full).to.eq(-1);
            expect(res.body[i].employeeGrossSalary.reduced).to.eq(-1);
            expect(res.body[i].numberOfShares).to.eq(-1);
          }
          for (i = 4; i < 6; i++) {
            expect(res.body[i].name).to.eq(contractors[i - 4].name);
            expect(res.body[i].contract).to.eq('Contractor');
            expect(res.body[i].employeeGrossSalary.full).to.eq(10000);
            expect(res.body[i].employeeGrossSalary.reduced).to.eq(8000);
            expect(res.body[i].numberOfShares).to.eq(10);
          }
          done();
        });
    });

    it("it shows all salaries if you're an admin", function(done) {
      employees[0].admin = true;
      employees[0].save(function() {
        chai.request(app)
          .get('/users')
          .set('Cookie', helper.sessionCookies({
            'passport': {
              'user': employees[0].id
            }
          }))
          .end(function(err, res) {
            var i;
            expect(res.body.length).to.eq(6);

            for (i = 0; i < 2; i++) {
              expect(res.body[i].name).to.eq(students[i].name);
              expect(res.body[i].contract).to.eq('Student');
              expect(res.body[i].employeeGrossSalary.full).to.eq(5000);
              expect(res.body[i].employeeGrossSalary.reduced).to.eq(4000);
              expect(res.body[i].numberOfShares).to.eq(0);
            }
            for (i = 2; i < 4; i++) {
              expect(res.body[i].name).to.eq(employees[i - 2].name);
              expect(res.body[i].contract).to.eq('Employee');
              expect(res.body[i].employeeGrossSalary.full).to.eq(8000);
              expect(res.body[i].employeeGrossSalary.reduced).to.eq(6000);
              expect(res.body[i].numberOfShares).to.eq(5);
            }
            for (i = 4; i < 6; i++) {
              expect(res.body[i].name).to.eq(contractors[i - 4].name);
              expect(res.body[i].contract).to.eq('Contractor');
              expect(res.body[i].employeeGrossSalary.full).to.eq(10000);
              expect(res.body[i].employeeGrossSalary.reduced).to.eq(8000);
              expect(res.body[i].numberOfShares).to.eq(10);
            }
            done();
          });
      });
    });
  });

  describe("#info", function() {
    var students, employees, contractors;

    before(function(done) {
      helper.clearDb()
        .then(function() {
          return helper.factories.createList('Student', 2);
        })
        .then(function(createdStudents) {
          students = createdStudents;
          return helper.factories.createList('Employee', 2);
        })
        .then(function(createdEmployees) {
          employees = createdEmployees;
          return helper.factories.createList('Contractor', 2)
        })
        .then(function(createdContractors) {
          contractors = createdContractors;
          done();
        });
    });

    it("is a success", function(done) {
      chai.request(app)
        .get('/users/info')
        .end(function(err, res) {
          expect(res).to.have.status(200);
          expect(res).to.be.json;
          done();
        });
    });

    it("returns only general data", function(done) {
      chai.request(app)
        .get('/users/info')
        .end(function(err, res) {
          var i;
          expect(res.body.length).to.eq(3);

          for (i = 0; i < 3; i++) {
            expect(res.body[i].name).to.be.undefined;
          }
          expect(res.body[0].contract).to.eq('Student');
          expect(res.body[0].employeeGrossSalary.full).to.eq(5000);
          expect(res.body[0].employeeGrossSalary.reduced).to.eq(4000);
          expect(res.body[0].numberOfShares).to.eq(0);
          expect(res.body[1].contract).to.eq('Employee');
          expect(res.body[1].employeeGrossSalary.full).to.eq(8000);
          expect(res.body[1].employeeGrossSalary.reduced).to.eq(6000);
          expect(res.body[1].numberOfShares).to.eq(5);
          expect(res.body[2].contract).to.eq('Contractor');
          expect(res.body[2].employeeGrossSalary.full).to.eq(10000);
          expect(res.body[2].employeeGrossSalary.reduced).to.eq(8000);
          expect(res.body[2].numberOfShares).to.eq(10);
          done();
        });
    });
  });

  describe("#current", function() {

    it("returns 401 if the user is not logged in", function(done) {
      chai.request(app)
        .get('/users/current')
        .end(function(err, res) {
          expect(res).to.have.status(401);
          expect(res).to.be.json;
          expect(res.body.error).to.equal("You must be logged in to perform this action");
          done();
        });
    });

    describe("when the user is logged in", function() {

      var user;

      before(function(done) {
        helper.clearDb()
          .then(function() {
            return helper.factories.create('Contractor')
          })
          .then(function(createdUser) {
            user = createdUser;
            done();
          });
      });

      it("is a success", function(done) {
        chai.request(app)
          .get('/users/current')
          .set('Cookie', helper.sessionCookies({
            'passport': {
              'user': user.id
            }
          }))
          .then(function(res) {
            expect(res).to.have.status(200);
            done();
          });
      });

      it("returns the user", function(done) {
        chai.request(app)
          .get('/users/current')
          .set('Cookie', helper.sessionCookies({
            'passport': {
              'user': user.id
            }
          }))
          .end(function(err, res) {
            expect(res).to.be.json;
            expect(res.body.name).to.equal(user.name);
            expect(res.body.contract).to.equal(user.contract);
            expect(res.body.employeeGrossSalary.full).to.equal(user.employeeGrossSalary.full);
            expect(res.body.employeeGrossSalary.reduced).to.equal(user.employeeGrossSalary.reduced);
            expect(res.body.numberOfShares).to.equal(user.numberOfShares);
            done();
          });
      });
    });
  });
});
<commit_msg>Added another console.log statement to debug failing travis builds<commit_after>"use strict";

var helper = require('../test_helper'),
  chai = require('chai'),
  chaiHttp = require('chai-http'),
  expect = require('chai').expect,
  app = require('../../lib/app'),
  mongoose = require('mongoose'),
  User = mongoose.model('User');

chai.use(chaiHttp);

if (!global.Promise) {
  var q = require('q');
  chai.request.addPromises(q.Promise);
}

describe('user routes', function() {
  describe("#updateAll", function() {
    it("returns 400 if the data is missing", function(done) {
      chai.request(app)
        .post('/users/update')
        .send({
          signature: 'asdf'
        })
        .end(function(err, res) {
          expect(res).to.have.status(400);
          done();
        });
    });

    it("returns 400 if the data is missing", function(done) {
      chai.request(app)
        .post('/users/update')
        .send({
          data: [
            ['asdf']
          ]
        })
        .end(function(err, res) {
          expect(res).to.have.status(400);
          done();
        });
    });

    it("returns 401 if the data doesn't match the signature", function(done) {
      chai.request(app)
        .post('/users/update')
        .send({
          data: [
            ['asdf']
          ],
          signature: 'qwerty'
        })
        .end(function(err, res) {
          expect(res).to.have.status(401);
          done();
        });
    });

    it("is a success", function(done) {
      chai.request(app)
        .post('/users/update')
        .send({
          data: [
            ['TestUser1',
              'testUser@test.com',
              'D--',
              'Student',
              0.6,
              5000,
              6500,
              6500,
              4500,
              4200,
              8000,
              7000,
              1500,
              1,
              3,
              75
            ]
          ],
          signature: 'REGphBS+alcE0YOyG90pZxniV/zXnywIi4tHmTBWUco='
        })
        .end(function(err, res) {
          expect(res).to.have.status(200);
          done();
        });
    });

    it("creates the users and updates existing ones", function(done) {
      helper.clearDb(function() {
        helper.factories.create('Employee', {
            email: 'testUser@test.com'
          })
          .then(function(createdStudents) {
            chai.request(app)
              .post('/users/update')
              .send({
                data: [
                  ['TestUser1',
                    'testUser@test.com',
                    'D--',
                    'Student',
                    0.6,
                    5000,
                    6600,
                    6500,
                    4500,
                    4200,
                    8000,
                    7000,
                    1500,
                    1,
                    3,
                    75
                  ],
                  ['TestUser2',
                    'testUser2@test.com',
                    'D',
                    'Contractor',
                    0.6,
                    9000,
                    10000,
                    7500,
                    5500,
                    500,
                    9000,
                    8000,
                    1500,
                    3,
                    9,
                    100
                  ]
                ],
                signature: 'vEWVc4cZftpTr6qWo0aGSzOnp3AHg2D60lnd+n6ww14='
              })
              .end(function(err, res) {
                expect(res).to.have.status(200);
                User.find().sort('name').exec().then(function(users) {
                  expect(users[0].name).to.equal('TestUser1');
                  expect(users[0].email).to.equal('testUser@test.com');
                  expect(users[0].contract).to.equal('Student');
                  expect(users[0].employeeGrossSalary.full).to.equal(6600);
                  expect(users[0].employeeGrossSalary.reduced).to.equal(6500);
                  expect(users[0].numberOfShares).to.equal(3);
                  expect(users[1].name).to.equal('TestUser2');
                  expect(users[1].email).to.equal('testUser2@test.com');
                  expect(users[1].contract).to.equal('Contractor');
                  expect(users[1].employeeGrossSalary.full).to.equal(10000);
                  expect(users[1].employeeGrossSalary.reduced).to.equal(7500);
                  expect(users[1].numberOfShares).to.equal(9);
                  done();
                });
              });
          });
      });
    });
  });

  describe("#index", function() {
    var students, employees, contractors;

    before(function(done) {
      helper.clearDb()
        .then(function() {
          return helper.factories.createList('Student', 2);
        })
        .then(function(createdStudents) {
          students = createdStudents;
          return helper.factories.createList('Employee', 2);
        })
        .then(function(createdEmployees) {
          employees = createdEmployees;
          return helper.factories.createList('Contractor', 2)
        })
        .then(function(createdContractors) {
          contractors = createdContractors;
          done();
        });
    });

    it("returns 401 if the user is not logged in", function(done) {
      chai.request(app)
        .get('/users')
        .end(function(err, res) {
          expect(res).to.have.status(401);
          expect(res).to.be.json;
          expect(res.body.error).to.equal("You must be logged in to perform this action");
          done();
        });
    });

    it("is a success", function(done) {
      chai.request(app)
        .get('/users')
        .set('Cookie', helper.sessionCookies({
          'passport': {
            'user': students[0].id
          }
        }))
        .end(function(err, res) {
          expect(res).to.have.status(200);
          expect(res).to.be.json;
          done();
        });
    });

    it("it only shows yours and contractor salaries if you're not an admin", function(done) {
      chai.request(app)
        .get('/users')
        .set('Cookie', helper.sessionCookies({
          'passport': {
            'user': students[0].id
          }
        }))
        .end(function(err, res) {
          console.log(res.body);
          console.log(employees);
          var i;
          expect(res.body.length).to.eq(6);
          for (i = 0; i < 2; i++) {
            expect(res.body[i].contract).to.eq('Student');
            expect(res.body[i].name).to.eq(students[i].name);
          }
          expect(res.body[0].employeeGrossSalary.full).to.eq(5000);
          expect(res.body[0].employeeGrossSalary.reduced).to.eq(4000);
          expect(res.body[0].numberOfShares).to.eq(0);
          expect(res.body[1].employeeGrossSalary.full).to.eq(-1);
          expect(res.body[1].employeeGrossSalary.reduced).to.eq(-1);
          expect(res.body[1].numberOfShares).to.eq(-1);
          for (i = 2; i < 4; i++) {
            expect(res.body[i].name).to.eq(employees[i%2].name);
            expect(res.body[i].contract).to.eq('Employee');
            expect(res.body[i].employeeGrossSalary.full).to.eq(-1);
            expect(res.body[i].employeeGrossSalary.reduced).to.eq(-1);
            expect(res.body[i].numberOfShares).to.eq(-1);
          }
          for (i = 4; i < 6; i++) {
            expect(res.body[i].name).to.eq(contractors[i - 4].name);
            expect(res.body[i].contract).to.eq('Contractor');
            expect(res.body[i].employeeGrossSalary.full).to.eq(10000);
            expect(res.body[i].employeeGrossSalary.reduced).to.eq(8000);
            expect(res.body[i].numberOfShares).to.eq(10);
          }
          done();
        });
    });

    it("it shows all salaries if you're an admin", function(done) {
      employees[0].admin = true;
      employees[0].save(function() {
        chai.request(app)
          .get('/users')
          .set('Cookie', helper.sessionCookies({
            'passport': {
              'user': employees[0].id
            }
          }))
          .end(function(err, res) {
            var i;
            expect(res.body.length).to.eq(6);

            for (i = 0; i < 2; i++) {
              expect(res.body[i].name).to.eq(students[i].name);
              expect(res.body[i].contract).to.eq('Student');
              expect(res.body[i].employeeGrossSalary.full).to.eq(5000);
              expect(res.body[i].employeeGrossSalary.reduced).to.eq(4000);
              expect(res.body[i].numberOfShares).to.eq(0);
            }
            for (i = 2; i < 4; i++) {
              expect(res.body[i].name).to.eq(employees[i - 2].name);
              expect(res.body[i].contract).to.eq('Employee');
              expect(res.body[i].employeeGrossSalary.full).to.eq(8000);
              expect(res.body[i].employeeGrossSalary.reduced).to.eq(6000);
              expect(res.body[i].numberOfShares).to.eq(5);
            }
            for (i = 4; i < 6; i++) {
              expect(res.body[i].name).to.eq(contractors[i - 4].name);
              expect(res.body[i].contract).to.eq('Contractor');
              expect(res.body[i].employeeGrossSalary.full).to.eq(10000);
              expect(res.body[i].employeeGrossSalary.reduced).to.eq(8000);
              expect(res.body[i].numberOfShares).to.eq(10);
            }
            done();
          });
      });
    });
  });

  describe("#info", function() {
    var students, employees, contractors;

    before(function(done) {
      helper.clearDb()
        .then(function() {
          return helper.factories.createList('Student', 2);
        })
        .then(function(createdStudents) {
          students = createdStudents;
          return helper.factories.createList('Employee', 2);
        })
        .then(function(createdEmployees) {
          employees = createdEmployees;
          return helper.factories.createList('Contractor', 2)
        })
        .then(function(createdContractors) {
          contractors = createdContractors;
          done();
        });
    });

    it("is a success", function(done) {
      chai.request(app)
        .get('/users/info')
        .end(function(err, res) {
          expect(res).to.have.status(200);
          expect(res).to.be.json;
          done();
        });
    });

    it("returns only general data", function(done) {
      chai.request(app)
        .get('/users/info')
        .end(function(err, res) {
          var i;
          expect(res.body.length).to.eq(3);

          for (i = 0; i < 3; i++) {
            expect(res.body[i].name).to.be.undefined;
          }
          expect(res.body[0].contract).to.eq('Student');
          expect(res.body[0].employeeGrossSalary.full).to.eq(5000);
          expect(res.body[0].employeeGrossSalary.reduced).to.eq(4000);
          expect(res.body[0].numberOfShares).to.eq(0);
          expect(res.body[1].contract).to.eq('Employee');
          expect(res.body[1].employeeGrossSalary.full).to.eq(8000);
          expect(res.body[1].employeeGrossSalary.reduced).to.eq(6000);
          expect(res.body[1].numberOfShares).to.eq(5);
          expect(res.body[2].contract).to.eq('Contractor');
          expect(res.body[2].employeeGrossSalary.full).to.eq(10000);
          expect(res.body[2].employeeGrossSalary.reduced).to.eq(8000);
          expect(res.body[2].numberOfShares).to.eq(10);
          done();
        });
    });
  });

  describe("#current", function() {

    it("returns 401 if the user is not logged in", function(done) {
      chai.request(app)
        .get('/users/current')
        .end(function(err, res) {
          expect(res).to.have.status(401);
          expect(res).to.be.json;
          expect(res.body.error).to.equal("You must be logged in to perform this action");
          done();
        });
    });

    describe("when the user is logged in", function() {

      var user;

      before(function(done) {
        helper.clearDb()
          .then(function() {
            return helper.factories.create('Contractor')
          })
          .then(function(createdUser) {
            user = createdUser;
            done();
          });
      });

      it("is a success", function(done) {
        chai.request(app)
          .get('/users/current')
          .set('Cookie', helper.sessionCookies({
            'passport': {
              'user': user.id
            }
          }))
          .then(function(res) {
            expect(res).to.have.status(200);
            done();
          });
      });

      it("returns the user", function(done) {
        chai.request(app)
          .get('/users/current')
          .set('Cookie', helper.sessionCookies({
            'passport': {
              'user': user.id
            }
          }))
          .end(function(err, res) {
            expect(res).to.be.json;
            expect(res.body.name).to.equal(user.name);
            expect(res.body.contract).to.equal(user.contract);
            expect(res.body.employeeGrossSalary.full).to.equal(user.employeeGrossSalary.full);
            expect(res.body.employeeGrossSalary.reduced).to.equal(user.employeeGrossSalary.reduced);
            expect(res.body.numberOfShares).to.equal(user.numberOfShares);
            done();
          });
      });
    });
  });
});
<|endoftext|>


<commit_before><commit_msg>Remove frontend/main.js<commit_after><|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor'
import { Mongo } from 'meteor/mongo'
import SimpleSchema from 'simpl-schema'
import { startingTime, endingTime, startingDate, endingDate, getHour, weekDays, determinePosition } from './helpers'
import possibleCategories from './helpers/possibleCategories.json'
import DaySchema from './DaysSchema'

// Extend SimpleSchema to support the uniforms field.
SimpleSchema.extendOptions(['uniforms'])

const Events = new Mongo.Collection('events')

const EventsSchema = new SimpleSchema({

  // Organiser
  'organiser': {
    type: Object,
    autoValue: function () {
      // Dont change this!
      const { _id, profile } = Meteor.user() || { _id: '-', profile: { name: '-' } }
      return {
        _id,
        name: profile.name
      }
    }
  },
  'organiser._id': {
    type: String
  },
  'organiser.name': {
    type: String
  },

  // Categories
  'categories': {
    type: Array,
    custom: function () {
      if (!this.value || !this.value[0]) {
        return 'required'
      }
    },
    uniforms: {
      customType: 'select',
      selectOptions: {
        multi: true,
        labelKey: 'name'
      },
      allowedValues: possibleCategories, // keep it here so options will be rendered by react-select
      label: 'Choose a Category',
      placeholder_: 'Pick your event\'s categories'
    }
  },
  'categories.$': {
    type: Object
  },
  'categories.$.name': {
    type: String,
    allowedValues: possibleCategories.reduce((arr, obj) => (arr.concat(obj.name)), [])
  },
  'categories.$.color': {
    type: String,
    allowedValues: possibleCategories.reduce((arr, obj) => (arr.concat(obj.color)), [])
  },

  // Details
  'name': {
    type: String,
    uniforms: {
      label: 'Name'
    }
  },
  'address': {
    type: Object,
    custom: function () {
      if (!this.value || !this.value.name) {
        return 'required'
      }
    },
    uniforms: {
      customType: 'select',
      selectOptions: {
        'googleMaps': true
      },
      label: 'Select an address',
      placeholder_: 'Ex: New York, USA'
    }
  },
  'address.name': {
    type: String
  },
  'address.location': {
    type: Object
  },
  'address.location.type': {
    type: String,
    defaultValue: 'Point',
    allowedValues: ['Point']
  },
  'address.location.coordinates': {
    type: Array,
    max: 2,
    min: 2
  },
  'address.location.coordinates.$': {
    type: Number
  },
  'findHints': {
    type: String,
    max: 250,
    uniforms: {
      customType: 'textarea',
      label: 'How to find you?'
    }
  },

  // Date and Time
  'when': {
    type: Object,
    custom: function () {
      const type = this.field('when.type')
      const obj = !this.field('when.' + type)

      // ensure we have a valid when object
      if (!type || obj.value) {
        return 'required'
      }
    }
  },
  'when.startingDate': startingDate,
  'when.endingDate': endingDate,
  'when.startingTime': {
    ...startingTime,
    optional: true,
    custom: function () {
      if (this.field('when.multipleDays').value) {
        return undefined
      }

      if (!this.value) {
        return 'required'
      }
    },
    autoValue: function () {
      if (this.field('when.multipleDays').value) {
        return null
      }
      if (!this.value) {
        return getHour()
      }
    }
  },
  'when.endingTime': {
    ...endingTime,
    optional: true,
    custom: function () {
      if (this.field('when.multipleDays').value) {
        return undefined
      }

      if (!this.value) {
        return 'required'
      }
    },
    autoValue: function () {
      if (this.field('when.multipleDays').value) {
        return null
      }

      if (!this.value) {
        return getHour(1)
      }
    }
  },
  'when.multipleDays': {
    type: Boolean,
    defaultValue: false
  },
  'when.days': { // used with multipleDays
    type: Array,
    optional: true,
    custom: function () {
      if (!this.field('when.multipleDays').value) {
        return undefined
      }

      if (!this.value || !this.value[0]) {
        return 'required'
      }
    },
    autoValue: function () {
      if (!this.field('when.multipleDays').value) {
        return null
      }
    }
  },
  'when.days.$': {
    type: DaySchema,
    optional: true
  },
  'when.repeat': {
    type: Boolean,
    defaultValue: false
  },
  'when.recurring': { // used with repeat
    type: Object,
    optional: true,
    autoValue: function () {
      if (!this.field('when.repeat').value) {
        return null
      }
    }
  },
  'when.recurring.type': {
    type: String,
    allowedValues: ['day', 'week', 'month'],
    defaultValue: 'day',
    uniforms: {
      customType: 'select',
      selectOptions: {
        labelMapper: {
          'day': 'day(s)',
          'week': 'week(s)',
          'month': 'month(s)'
        }
      }
    }
  },
  'when.recurring.days': { // used with 'week'
    type: Array,
    optional: true,
    custom: function () {
      if (this.siblingField('type') === 'week') {
        const atLeastOneDay = !this.value || !this.value.join('')
        return atLeastOneDay ? 'required' : undefined
      }
    },
    autoValue: function () {
      const type = this.siblingField('type')
      if (type.value !== 'week') {
        return null
      }
    }
  },
  'when.recurring.days.$': {
    type: String,
    allowedValues: weekDays
  },
  'when.recurring.monthly': {
    type: Object,
    optional: true,
    autoValue: function () {
      if (this.siblingField('type').value === 'month') {
        return this.value || {} // empty object will generate default values automatically
      } else {
        return null
      }
    }
  },
  'when.recurring.monthly.type': {
    type: String,
    allowedValues: ['byPosition', 'byDayInMonth'],
    autoValue: function () {
      if (!this.value) {
        return 'byDayInMonth'
      }
    }
  },
  'when.recurring.monthly.value': {
    type: Number,
    autoValue: function () {
      const type = this.siblingField('type')
      let value = this.value
      let dayInMonth = new Date().getDate()

      if (type.value === 'byDayInMonth') {
        value = (typeof value) === 'number' && value >= 0 ? value : dayInMonth
        return value > 31 ? 31 : value < 1 ? 1 : value
      } else {
        value = (typeof value) === 'number' && value >= 0 ? value : Number(determinePosition(dayInMonth)[0])
        return value > 4 ? 4 : value < 1 ? 1 : value
      }
    }
  },
  'when.recurring.every': {
    type: Number,
    min: 1,
    max: 12,
    defaultValue: 1
  },
  'when.recurring.forever': {
    type: Boolean,
    optional: true
  },
  'when.recurring.occurences': {
    type: Number,
    min: 1,
    max: 999,
    optional: true,
    custom: function () {
      if (this.siblingField('forever').value) {
        return undefined
      }
    },
    autoValue: function () {
      if (this.siblingField('forever').value) {
        return null
      }
    }
  },
  'when.recurring.until': {
    type: Date,
    optional: true
  },

  // Description and More
  'overview': {
    type: String,
    max: 150,
    uniforms: {
      customType: 'textarea',
      label: 'Overview'
    }
  },
  'description': {
    type: String,
    max: 400,
    uniforms: {
      customType: 'textarea',
      label: 'Description'
    }
  },
  engagement: {
    type: Object,
    defaultValue: {}
  },
  'engagement.limit': {
    type: Number,
    min: 0,
    defaultValue: 0,
    uniforms: {
      customType: 'number',
      label: 'Attendee limit (leave empty if no limit)'
    }
  },
  'engagement.attendees': {
    type: Array,
    defaultValue: []
  },
  'engagement.attendees.$': {
    type: String,
    optional: true
  },
  'createdAt': {
    type: Date,
    autoValue: () => new Date()
  }
}, {
  clean: {
    filter: true,
    autoConvert: true,
    removeEmptyStrings: true,
    trimStrings: true,
    getAutoValues: true,
    removeNullsFromArray: true
  }
})

Events.attachSchema(EventsSchema)

if (Meteor.isServer) {
  Events._ensureIndex({ 'address.location': '2dsphere' })
}

export {
  Events as default,
  EventsSchema
}
<commit_msg>fix recurring field bug<commit_after>import { Meteor } from 'meteor/meteor'
import { Mongo } from 'meteor/mongo'
import SimpleSchema from 'simpl-schema'
import { startingTime, endingTime, startingDate, endingDate, getHour, weekDays, determinePosition } from './helpers'
import possibleCategories from './helpers/possibleCategories.json'
import DaySchema from './DaysSchema'

// Extend SimpleSchema to support the uniforms field.
SimpleSchema.extendOptions(['uniforms'])

const Events = new Mongo.Collection('events')

const EventsSchema = new SimpleSchema({

  // Organiser
  'organiser': {
    type: Object,
    autoValue: function () {
      // Dont change this!
      const { _id, profile } = Meteor.user() || { _id: '-', profile: { name: '-' } }
      return {
        _id,
        name: profile.name
      }
    }
  },
  'organiser._id': {
    type: String
  },
  'organiser.name': {
    type: String
  },

  // Categories
  'categories': {
    type: Array,
    custom: function () {
      if (!this.value || !this.value[0]) {
        return 'required'
      }
    },
    uniforms: {
      customType: 'select',
      selectOptions: {
        multi: true,
        labelKey: 'name'
      },
      allowedValues: possibleCategories, // keep it here so options will be rendered by react-select
      label: 'Choose a Category',
      placeholder_: 'Pick your event\'s categories'
    }
  },
  'categories.$': {
    type: Object
  },
  'categories.$.name': {
    type: String,
    allowedValues: possibleCategories.reduce((arr, obj) => (arr.concat(obj.name)), [])
  },
  'categories.$.color': {
    type: String,
    allowedValues: possibleCategories.reduce((arr, obj) => (arr.concat(obj.color)), [])
  },

  // Details
  'name': {
    type: String,
    uniforms: {
      label: 'Name'
    }
  },
  'address': {
    type: Object,
    custom: function () {
      if (!this.value || !this.value.name) {
        return 'required'
      }
    },
    uniforms: {
      customType: 'select',
      selectOptions: {
        'googleMaps': true
      },
      label: 'Select an address',
      placeholder_: 'Ex: New York, USA'
    }
  },
  'address.name': {
    type: String
  },
  'address.location': {
    type: Object
  },
  'address.location.type': {
    type: String,
    defaultValue: 'Point',
    allowedValues: ['Point']
  },
  'address.location.coordinates': {
    type: Array,
    max: 2,
    min: 2
  },
  'address.location.coordinates.$': {
    type: Number
  },
  'findHints': {
    type: String,
    max: 250,
    uniforms: {
      customType: 'textarea',
      label: 'How to find you?'
    }
  },

  // Date and Time
  'when': {
    type: Object,
    custom: function () {
      const type = this.field('when.type')
      const obj = !this.field('when.' + type)

      // ensure we have a valid when object
      if (!type || obj.value) {
        return 'required'
      }
    }
  },
  'when.startingDate': startingDate,
  'when.endingDate': endingDate,
  'when.startingTime': {
    ...startingTime,
    optional: true,
    custom: function () {
      if (this.field('when.multipleDays').value) {
        return undefined
      }

      if (!this.value) {
        return 'required'
      }
    },
    autoValue: function () {
      if (this.field('when.multipleDays').value) {
        return null
      }
      if (!this.value) {
        return getHour()
      }
    }
  },
  'when.endingTime': {
    ...endingTime,
    optional: true,
    custom: function () {
      if (this.field('when.multipleDays').value) {
        return undefined
      }

      if (!this.value) {
        return 'required'
      }
    },
    autoValue: function () {
      if (this.field('when.multipleDays').value) {
        return null
      }

      if (!this.value) {
        return getHour(1)
      }
    }
  },
  'when.multipleDays': {
    type: Boolean,
    defaultValue: false
  },
  'when.days': { // used with multipleDays
    type: Array,
    optional: true,
    custom: function () {
      if (!this.field('when.multipleDays').value) {
        return undefined
      }

      if (!this.value || !this.value[0]) {
        return 'required'
      }
    },
    autoValue: function () {
      if (!this.field('when.multipleDays').value) {
        return null
      }
    }
  },
  'when.days.$': {
    type: DaySchema,
    optional: true
  },
  'when.repeat': {
    type: Boolean,
    defaultValue: false
  },
  'when.recurring': { // used with repeat
    type: Object,
    optional: true,
    autoValue: function () {
      if (!this.field('when.repeat').value) {
        return null
      }
    }
  },
  'when.recurring.type': {
    type: String,
    allowedValues: ['day', 'week', 'month'],
    defaultValue: 'day',
    uniforms: {
      customType: 'select',
      selectOptions: {
        labelMapper: {
          'day': 'day(s)',
          'week': 'week(s)',
          'month': 'month(s)'
        }
      }
    }
  },
  'when.recurring.days': { // used with 'week'
    type: Array,
    optional: true,
    custom: function () {
      if (this.siblingField('type') === 'week') {
        const atLeastOneDay = !this.value || !this.value.join('')
        return atLeastOneDay ? 'required' : undefined
      }
    },
    autoValue: function () {
      const type = this.siblingField('type')
      if (type.value !== 'week') {
        return null
      }
    }
  },
  'when.recurring.days.$': {
    type: String,
    allowedValues: weekDays
  },
  'when.recurring.monthly': {
    type: Object,
    optional: true,
    autoValue: function () {
      if (this.siblingField('type').value === 'month') {
        return this.value || {} // empty object will generate default values automatically
      } else {
        return null
      }
    }
  },
  'when.recurring.monthly.type': {
    type: String,
    allowedValues: ['byPosition', 'byDayInMonth'],
    autoValue: function () {
      if (!this.value) {
        return 'byDayInMonth'
      }
    }
  },
  'when.recurring.monthly.value': {
    type: Number,
    autoValue: function () {
      const type = this.siblingField('type')
      let value = this.value
      let dayInMonth = new Date().getDate()

      if (type.value === 'byDayInMonth') {
        value = (typeof value) === 'number' && value >= 0 ? value : dayInMonth
        return value > 31 ? 31 : value < 1 ? 1 : value
      } else {
        value = (typeof value) === 'number' && value >= 0 ? value : Number(determinePosition(dayInMonth)[0])
        return value > 4 ? 4 : value < 1 ? 1 : value
      }
    }
  },
  'when.recurring.every': {
    type: Number,
    min: 0,
    max: 12,
    defaultValue: 1,
    autoValue: function () {
      if (!this.value || this.value < 1) {
        return 1
      }
    }
  },
  'when.recurring.forever': {
    type: Boolean,
    optional: true
  },
  'when.recurring.occurences': {
    type: Number,
    min: 1,
    max: 999,
    optional: true,
    custom: function () {
      if (this.siblingField('forever').value) {
        return undefined
      }
    },
    autoValue: function () {
      if (this.siblingField('forever').value) {
        return null
      }
    }
  },
  'when.recurring.until': {
    type: Date,
    optional: true
  },

  // Description and More
  'overview': {
    type: String,
    max: 150,
    uniforms: {
      customType: 'textarea',
      label: 'Overview'
    }
  },
  'description': {
    type: String,
    max: 400,
    uniforms: {
      customType: 'textarea',
      label: 'Description'
    }
  },
  engagement: {
    type: Object,
    defaultValue: {}
  },
  'engagement.limit': {
    type: Number,
    min: 0,
    defaultValue: 0,
    uniforms: {
      customType: 'number',
      label: 'Attendee limit (leave empty if no limit)'
    }
  },
  'engagement.attendees': {
    type: Array,
    defaultValue: []
  },
  'engagement.attendees.$': {
    type: String,
    optional: true
  },
  'createdAt': {
    type: Date,
    autoValue: () => new Date()
  }
}, {
  clean: {
    filter: true,
    autoConvert: true,
    removeEmptyStrings: true,
    trimStrings: true,
    getAutoValues: true,
    removeNullsFromArray: true
  }
})

Events.attachSchema(EventsSchema)

if (Meteor.isServer) {
  Events._ensureIndex({ 'address.location': '2dsphere' })
}

export {
  Events as default,
  EventsSchema
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved.
 */

// TODO: break out the definition of brackets into a separate module from the application controller logic

// Define core brackets namespace
brackets = window.brackets || {};

brackets.inBrowser = !brackets.hasOwnProperty("fs");

/**
 * General purpose modal error dialog.
 *
 * @param {string} title The title of the error dialog. Can contain HTML markup.
 * @param {string} message The message to display in the error dialog. Can contain HTML markup.
 */
brackets.showErrorDialog = function(title, message) {
    var dlg = $("#error-dialog");

    // Set title and message
    $("#error-dialog-title").html(title);
    $("#error-dialog-message").html(message);

    // Click handler for OK button
    dlg.delegate("#error-dialog-ok", "click", function(e) {
        dlg.modal(true).hide();
    });

    // Run the dialog
    dlg.modal(
        { backdrop: "static"
        , show: true
        }
    );
}

$(document).ready(function() {

    var editor = CodeMirror($('#editor').get(0));

    var myCodeMirror = CodeMirror($('#editor').get(0), {
        value: 'var myResponse="Yes, it will be!"\n'
    });

    // Load a default project into the tree
    if (brackets.inBrowser) {
        // In browser: dummy folder tree (hardcoded in ProjectManager)
        ProjectManager.loadProject("DummyProject");
    } else {
        // In app shell: load Brackets itself
        var loadedPath = window.location.pathname;
        var bracketsSrc = loadedPath.substr(0, loadedPath.lastIndexOf("/"));
        ProjectManager.loadProject(bracketsSrc);
    }

    // Open project button
    $("#btn-open-project").click(function() {
        ProjectManager.openProject();
    });

    // Implements the "Open File" menu
    $("#menu-file-open").click(function() {
        CommandManager.execute(Commands.FILE_OPEN);
    });

    // Implements the 'Run Tests' menu to bring up the Jasmine unit test window
    var testWindow = null;
    $("#menu-runtests").click(function(){
        if (!(testWindow === null)) {
            try {
                testWindow.location.reload();
            } catch(e) {
                testWindow = null;  // the window was probably closed
            }
        }

        if (testWindow === null) {
            testWindow = window.open("../test/SpecRunner.html");
            testWindow.location.reload(); // if it was opened before, we need to reload because it will be cached
        }
    });

    // Ty test code hooked up to "new" menu. Test reads a file and prints its constents to the log.
    // uncomment to test
    /*$("#menu-file-new").click(function(){
        var fileEntry = new NativeFileSystem.FileEntry( "/Users/tvoliter/github/brackets-app/README.md" );
        var file;
        fileEntry.file( function( file ){
            var reader = new NativeFileSystem.FileReader();
            reader.onerror = errorHandler;

            reader.onabort = function(e) {
              alert('File read cancelled');
            };

            reader.onloadstart = function(e) {
              console.log( "loading" );
            };

            reader.onload = function ( event ){
                console.log( event.target.result );
            };

            // Read in the image file as a binary string.
            reader.readAsText(file, "utf8");

            function errorHandler(evt) {
                switch(evt.target.error.code) {
                  case evt.target.error.NOT_FOUND_ERR:
                    alert('File Not Found!');
                    break;
                  case evt.target.error.NOT_READABLE_ERR:
                    alert('File is not readable');
                    break;
                  case evt.target.error.ABORT_ERR:
                    break; // noop
                  default:
                    alert('An error occurred reading this file.');
                };
            }
        });
    });*/

    // Utility functions
    function doOpen(fullPath) {
        if (fullPath) {
            var reader = new NativeFileSystem.FileReader();

            // TODO: we should implement something like NativeFileSystem.resolveNativeFileSystemURL() (similar
            // to what's in the standard file API) to get a FileEntry, rather than manually constructing it
            var fileEntry = new NativeFileSystem.FileEntry(fullPath);

            // TODO: it's weird to have to construct a FileEntry just to get a File.
            fileEntry.file(function(file) {
                reader.onload = function(event) {
                    // TODO: have a real controller object for the editor
                    editor.setValue(event.target.result);
                    editor.clearHistory();

                    // In the titlebar, show the project-relative path (if the file is inside the current project)
                    // or the full absolute path (if it's not in the project).
                    var projectRootPath = ProjectManager.getProjectRoot().fullPath;
                    if (projectRootPath.length > 0 && projectRootPath.charAt(projectRootPath.length - 1) != "/") {
                        projectRootPath += "/";
                    }
                    if (fullPath.indexOf(projectRootPath) == 0) {
                        fullPath = fullPath.slice(projectRootPath.length);
                        if (fullPath.charAt(0) == '/') {
                            fullPath = fullPath.slice(1);
                        }
                    }
                    $("#main-toolbar .title").text(fullPath);
                };
                reader.onerror = function(event) {
                    // TODO--display meaningful error
                }

                reader.readAsText(file, "utf8");
            });
        }
    }

    // Register global commands
    CommandManager.register(Commands.FILE_OPEN, function(fullPath) {
        if (!fullPath) {
            // Prompt the user with a dialog
            NativeFileSystem.showOpenDialog(false, false, "Open File", ProjectManager.getProjectRoot().fullPath,
                ["htm", "html", "js", "css"], function(files) {
                    if (files.length > 0) {
                        doOpen(files[0]);
                    }
                });
        }
        else {
            doOpen(fullPath);
        }
    });

});
<commit_msg>Fixed bug in previous merge<commit_after>/*
 * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved.
 */

// TODO: break out the definition of brackets into a separate module from the application controller logic

// Define core brackets namespace
brackets = window.brackets || {};

brackets.inBrowser = !brackets.hasOwnProperty("fs");

/**
 * General purpose modal error dialog.
 *
 * @param {string} title The title of the error dialog. Can contain HTML markup.
 * @param {string} message The message to display in the error dialog. Can contain HTML markup.
 */
brackets.showErrorDialog = function(title, message) {
    var dlg = $("#error-dialog");

    // Set title and message
    $("#error-dialog-title").html(title);
    $("#error-dialog-message").html(message);

    // Click handler for OK button
    dlg.delegate("#error-dialog-ok", "click", function(e) {
        dlg.modal(true).hide();
    });

    // Run the dialog
    dlg.modal(
        { backdrop: "static"
        , show: true
        }
    );
}

$(document).ready(function() {

    var editor = CodeMirror($('#editor').get(0));

    // Load a default project into the tree
    if (brackets.inBrowser) {
        // In browser: dummy folder tree (hardcoded in ProjectManager)
        ProjectManager.loadProject("DummyProject");
    } else {
        // In app shell: load Brackets itself
        var loadedPath = window.location.pathname;
        var bracketsSrc = loadedPath.substr(0, loadedPath.lastIndexOf("/"));
        ProjectManager.loadProject(bracketsSrc);
    }

    // Open project button
    $("#btn-open-project").click(function() {
        ProjectManager.openProject();
    });

    // Implements the "Open File" menu
    $("#menu-file-open").click(function() {
        CommandManager.execute(Commands.FILE_OPEN);
    });

    // Implements the 'Run Tests' menu to bring up the Jasmine unit test window
    var testWindow = null;
    $("#menu-runtests").click(function(){
        if (!(testWindow === null)) {
            try {
                testWindow.location.reload();
            } catch(e) {
                testWindow = null;  // the window was probably closed
            }
        }

        if (testWindow === null) {
            testWindow = window.open("../test/SpecRunner.html");
            testWindow.location.reload(); // if it was opened before, we need to reload because it will be cached
        }
    });

    // Ty test code hooked up to "new" menu. Test reads a file and prints its constents to the log.
    // uncomment to test
    /*$("#menu-file-new").click(function(){
        var fileEntry = new NativeFileSystem.FileEntry( "/Users/tvoliter/github/brackets-app/README.md" );
        var file;
        fileEntry.file( function( file ){
            var reader = new NativeFileSystem.FileReader();
            reader.onerror = errorHandler;

            reader.onabort = function(e) {
              alert('File read cancelled');
            };

            reader.onloadstart = function(e) {
              console.log( "loading" );
            };

            reader.onload = function ( event ){
                console.log( event.target.result );
            };

            // Read in the image file as a binary string.
            reader.readAsText(file, "utf8");

            function errorHandler(evt) {
                switch(evt.target.error.code) {
                  case evt.target.error.NOT_FOUND_ERR:
                    alert('File Not Found!');
                    break;
                  case evt.target.error.NOT_READABLE_ERR:
                    alert('File is not readable');
                    break;
                  case evt.target.error.ABORT_ERR:
                    break; // noop
                  default:
                    alert('An error occurred reading this file.');
                };
            }
        });
    });*/

    // Utility functions
    function doOpen(fullPath) {
        if (fullPath) {
            var reader = new NativeFileSystem.FileReader();

            // TODO: we should implement something like NativeFileSystem.resolveNativeFileSystemURL() (similar
            // to what's in the standard file API) to get a FileEntry, rather than manually constructing it
            var fileEntry = new NativeFileSystem.FileEntry(fullPath);

            // TODO: it's weird to have to construct a FileEntry just to get a File.
            fileEntry.file(function(file) {
                reader.onload = function(event) {
                    // TODO: have a real controller object for the editor
                    editor.setValue(event.target.result);
                    editor.clearHistory();

                    // In the titlebar, show the project-relative path (if the file is inside the current project)
                    // or the full absolute path (if it's not in the project).
                    var projectRootPath = ProjectManager.getProjectRoot().fullPath;
                    if (projectRootPath.length > 0 && projectRootPath.charAt(projectRootPath.length - 1) != "/") {
                        projectRootPath += "/";
                    }
                    if (fullPath.indexOf(projectRootPath) == 0) {
                        fullPath = fullPath.slice(projectRootPath.length);
                        if (fullPath.charAt(0) == '/') {
                            fullPath = fullPath.slice(1);
                        }
                    }
                    $("#main-toolbar .title").text(fullPath);
                };
                reader.onerror = function(event) {
                    // TODO--display meaningful error
                }

                reader.readAsText(file, "utf8");
            });
        }
    }

    // Register global commands
    CommandManager.register(Commands.FILE_OPEN, function(fullPath) {
        if (!fullPath) {
            // Prompt the user with a dialog
            NativeFileSystem.showOpenDialog(false, false, "Open File", ProjectManager.getProjectRoot().fullPath,
                ["htm", "html", "js", "css"], function(files) {
                    if (files.length > 0) {
                        doOpen(files[0]);
                    }
                });
        }
        else {
            doOpen(fullPath);
        }
    });

});
<|endoftext|>


<commit_before>/*

  This file unifies the API from the cordova and audio5 depending on env

*/

if (Meteor.isCordova) {
  document.addEventListener("deviceready", (event) => {

    Media.prototype.timeupdate = function(callback){
      return setInterval(() => {
        this.getCurrentPosition(function(position) {
            if (position > -1) {
              const mins = Math.floor(position / 600);
              const seconds = (position % 600).toFixed(0);

              const date = `${mins}:${seconds}`;
              callback(date);
            }

        });
      }, 1000);

    };

    Media.prototype.ended = function(callback) {

      const getDuration = () => {
        return this.getDuration();
      };

      let interval = setInterval(() => {
        this.getCurrentPosition(function(position) {
          if (position > -1) {
            const duration = getDuration();
            if (position.toFixed(1) === duration.toFixed(1)) {
              clearInterval(interval);
              callback(null);
              return;
            }
          }
        });
      }, 10);
    };

    Media.prototype.playPause = function(){

      if (this.isPlaying) {
        this.pause();
        this.isPlaying = false;
        return;
      }

      this.isPlaying = true;
      this.play();

    };
  });
}

  class Audio {

    constructor(src, success, error, status) {

      try {
        this._audio5 = new Audio5({
          ready: function(player) {
            this.load(src);
          }

        });
      } catch (e) {
        console.error(e);
      }

      this._audio5.one("canplay", success);

      this._audio5.on("timeupdate", () => {
        this.position = this._audio5.position;
      });

      this.position = null;
      this.duration = this._audio5.duration;

    }

    getCurrentPosition = () => { this._audio5.position }

    timeupdate = (callback) => {
      this._audio5.on("timeupdate", () => {
        callback(this.position);
      });
    }

    getDuration = () => { this._audio5.duration }

    play = () => { this._audio5.play() }

    pause = () => { this._audio5.pause() }
    playPause = () => { this._audio5.playPause() }

    // native only
    release(){ return }

    seekTo = (pos) => { this._audio5.seek(pos / 1000) }

    setVolume = (vol) => { this._audio5.volume(vol) }

    startRecord(){ return }
    stopRecord(){ return }

    stop = () => { this._audio5.pause() }
    release = () => { this._audio5.destroy() }

    ended = (callback) => { this._audio5.on("ended", callback) }

  }

export {
  Audio,
};

export default Audio;
<commit_msg>should be on not one<commit_after>/*

  This file unifies the API from the cordova and audio5 depending on env

*/

if (Meteor.isCordova) {
  document.addEventListener("deviceready", (event) => {

    Media.prototype.timeupdate = function(callback){
      return setInterval(() => {
        this.getCurrentPosition(function(position) {
            if (position > -1) {
              const mins = Math.floor(position / 600);
              const seconds = (position % 600).toFixed(0);

              const date = `${mins}:${seconds}`;
              callback(date);
            }

        });
      }, 1000);

    };

    Media.prototype.ended = function(callback) {

      const getDuration = () => {
        return this.getDuration();
      };

      let interval = setInterval(() => {
        this.getCurrentPosition(function(position) {
          if (position > -1) {
            const duration = getDuration();
            if (position.toFixed(1) === duration.toFixed(1)) {
              clearInterval(interval);
              callback(null);
              return;
            }
          }
        });
      }, 10);
    };

    Media.prototype.playPause = function(){

      if (this.isPlaying) {
        this.pause();
        this.isPlaying = false;
        return;
      }

      this.isPlaying = true;
      this.play();

    };
  });
}

  class Audio {

    constructor(src, success, error, status) {

      try {
        this._audio5 = new Audio5({
          ready: function(player) {
            this.load(src);
          }

        });
      } catch (e) {
        console.error(e);
      }

      this._audio5.on("canplay", success);

      this._audio5.on("timeupdate", () => {
        this.position = this._audio5.position;
      });

      this.position = null;
      this.duration = this._audio5.duration;

    }

    getCurrentPosition = () => { this._audio5.position }

    timeupdate = (callback) => {
      this._audio5.on("timeupdate", () => {
        callback(this.position);
      });
    }

    getDuration = () => { this._audio5.duration }

    play = () => { this._audio5.play() }

    pause = () => { this._audio5.pause() }
    playPause = () => { this._audio5.playPause() }

    // native only
    release(){ return }

    seekTo = (pos) => { this._audio5.seek(pos / 1000) }

    setVolume = (vol) => { this._audio5.volume(vol) }

    startRecord(){ return }
    stopRecord(){ return }

    stop = () => { this._audio5.pause() }
    release = () => { this._audio5.destroy() }

    ended = (callback) => { this._audio5.on("ended", callback) }

  }

export {
  Audio,
};

export default Audio;
<|endoftext|>