PageRenderTime 93ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/public/JS/main.js

https://bitbucket.org/sampepose/stl-food-rescue
JavaScript | 252 lines | 243 code | 9 blank | 0 comment | 50 complexity | c3680fbd2cc27c00ccdd2983ec543327 MD5 | raw file
Possible License(s): Apache-2.0
  1. var getFirstDayOfWeek = function (d) {
  2. d = new Date(d);
  3. var day = d.getDay(),
  4. diff = d.getDate() - day + (day == 0 ? -6 : 1); // adjust when day is sunday
  5. return new Date(d.setDate(diff));
  6. };
  7. var isEmail = function (x) {
  8. 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/
  9. return re.test(x);
  10. };
  11. var FoodRunModel = Backbone.Model.extend({
  12. initialize:function () {
  13. if (this.get("total_volunteer_amount") == null) {
  14. this.set("total_volunteer_amount", 0);
  15. }
  16. if (this.get("total_car_amount") == null) {
  17. this.set("total_car_amount", 0);
  18. }
  19. },
  20. defaults:{
  21. food_run_id:"",
  22. pick_up_location:"",
  23. drop_off_location:"",
  24. time:"",
  25. total_volunteer_amount:"",
  26. total_car_amount:""
  27. },
  28. idAttribute:"food_run_id"
  29. });
  30. var FoodRunCollection = Backbone.Collection.extend({
  31. model:FoodRunModel,
  32. url:"/data/foodrun/filter/week1"
  33. });
  34. var SignUpPageView = Backbone.View.extend({
  35. template:_.template($("#sign-up-container-tmplt").html()),
  36. datesWeek1:[],
  37. datesWeek2:[],
  38. initialize:function () {
  39. this.datesWeek1 = [], this.datesWeek2 = [];
  40. var firstDay = new XDate(getFirstDayOfWeek(new Date().setHours(0, 0, 0, 0)), true);
  41. for (var i = 0; i < 7; i++) {
  42. this.datesWeek1.push(firstDay.clone().addDays(i).setHours(21).setMinutes(0).setSeconds(0).setMilliseconds(0));
  43. }
  44. firstDay.addWeeks(1);
  45. for (var i = 0; i < 7; i++) {
  46. this.datesWeek2.push(firstDay.clone().addDays(i).setHours(21).setMinutes(0).setSeconds(0).setMilliseconds(0));
  47. }
  48. },
  49. render:function () {
  50. $(".side-paddings").children().hide();
  51. $(".side-paddings").append(this.template());
  52. $("#week1Header").html(this.datesWeek1[0].toString("MMM. d") + "-" + this.datesWeek1[6].toString("MMM. d"));
  53. $("#week2Header").html(this.datesWeek2[0].toString("MMM. d") + "-" + this.datesWeek2[6].toString("MMM. d"));
  54. this.addTables();
  55. return this;
  56. },
  57. addTables:function () {
  58. new SignUpPageTableView({el:"#week1", collection:Week1FoodRunColl, daysOfWeek:this.datesWeek1}).render();
  59. new SignUpPageTableView({el:"#week2", collection:Week2FoodRunColl, daysOfWeek:this.datesWeek2}).render();
  60. }
  61. });
  62. var SignUpPageTableView = Backbone.View.extend({
  63. template:_.template($("#sign-up-table-tmplt").html()),
  64. render:function () {
  65. this.$el.html(this.template());
  66. this.$el.append(new SignUpPageRowView({template:_.template($("#sign-up-table-row-tmplt").html()), collection:this.collection, daysOfWeek:this.options.daysOfWeek}).render());
  67. return this.$el;
  68. }
  69. });
  70. var SignUpPageRowView = Backbone.View.extend({
  71. tagName:'tr',
  72. render:function () {
  73. this.$el.html(this.options.template());
  74. this.addAll();
  75. return this.$el;
  76. },
  77. addAll:function () {
  78. loop1:
  79. for (var i = 0; i < this.options.daysOfWeek.length; i++) {
  80. for (var j = 0; j < this.collection.length; j++) {
  81. if (new XDate(this.collection.at(j).get("time"), true).getTime() === this.options.daysOfWeek[i].getTime()) {
  82. if (this.options.daysOfWeek[i].getTime() < new XDate().setUTCMode(true, true).getTime()) {
  83. this.$el.append("<td><p class='largeText tac' style='line-height: 150%'>Successfully Delivered!</td>");
  84. continue loop1;
  85. }
  86. this.$el.append(new FoodRunView({model:this.collection.at(j)}).render());
  87. continue loop1;
  88. }
  89. }
  90. this.$el.append(new FoodRunView({model:null}).render())
  91. }
  92. }
  93. });
  94. var FoodRunView = Backbone.View.extend({
  95. tagName:'td',
  96. template:_.template($("#sign-up-table-cell-tmplt").html()),
  97. events:{
  98. "click":"enterInfo"
  99. },
  100. enterInfo:function () {
  101. if (this.model) {
  102. if (this.model.get("total_car_amount") >= 3 && this.model.get("total_volunteer_amount") >= 5) {
  103. return;
  104. }
  105. $("#popup").modal();
  106. var keypress = function (e) {
  107. return (!(e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)));
  108. };
  109. $("#carAmountInput").keypress(keypress);
  110. $("#groupSizeInput").keypress(keypress);
  111. var model = this.model;
  112. $("#submit").click(function () {
  113. var info = {
  114. 'email':{'name':'email', 'selector':'#emailInput', 'val':$("#emailInput").val(), 'error':$("#emailErrorMessage")},
  115. 'groupSize':{'name':'amount of volunteers', 'selector':'#groupSizeInput', 'val':$("#groupSizeInput").val(), 'error':$("#groupErrorMessage")},
  116. 'carAmount':{'name':'amount of cars', 'selector':'#carAmountInput', 'val':$("#carAmountInput").val(), 'error':$("#carErrorMessage")}
  117. };
  118. for (var h in info) {
  119. if (info[h]['val'] == '') {
  120. $(info[h]['selector']).css("border", "2px solid red");
  121. info[h]['error'].text("Please enter an " + info[h]['name'] + "!").show();
  122. return;
  123. } else {
  124. $(info[h]['selector']).css("border", "none");
  125. info[h]['error'].hide();
  126. }
  127. if (h === 'email') {
  128. if (!isEmail(info[h]['val'])) {
  129. $(info[h]['selector']).css("border", "2px solid red");
  130. info[h]['error'].text("Please enter a valid email!").show();
  131. return;
  132. } else {
  133. $(info[h]['selector']).css("border", "none");
  134. info[h]['error'].hide();
  135. }
  136. }
  137. if (h === 'groupSize' || h === 'carAmount') {
  138. if (isNaN(info[h]['val'])) {
  139. $(info[h]['selector']).css("border", "2px solid red");
  140. info[h]['error'].text("Please enter a valid number!").show();
  141. return;
  142. } else {
  143. $(info[h]['selector']).css("border", "none");
  144. info[h]['error'].hide();
  145. }
  146. }
  147. }
  148. if (model.get("total_volunteer_amount") >= 4 && model.get("total_car_amount") < 3 && info['carAmount']['val'] == 0) {
  149. $(info['carAmount']['selector']).css("border", "2px solid red");
  150. alert("Sorry, we need someone with a vehicle to sign up for this food-run!");
  151. return;
  152. } else {
  153. $(info['carAmount']['selector']).css("border", "none");
  154. }
  155. if (info['carAmount']['val'] > info['groupSize']['val']) {
  156. alert("Whoa! How do you have more vehicles than people?");
  157. return;
  158. }
  159. $("#popup").find(":input").attr("disabled", "disabled");
  160. $.ajax({
  161. type:'POST',
  162. url:'/data/volunteer/check',
  163. dataType:'json',
  164. data:{ 'email':info['email']['val']},
  165. timeout:10000,
  166. async:false,
  167. success:function (data) {
  168. if (data) { //Email is a valid volunteer
  169. $.ajax({
  170. type:'POST',
  171. url:'/data/foodrun/' + model.id + '/volunteer',
  172. dataType:'json',
  173. data:{ 'email':data['email'], 'volunteer_amount':info['groupSize']['val'], 'car_amount':info['carAmount']['val']},
  174. timeout:10000,
  175. async:false,
  176. success:function (data) {
  177. if (data != null && data['error']) {
  178. if (data['error'] == 'AlreadyFull') {
  179. alert("Sorry, this delivery is already completely booked! Your page will be refreshed in order to load up-to-date information.");
  180. document.location.reload(true);
  181. } else if (data['error'] == 'TooMany') {
  182. 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.");
  183. $.modal.close();
  184. }
  185. } else {
  186. $.modal.close();
  187. $("#success-popup").modal({overlayClose:true});
  188. }
  189. },
  190. error:function (xhr, type) {
  191. alert('Ajax error!');
  192. }
  193. });
  194. } else {
  195. $.modal.close();
  196. $("#no-email-popup").modal({overlayClose:true});
  197. }
  198. },
  199. error:function (xhr, type) {
  200. alert('Ajax error!');
  201. }
  202. });
  203. });
  204. }
  205. },
  206. render:function () {
  207. if (this.model == null) {
  208. return $(this.el).html(this.template());
  209. } else {
  210. return $(this.el).html(this.template(this.model.toJSON()));
  211. }
  212. }
  213. });
  214. var AppRouter = Backbone.Router.extend({
  215. routes:{
  216. "":"signUp",
  217. "*path":"error"
  218. },
  219. initialize:function () {
  220. return this.bind('all', this._trackPageview);
  221. },
  222. _trackPageview:function () {
  223. var url;
  224. url = Backbone.history.getFragment();
  225. return _gaq.push(['_trackPageview', "/" + url]);
  226. },
  227. signUp:function () {
  228. Week1FoodRunColl = new FoodRunCollection;
  229. Week1FoodRunColl.fetch({async:false});
  230. Week2FoodRunColl = new FoodRunCollection;
  231. Week2FoodRunColl.url = "/data/foodrun/filter/week2";
  232. Week2FoodRunColl.fetch({async:false});
  233. new SignUpPageView().render();
  234. },
  235. error:function () {
  236. this.navigate("#");
  237. this.signUp();
  238. }
  239. });
  240. $(document).ready(function () {
  241. new AppRouter;
  242. Backbone.history.start();
  243. });