<commit_before>/*\
title: $:/plugins/gsd5/core/modules/filters/datefilter.js
type: application/javascript
module-type: filteroperator

Filter operator for comparing date with date field.

\*/
(function(){

/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";

/*
Export our filter function
*/
exports.date = function(source,operator,options) {
  var results = [],
    fieldname = (operator.suffix || "created").toLowerCase();
  if(operator.prefix === "!") {
    source(function(tiddler,title) {
      if(tiddler) {
        var field_string = tiddler.getFieldString(fieldname);
        var field_object = $tw.utils.parseDate(field_string);
        if(operator.operand.split("-").length === 1) {
          var now = new Date();
          now.setUTCHours(0);
          now.setUTCMinutes(0);
          now.setUTCSeconds(0);
          now.setUTCMilliseconds(0);
          var offsetDays = parseInt(operator.operand)*86400000;
          var test_object = new Date(now-offsetDays);
        } else {
          var test_object = new Date(operator.operand);
        }
        if(isNaN(field_object.valueOf()) === false && isNaN(test_object.valueOf()) === false && field_object <= test_object) {
          results.push(title);
        }
      }
    });
  } else {
    source(function(tiddler,title) {
      if(tiddler) {
        var field_string = tiddler.getFieldString(fieldname);
        var field_object = $tw.utils.parseDate(field_string);
        if(operator.operand.split("-").length === 1) {
          var now = new Date();
          now.setUTCHours(0);
          now.setUTCMinutes(0);
          now.setUTCSeconds(0);
          now.setUTCMilliseconds(0);
          var offsetDays = parseInt(operator.operand)*86400000
          var test_object = new Date(now-offsetDays);
        } else {
          var test_object = new Date(operator.operand);
        }
        if(isNaN(field_object.valueOf()) === false && isNaN(test_object.valueOf()) === false && field_object >= test_object) {
          results.push(title);
        }
      }
    });
  }
  return results;
};

})();
<commit_msg>Code cleanup.<commit_after>/*\
title: $:/plugins/gsd5/core/modules/filters/datefilter.js
type: application/javascript
module-type: filteroperator

Filter operator for comparing date with date field.

\*/
(function(){
// jslint node: true, browser: true
// global $tw: false
"use strict";
// Export our filter function
exports.date = function(source,operator,options) {
    var results = [],
        fieldname = (operator.suffix || "created").toLowerCase();
    if(operator.prefix === "!") {
        source(function(tiddler,title) {
            if(tiddler) {
                var field_string = tiddler.getFieldString(fieldname);
                var field_object = $tw.utils.parseDate(field_string);
                if(operator.operand.split("-").length === 1) {
                    var now = new Date();
                    now.setUTCHours(0);
                    now.setUTCMinutes(0);
                    now.setUTCSeconds(0);
                    now.setUTCMilliseconds(0);
                    var offsetDays = parseInt(operator.operand) * 86400000;
                    var test_object = new Date(now - offsetDays);
                } else {
                    var test_object = new Date(operator.operand);
                }
                if(isNaN(field_object.valueOf()) === false && isNaN(test_object.valueOf()) === false && field_object <= test_object) {
                    results.push(title);
                }
            }
        });
    } else {
        source(function(tiddler,title) {
            if(tiddler) {
                var field_string = tiddler.getFieldString(fieldname);
                var field_object = $tw.utils.parseDate(field_string);
                if(operator.operand.split("-").length === 1) {
                    var now = new Date();
                    now.setUTCHours(0);
                    now.setUTCMinutes(0);
                    now.setUTCSeconds(0);
                    now.setUTCMilliseconds(0);
                    var offsetDays = parseInt(operator.operand) * 86400000
                    var test_object = new Date(now-offsetDays);
                } else {
                    var test_object = new Date(operator.operand);
                }
                if(isNaN(field_object.valueOf()) === false && isNaN(test_object.valueOf()) === false && field_object >= test_object) {
                    results.push(title);
                }
            }
        });
    }
    return results;
};

})();
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name projectVApp.controller:FaqCtrl
 * @description
 * # FaqCtrl
 * Controller of the projectVApp
 */
angular.module('projectVApp')
  .controller('FaqCtrl', function ($scope) {
    $scope.items = [
      {
        q: '因為不知道志工要作什麼，所以不太敢答應',
        a: '我們 V 計畫一日志工，主要是希望您可以在投完票後，能夠去您所在的投開票所，或是你所' +
           '想要佔領的投開票所，同我們一起當「割友」現場收取連署書！'
      }, {
        q: '網站要求張貼到 facebook 的權限，但沒有說明會貼什麼，請問會張貼哪些資訊到' +
           ' Facebook？',
        a: '我們在臉書上僅會貼出「你已報名當志工！」等宣傳網站資訊，希望可以分享給您臉書社群的' +
           '好朋友一起共襄盛舉！而割闌尾團隊有法律團隊把關著，個資資料僅會作於聯繫您使用，絕對' +
           '不會將個資外洩！！'
      }, {
        q: '我的問題沒有列在 FAQ 裡面',
        a: '請寄信至 appy.service@gmail.com，我們將會盡快回覆您'
      }, {
        q: '我發現網站有 bug!',
        a: '請到 github 回報網站錯誤'
      }
    ];
  });
<commit_msg>Added Q&A for 500m umbrella<commit_after>'use strict';

/**
 * @ngdoc function
 * @name projectVApp.controller:FaqCtrl
 * @description
 * # FaqCtrl
 * Controller of the projectVApp
 */
angular.module('projectVApp')
  .controller('FaqCtrl', function ($scope) {
    $scope.items = [
      {
        q: '因為不知道志工要作什麼，所以不太敢答應',
        a: '我們 V 計畫一日志工，主要是希望您可以在投完票後，能夠去您所在的投開票所，或是你所' +
           '想要佔領的投開票所，同我們一起當「割友」現場收取連署書！'
      }, {
        q: '網站要求張貼到 facebook 的權限，但沒有說明會貼什麼，請問會張貼哪些資訊到' +
           ' Facebook？',
        a: '我們在臉書上僅會貼出「你已報名當志工！」等宣傳網站資訊，希望可以分享給您臉書社群的' +
           '好朋友一起共襄盛舉！而割闌尾團隊有法律團隊把關著，個資資料僅會作於聯繫您使用，絕對' +
           '不會將個資外洩！！'
      }, {
        q: '物資表裡面有個項目我不懂，什麼是五百萬傘阿？',
        a: '讓我們一起看笨版長知識 XDDDD [無言] 500萬的傘'
      }, {
        q: '我的問題沒有列在 FAQ 裡面',
        a: '請寄信至 appy.service@gmail.com，我們將會盡快回覆您'
      }, {
        q: '我發現網站有 bug!',
        a: '請到 github 回報網站錯誤'
      }
    ];
  });
<|endoftext|>


<commit_before>'use strict';

angular.module('emulvcApp')
	.directive('tier', function() {
		return {
			templateUrl: 'views/tier.html',
			restrict: 'E',
			link: function postLink(scope, element) {
				// select the needed DOM elements from the template
				var canvas = element.find('canvas');

				// var myid = scope.tier.TierName;
				scope.$watch('tierDetails', function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
				}, true);

				scope.$watch('vs', function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
					$('.HandletiersCtrl').css('padding-top', (scope.vs.getscroll() + scope.vs.getheightOsci() + scope.vs.getheightSpectro() + (2 * $('.menu').height()) + 5) + 'px');
				}, true);

				scope.updateView = function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
				};

				/**
				 * draw tier details
				 * @param tierDetails
				 * @param viewPort
				 * @param cps
				 */

				function drawTierDetails(tierDetails, viewPort, config) {

					if ($.isEmptyObject(tierDetails)) {
						//console.log("undef tierDetails");
						return;
					}
					if ($.isEmptyObject(viewPort)) {
						//console.log("undef viewPort");
						return;
					}
					if ($.isEmptyObject(config)) {
						//console.log("undef config");
						return;
					}

					var ctx = canvas[0].getContext('2d');
					ctx.clearRect(0, 0, canvas[0].width, canvas[0].height);

					if (tierDetails.TierName === viewPort.curClickTierName) {
						ctx.fillStyle = config.vals.colors.selectedTierColor;
						ctx.fillRect(0, 0, canvas[0].width, canvas[0].height);
					}

					//predef vars
					var sDist, posS, posE;

					sDist = viewPort.getSampleDist(canvas[0].width);
					// var selection = viewPort.getSelect();

					// draw name of tier
					ctx.fillStyle = config.vals.colors.labelColor;
					ctx.font = (config.vals.colors.fontPxSize + 'px' + ' ' + config.vals.colors.fontType);
					ctx.fillText(tierDetails.TierName, 5, config.vals.colors.fontPxSize);
					ctx.fillText('(' + tierDetails.type + ')', 5, config.vals.colors.fontPxSize * 2);

					var segMId = viewPort.getcurMouseSegmentId();
					var segCId = viewPort.getselected();
					var curID = -1;
					// var curPoS = selection[0];
					// var curPoE = selection[1];
					if (tierDetails.type === 'seg') {
						posS = viewPort.getPos(canvas[0].width, viewPort.curViewPort.selectS);
						posE = viewPort.getPos(canvas[0].width, viewPort.curViewPort.selectE);
						sDist = viewPort.getSampleDist(canvas[0].width);
						var xOffset;
						if (posS === posE) {
							// calc. offset dependant on type of tier of mousemove  -> default is sample exact
							if (viewPort.curMouseMoveTierType === 'seg') {
								xOffset = 0;
							} else {
								xOffset = (sDist / 2);
							}
							ctx.fillStyle = config.vals.colors.selectedBorderColor;
							ctx.fillRect(posS + xOffset, 0, 1, canvas[0].height);
						} else {
							ctx.fillStyle = config.vals.colors.selectedAreaColor;
							ctx.fillRect(posS, 0, posE - posS, canvas[0].height);
							ctx.strokeStyle = config.vals.colors.selectedBoundaryColor;
							ctx.beginPath();
							ctx.moveTo(posS, 0);
							ctx.lineTo(posS, canvas[0].height);
							ctx.moveTo(posE, 0);
							ctx.lineTo(posE, canvas[0].height);
							ctx.closePath();
							ctx.stroke();

						}

						ctx.fillStyle = config.vals.colors.startBoundaryColor;
						// draw segments
						var e = tierDetails.events;

						e.forEach(function(curEvt) {
							++curID;

							if (curEvt.startSample > viewPort.curViewPort.sS &&
								curEvt.startSample < viewPort.curViewPort.eS || //within segment
								curEvt.startSample + curEvt.sampleDur > viewPort.curViewPort.sS &&
								curEvt.startSample + curEvt.sampleDur < viewPort.curViewPort.eS || //end in segment
								curEvt.startSample < viewPort.curViewPort.sS &&
								curEvt.startSample + curEvt.sampleDur > viewPort.curViewPort.eS // within sample
							) {

								// draw segment start
								posS = Math.round(viewPort.getPos(canvas[0].width, curEvt.startSample));
								posE = Math.round(viewPort.getPos(canvas[0].width, curEvt.startSample + curEvt.sampleDur + 1));

								// check if selected -> if draw as marked
								var tierId = viewPort.getcurClickTierName();

								if (tierId === tierDetails.TierName) {

									segCId.forEach(function(entry) {
										if (entry === curID) {
											ctx.fillStyle = config.vals.colors.selectedSegmentColor;
											ctx.fillRect(posS, 0, posE - posS, canvas[0].height);
											ctx.fillStyle = config.vals.colors.startBoundaryColor;
										}
									});

								}

								if (segMId === curID && tierDetails.TierName === viewPort.getcurMouseTierName()) {
									ctx.fillStyle = 'blue'; //SIC -> colors externally defined
									ctx.fillRect(posS, 0, 3, canvas[0].height);
									ctx.fillStyle = 'black'; //SIC -> colors externally defined
								} else {
									ctx.fillStyle = 'black'; //SIC -> colors externally defined
									ctx.fillRect(posS, 0, 2, canvas[0].height / 2);
								}

								//draw segment end

								ctx.fillStyle = config.vals.colors.endBoundaryColor;
								ctx.fillRect(posE, canvas[0].height / 2, 2, canvas[0].height);

								// draw label
								ctx.strokeStyle = config.vals.colors.labelColor;
								ctx.fillStyle = config.vals.colors.labelColor;
								var tW = ctx.measureText(curEvt.label).width;
								var tX = posS + (posE - posS) / 2 - tW / 2;
								// 			//check for enough space to stroke text
								if (posE - posS > tW) {
									ctx.fillText(curEvt.label, tX, canvas[0].height / 2 + 3);
								}

								//draw helper lines
								if (posE - posS > ctx.measureText('m').width * 3) {
									// start helper line
									ctx.strokeStyle = config.vals.colors.startBoundaryColor;
									ctx.beginPath();
									ctx.moveTo(posS, canvas[0].height / 4);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 + 10);
									ctx.stroke();

									// draw startSample numbers
									ctx.fillStyle = config.vals.colors.startBoundaryColor;
									var sStW = ctx.measureText(curEvt.startSample).width;
									//check for enough space to stroke text
									if (posE - posS > sStW) {
										ctx.fillText(curEvt.startSample, posS + 3, canvas[0].height / 5);
									}
									// end helper line
									ctx.strokeStyle = config.vals.colors.endBoundaryColor;
									ctx.beginPath();
									ctx.moveTo(posE, canvas[0].height / 4 * 3);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 * 3);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 * 3 - 10);
									ctx.stroke();
								}
								// draw sampleDur numbers.
								ctx.fillStyle = config.vals.colors.endBoundaryColor;
								var sDtW = ctx.measureText('dur: ' + curEvt.sampleDur).width;
								//check for enough space to stroke text
								if (posE - posS > sDtW) {
									ctx.fillText('dur: ' + curEvt.sampleDur, posE - sDtW, canvas[0].height - canvas[0].height / 12);
								}
							}
						});
					} else if (tierDetails.type == 'point') {
						ctx.fillStyle = config.vals.colors.startBoundaryColor;
						// predef. vars
						var perc, tW;

						for (var k in tierDetails.events) {
							//for (curEvtNr = 0; curEvtNr < tierDetails.events.length; curEvtNr++) {
							var curEvt = tierDetails.events[k];
							// var id = viewPort.getId(tierDetails, curEvt.label, curEvt.startSample);
							if (curEvt.startSample > viewPort.curViewPort.sS && curEvt.startSample < viewPort.curViewPort.eS) {
								perc = Math.round(viewPort.getPos(canvas[0].width, curEvt.startSample) + (sDist / 2));
								console.log(perc)

								// 	if (tierDetails.TierName == emulabeller.viewPort.curMouseMoveTierName && id == emulabeller.viewPort.curMouseMoveSegmentName) {
								// 		ctx.fillStyle = this.params.selectedBoundaryColor;
								// 		ctx.fillRect(perc, 0, 8, canvas[0].height / 2 - canvas[0].height / 10);
								// 		ctx.fillRect(perc, canvas[0].height / 2 + canvas[0].height / 10, 8, canvas[0].height / 2 - canvas[0].height / 10);
								// 		tW = ctx.measureText(tierDetails.events[k].label).width;
								// 		ctx.fillStyle = this.params.labelColor;
								// 		ctx.fillText(tierDetails.events[k].label, perc - tW / 2 + 1, canvas[0].height / 2);
								// 	} else {
								ctx.fillStyle = config.vals.colors.startBoundaryColor;
								ctx.fillRect(perc, 0, 1, canvas[0].height / 2 - canvas[0].height / 10);
								ctx.fillRect(perc, canvas[0].height / 2 + canvas[0].height / 10, 1, canvas[0].height / 2 - canvas[0].height / 10);
								tW = ctx.measureText(tierDetails.events[k].label).width;
								ctx.fillStyle = config.vals.colors.labelColor;
								ctx.fillText(tierDetails.events[k].label, perc - tW / 2 + 1, canvas[0].height / 2);
								// 	}
								ctx.fillStyle = config.vals.colors.startBoundaryColor;
								tW = ctx.measureText(curEvt.startSample).width;
								ctx.fillText(curEvt.startSample, perc + 5, canvas[0].height / 8);

							}
						}
					}
					// draw cursor/selected area
				}
			}
		};
	});<commit_msg>changed viewport to viewstate var<commit_after>'use strict';

angular.module('emulvcApp')
	.directive('tier', function() {
		return {
			templateUrl: 'views/tier.html',
			restrict: 'E',
			link: function postLink(scope, element) {
				// select the needed DOM elements from the template
				var canvas = element.find('canvas');

				// var myid = scope.tier.TierName;
				scope.$watch('tierDetails', function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
				}, true);

				scope.$watch('vs', function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
					$('.HandletiersCtrl').css('padding-top', (scope.vs.getscroll() + scope.vs.getheightOsci() + scope.vs.getheightSpectro() + (2 * $('.menu').height()) + 5) + 'px');
				}, true);

				scope.updateView = function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
				};

				/**
				 * draw tier details
				 * @param tierDetails
				 * @param viewState
				 * @param cps
				 */

				function drawTierDetails(tierDetails, viewState, config) {

					if ($.isEmptyObject(tierDetails)) {
						//console.log("undef tierDetails");
						return;
					}
					if ($.isEmptyObject(viewState)) {
						//console.log("undef viewState");
						return;
					}
					if ($.isEmptyObject(config)) {
						//console.log("undef config");
						return;
					}

					var ctx = canvas[0].getContext('2d');
					ctx.clearRect(0, 0, canvas[0].width, canvas[0].height);

					if (tierDetails.TierName === viewState.curClickTierName) {
						ctx.fillStyle = config.vals.colors.selectedTierColor;
						ctx.fillRect(0, 0, canvas[0].width, canvas[0].height);
					}

					//predef vars
					var sDist, posS, posE;

					sDist = viewState.getSampleDist(canvas[0].width);
					// var selection = viewState.getSelect();

					// draw name of tier
					ctx.fillStyle = config.vals.colors.labelColor;
					ctx.font = (config.vals.colors.fontPxSize + 'px' + ' ' + config.vals.colors.fontType);
					ctx.fillText(tierDetails.TierName, 5, config.vals.colors.fontPxSize);
					ctx.fillText('(' + tierDetails.type + ')', 5, config.vals.colors.fontPxSize * 2);

					var segMId = viewState.getcurMouseSegmentId();
					var segCId = viewState.getselected();
					var curID = -1;
					// var curPoS = selection[0];
					// var curPoE = selection[1];
					if (tierDetails.type === 'seg') {
						posS = viewState.getPos(canvas[0].width, viewState.curViewPort.selectS);
						posE = viewState.getPos(canvas[0].width, viewState.curViewPort.selectE);
						sDist = viewState.getSampleDist(canvas[0].width);
						var xOffset;
						if (posS === posE) {
							// calc. offset dependant on type of tier of mousemove  -> default is sample exact
							if (viewState.curMouseMoveTierType === 'seg') {
								xOffset = 0;
							} else {
								xOffset = (sDist / 2);
							}
							ctx.fillStyle = config.vals.colors.selectedBorderColor;
							ctx.fillRect(posS + xOffset, 0, 1, canvas[0].height);
						} else {
							ctx.fillStyle = config.vals.colors.selectedAreaColor;
							ctx.fillRect(posS, 0, posE - posS, canvas[0].height);
							ctx.strokeStyle = config.vals.colors.selectedBoundaryColor;
							ctx.beginPath();
							ctx.moveTo(posS, 0);
							ctx.lineTo(posS, canvas[0].height);
							ctx.moveTo(posE, 0);
							ctx.lineTo(posE, canvas[0].height);
							ctx.closePath();
							ctx.stroke();

						}

						ctx.fillStyle = config.vals.colors.startBoundaryColor;
						// draw segments
						var e = tierDetails.events;

						e.forEach(function(curEvt) {
							++curID;

							if (curEvt.startSample > viewState.curViewPort.sS &&
								curEvt.startSample < viewState.curViewPort.eS || //within segment
								curEvt.startSample + curEvt.sampleDur > viewState.curViewPort.sS &&
								curEvt.startSample + curEvt.sampleDur < viewState.curViewPort.eS || //end in segment
								curEvt.startSample < viewState.curViewPort.sS &&
								curEvt.startSample + curEvt.sampleDur > viewState.curViewPort.eS // within sample
							) {

								// draw segment start
								posS = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample));
								posE = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample + curEvt.sampleDur + 1));

								// check if selected -> if draw as marked
								var tierId = viewState.getcurClickTierName();

								if (tierId === tierDetails.TierName) {

									segCId.forEach(function(entry) {
										if (entry === curID) {
											ctx.fillStyle = config.vals.colors.selectedSegmentColor;
											ctx.fillRect(posS, 0, posE - posS, canvas[0].height);
											ctx.fillStyle = config.vals.colors.startBoundaryColor;
										}
									});

								}

								if (segMId === curID && tierDetails.TierName === viewState.getcurMouseTierName()) {
									ctx.fillStyle = 'blue'; //SIC -> colors externally defined
									ctx.fillRect(posS, 0, 3, canvas[0].height);
									ctx.fillStyle = 'black'; //SIC -> colors externally defined
								} else {
									ctx.fillStyle = 'black'; //SIC -> colors externally defined
									ctx.fillRect(posS, 0, 2, canvas[0].height / 2);
								}

								//draw segment end

								ctx.fillStyle = config.vals.colors.endBoundaryColor;
								ctx.fillRect(posE, canvas[0].height / 2, 2, canvas[0].height);

								// draw label
								ctx.strokeStyle = config.vals.colors.labelColor;
								ctx.fillStyle = config.vals.colors.labelColor;
								var tW = ctx.measureText(curEvt.label).width;
								var tX = posS + (posE - posS) / 2 - tW / 2;
								// 			//check for enough space to stroke text
								if (posE - posS > tW) {
									ctx.fillText(curEvt.label, tX, canvas[0].height / 2 + 3);
								}

								//draw helper lines
								if (posE - posS > ctx.measureText('m').width * 3) {
									// start helper line
									ctx.strokeStyle = config.vals.colors.startBoundaryColor;
									ctx.beginPath();
									ctx.moveTo(posS, canvas[0].height / 4);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 + 10);
									ctx.stroke();

									// draw startSample numbers
									ctx.fillStyle = config.vals.colors.startBoundaryColor;
									var sStW = ctx.measureText(curEvt.startSample).width;
									//check for enough space to stroke text
									if (posE - posS > sStW) {
										ctx.fillText(curEvt.startSample, posS + 3, canvas[0].height / 5);
									}
									// end helper line
									ctx.strokeStyle = config.vals.colors.endBoundaryColor;
									ctx.beginPath();
									ctx.moveTo(posE, canvas[0].height / 4 * 3);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 * 3);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 * 3 - 10);
									ctx.stroke();
								}
								// draw sampleDur numbers.
								ctx.fillStyle = config.vals.colors.endBoundaryColor;
								var sDtW = ctx.measureText('dur: ' + curEvt.sampleDur).width;
								//check for enough space to stroke text
								if (posE - posS > sDtW) {
									ctx.fillText('dur: ' + curEvt.sampleDur, posE - sDtW, canvas[0].height - canvas[0].height / 12);
								}
							}
						});
					} else if (tierDetails.type == 'point') {
						ctx.fillStyle = config.vals.colors.startBoundaryColor;
						// predef. vars
						var perc, tW;

						for (var k in tierDetails.events) {
							//for (curEvtNr = 0; curEvtNr < tierDetails.events.length; curEvtNr++) {
							var curEvt = tierDetails.events[k];
							// var id = viewState.getId(tierDetails, curEvt.label, curEvt.startSample);
							if (curEvt.startSample > viewState.curViewPort.sS && curEvt.startSample < viewState.curViewPort.eS) {
								perc = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample) + (sDist / 2));

								// 	if (tierDetails.TierName == emulabeller.viewPort.curMouseMoveTierName && id == emulabeller.viewPort.curMouseMoveSegmentName) {
								// 		ctx.fillStyle = this.params.selectedBoundaryColor;
								// 		ctx.fillRect(perc, 0, 8, canvas[0].height / 2 - canvas[0].height / 10);
								// 		ctx.fillRect(perc, canvas[0].height / 2 + canvas[0].height / 10, 8, canvas[0].height / 2 - canvas[0].height / 10);
								// 		tW = ctx.measureText(tierDetails.events[k].label).width;
								// 		ctx.fillStyle = this.params.labelColor;
								// 		ctx.fillText(tierDetails.events[k].label, perc - tW / 2 + 1, canvas[0].height / 2);
								// 	} else {
								ctx.fillStyle = config.vals.colors.startBoundaryColor;
								ctx.fillRect(perc, 0, 1, canvas[0].height / 2 - canvas[0].height / 10);
								ctx.fillRect(perc, canvas[0].height / 2 + canvas[0].height / 10, 1, canvas[0].height / 2 - canvas[0].height / 10);
								tW = ctx.measureText(tierDetails.events[k].label).width;
								ctx.fillStyle = config.vals.colors.labelColor;
								ctx.fillText(tierDetails.events[k].label, perc - tW / 2 + 1, canvas[0].height / 2);
								// 	}
								ctx.fillStyle = config.vals.colors.startBoundaryColor;
								tW = ctx.measureText(curEvt.startSample).width;
								ctx.fillText(curEvt.startSample, perc + 5, canvas[0].height / 8);

							}
						}
					}
					// draw cursor/selected area
				}
			}
		};
	});<|endoftext|>


<commit_before>function setCookie(cname, cvalue, exdays) {
	var d = new Date();
	d.setTime(d.getTime() + (exdays*24*60*60*1000));
	var expires = "expires="+d.toUTCString();
	document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1);
		}
		if (c.indexOf(name) == 0) {
			return c.substring(name.length, c.length);
		}
	}
	return "";
}

function getSavedPadding(){
	paddingstart = getCookie("paddingstart");
	paddingend = getCookie("paddingend");
	if(paddingstart != ""){
		document.getElementById("paddingstart").value = paddingstart;
	}
	if(paddingend != ""){
		document.getElementById("paddingend").value = paddingend;
	}
}

function deleteRule(evt, rule_id, reveal) {
	deleteRuleByID(rule_id,false);
	hideReveal(evt, reveal);
}

function deleteRule2(evt, rule_id, reveal) {
	var searchstring = document.getElementById("searchString").value;
	deleteRuleFromSearch(searchstring,rule_id);
	hideReveal(evt, reveal);
}

function reveal(evt, modal) {
	document.getElementById(modal).style.display = "block";
}

function hideReveal(evt, modal) {
	document.getElementById(modal).style.display = 'none';
}

function RuleDeleteReveal(evt, ruleid){
	document.getElementById("RuleDeleteDetails").innerHTML = document.getElementById(ruleid).innerHTML;
	document.getElementById("druleid").value = ruleid;
	reveal(evt, 'RuleDelete');
}

function RecordingDeleteReveal(evt, recordingid, rerecord){
	document.getElementById("RecordingDeleteDetails").innerHTML = document.getElementById(recordingid).innerHTML;
	document.getElementById("drecordingid").value = recordingid;
	document.getElementById("drerecord").value = rerecord;
	reveal(evt, 'RecordingDelete');
}

function submitDeleteRule(){
	rule_id = document.getElementById("druleid").value;
	deleteRuleByID(rule_id, false);
	hideReveal(evt, 'RuleDelete');
}

function submitDeleteRecording(){
	recording_id = document.getElementById("drecordingid").value;
	rerecord = document.getElementById("drerecord").value;
	seriesid = document.getElementById("seriesid").value;
	deleteRecordingByID(recording_id,rerecord,seriesid);
	hideReveal(evt, 'RecordingDelete');
}

function revealRuleForm(evt, modal,seriesid,seriesname){
	reveal(evt, modal);
	document.getElementById("seriesid").value = seriesid;
	document.getElementById("seriesname").value = seriesname;
	getSavedPadding();
}

function sortRecordings(sortby){
	setCookie("sortby",sortby,3000);
	openRecordingsPage("");
}

function selectSeries(seriesID){
	document.getElementById("series_page").style.display = "none";
	openRecordingsPage(seriesID);
	document.getElementById("recordings_page").style.display = "block";
}

function selectRule(seriesID){
	document.getElementById("series_page").style.display = "none";
	openRulesPage(seriesID);
	document.getElementById("rules_page").style.display = "block";
}
function selectUpcoming(seriesID){
	document.getElementById("series_page").style.display = "none";
	openUpcomingPage(seriesID);
	document.getElementById("upcoming_page").style.display = "block";
}
function viewUpcomingFromRule(seriesID){
	document.getElementById("rules_page").style.display = "none";
	openUpcomingPage(seriesID);
	document.getElementById("upcoming_page").style.display = "block";
}
function viewUpcomingFromSearch(seriesID){
	document.getElementById("search_page").style.display = "none";
	openUpcomingPage(seriesID);
	document.getElementById("upcoming_page").style.display = "block";
}

function handleRecordingType(myRadio){
	if(myRadio.value == "all"){
		document.getElementById("recordtime").style = "display: none;";
		document.getElementById("recordafter").style = "display: none;";
	}else if(myRadio.value == "recent"){
		document.getElementById("recordtime").style = "display: none;";
		document.getElementById("recordafter").style = "display: none;";
	}else if(myRadio.value == "time"){
		document.getElementById("recordtime").style = "display: relative;";
		document.getElementById("recordafter").style = "display: none;";
	}else if(myRadio.value == "aftertime"){
		document.getElementById("recordtime").style = "display: none;";
		document.getElementById("recordafter").style = "display: relative;";
	}
}

function createQRule(seriesid,recentonly){
	var searchstring = document.getElementById("searchString").value;
	createRuleFromSearch(searchstring,seriesid,recentonly,"30","30",null,null,null);
}

function submitCreateRule(){
	var searchstring = document.getElementById("searchString").value;
	var seriesid = document.getElementById("seriesid").value;
	var pstart = document.getElementById("paddingstart").value;
	var pend = document.getElementById("paddingend").value;
	var channel = document.getElementById("channel").value;
	var recordtime = document.getElementById("recordtime").value;
	var recordafter = document.getElementById("recordafter").value;
	var radios = document.getElementsByName('recordtype');
	var recentonly = "";
	var recordtype = "";

	setCookie("paddingstart",pstart,3000);
	setCookie("paddingend",pend,3000);

	for (var i = 0, length = radios.length; i < length; i++) {
	    if (radios[i].checked) {
		recordtype = radios[i].value;
		break;
	    }
	}
	if(recordtype == "all"){
		createRuleFromSearch(searchstring,seriesid,0,pstart,pend,channel,null,null);
	}else if(recordtype == "recent"){
		createRuleFromSearch(searchstring,seriesid,1,pstart,pend,channel,null,null);
	}else if(recordtype == "time"){
		if(recordtime){
			recordtime = moment(recordtime).unix();
			createRuleFromSearch(searchstring,seriesid,0,pstart,pend,channel,recordtime,null);
		}else{
			alert("specify a valid date/time for this type of recording");
		}
	}else if(recordtype == "aftertime"){
		if(recordafter){
			recordafter = moment(recordafter).unix();
			createRuleFromSearch(searchstring,seriesid,0,pstart,pend,channel,null,recordafter);
		}else{
			alert("specify a valid date for this type of recording");
		}
	}
	return false;
}

function openTab(evt, tabname) {
	var i, tabcontent, tablinks;
	// get elements with class="tabcontent" and hide
	tabcontent = document.getElementsByClassName("tabcontent");
	for (i=-0; i < tabcontent.length; i++) {
		tabcontent[i].style.display = "none";
	}

	// get elements with class="tablink" and remove the active
	tablinks = document.getElementsByClassName("tablink");
	for (i=0; i < tablinks.length; i++) {
		tablinks[i].className = tablinks[i].className.replace(" active", "");
	}

	// load the page
	if (tabname == 'series_page') {
		openSeriesPage("");
	}
	if (tabname == 'recordings_page') {
		openRecordingsPage("");
	}
	if (tabname == 'rules_page') {
		openRulesPage("");
	}
	if (tabname == 'search_page') {
		openSearchPage();
	}
	if (tabname == 'settings_page') {
		openSettingsPage();
	}
	if (tabname == 'upcoming_page') {
		openUpcomingPage("");
	}

	//show the tablinks
	document.getElementById(tabname).style.display = "block";
	evt.currentTarget.className += " active";
}

/* Set the status message */
function setStatus(msg)
{
	isStatusIdle = 0;
	if(msg == '' || msg == null || msg == undefined)
	{
		isStatusIdle = 1;
		msg = "Idle.";
	}
	document.getElementById('statusMessage').innerHTML = msg;
}

function goSearch()
{
	var str = document.getElementById('searchString').value;
	openSearchPage(str);
}

function deleteRecording(evt, recording_id, reveal) {
	deleteRecordingByID(recording_id,false);
	hideReveal(evt, reveal);
}

function rerecordRecording(evt, recording_id, reveal) {
	deleteRecordingByID(recording_id,true);
	hideReveal(evt, reveal);
}
<commit_msg>upcoming improvements<commit_after>function goto(eleID) {
   var e = document.getElementById(eleID);
   if (!!e && e.scrollIntoView) {
       e.scrollIntoView(true);
   	window.scrollBy(0,-100);
	}
}

function setCookie(cname, cvalue, exdays) {
	var d = new Date();
	d.setTime(d.getTime() + (exdays*24*60*60*1000));
	var expires = "expires="+d.toUTCString();
	document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1);
		}
		if (c.indexOf(name) == 0) {
			return c.substring(name.length, c.length);
		}
	}
	return "";
}

function getSavedPadding(){
	paddingstart = getCookie("paddingstart");
	paddingend = getCookie("paddingend");
	if(paddingstart != ""){
		document.getElementById("paddingstart").value = paddingstart;
	}
	if(paddingend != ""){
		document.getElementById("paddingend").value = paddingend;
	}
}

function deleteRule(evt, rule_id, reveal) {
	deleteRuleByID(rule_id,false);
	hideReveal(evt, reveal);
}

function deleteRule2(evt, rule_id, reveal) {
	var searchstring = document.getElementById("searchString").value;
	deleteRuleFromSearch(searchstring,rule_id);
	hideReveal(evt, reveal);
}

function reveal(evt, modal) {
	document.getElementById(modal).style.display = "block";
}

function hideReveal(evt, modal) {
	document.getElementById(modal).style.display = 'none';
}

function RuleDeleteReveal(evt, ruleid){
	document.getElementById("RuleDeleteDetails").innerHTML = document.getElementById(ruleid).innerHTML;
	document.getElementById("druleid").value = ruleid;
	reveal(evt, 'RuleDelete');
}

function RecordingDeleteReveal(evt, recordingid, rerecord){
	document.getElementById("RecordingDeleteDetails").innerHTML = document.getElementById(recordingid).innerHTML;
	document.getElementById("drecordingid").value = recordingid;
	document.getElementById("drerecord").value = rerecord;
	reveal(evt, 'RecordingDelete');
}

function submitDeleteRule(){
	rule_id = document.getElementById("druleid").value;
	deleteRuleByID(rule_id, false);
	hideReveal(evt, 'RuleDelete');
}

function submitDeleteRecording(){
	recording_id = document.getElementById("drecordingid").value;
	rerecord = document.getElementById("drerecord").value;
	seriesid = document.getElementById("seriesid").value;
	deleteRecordingByID(recording_id,rerecord,seriesid);
	hideReveal(evt, 'RecordingDelete');
}

function revealRuleForm(evt, modal,seriesid,seriesname){
	reveal(evt, modal);
	document.getElementById("seriesid").value = seriesid;
	document.getElementById("seriesname").value = seriesname;
	getSavedPadding();
}

function sortRecordings(sortby){
	setCookie("sortby",sortby,3000);
	openRecordingsPage("");
}

function selectSeries(seriesID){
	document.getElementById("series_page").style.display = "none";
	openRecordingsPage(seriesID);
	document.getElementById("recordings_page").style.display = "block";
}

function selectRule(seriesID){
	document.getElementById("series_page").style.display = "none";
	openRulesPage(seriesID);
	document.getElementById("rules_page").style.display = "block";
}
function selectUpcoming(seriesID){
	document.getElementById("series_page").style.display = "none";
	openUpcomingPage(seriesID);
	document.getElementById("upcoming_page").style.display = "block";
}
function viewUpcomingFromRule(seriesID){
	document.getElementById("rules_page").style.display = "none";
	openUpcomingPage(seriesID);
	document.getElementById("upcoming_page").style.display = "block";
}
function viewUpcomingFromSearch(seriesID){
	document.getElementById("search_page").style.display = "none";
	openUpcomingPage(seriesID);
	document.getElementById("upcoming_page").style.display = "block";
}

function handleRecordingType(myRadio){
	if(myRadio.value == "all"){
		document.getElementById("recordtime").style = "display: none;";
		document.getElementById("recordafter").style = "display: none;";
	}else if(myRadio.value == "recent"){
		document.getElementById("recordtime").style = "display: none;";
		document.getElementById("recordafter").style = "display: none;";
	}else if(myRadio.value == "time"){
		document.getElementById("recordtime").style = "display: relative;";
		document.getElementById("recordafter").style = "display: none;";
	}else if(myRadio.value == "aftertime"){
		document.getElementById("recordtime").style = "display: none;";
		document.getElementById("recordafter").style = "display: relative;";
	}
}

function createQRule(seriesid,recentonly){
	var searchstring = document.getElementById("searchString").value;
	createRuleFromSearch(searchstring,seriesid,recentonly,"30","30",null,null,null);
}

function submitCreateRule(){
	var searchstring = document.getElementById("searchString").value;
	var seriesid = document.getElementById("seriesid").value;
	var pstart = document.getElementById("paddingstart").value;
	var pend = document.getElementById("paddingend").value;
	var channel = document.getElementById("channel").value;
	var recordtime = document.getElementById("recordtime").value;
	var recordafter = document.getElementById("recordafter").value;
	var radios = document.getElementsByName('recordtype');
	var recentonly = "";
	var recordtype = "";

	setCookie("paddingstart",pstart,3000);
	setCookie("paddingend",pend,3000);

	for (var i = 0, length = radios.length; i < length; i++) {
	    if (radios[i].checked) {
		recordtype = radios[i].value;
		break;
	    }
	}
	if(recordtype == "all"){
		createRuleFromSearch(searchstring,seriesid,0,pstart,pend,channel,null,null);
	}else if(recordtype == "recent"){
		createRuleFromSearch(searchstring,seriesid,1,pstart,pend,channel,null,null);
	}else if(recordtype == "time"){
		if(recordtime){
			recordtime = moment(recordtime).unix();
			createRuleFromSearch(searchstring,seriesid,0,pstart,pend,channel,recordtime,null);
		}else{
			alert("specify a valid date/time for this type of recording");
		}
	}else if(recordtype == "aftertime"){
		if(recordafter){
			recordafter = moment(recordafter).unix();
			createRuleFromSearch(searchstring,seriesid,0,pstart,pend,channel,null,recordafter);
		}else{
			alert("specify a valid date for this type of recording");
		}
	}
	return false;
}

function openTab(evt, tabname) {
	var i, tabcontent, tablinks;
	// get elements with class="tabcontent" and hide
	tabcontent = document.getElementsByClassName("tabcontent");
	for (i=-0; i < tabcontent.length; i++) {
		tabcontent[i].style.display = "none";
	}

	// get elements with class="tablink" and remove the active
	tablinks = document.getElementsByClassName("tablink");
	for (i=0; i < tablinks.length; i++) {
		tablinks[i].className = tablinks[i].className.replace(" active", "");
	}

	// load the page
	if (tabname == 'series_page') {
		openSeriesPage("");
	}
	if (tabname == 'recordings_page') {
		openRecordingsPage("");
	}
	if (tabname == 'rules_page') {
		openRulesPage("");
	}
	if (tabname == 'search_page') {
		openSearchPage();
	}
	if (tabname == 'settings_page') {
		openSettingsPage();
	}
	if (tabname == 'upcoming_page') {
		openUpcomingPage("");
	}

	//show the tablinks
	document.getElementById(tabname).style.display = "block";
	evt.currentTarget.className += " active";
}

/* Set the status message */
function setStatus(msg)
{
	isStatusIdle = 0;
	if(msg == '' || msg == null || msg == undefined)
	{
		isStatusIdle = 1;
		msg = "Idle.";
	}
	document.getElementById('statusMessage').innerHTML = msg;
}

function goSearch()
{
	var str = document.getElementById('searchString').value;
	openSearchPage(str);
}

function deleteRecording(evt, recording_id, reveal) {
	deleteRecordingByID(recording_id,false);
	hideReveal(evt, reveal);
}

function rerecordRecording(evt, recording_id, reveal) {
	deleteRecordingByID(recording_id,true);
	hideReveal(evt, reveal);
}
<|endoftext|>


<commit_before>'use strict';

console.log('**********************USING MOCK BACKEND**********************');

angular.module('confRegistrationWebApp')
  .run(function ($httpBackend, uuid) {

    $httpBackend.whenGET(/views\/.*/).passThrough();

    var registrations = {
      '012': [
        {
          'user': 'user-1',
          'answers': [
            {
              'block': 'block-2',
              'value': {
                firstName: 'Ron',
                lastName: 'Steve'
              }
            },
            {
              'block': 'block-4',
              'value': 'Man'
            },
            {
              'block': 'block-5',
              'value': 'Yes'
            },
            {
              'block': 'block-6',
              'value': 'No'
            },
            {
              'block': 'block-7',
              'value': 'Waffles'
            },
            {
              'block': 'block-8',
              'value': 'Burger'
            },
            {
              'block': 'block-9',
              'value': 'Steak'
            }
          ]
        },
        {
          'user': 'user-2',
          'answers': [
            {
              'block': 'block-2',
              'value': 'Jerry'
            },
            {
              'block': 'block-3',
              'value': 'Perdue'
            },
            {
              'block': 'block-4',
              'value': 'Man'
            },
            {
              'block': 'block-5',
              'value': 'Yes'
            },
            {
              'block': 'block-6',
              'value': 'Yes'
            },
            {
              'block': 'block-7',
              'value': 'Pancakes'
            },
            {
              'block': 'block-8',
              'value': 'Sandwich'
            },
            {
              'block': 'block-9',
              'value': 'Shrimp'
            }
          ]
        },
        {
          'user': 'user-3',
          'answers': [
            {
              'block': 'block-2',
              'value': 'Tom'
            },
            {
              'block': 'block-4',
              'value': 'Man'
            },
            {
              'block': 'block-5',
              'value': 'No'
            },
            {
              'block': 'block-6',
              'value': 'Yes'
            },
            {
              'block': 'block-7',
              'value': 'Omelettes'
            },
            {
              'block': 'block-8',
              'value': 'Soup'
            },
            {
              'block': 'block-9',
              'value': 'Lobster'
            }
          ]
        }
      ]
    };

    var conferences = [
      {
        'id': '012',
        'name': 'A Sweet Fall Retreat',
        'landingPage': {
          'blocks':[
            {
              'id': 'landingpage-1',
              'title': 'Location',
              'type': 'paragraphContent',
              'content': '123 Main St. Orlando, FL, 32828'
            },
            {
              'id': 'landingpage-2',
              'title': 'Registration Begins',
              'type': 'paragraphContent',
              'content': 'August 19, 2013 12:00 AM Eastern Time'
            },
            {
              'id': 'landingpage-2',
              'title': 'Registration Ends',
              'type': 'paragraphContent',
              'content': 'October 12, 2013 3:00 AM Eastern Time'
            },
            {
              'id': 'landingpage-2',
              'title': 'Fall Retreat Starts',
              'type': 'paragraphContent',
              'content': 'October 18, 2013 6:00 PM Eastern Time'
            },
            {
              'id': 'landingpage-2',
              'title': 'Fall Retreat Ends',
              'type': 'paragraphContent',
              'content': 'October 20, 2013 10:00 AM Eastern Time'
            },
            {
              'id': 'landingpage-2',
              'title': 'Contact Info',
              'type': 'paragraphContent',
              'content': 'John Smith <john.smith@example.com> 555-555-5555'
            }
          ]
        },
        'pages': [
          {
            'id': '1',
            'title': 'About You',
            'blocks': [
              {
                'id': 'block-1',
                'title': 'Important Information',
                'type': 'paragraphContent',
                'content': 'We are glad you are coming to Fall Retreat!'
              },
              {
                'id': 'block-2',
                'title': 'What\'s your name?',
                'required': true,
                'type': 'nameQuestion'
              },
              {
                'id': 'block-3',
                'title': 'What school do you currently attend?',
                'type': 'textQuestion'
              },
              {
                'id': 'block-4',
                'title': 'Man or Lady?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Man',
                  'Lady'
                ]
              }
            ]
          },
          {
            'id': '2',
            'title': 'Rides',
            'blocks': [
              {
                'id': 'block-1',
                'title': 'Ride Situation',
                'type': 'paragraphContent',
                'content': 'If you are driving, please give someone a ride.'
              },
              {
                'id': 'block-5',
                'title': 'Do you have a car?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Yes',
                  'No'
                ]
              },
              {
                'id': 'block-6',
                'title': 'Do you need a ride?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Yes',
                  'No'
                ]
              }
            ]
          },
          {
            'id': '3',
            'title': 'Food',
            'blocks': [
              {
                'id': 'block-7',
                'title': 'What do you want to eat for breakfast?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Pancakes',
                  'Waffles',
                  'Omelettes'
                ]
              },
              {
                'id': 'block-8',
                'title': 'What do you want to eat for lunch?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Sandwich',
                  'Soup',
                  'Burger'
                ]
              },
              {
                'id': 'block-9',
                'title': 'What do you want to eat for dinner?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Steak',
                  'Shrimp',
                  'Lobster'
                ]
              }
            ]
          }
        ]
      },
      {
        'id': '123',
        'name': 'Fall Retreat WOOO'
      },
      {
        'id': '234',
        'name': 'Fall Retreat!'
      },
      {
        'id': '345',
        'name': 'Yet Another Fall Retreat (YAFR)'
      },
      {
        'id': '456',
        'name': 'Fall Retreat Is Never Gonna Give You Up'
      }
    ];

    $httpBackend.whenGET('conferences').respond(function () {
      console.log(arguments);
      var headers = {};
      return [200, conferences, headers];
    });
    $httpBackend.whenPOST('conferences').respond(function (verb, url, data) {
      console.log(arguments);

      var conference = angular.extend(angular.fromJson(data), { id: uuid() });

      var headers = {
        'Location': '/conferences/' + conference.id
      };
      return [201, conference, headers];
    });
    $httpBackend.whenGET(/^conferences\/[-a-zA-Z0-9]+\/?$/).respond(function (verb, url) {
      console.log(arguments);

      var conferenceId = url.split('/')[1];

      var conference = _.find(conferences, function (conference) {
        return angular.equals(conference.id, conferenceId);
      });

      return [200, conference, {}];
    });
    $httpBackend.whenPUT(/^conferences\/[-a-zA-Z0-9]+\/?$/).respond(function (verb, url, data) {
      console.log(arguments);

      var conferenceId = url.split('/')[1];

      var conference = _.find(conferences, function (conference) {
        return angular.equals(conference.id, conferenceId);
      });

      angular.extend(conference, angular.fromJson(data));

      return [200, conference, {}];
    });

    $httpBackend.whenGET(/^conferences\/[-a-zA-Z0-9]+\/registrations\/?$/).respond(function (verb, url) {
      console.log(arguments);

      var conferenceId = url.split('/')[1];

      return [200, registrations[conferenceId], {}];
    });
    $httpBackend.whenPOST(/^conferences\/[-a-zA-Z0-9]+\/registrations\/?$/).respond(function (verb, url) {
      console.log(arguments);

      var conferenceId = url.split('/')[1];

      var registration = {
        id: uuid(),
        conference: conferenceId,
        answers: []
      };

      var headers = {
        'Location': '/registrations/' + registration.id
      };

      var registrationJson = angular.toJson(registration);
      sessionStorage.setItem(headers.Location, registrationJson);
      sessionStorage.setItem('/conferences/' + conferenceId + '/registrations/current', registration.id);

      return [201, registration, headers];
    });
    $httpBackend.whenGET(/^conferences\/[-a-zA-Z0-9]+\/registrations\/current\/?$/).respond(function (verb, url) {
      console.log(arguments);

      var conferenceId = url.split('/')[1];

      var registrationId = sessionStorage.getItem('/conferences/' + conferenceId + '/registrations/current');
      if(registrationId) {
        return [200, sessionStorage.getItem('/registrations/' + registrationId)];
      }

      return [404];
    });
    $httpBackend.whenGET(/^registrations\/[-a-zA-Z0-9]+\/?$/).respond(function (verb, url) {
      console.log(arguments);

      var registrationId = url.split('/')[1];
      var registration = sessionStorage.getItem('/registrations/' + registrationId);
      if(registration) {
        return [200, registration];
      }

      return [404];
    });

    $httpBackend.whenPUT(/^answers\/[-a-zA-Z0-9]+\/?$/).respond(function (verb, url, data) {
      console.log(arguments);
      var answer = angular.fromJson(data);

      if(!answer.registration) {
        return [400, { message: 'registration must be present' }];
      }
      if(!answer.block) {
        return [400, { message: 'block must be present' }];
      }
      if(!answer.value) {
        return [400, { message: 'value must be present' }];
      }
      if(!answer.id) {
        answer.id = uuid();
      }

      var registration = sessionStorage.getItem('/registrations/' + data.registration);
      if(registration) {
        var answers = registration.answers;
        var existingAnswerIndex = _.findIndex(answers, { block: answer.block });
        if(existingAnswerIndex != -1) {
          answers.splice(existingAnswerIndex, 1);
        }
        answers.push(answer);
      }

      return [200, answer];
    });

    /*
    angular.forEach(conferences, function (conference) {
      $httpBackend.whenGET('conferences/' + conference.id).respond(function () {
        console.log(arguments);

        var headers = {};
        return [200, conference, headers];
      });

      $httpBackend.whenGET('conferences/' + conference.id + '/registrations').respond(function () {
        console.log(arguments);

        var headers = {};
        return [200, registrations[conference.id], headers];
      });

      $httpBackend.whenPOST('conferences/' + conference.id + '/registrations').respond(function () {
        console.log(arguments);

        var registration = {
          id: '752bab92-e8bf-11e2-91e2-0800200c9a66',
          user: 'c8cfaf61-e8a8-11e2-91e2-0800200c9a66',
          answers: []
        };

        var headers = {
          location: 'registrations/' + registration.id
        };
        return [201, registrations[conference.id], headers];
      });

      $httpBackend.whenGET('conferences/' + conference.id + '/registrations/current').respond(function () {
        console.log(arguments);

        var headers = {};
        var regForConf = registrations[conference.id];
        var theReg = _.find(regForConf, function (registration) {
          return angular.equals(registration.user, 'user-1');
        });
        console.log(theReg);
        return [200, theReg, headers];
      });
    });
    */
  });
<commit_msg>jshint and 'answer' not 'data'<commit_after>'use strict';

console.log('**********************USING MOCK BACKEND**********************');

angular.module('confRegistrationWebApp')
  .run(function ($httpBackend, uuid) {

    $httpBackend.whenGET(/views\/.*/).passThrough();

    var registrations = {
      '012': [
        {
          'user': 'user-1',
          'answers': [
            {
              'block': 'block-2',
              'value': {
                firstName: 'Ron',
                lastName: 'Steve'
              }
            },
            {
              'block': 'block-4',
              'value': 'Man'
            },
            {
              'block': 'block-5',
              'value': 'Yes'
            },
            {
              'block': 'block-6',
              'value': 'No'
            },
            {
              'block': 'block-7',
              'value': 'Waffles'
            },
            {
              'block': 'block-8',
              'value': 'Burger'
            },
            {
              'block': 'block-9',
              'value': 'Steak'
            }
          ]
        },
        {
          'user': 'user-2',
          'answers': [
            {
              'block': 'block-2',
              'value': 'Jerry'
            },
            {
              'block': 'block-3',
              'value': 'Perdue'
            },
            {
              'block': 'block-4',
              'value': 'Man'
            },
            {
              'block': 'block-5',
              'value': 'Yes'
            },
            {
              'block': 'block-6',
              'value': 'Yes'
            },
            {
              'block': 'block-7',
              'value': 'Pancakes'
            },
            {
              'block': 'block-8',
              'value': 'Sandwich'
            },
            {
              'block': 'block-9',
              'value': 'Shrimp'
            }
          ]
        },
        {
          'user': 'user-3',
          'answers': [
            {
              'block': 'block-2',
              'value': 'Tom'
            },
            {
              'block': 'block-4',
              'value': 'Man'
            },
            {
              'block': 'block-5',
              'value': 'No'
            },
            {
              'block': 'block-6',
              'value': 'Yes'
            },
            {
              'block': 'block-7',
              'value': 'Omelettes'
            },
            {
              'block': 'block-8',
              'value': 'Soup'
            },
            {
              'block': 'block-9',
              'value': 'Lobster'
            }
          ]
        }
      ]
    };

    var conferences = [
      {
        'id': '012',
        'name': 'A Sweet Fall Retreat',
        'landingPage': {
          'blocks':[
            {
              'id': 'landingpage-1',
              'title': 'Location',
              'type': 'paragraphContent',
              'content': '123 Main St. Orlando, FL, 32828'
            },
            {
              'id': 'landingpage-2',
              'title': 'Registration Begins',
              'type': 'paragraphContent',
              'content': 'August 19, 2013 12:00 AM Eastern Time'
            },
            {
              'id': 'landingpage-2',
              'title': 'Registration Ends',
              'type': 'paragraphContent',
              'content': 'October 12, 2013 3:00 AM Eastern Time'
            },
            {
              'id': 'landingpage-2',
              'title': 'Fall Retreat Starts',
              'type': 'paragraphContent',
              'content': 'October 18, 2013 6:00 PM Eastern Time'
            },
            {
              'id': 'landingpage-2',
              'title': 'Fall Retreat Ends',
              'type': 'paragraphContent',
              'content': 'October 20, 2013 10:00 AM Eastern Time'
            },
            {
              'id': 'landingpage-2',
              'title': 'Contact Info',
              'type': 'paragraphContent',
              'content': 'John Smith <john.smith@example.com> 555-555-5555'
            }
          ]
        },
        'pages': [
          {
            'id': '1',
            'title': 'About You',
            'blocks': [
              {
                'id': 'block-1',
                'title': 'Important Information',
                'type': 'paragraphContent',
                'content': 'We are glad you are coming to Fall Retreat!'
              },
              {
                'id': 'block-2',
                'title': 'What\'s your name?',
                'required': true,
                'type': 'nameQuestion'
              },
              {
                'id': 'block-3',
                'title': 'What school do you currently attend?',
                'type': 'textQuestion'
              },
              {
                'id': 'block-4',
                'title': 'Man or Lady?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Man',
                  'Lady'
                ]
              }
            ]
          },
          {
            'id': '2',
            'title': 'Rides',
            'blocks': [
              {
                'id': 'block-1',
                'title': 'Ride Situation',
                'type': 'paragraphContent',
                'content': 'If you are driving, please give someone a ride.'
              },
              {
                'id': 'block-5',
                'title': 'Do you have a car?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Yes',
                  'No'
                ]
              },
              {
                'id': 'block-6',
                'title': 'Do you need a ride?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Yes',
                  'No'
                ]
              }
            ]
          },
          {
            'id': '3',
            'title': 'Food',
            'blocks': [
              {
                'id': 'block-7',
                'title': 'What do you want to eat for breakfast?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Pancakes',
                  'Waffles',
                  'Omelettes'
                ]
              },
              {
                'id': 'block-8',
                'title': 'What do you want to eat for lunch?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Sandwich',
                  'Soup',
                  'Burger'
                ]
              },
              {
                'id': 'block-9',
                'title': 'What do you want to eat for dinner?',
                'type': 'radioQuestion',
                'required': true,
                'choices': [
                  'Steak',
                  'Shrimp',
                  'Lobster'
                ]
              }
            ]
          }
        ]
      },
      {
        'id': '123',
        'name': 'Fall Retreat WOOO'
      },
      {
        'id': '234',
        'name': 'Fall Retreat!'
      },
      {
        'id': '345',
        'name': 'Yet Another Fall Retreat (YAFR)'
      },
      {
        'id': '456',
        'name': 'Fall Retreat Is Never Gonna Give You Up'
      }
    ];

    $httpBackend.whenGET('conferences').respond(function () {
      console.log(arguments);
      var headers = {};
      return [200, conferences, headers];
    });
    $httpBackend.whenPOST('conferences').respond(function (verb, url, data) {
      console.log(arguments);

      var conference = angular.extend(angular.fromJson(data), { id: uuid() });

      var headers = {
        'Location': '/conferences/' + conference.id
      };
      return [201, conference, headers];
    });
    $httpBackend.whenGET(/^conferences\/[-a-zA-Z0-9]+\/?$/).respond(function (verb, url) {
      console.log(arguments);

      var conferenceId = url.split('/')[1];

      var conference = _.find(conferences, function (conference) {
        return angular.equals(conference.id, conferenceId);
      });

      return [200, conference, {}];
    });
    $httpBackend.whenPUT(/^conferences\/[-a-zA-Z0-9]+\/?$/).respond(function (verb, url, data) {
      console.log(arguments);

      var conferenceId = url.split('/')[1];

      var conference = _.find(conferences, function (conference) {
        return angular.equals(conference.id, conferenceId);
      });

      angular.extend(conference, angular.fromJson(data));

      return [200, conference, {}];
    });

    $httpBackend.whenGET(/^conferences\/[-a-zA-Z0-9]+\/registrations\/?$/).respond(function (verb, url) {
      console.log(arguments);

      var conferenceId = url.split('/')[1];

      return [200, registrations[conferenceId], {}];
    });
    $httpBackend.whenPOST(/^conferences\/[-a-zA-Z0-9]+\/registrations\/?$/).respond(function (verb, url) {
      console.log(arguments);

      var conferenceId = url.split('/')[1];

      var registration = {
        id: uuid(),
        conference: conferenceId,
        answers: []
      };

      var headers = {
        'Location': '/registrations/' + registration.id
      };

      var registrationJson = angular.toJson(registration);
      sessionStorage.setItem(headers.Location, registrationJson);
      sessionStorage.setItem('/conferences/' + conferenceId + '/registrations/current', registration.id);

      return [201, registration, headers];
    });
    $httpBackend.whenGET(/^conferences\/[-a-zA-Z0-9]+\/registrations\/current\/?$/).respond(function (verb, url) {
      console.log(arguments);

      var conferenceId = url.split('/')[1];

      var registrationId = sessionStorage.getItem('/conferences/' + conferenceId + '/registrations/current');
      if(registrationId) {
        return [200, sessionStorage.getItem('/registrations/' + registrationId)];
      }

      return [404];
    });
    $httpBackend.whenGET(/^registrations\/[-a-zA-Z0-9]+\/?$/).respond(function (verb, url) {
      console.log(arguments);

      var registrationId = url.split('/')[1];
      var registration = sessionStorage.getItem('/registrations/' + registrationId);
      if(registration) {
        return [200, registration];
      }

      return [404];
    });

    $httpBackend.whenPUT(/^answers\/[-a-zA-Z0-9]+\/?$/).respond(function (verb, url, data) {
      console.log(arguments);
      var answer = angular.fromJson(data);

      if(!answer.registration) {
        return [400, { message: 'registration must be present' }];
      }
      if(!answer.block) {
        return [400, { message: 'block must be present' }];
      }
      if(!answer.value) {
        return [400, { message: 'value must be present' }];
      }
      if(!answer.id) {
        answer.id = uuid();
      }

      var registration = sessionStorage.getItem('/registrations/' + answer.registration);
      if(registration) {
        var answers = registration.answers;
        var existingAnswerIndex = _.findIndex(answers, { block: answer.block });
        if(existingAnswerIndex !== -1) {
          answers.splice(existingAnswerIndex, 1);
        }
        answers.push(answer);
      }

      return [200, answer];
    });

    /*
    angular.forEach(conferences, function (conference) {
      $httpBackend.whenGET('conferences/' + conference.id).respond(function () {
        console.log(arguments);

        var headers = {};
        return [200, conference, headers];
      });

      $httpBackend.whenGET('conferences/' + conference.id + '/registrations').respond(function () {
        console.log(arguments);

        var headers = {};
        return [200, registrations[conference.id], headers];
      });

      $httpBackend.whenPOST('conferences/' + conference.id + '/registrations').respond(function () {
        console.log(arguments);

        var registration = {
          id: '752bab92-e8bf-11e2-91e2-0800200c9a66',
          user: 'c8cfaf61-e8a8-11e2-91e2-0800200c9a66',
          answers: []
        };

        var headers = {
          location: 'registrations/' + registration.id
        };
        return [201, registrations[conference.id], headers];
      });

      $httpBackend.whenGET('conferences/' + conference.id + '/registrations/current').respond(function () {
        console.log(arguments);

        var headers = {};
        var regForConf = registrations[conference.id];
        var theReg = _.find(regForConf, function (registration) {
          return angular.equals(registration.user, 'user-1');
        });
        console.log(theReg);
        return [200, theReg, headers];
      });
    });
    */
  });
<|endoftext|>


<commit_before>import config from 'config'
import * as types from '../../mutation-types'
import rootStore from '../../'
import EventBus from 'core/plugins/event-bus'
import i18n from 'core/lib/i18n'
import hash from 'object-hash'

const CART_PULL_INTERVAL_MS = 2000
const CART_CREATE_INTERVAL_MS = 1000
const CART_TOTALS_INTERVAL_MS = 200

export default {
  serverTokenClear (context) {
    context.commit(types.CART_LOAD_CART_SERVER_TOKEN, '')
  },
  clear (context) {
    context.commit(types.CART_LOAD_CART, [])
    context.commit(types.CART_LOAD_CART_SERVER_TOKEN, '')
    if (config.cart.synchronize) {
      rootStore.dispatch('cart/serverCreate', { guestCart: true }, {root: true}) // guest cart because when the order hasn't been passed to magento yet it will repopulate your cart
    }
  },
  save (context) {
    context.commit(types.CART_SAVE)
  },
  serverPull (context, { forceClientState = false }) { // pull current cart FROM the server
    if (config.cart.synchronize) {
      const newItemsHash = hash({ items: context.state.cartItems, token: context.state.cartServerToken })
      if ((new Date() - context.state.cartServerPullAt) >= CART_PULL_INTERVAL_MS || (newItemsHash !== context.state.cartItemsHash)) {
        context.state.cartServerPullAt = new Date()
        context.state.cartItemsHash = newItemsHash
        context.dispatch('sync/execute', { url: config.cart.pull_endpoint, // sync the cart
          payload: {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
            mode: 'cors'
          },
          silent: true,
          force_client_state: forceClientState,
          callback_event: 'servercart-after-pulled'
        }, { root: true }).then(task => {
          rootStore.dispatch('cart/getPaymentMethods')
          if (context.state.cartItems.length > 0) {
            let country = rootStore.state.checkout.shippingDetails.country ? rootStore.state.checkout.shippingDetails.country : config.tax.defaultCountry
            rootStore.dispatch('cart/getShippingMethods', {
              country_id: country
            })
          }
        })
      } else {
        console.log('Too short interval for refreshing the cart or items not changed', newItemsHash, context.state.cartItemsHash)
      }
    }
  },
  serverTotals (context, { forceClientState = false }) { // pull current cart FROM the server
    if (config.cart.synchronize_totals) {
      if ((new Date() - context.state.cartServerTotalsAt) >= CART_TOTALS_INTERVAL_MS) {
        context.state.cartServerPullAt = new Date()
        context.dispatch('sync/execute', { url: config.cart.totals_endpoint, // sync the cart
          payload: {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
            mode: 'cors'
          },
          silent: true,
          force_client_state: forceClientState,
          callback_event: 'servercart-after-totals'
        }, { root: true }).then(task => {

        })
      } else {
        console.log('Too short interval for refreshing the cart totals')
      }
    }
  },
  serverCreate (context, { guestCart = false }) {
    if (config.cart.synchronize) {
      if ((new Date() - context.state.cartServerCreatedAt) >= CART_CREATE_INTERVAL_MS) {
        const task = { url: guestCart ? config.cart.create_endpoint.replace('{{token}}', '') : config.cart.create_endpoint, // sync the cart
          payload: {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            mode: 'cors'
          },
          silent: true,
          callback_event: 'servercart-after-created'
        }
        context.dispatch('sync/execute', task, { root: true }).then(task => {})
        return task
      }
    }
  },
  serverUpdateItem (context, cartItem) {
    if (config.cart.synchronize) {
      if (!cartItem.quoteId) {
        cartItem = Object.assign(cartItem, { quoteId: context.state.cartServerToken })
      }
      context.dispatch('sync/execute', { url: config.cart.updateitem_endpoint, // sync the cart
        payload: {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          mode: 'cors',
          body: JSON.stringify({
            cartItem: cartItem
          })
        },
        callback_event: 'servercart-after-itemupdated'
      }, { root: true }).then(task => {
        // eslint-disable-next-line no-useless-return
        if (config.cart.synchronize_totals) {
          context.dispatch('refreshTotals')
        }
        return
      })
    }
  },
  serverDeleteItem (context, cartItem) {
    if (config.cart.synchronize) {
      if (!cartItem.quoteId) {
        cartItem = Object.assign(cartItem, { quoteId: context.state.cartServerToken })
      }
      cartItem = Object.assign(cartItem, { quoteId: context.state.cartServerToken })
      context.dispatch('sync/execute', { url: config.cart.deleteitem_endpoint, // sync the cart
        payload: {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          mode: 'cors',
          body: JSON.stringify({
            cartItem: cartItem
          })
        },
        silent: true,
        callback_event: 'servercart-after-itemdeleted'
      }, { root: true }).then(task => {
        // eslint-disable-next-line no-useless-return
        if (config.cart.synchronize_totals && context.state.cartItems.length > 0) {
          context.dispatch('refreshTotals')
        }
        return
      })
    }
  },
  load (context) {
    console.log('Loading cart ...')
    const commit = context.commit
    const rootState = context.rootState
    const state = context.state

    if (!state.shipping.code) {
      state.shipping = rootState.shipping.methods.find((el) => { if (el.default === true) return el }) // TODO: use commit() instead of modifying the state in actions
    }
    if (!state.payment.code) {
      state.payment = rootState.payment.methods.find((el) => { if (el.default === true) return el })
    }
    global.db.cartsCollection.getItem('current-cart', (err, storedItems) => {
      if (err) throw new Error(err)

      if (config.cart.synchronize) {
        global.db.cartsCollection.getItem('current-cart-token', (err, token) => {
          if (err) throw new Error(err)
          // TODO: if token is null create cart server side and store the token!
          if (token) { // previously set token
            commit(types.CART_LOAD_CART_SERVER_TOKEN, token)
            console.log('Existing cart token = ' + token)
            context.dispatch('serverPull', { forceClientState: false })
          } else {
            console.log('Creating server cart ...')
            context.dispatch('serverCreate', { guestCart: false })
          }
        })
      }
      commit(types.CART_LOAD_CART, storedItems)
    })
  },

  getItem ({ commit, dispatch, state }, sku) {
    return state.cartItems.find(p => p.sku === sku)
  },

  addItem ({ commit, dispatch, state }, { productToAdd, forceServerSilence = false }) {
    let productsToAdd = []
    if (productToAdd.type_id === 'grouped') {
      productsToAdd = productToAdd.product_links.map((pl) => { return pl.product })
    } else {
      productsToAdd.push(productToAdd)
    }

    for (let product of productsToAdd) {
      if (product.priceInclTax <= 0) {
        EventBus.$emit('notification', {
          type: 'error',
          message: i18n.t('Product price is unknown, product cannot be added to the cart!'),
          action1: { label: 'OK', action: 'close' }
        })
        continue
      }
      const record = state.cartItems.find(p => p.sku === product.sku)
      dispatch('stock/check', { product: product, qty: record ? record.qty + 1 : (product.qty ? product.qty : 1) }, {root: true}).then(result => {
        product.onlineStockCheckid = result.onlineCheckTaskId // used to get the online check result
        if (result.status === 'volatile') {
          EventBus.$emit('notification', {
            type: 'warning',
            message: i18n.t('The system is not sure about the stock quantity (volatile). Product has been added to the cart for pre-reservation.'),
            action1: { label: 'OK', action: 'close' }
          })
        }
        if (result.status === 'out_of_stock') {
          EventBus.$emit('notification', {
            type: 'error',
            message: i18n.t('The product is out of stock and cannot be added to the cart!'),
            action1: { label: 'OK', action: 'close' }
          })
        }
        if (result.status === 'ok' || result.status === 'volatile') {
          commit(types.CART_ADD_ITEM, { product })
          if (config.cart.synchronize && !forceServerSilence) {
            /* dispatch('serverUpdateItem', {
              sku: product.sku,
              qty: 1
            }) */
            dispatch('serverPull', { forceClientState: true })
          }

          EventBus.$emit('notification', {
            type: 'success',
            message: i18n.t('Product has been added to the cart!'),
            action1: { label: 'OK', action: 'close' }
          })
        }
      })
    }
  },
  removeItem ({ commit, dispatch }, product) {
    commit(types.CART_DEL_ITEM, { product })
    if (config.cart.synchronize && product.server_item_id) {
      /* dispatch('serverDeleteItem', {
        sku: product.sku,
        item_id: product.server_item_id
      }) */
      dispatch('serverPull', { forceClientState: true })
    }
  },
  updateQuantity ({ commit, dispatch }, { product, qty, forceServerSilence = false }) {
    commit(types.CART_UPD_ITEM, { product, qty })
    if (config.cart.synchronize && product.server_item_id && !forceServerSilence) {
      /* dispatch('serverUpdateItem', {
        sku: product.sku,
        item_id: product.server_item_id,
        qty: qty
      }) */
      dispatch('serverPull', { forceClientState: true })
    }
  },
  updateItem ({ commit }, { product }) {
    commit(types.CART_UPD_ITEM_PROPS, { product })
  },
  getPaymentMethods (context) {
    if (config.cart.synchronize_totals && (typeof navigator !== 'undefined' ? navigator.onLine : true)) {
      context.dispatch('sync/execute', { url: config.cart.paymentmethods_endpoint,
        payload: {
          method: 'GET',
          headers: { 'Content-Type': 'application/json' },
          mode: 'cors'
        }
      }, { root: true }).then(task => {
        let backendMethods = task.result
        let paymentMethods = JSON.parse(JSON.stringify(rootStore.state.payment.methods))
        let uniqueBackendMethods = []
        for (let i = 0; i < backendMethods.length; i++) {
          if (!paymentMethods.find(item => item.code === backendMethods[i].code)) {
            paymentMethods.push(backendMethods[i])
            uniqueBackendMethods.push(backendMethods[i])
          }
        }
        context.commit(types.CART_UPD_PAYMENT, paymentMethods)
        rootStore.commit('setBackendPaymentMethods', uniqueBackendMethods)
      }).catch(e => {
        console.error(e)
      })
    }
  },
  getShippingMethods (context, address) {
    if (config.cart.synchronize_totals && (typeof navigator !== 'undefined' ? navigator.onLine : true)) {
      context.dispatch('sync/execute', { url: config.cart.shippingmethods_endpoint,
        payload: {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          mode: 'cors',
          body: JSON.stringify({
            address: address
          })
        }
      }, { root: true }).then(task => {
        if (task.result.length > 0) {
          context.commit(types.CART_UPD_SHIPPING, task.result)
        }
      }).catch(e => {
        console.error(e)
      })
    }
  },
  refreshTotals (context, methodsData) {
    if (config.cart.synchronize_totals && (typeof navigator !== 'undefined' ? navigator.onLine : true)) {
      if (!methodsData) {
        let country = rootStore.state.checkout.shippingDetails.country ? rootStore.state.checkout.shippingDetails.country : config.tax.defaultCountry
        let shipping = context.getters.shippingMethods[0]
        let payment = context.getters.paymentMethods[0]
        methodsData = {
          country: country,
          method_code: shipping ? shipping.method_code : null,
          carrier_code: shipping ? shipping.carrier_code : null,
          payment_method: payment.code
        }
      }
      if (methodsData.country && methodsData.carrier_code) {
        context.dispatch('sync/execute', { url: config.cart.shippinginfo_endpoint,
          payload: {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            mode: 'cors',
            body: JSON.stringify({
              addressInformation: {
                shipping_address: {
                  country_id: methodsData.country
                },
                shipping_method_code: methodsData.method_code,
                shipping_carrier_code: methodsData.carrier_code
              }
            })
          }
        }, { root: true }).then(task => {
          context.dispatch('sync/execute', { url: config.cart.collecttotals_endpoint,
            payload: {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              mode: 'cors',
              body: JSON.stringify({
                methods: {
                  paymentMethod: {
                    method: methodsData.payment_method
                  },
                  shippingCarrierCode: methodsData.carrier_code,
                  shippingMethodCode: methodsData.method_code
                }
              })
            },
            callback_event: 'servercart-after-totals'
          }, { root: true }).then(task => {}).catch(e => {
            console.error(e)
          })
        }).catch(e => {
          console.error(e)
        })
      } else {
        context.dispatch('cart/serverTotals', {}, { root: true })
      }
    }
  }
}
<commit_msg>Changing the way the payment methods are copied over.<commit_after>import config from 'config'
import * as types from '../../mutation-types'
import rootStore from '../../'
import EventBus from 'core/plugins/event-bus'
import i18n from 'core/lib/i18n'
import hash from 'object-hash'

const CART_PULL_INTERVAL_MS = 2000
const CART_CREATE_INTERVAL_MS = 1000
const CART_TOTALS_INTERVAL_MS = 200

export default {
  serverTokenClear (context) {
    context.commit(types.CART_LOAD_CART_SERVER_TOKEN, '')
  },
  clear (context) {
    context.commit(types.CART_LOAD_CART, [])
    context.commit(types.CART_LOAD_CART_SERVER_TOKEN, '')
    if (config.cart.synchronize) {
      rootStore.dispatch('cart/serverCreate', { guestCart: true }, {root: true}) // guest cart because when the order hasn't been passed to magento yet it will repopulate your cart
    }
  },
  save (context) {
    context.commit(types.CART_SAVE)
  },
  serverPull (context, { forceClientState = false }) { // pull current cart FROM the server
    if (config.cart.synchronize) {
      const newItemsHash = hash({ items: context.state.cartItems, token: context.state.cartServerToken })
      if ((new Date() - context.state.cartServerPullAt) >= CART_PULL_INTERVAL_MS || (newItemsHash !== context.state.cartItemsHash)) {
        context.state.cartServerPullAt = new Date()
        context.state.cartItemsHash = newItemsHash
        context.dispatch('sync/execute', { url: config.cart.pull_endpoint, // sync the cart
          payload: {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
            mode: 'cors'
          },
          silent: true,
          force_client_state: forceClientState,
          callback_event: 'servercart-after-pulled'
        }, { root: true }).then(task => {
          rootStore.dispatch('cart/getPaymentMethods')
          if (context.state.cartItems.length > 0) {
            let country = rootStore.state.checkout.shippingDetails.country ? rootStore.state.checkout.shippingDetails.country : config.tax.defaultCountry
            rootStore.dispatch('cart/getShippingMethods', {
              country_id: country
            })
          }
        })
      } else {
        console.log('Too short interval for refreshing the cart or items not changed', newItemsHash, context.state.cartItemsHash)
      }
    }
  },
  serverTotals (context, { forceClientState = false }) { // pull current cart FROM the server
    if (config.cart.synchronize_totals) {
      if ((new Date() - context.state.cartServerTotalsAt) >= CART_TOTALS_INTERVAL_MS) {
        context.state.cartServerPullAt = new Date()
        context.dispatch('sync/execute', { url: config.cart.totals_endpoint, // sync the cart
          payload: {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
            mode: 'cors'
          },
          silent: true,
          force_client_state: forceClientState,
          callback_event: 'servercart-after-totals'
        }, { root: true }).then(task => {

        })
      } else {
        console.log('Too short interval for refreshing the cart totals')
      }
    }
  },
  serverCreate (context, { guestCart = false }) {
    if (config.cart.synchronize) {
      if ((new Date() - context.state.cartServerCreatedAt) >= CART_CREATE_INTERVAL_MS) {
        const task = { url: guestCart ? config.cart.create_endpoint.replace('{{token}}', '') : config.cart.create_endpoint, // sync the cart
          payload: {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            mode: 'cors'
          },
          silent: true,
          callback_event: 'servercart-after-created'
        }
        context.dispatch('sync/execute', task, { root: true }).then(task => {})
        return task
      }
    }
  },
  serverUpdateItem (context, cartItem) {
    if (config.cart.synchronize) {
      if (!cartItem.quoteId) {
        cartItem = Object.assign(cartItem, { quoteId: context.state.cartServerToken })
      }
      context.dispatch('sync/execute', { url: config.cart.updateitem_endpoint, // sync the cart
        payload: {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          mode: 'cors',
          body: JSON.stringify({
            cartItem: cartItem
          })
        },
        callback_event: 'servercart-after-itemupdated'
      }, { root: true }).then(task => {
        // eslint-disable-next-line no-useless-return
        if (config.cart.synchronize_totals) {
          context.dispatch('refreshTotals')
        }
        return
      })
    }
  },
  serverDeleteItem (context, cartItem) {
    if (config.cart.synchronize) {
      if (!cartItem.quoteId) {
        cartItem = Object.assign(cartItem, { quoteId: context.state.cartServerToken })
      }
      cartItem = Object.assign(cartItem, { quoteId: context.state.cartServerToken })
      context.dispatch('sync/execute', { url: config.cart.deleteitem_endpoint, // sync the cart
        payload: {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          mode: 'cors',
          body: JSON.stringify({
            cartItem: cartItem
          })
        },
        silent: true,
        callback_event: 'servercart-after-itemdeleted'
      }, { root: true }).then(task => {
        // eslint-disable-next-line no-useless-return
        if (config.cart.synchronize_totals && context.state.cartItems.length > 0) {
          context.dispatch('refreshTotals')
        }
        return
      })
    }
  },
  load (context) {
    console.log('Loading cart ...')
    const commit = context.commit
    const rootState = context.rootState
    const state = context.state

    if (!state.shipping.code) {
      state.shipping = rootState.shipping.methods.find((el) => { if (el.default === true) return el }) // TODO: use commit() instead of modifying the state in actions
    }
    if (!state.payment.code) {
      state.payment = rootState.payment.methods.find((el) => { if (el.default === true) return el })
    }
    global.db.cartsCollection.getItem('current-cart', (err, storedItems) => {
      if (err) throw new Error(err)

      if (config.cart.synchronize) {
        global.db.cartsCollection.getItem('current-cart-token', (err, token) => {
          if (err) throw new Error(err)
          // TODO: if token is null create cart server side and store the token!
          if (token) { // previously set token
            commit(types.CART_LOAD_CART_SERVER_TOKEN, token)
            console.log('Existing cart token = ' + token)
            context.dispatch('serverPull', { forceClientState: false })
          } else {
            console.log('Creating server cart ...')
            context.dispatch('serverCreate', { guestCart: false })
          }
        })
      }
      commit(types.CART_LOAD_CART, storedItems)
    })
  },

  getItem ({ commit, dispatch, state }, sku) {
    return state.cartItems.find(p => p.sku === sku)
  },

  addItem ({ commit, dispatch, state }, { productToAdd, forceServerSilence = false }) {
    let productsToAdd = []
    if (productToAdd.type_id === 'grouped') {
      productsToAdd = productToAdd.product_links.map((pl) => { return pl.product })
    } else {
      productsToAdd.push(productToAdd)
    }

    for (let product of productsToAdd) {
      if (product.priceInclTax <= 0) {
        EventBus.$emit('notification', {
          type: 'error',
          message: i18n.t('Product price is unknown, product cannot be added to the cart!'),
          action1: { label: 'OK', action: 'close' }
        })
        continue
      }
      const record = state.cartItems.find(p => p.sku === product.sku)
      dispatch('stock/check', { product: product, qty: record ? record.qty + 1 : (product.qty ? product.qty : 1) }, {root: true}).then(result => {
        product.onlineStockCheckid = result.onlineCheckTaskId // used to get the online check result
        if (result.status === 'volatile') {
          EventBus.$emit('notification', {
            type: 'warning',
            message: i18n.t('The system is not sure about the stock quantity (volatile). Product has been added to the cart for pre-reservation.'),
            action1: { label: 'OK', action: 'close' }
          })
        }
        if (result.status === 'out_of_stock') {
          EventBus.$emit('notification', {
            type: 'error',
            message: i18n.t('The product is out of stock and cannot be added to the cart!'),
            action1: { label: 'OK', action: 'close' }
          })
        }
        if (result.status === 'ok' || result.status === 'volatile') {
          commit(types.CART_ADD_ITEM, { product })
          if (config.cart.synchronize && !forceServerSilence) {
            /* dispatch('serverUpdateItem', {
              sku: product.sku,
              qty: 1
            }) */
            dispatch('serverPull', { forceClientState: true })
          }

          EventBus.$emit('notification', {
            type: 'success',
            message: i18n.t('Product has been added to the cart!'),
            action1: { label: 'OK', action: 'close' }
          })
        }
      })
    }
  },
  removeItem ({ commit, dispatch }, product) {
    commit(types.CART_DEL_ITEM, { product })
    if (config.cart.synchronize && product.server_item_id) {
      /* dispatch('serverDeleteItem', {
        sku: product.sku,
        item_id: product.server_item_id
      }) */
      dispatch('serverPull', { forceClientState: true })
    }
  },
  updateQuantity ({ commit, dispatch }, { product, qty, forceServerSilence = false }) {
    commit(types.CART_UPD_ITEM, { product, qty })
    if (config.cart.synchronize && product.server_item_id && !forceServerSilence) {
      /* dispatch('serverUpdateItem', {
        sku: product.sku,
        item_id: product.server_item_id,
        qty: qty
      }) */
      dispatch('serverPull', { forceClientState: true })
    }
  },
  updateItem ({ commit }, { product }) {
    commit(types.CART_UPD_ITEM_PROPS, { product })
  },
  getPaymentMethods (context) {
    if (config.cart.synchronize_totals && (typeof navigator !== 'undefined' ? navigator.onLine : true)) {
      context.dispatch('sync/execute', { url: config.cart.paymentmethods_endpoint,
        payload: {
          method: 'GET',
          headers: { 'Content-Type': 'application/json' },
          mode: 'cors'
        }
      }, { root: true }).then(task => {
        let backendMethods = task.result
        let paymentMethods = Object.assign({}, rootStore.state.payment.methods)
        let uniqueBackendMethods = []
        for (let i = 0; i < backendMethods.length; i++) {
          if (!paymentMethods.find(item => item.code === backendMethods[i].code)) {
            paymentMethods.push(backendMethods[i])
            uniqueBackendMethods.push(backendMethods[i])
          }
        }
        context.commit(types.CART_UPD_PAYMENT, paymentMethods)
        rootStore.commit('setBackendPaymentMethods', uniqueBackendMethods)
      }).catch(e => {
        console.error(e)
      })
    }
  },
  getShippingMethods (context, address) {
    if (config.cart.synchronize_totals && (typeof navigator !== 'undefined' ? navigator.onLine : true)) {
      context.dispatch('sync/execute', { url: config.cart.shippingmethods_endpoint,
        payload: {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          mode: 'cors',
          body: JSON.stringify({
            address: address
          })
        }
      }, { root: true }).then(task => {
        if (task.result.length > 0) {
          context.commit(types.CART_UPD_SHIPPING, task.result)
        }
      }).catch(e => {
        console.error(e)
      })
    }
  },
  refreshTotals (context, methodsData) {
    if (config.cart.synchronize_totals && (typeof navigator !== 'undefined' ? navigator.onLine : true)) {
      if (!methodsData) {
        let country = rootStore.state.checkout.shippingDetails.country ? rootStore.state.checkout.shippingDetails.country : config.tax.defaultCountry
        let shipping = context.getters.shippingMethods[0]
        let payment = context.getters.paymentMethods[0]
        methodsData = {
          country: country,
          method_code: shipping ? shipping.method_code : null,
          carrier_code: shipping ? shipping.carrier_code : null,
          payment_method: payment.code
        }
      }
      if (methodsData.country && methodsData.carrier_code) {
        context.dispatch('sync/execute', { url: config.cart.shippinginfo_endpoint,
          payload: {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            mode: 'cors',
            body: JSON.stringify({
              addressInformation: {
                shipping_address: {
                  country_id: methodsData.country
                },
                shipping_method_code: methodsData.method_code,
                shipping_carrier_code: methodsData.carrier_code
              }
            })
          }
        }, { root: true }).then(task => {
          context.dispatch('sync/execute', { url: config.cart.collecttotals_endpoint,
            payload: {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              mode: 'cors',
              body: JSON.stringify({
                methods: {
                  paymentMethod: {
                    method: methodsData.payment_method
                  },
                  shippingCarrierCode: methodsData.carrier_code,
                  shippingMethodCode: methodsData.method_code
                }
              })
            },
            callback_event: 'servercart-after-totals'
          }, { root: true }).then(task => {}).catch(e => {
            console.error(e)
          })
        }).catch(e => {
          console.error(e)
        })
      } else {
        context.dispatch('cart/serverTotals', {}, { root: true })
      }
    }
  }
}
<|endoftext|>


<commit_before>define([
    'openlayers',
    'underscore',
    'knockout',
    'arches',
    'layer-info',
    'map/resource-layer-model'
], function(ol, _, ko, arches, layerInfo, ResourceLayerModel) {
    var resourceFeatures = ko.observableArray();
    var layers = [];

    _.each(layerInfo, function (item, entitytypeid) {
      item.entitytypeid = entitytypeid;
      layers.push(new ResourceLayerModel(item, function(features) {
        resourceFeatures(resourceFeatures().concat(features));
      }));
    });

    return {
      layers: layers,
      features: resourceFeatures
    };
});<commit_msg>cleaning up indentation<commit_after>define([
        'openlayers',
        'underscore',
        'knockout',
        'arches',
        'layer-info',
        'map/resource-layer-model'
], function(ol, _, ko, arches, layerInfo, ResourceLayerModel) {
        var resourceFeatures = ko.observableArray();
        var layers = [];

        _.each(layerInfo, function (item, entitytypeid) {
            item.entitytypeid = entitytypeid;
            layers.push(new ResourceLayerModel(item, function(features) {
                resourceFeatures(resourceFeatures().concat(features));
            }));
        });

        return {
            layers: layers,
            features: resourceFeatures
        };
});<|endoftext|>