/public/JS/main.js
JavaScript | 252 lines | 243 code | 9 blank | 0 comment | 50 complexity | c3680fbd2cc27c00ccdd2983ec543327 MD5 | raw file
Possible License(s): Apache-2.0
- var getFirstDayOfWeek = function (d) {
- d = new Date(d);
- var day = d.getDay(),
- diff = d.getDate() - day + (day == 0 ? -6 : 1); // adjust when day is sunday
- return new Date(d.setDate(diff));
- };
- var isEmail = function (x) {
- var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum|us)\b/
- return re.test(x);
- };
- var FoodRunModel = Backbone.Model.extend({
- initialize:function () {
- if (this.get("total_volunteer_amount") == null) {
- this.set("total_volunteer_amount", 0);
- }
- if (this.get("total_car_amount") == null) {
- this.set("total_car_amount", 0);
- }
- },
- defaults:{
- food_run_id:"",
- pick_up_location:"",
- drop_off_location:"",
- time:"",
- total_volunteer_amount:"",
- total_car_amount:""
- },
- idAttribute:"food_run_id"
- });
- var FoodRunCollection = Backbone.Collection.extend({
- model:FoodRunModel,
- url:"/data/foodrun/filter/week1"
- });
- var SignUpPageView = Backbone.View.extend({
- template:_.template($("#sign-up-container-tmplt").html()),
- datesWeek1:[],
- datesWeek2:[],
- initialize:function () {
- this.datesWeek1 = [], this.datesWeek2 = [];
- var firstDay = new XDate(getFirstDayOfWeek(new Date().setHours(0, 0, 0, 0)), true);
- for (var i = 0; i < 7; i++) {
- this.datesWeek1.push(firstDay.clone().addDays(i).setHours(21).setMinutes(0).setSeconds(0).setMilliseconds(0));
- }
- firstDay.addWeeks(1);
- for (var i = 0; i < 7; i++) {
- this.datesWeek2.push(firstDay.clone().addDays(i).setHours(21).setMinutes(0).setSeconds(0).setMilliseconds(0));
- }
- },
- render:function () {
- $(".side-paddings").children().hide();
- $(".side-paddings").append(this.template());
- $("#week1Header").html(this.datesWeek1[0].toString("MMM. d") + "-" + this.datesWeek1[6].toString("MMM. d"));
- $("#week2Header").html(this.datesWeek2[0].toString("MMM. d") + "-" + this.datesWeek2[6].toString("MMM. d"));
- this.addTables();
- return this;
- },
- addTables:function () {
- new SignUpPageTableView({el:"#week1", collection:Week1FoodRunColl, daysOfWeek:this.datesWeek1}).render();
- new SignUpPageTableView({el:"#week2", collection:Week2FoodRunColl, daysOfWeek:this.datesWeek2}).render();
- }
- });
- var SignUpPageTableView = Backbone.View.extend({
- template:_.template($("#sign-up-table-tmplt").html()),
- render:function () {
- this.$el.html(this.template());
- this.$el.append(new SignUpPageRowView({template:_.template($("#sign-up-table-row-tmplt").html()), collection:this.collection, daysOfWeek:this.options.daysOfWeek}).render());
- return this.$el;
- }
- });
- var SignUpPageRowView = Backbone.View.extend({
- tagName:'tr',
- render:function () {
- this.$el.html(this.options.template());
- this.addAll();
- return this.$el;
- },
- addAll:function () {
- loop1:
- for (var i = 0; i < this.options.daysOfWeek.length; i++) {
- for (var j = 0; j < this.collection.length; j++) {
- if (new XDate(this.collection.at(j).get("time"), true).getTime() === this.options.daysOfWeek[i].getTime()) {
- if (this.options.daysOfWeek[i].getTime() < new XDate().setUTCMode(true, true).getTime()) {
- this.$el.append("<td><p class='largeText tac' style='line-height: 150%'>Successfully Delivered!</td>");
- continue loop1;
- }
- this.$el.append(new FoodRunView({model:this.collection.at(j)}).render());
- continue loop1;
- }
- }
- this.$el.append(new FoodRunView({model:null}).render())
- }
- }
- });
- var FoodRunView = Backbone.View.extend({
- tagName:'td',
- template:_.template($("#sign-up-table-cell-tmplt").html()),
- events:{
- "click":"enterInfo"
- },
- enterInfo:function () {
- if (this.model) {
- if (this.model.get("total_car_amount") >= 3 && this.model.get("total_volunteer_amount") >= 5) {
- return;
- }
- $("#popup").modal();
- var keypress = function (e) {
- return (!(e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)));
- };
- $("#carAmountInput").keypress(keypress);
- $("#groupSizeInput").keypress(keypress);
- var model = this.model;
- $("#submit").click(function () {
- var info = {
- 'email':{'name':'email', 'selector':'#emailInput', 'val':$("#emailInput").val(), 'error':$("#emailErrorMessage")},
- 'groupSize':{'name':'amount of volunteers', 'selector':'#groupSizeInput', 'val':$("#groupSizeInput").val(), 'error':$("#groupErrorMessage")},
- 'carAmount':{'name':'amount of cars', 'selector':'#carAmountInput', 'val':$("#carAmountInput").val(), 'error':$("#carErrorMessage")}
- };
- for (var h in info) {
- if (info[h]['val'] == '') {
- $(info[h]['selector']).css("border", "2px solid red");
- info[h]['error'].text("Please enter an " + info[h]['name'] + "!").show();
- return;
- } else {
- $(info[h]['selector']).css("border", "none");
- info[h]['error'].hide();
- }
- if (h === 'email') {
- if (!isEmail(info[h]['val'])) {
- $(info[h]['selector']).css("border", "2px solid red");
- info[h]['error'].text("Please enter a valid email!").show();
- return;
- } else {
- $(info[h]['selector']).css("border", "none");
- info[h]['error'].hide();
- }
- }
- if (h === 'groupSize' || h === 'carAmount') {
- if (isNaN(info[h]['val'])) {
- $(info[h]['selector']).css("border", "2px solid red");
- info[h]['error'].text("Please enter a valid number!").show();
- return;
- } else {
- $(info[h]['selector']).css("border", "none");
- info[h]['error'].hide();
- }
- }
- }
- if (model.get("total_volunteer_amount") >= 4 && model.get("total_car_amount") < 3 && info['carAmount']['val'] == 0) {
- $(info['carAmount']['selector']).css("border", "2px solid red");
- alert("Sorry, we need someone with a vehicle to sign up for this food-run!");
- return;
- } else {
- $(info['carAmount']['selector']).css("border", "none");
- }
- if (info['carAmount']['val'] > info['groupSize']['val']) {
- alert("Whoa! How do you have more vehicles than people?");
- return;
- }
- $("#popup").find(":input").attr("disabled", "disabled");
- $.ajax({
- type:'POST',
- url:'/data/volunteer/check',
- dataType:'json',
- data:{ 'email':info['email']['val']},
- timeout:10000,
- async:false,
- success:function (data) {
- if (data) { //Email is a valid volunteer
- $.ajax({
- type:'POST',
- url:'/data/foodrun/' + model.id + '/volunteer',
- dataType:'json',
- data:{ 'email':data['email'], 'volunteer_amount':info['groupSize']['val'], 'car_amount':info['carAmount']['val']},
- timeout:10000,
- async:false,
- success:function (data) {
- if (data != null && data['error']) {
- if (data['error'] == 'AlreadyFull') {
- alert("Sorry, this delivery is already completely booked! Your page will be refreshed in order to load up-to-date information.");
- document.location.reload(true);
- } else if (data['error'] == 'TooMany') {
- alert("Sorry, you are trying to sign up with too many volunteers/vehicles! We only need " + data['volunteer'] + " volunteers and " + data['car'] + " cars for this delivery! Please either plan on bringing less volunteers/vehicles, or sign up for a different delivery date.");
- $.modal.close();
- }
- } else {
- $.modal.close();
- $("#success-popup").modal({overlayClose:true});
- }
- },
- error:function (xhr, type) {
- alert('Ajax error!');
- }
- });
- } else {
- $.modal.close();
- $("#no-email-popup").modal({overlayClose:true});
- }
- },
- error:function (xhr, type) {
- alert('Ajax error!');
- }
- });
- });
- }
- },
- render:function () {
- if (this.model == null) {
- return $(this.el).html(this.template());
- } else {
- return $(this.el).html(this.template(this.model.toJSON()));
- }
- }
- });
- var AppRouter = Backbone.Router.extend({
- routes:{
- "":"signUp",
- "*path":"error"
- },
- initialize:function () {
- return this.bind('all', this._trackPageview);
- },
- _trackPageview:function () {
- var url;
- url = Backbone.history.getFragment();
- return _gaq.push(['_trackPageview', "/" + url]);
- },
- signUp:function () {
- Week1FoodRunColl = new FoodRunCollection;
- Week1FoodRunColl.fetch({async:false});
- Week2FoodRunColl = new FoodRunCollection;
- Week2FoodRunColl.url = "/data/foodrun/filter/week2";
- Week2FoodRunColl.fetch({async:false});
- new SignUpPageView().render();
- },
- error:function () {
- this.navigate("#");
- this.signUp();
- }
- });
- $(document).ready(function () {
- new AppRouter;
- Backbone.history.start();
- });