<commit_before>

$(function() {

	// ..........................................................
	//
	// helper
	//
	// ..........................................................

	var __getArrow = function(last,before){
		return (last == before)?"fa-arrow-right":((last < before)?"fa-arrow-down":"fa-arrow-up");
	};

	var __getIcon = function(labels){
		if ( labels.match(/form/i) ){
			return "fa-file-text-o";
		}
		if ( labels.match(/facebook/i) ){
			return "fa-facebook";
		}
		if ( labels.match(/twitter/i) ){
			return "fa-twitter";
		}
		if ( labels.match(/telegram/i) ){
			return "fa-paper-plane-o";
		}
		return "fa-user";
	};

	var __getDataDefinition = function(element){
		var txt = $(element).attr("data-path");
		if (txt) {
			var textA = txt.split("::");
			var x = {};
			x.type = textA[0];
			x.table = textA[1];
			x.column = textA[2].split('[')[0];
			x.selection = textA[2].split('[')[1]?(textA[2].split('[')[1].split(']')[0]):"";
			return x;
		}
		return null;
	};

	// needed for safari !
	var __normalizeTime = function(date){
		return date.replace(/\-/gi,'/');
	};

	// ..........................................................
	//
	// get data an go ----->
	//
	// ..........................................................

	// var mytest = Data.object("Segnalazioni",{"source":issues,"type":"json"}).import(function(mydata){

	var szUrl = "http://terremotocentroitalia.info/_data/issuesjson.json";
	var myfeed = Data.feed("Segnalazioni",{"source":szUrl,"type":"json"}).load(function(mydata){

		// json -> 2 dimensional table
		// take the isue object and create the columns we know from the CSV

		mydata.addColumn({'source':'issue','destination':'created_at'},function(value){
							return value['created_at'].replace("T"," ").split("+")[0];
							}
						);
		mydata.addColumn({'source':'issue','destination':'title'},function(value){
							return value['title'];
							}
						);
		mydata.addColumn({'source':'issue','destination':'url'},function(value){
							return value['url'];
							}
						);
		mydata.addColumn({'source':'issue','destination':'labels'},function(value){
							return JSON.stringify(value['labels']);
							}
						);
		mydata.addColumn({'source':'issue','destination':'lat'},function(value){
							return value['lat'];
							}
						);
		mydata.addColumn({'source':'issue','destination':'lon'},function(value){
							return value['lon'];
							}
						);

		$("#loading").hide();

		// create list of last 100 messages
		// --------------------------------------------------

		var iUrl	 = mydata.columnIndex("url");
		var iLabels	 = mydata.columnIndex("labels");
		var iDate    = mydata.columnIndex("created_at");
		var iTitle   = mydata.columnIndex("title");

		var list = "";
		for (i=0; i<100; i++ ){
			list += '';
			list += '
';
			list += '';
			list += '
';
			list += '
'+mydata.records[i][iDate]+' '+mydata.records[i][iLabels]+'';
			list += '
';
			list += '
'+mydata.records[i][iTitle]+'
';
			list += '
';
			list += '
';
			list += '';
		}
		$('.message-list').html(list);
		// --------------------------------------------------

		// create new columns 'date' and 'hour' from one timestamp column
		// we need them to create pivot tables
		// ---------------------------------------------------------------
		mydata.addColumn({'source':'created_at','destination':'date'},
								   function(value){
										var d = new Date(__normalizeTime(value));
										return( String(d.getDate()) + "." + String(d.getMonth()+1) + "." + String(d.getFullYear()) );
										}
									);
		mydata.addColumn({'source':'created_at','destination':'hour'},
								   function(value){
										var d = new Date(__normalizeTime(value));
										return( d.getHours() );
										}
									);

		// ..........................................................
		//
		// 1. loop over data request and set value into card templates
		//
		// ..........................................................

		$(".data-dynamic").each( function( index ) {

			var dataPath = __getDataDefinition($(this));
			if (dataPath) {
				if ( dataPath.type == "data" ){

					if ( (dataPath.table == "segnalazioni") && (dataPath.column == "records") && (dataPath.selection == "") ){

						var records = mydata.table.records;
						var pivot = mydata.pivot({ "lead":	'date',
												   "keep":  ['created_at']
												});

						var daysA = pivot.column("Total");
						var dateA = pivot.column("created_at");

						// get last 7 and 14 days timestamp
						var d = new Date();
						d = new Date(d.getFullYear(),d.getMonth(),d.getDate());
						var dateplus7  = d.getTime() - (1000*60*60*24 * (7-1));
						var dateplus14 = d.getTime() - (1000*60*60*24 * (14-1));

						// get last 7 and 14 days values
						var last = 0;
						var before = 0;
						var i = 0;
						while ( new Date(__normalizeTime(dateA[i])).getTime() > dateplus7 ){
							last += daysA[i++];
						}
						while ( new Date(__normalizeTime(dateA[i])).getTime() > dateplus14 ){
							before += daysA[i++];
						}

						// display sum, last 7 and trend arrow
						var szArrow = __getArrow(last,before);
						$(this).html(""+records+"
"+Math.abs(last)+" ");

					}else

					if ( (dataPath.table == "segnalazioni") && (dataPath.column == "records") ){

						// make reduced data tabel by selection
						var sdata = mydata.select(dataPath.selection);
						var records = sdata.table.records;

						// make pivot from this
						var spivot = sdata.pivot({ "lead":	'date',
												   "keep":  ['created_at']
												});

						var daysA = spivot.column("Total");
						var dateA = spivot.column("created_at");

						// get last 7 and 14 days timestamp
						var d = new Date();
						d = new Date(d.getFullYear(),d.getMonth(),d.getDate());
						var dateplus7  = d.getTime() - (1000*60*60*24 * (7-1));
						var dateplus14 = d.getTime() - (1000*60*60*24 * (14-1));

						// get last 7 and 14 days values
						var last = 0;
						var before = 0;
						var i = 0;
						while ( new Date(__normalizeTime(dateA[i])).getTime() > dateplus7 ){
							last += daysA[i++];
						}
						while ( new Date(__normalizeTime(dateA[i])).getTime() > dateplus14 ){
							before += daysA[i++];
						}
						// display sum, last 7 and trend arrow
						var szArrow = __getArrow(last,before);
						$(this).html(""+records+"
"+Math.abs(last)+" ");
					}
				}
			}

		});

		// ..........................................................
		//
		// 2. make day per day curve chart
		//
		// ..........................................................

		var pivot = mydata.pivot({ "lead":	'date',
								   "keep":  ['created_at'],
								   "cols":	'state'
								});

		// invert data table (make last record the first)
		// ----------------------------------------------
		pivot = pivot.revert();

		// make chart with 2 curves, total and closed issues
		// -------------------------------------------------
		var set1  = pivot.column("Total");
		var set2  = pivot.column("closed");
		var label = pivot.column("date");

		if (0){
			var sum = 0;
			for ( i=0; i<set1.length; i++ ){
				set1[i] += sum;
				sum = set1[i];
			}
			sum = 0;
			for ( i=0; i<set2.length; i++ ){
				set2[i] += sum;
				sum = set2[i];
			}
		}

		var ctx, data, myBarChart, option_bars;
		Chart.defaults.global.responsive = true;
		ctx = $('#jumbotron-bar-chart').get(0).getContext('2d');
		options = {
		showScale: false,
		scaleShowGridLines: false,
		scaleGridLineColor: "rgba(0,0,0,.05)",
		scaleGridLineWidth: 1,
		scaleShowHorizontalLines: true,
		scaleShowVerticalLines: true,
		bezierCurve: false,
		bezierCurveTension: 0.4,
		pointDot: false,
		pointDotRadius: 4,
		pointDotStrokeWidth: 1,
		pointHitDetectionRadius: 20,
		datasetStroke: true,
		datasetStrokeWidth: 4,
		datasetFill: true,
		legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%>
<span style=\"background-color:<%=datasets[i].strokeColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
<%}%>
"
		};
		options.type = "line";
		options.data = {
		labels: label,
		datasets: [
		  {
			label: "Total",
			backgroundColor: "rgba(188, 188, 188,0.2)",
			borderColor: "#9C9C9C",
			pointDot: false,
			pointColor: "#9C9C9C",
			pointStrokeColor: "#fff",
			pointHighlightFill: "#fff",
			pointHighlightStroke: "#9C9C9C",
			data: set1
		  }, {
			label: "closed",
			backgroundColor: "rgba(26, 188, 156,0.2)",
			borderColor: "#1ABC9C",
			pointDot: false,
			pointColor: "#1ABC9C",
			pointStrokeColor: "#fff",
			pointHighlightFill: "#fff",
			pointHighlightStroke: "#1ABC9C",
			data: set2
		  }
		]
		};
		options.options = {
		  scales : {
			xAxes: [{
				scaleLabel: {
					display: false,
					labelString: 'Day'
				}
			}],
			yAxes: [{
				ticks: {
					min: 0,
				},
				scaleLabel: {
					labelString: 'Value'
				}
			}]
		  }
		};

		myBarChart = new Chart(ctx, options);

	});
});

<commit_msg>Update dashboard_index_json.js<commit_after>

$(function() {

	// ..........................................................
	//
	// helper
	//
	// ..........................................................

	var __getArrow = function(last,before){
		return (last == before)?"fa-arrow-right":((last < before)?"fa-arrow-down":"fa-arrow-up");
	};

	var __getIcon = function(labels){
		if ( labels.match(/form/i) ){
			return "fa-file-text-o";
		}
		if ( labels.match(/facebook/i) ){
			return "fa-facebook";
		}
		if ( labels.match(/twitter/i) ){
			return "fa-twitter";
		}
		if ( labels.match(/telegram/i) ){
			return "fa-paper-plane-o";
		}
		return "fa-user";
	};

	var __getDataDefinition = function(element){
		var txt = $(element).attr("data-path");
		if (txt) {
			var textA = txt.split("::");
			var x = {};
			x.type = textA[0];
			x.table = textA[1];
			x.column = textA[2].split('[')[0];
			x.selection = textA[2].split('[')[1]?(textA[2].split('[')[1].split(']')[0]):"";
			return x;
		}
		return null;
	};

	// needed for safari !
	var __normalizeTime = function(date){
		return date.replace(/\-/gi,'/');
	};

	// ..........................................................
	//
	// get data an go ----->
	//
	// ..........................................................

	// var mytest = Data.object("Segnalazioni",{"source":issues,"type":"json"}).import(function(mydata){

	var szUrl = "http://terremotocentroitalia.info/_data/issuesjson.json";
	var myfeed = Data.feed("Segnalazioni",{"source":szUrl,"type":"json"}).load(function(mydata){

		// json -> 2 dimensional table
		// take the isue object and create the columns we know from the CSV

		mydata.addColumn({'source':'issue','destination':'created_at'},function(value){
							return value['created_at'].replace("T"," ").split("+")[0];
							}
						);
		mydata.addColumn({'source':'issue','destination':'title'},function(value){
							return value['title'];
							}
						);
		mydata.addColumn({'source':'issue','destination':'url'},function(value){
							return value['url'];
							}
						);
		mydata.addColumn({'source':'issue','destination':'labels'},function(value){
							return JSON.stringify(value['labels']);
							}
						);
		mydata.addColumn({'source':'issue','destination':'lat'},function(value){
							return value['lat'];
							}
						);
		mydata.addColumn({'source':'issue','destination':'lon'},function(value){
							return value['lon'];
							}
						);

		$("#loading").hide();

		// create list of last 100 messages
		// --------------------------------------------------

		var iUrl	 = mydata.columnIndex("url");
		var iLabels	 = mydata.columnIndex("labels");
		var iDate    = mydata.columnIndex("created_at");
		var iTitle   = mydata.columnIndex("title");

		var list = "";
		for (i=0; i<100; i++ ){
			list += '';
			list += '
';
			list += '';
			list += '
';
			list += '
'+mydata.records[i][iDate]+' '+mydata.records[i][iLabels]+'';
			list += '
';
			list += '
'+mydata.records[i][iTitle]+'
';
			list += '
';
			list += '
';
			list += '';
		}
		$('.message-list').html(list);
		// --------------------------------------------------

		// create new columns 'date' and 'hour' from one timestamp column
		// we need them to create pivot tables
		// ---------------------------------------------------------------
		mydata.addColumn({'source':'created_at','destination':'date'},
								   function(value){
										var d = new Date(__normalizeTime(value));
										return( String(d.getDate()) + "." + String(d.getMonth()+1) + "." + String(d.getFullYear()) );
										}
									);
		mydata.addColumn({'source':'created_at','destination':'hour'},
								   function(value){
										var d = new Date(__normalizeTime(value));
										return( d.getHours() );
										}
									);

		// ..........................................................
		//
		// 1. loop over data request and set value into card templates
		//
		// ..........................................................

		$(".data-dynamic").each( function( index ) {

			var dataPath = __getDataDefinition($(this));
			if (dataPath) {
				if ( dataPath.type == "data" ){

					if ( (dataPath.table == "segnalazioni") && (dataPath.column == "records") && (dataPath.selection == "") ){

						var records = mydata.table.records;
						var pivot = mydata.pivot({ "lead":	'date',
												   "keep":  ['created_at']
												});

						var daysA = pivot.column("Total").values() || pivot.column("Total");
						var dateA = pivot.column("created_at").values() || pivot.column("created_at");

						// get last 7 and 14 days timestamp
						var d = new Date();
						d = new Date(d.getFullYear(),d.getMonth(),d.getDate());
						var dateplus7  = d.getTime() - (1000*60*60*24 * (7-1));
						var dateplus14 = d.getTime() - (1000*60*60*24 * (14-1));

						// get last 7 and 14 days values
						var last = 0;
						var before = 0;
						var i = 0;
						while ( new Date(__normalizeTime(dateA[i])).getTime() > dateplus7 ){
							last += daysA[i++];
						}
						while ( new Date(__normalizeTime(dateA[i])).getTime() > dateplus14 ){
							before += daysA[i++];
						}

						// display sum, last 7 and trend arrow
						var szArrow = __getArrow(last,before);
						$(this).html(""+records+"
"+Math.abs(last)+" ");

					}else

					if ( (dataPath.table == "segnalazioni") && (dataPath.column == "records") ){

						// make reduced data tabel by selection
						var sdata = mydata.select(dataPath.selection);
						var records = sdata.table.records;

						if ( records ){

							// make pivot from this
							var spivot = sdata.pivot({ "lead":	'date',
												   "keep":  ['created_at']
												});

							var daysA = spivot.column("Total").values() || spivot.column("Total");
							var dateA = spivot.column("created_at").values() || spivot.column("created_at");

							// get last 7 and 14 days timestamp
							var d = new Date();
							d = new Date(d.getFullYear(),d.getMonth(),d.getDate());
							var dateplus7  = d.getTime() - (1000*60*60*24 * (7-1));
							var dateplus14 = d.getTime() - (1000*60*60*24 * (14-1));

							// get last 7 and 14 days values
							var last = 0;
							var before = 0;
							var i = 0;
							while ( daysA[i] && new Date(__normalizeTime(dateA[i])).getTime() > dateplus7 ){
								last += daysA[i++];
							}
							while ( daysA[i] && new Date(__normalizeTime(dateA[i])).getTime() > dateplus14 ){
								before += daysA[i++];
							}
							// display sum, last 7 and trend arrow
							var szArrow = __getArrow(last,before);
							$(this).html(""+records+"
"+Math.abs(last)+" ");

						}
					}
				}
			}

		});

		// ..........................................................
		//
		// 2. make day per day curve chart
		//
		// ..........................................................

		var pivot = mydata.pivot({ "lead":	'date',
								   "keep":  ['created_at'],
								   "cols":	'state'
								});

		// invert data table (make last record the first)
		// ----------------------------------------------
		pivot = pivot.revert();

		// make chart with 2 curves, total and closed issues
		// -------------------------------------------------
		var set1  = pivot.column("Total").values() || pivot.column("Total");
		var set2  = pivot.column("closed").values() || pivot.column("closed");
		var label = pivot.column("date").values() || pivot.column("date");

		if (0){
			var sum = 0;
			for ( i=0; i<set1.length; i++ ){
				set1[i] += sum;
				sum = set1[i];
			}
			sum = 0;
			for ( i=0; i<set2.length; i++ ){
				set2[i] += sum;
				sum = set2[i];
			}
		}

		var ctx, data, myBarChart, option_bars;
		Chart.defaults.global.responsive = true;
		ctx = $('#jumbotron-bar-chart').get(0).getContext('2d');
		options = {
		showScale: false,
		scaleShowGridLines: false,
		scaleGridLineColor: "rgba(0,0,0,.05)",
		scaleGridLineWidth: 1,
		scaleShowHorizontalLines: true,
		scaleShowVerticalLines: true,
		bezierCurve: false,
		bezierCurveTension: 0.4,
		pointDot: false,
		pointDotRadius: 4,
		pointDotStrokeWidth: 1,
		pointHitDetectionRadius: 20,
		datasetStroke: true,
		datasetStrokeWidth: 4,
		datasetFill: true,
		legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%>
<span style=\"background-color:<%=datasets[i].strokeColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
<%}%>
"
		};
		options.type = "line";
		options.data = {
		labels: label,
		datasets: [
		  {
			label: "Total",
			backgroundColor: "rgba(188, 188, 188,0.2)",
			borderColor: "#9C9C9C",
			pointDot: false,
			pointColor: "#9C9C9C",
			pointStrokeColor: "#fff",
			pointHighlightFill: "#fff",
			pointHighlightStroke: "#9C9C9C",
			data: set1
		  }, {
			label: "closed",
			backgroundColor: "rgba(26, 188, 156,0.2)",
			borderColor: "#1ABC9C",
			pointDot: false,
			pointColor: "#1ABC9C",
			pointStrokeColor: "#fff",
			pointHighlightFill: "#fff",
			pointHighlightStroke: "#1ABC9C",
			data: set2
		  }
		]
		};
		options.options = {
		  scales : {
			xAxes: [{
				scaleLabel: {
					display: false,
					labelString: 'Day'
				}
			}],
			yAxes: [{
				ticks: {
					min: 0,
				},
				scaleLabel: {
					labelString: 'Value'
				}
			}]
		  }
		};

		myBarChart = new Chart(ctx, options);

	});
});

<|endoftext|>


<commit_before>define([
  'jquery',
  'underscore',
  'backbone',
  'geo-util',
  'map',
  'collection',
  'app-state',
  'moment-timezone',
  'moment-timezone-data',
  'moment-lang-cs'
], function ($, _, Backbone, geoUtil, map, collection, appState, moment) {

  "use strict";

  var
    // instantiate global event handler
    vent = _.extend({}, Backbone.Events),

    // view shows marker on the map and asks user to place it to correct location
    GeoLocatePlace = Backbone.View.extend({
      initialize:function () {
        _.bindAll(this, 'render', 'addMarker', 'afterMarkerDrag',
          'updateMarkerBindings', 'unknownPlaced', 'unknownNotPlaced');

        //clear pins on the map
        vent.trigger('geoLocatePlace:placementStarted');
      },
      render: function() {
        if (!this.model.hasLocation()) {
          // try to geocode the location
          geoUtil.geoLocate(this.model.get('place_name'), this.addMarker);
        } else {
          this.addMarker([this.model.get('lat'), this.model.get('lng')]);
        }

        return this;
      },
      addMarker: function(loc) {
        // add pin and show info message
        this.marker = L.marker(loc, {draggable:true})
          .bindPopup('
Umístěte mne na místo ' + this.model.get('place_name') + '

<button id="setPlaceOkButton" type="button" class="btn btn-primary btn-sm btn-block"">Hotovo</button><button id="setPlaceCancelButton" type="button" class="btn btn-link btn-sm btn-block"">Zrušit</button>', {closeButton:false})
          .on('dragend', this.afterMarkerDrag)
          .on('popupopen', this.updateMarkerBindings)
          .addTo(map)
          .openPopup();
        this.afterMarkerDrag();
      },
      // function opens marker popup and binds click actions on buttons
      afterMarkerDrag:function () {
        this.marker.openPopup();
      },
      updateMarkerBindings:function () {
        $('#setPlaceOkButton').click(this.unknownPlaced);
        $('#setPlaceCancelButton').click(this.unknownNotPlaced);
      },
      // function is called whenever user confirms placement of unknown place
      unknownPlaced:function (e) {
        this.model.save({
          lat:this.marker.getLatLng().lat,
          lng:this.marker.getLatLng().lng
        }, {wait:true});
        map.removeLayer(this.marker);
        vent.trigger('geoLocatePlace:placementFinished');

        return e.preventDefault();
      },
      // function is called whenever user cancels placement of unknown place
      unknownNotPlaced:function (e) {
        map.removeLayer(this.marker);
        vent.trigger('geoLocatePlace:placementCanceled');

        return e.preventDefault();
      }
    }),

    // view shows marker to localize unknown place and submits it to server
    UnknownPlaces = Backbone.View.extend({
      initialize:function () {
        _.bindAll(this, 'render', 'setPlace', 'enableMenu', 'disableMenu', 'updateFilter');

        this.filteredModel = new collection.Places();
        this.filteredModel.on('reset', this.render);
        this.model.on({
          reset:this.updateFilter,
          change:this.updateFilter
        });
        vent.on('geoLocatePlace:placementStarted', this.disableMenu);
        vent.on('geoLocatePlace:placementFinished', this.enableMenu);
        vent.on('geoLocatePlace:placementCanceled', this.enableMenu);
      },
      render:function () {
        if (this.filteredModel.size() > 0) {
          this.menuItem = $('' +
            '  Neznámá místa ' +
            '' + this.filteredModel.size() + ' ');
          // create items of dropdown menu
          var dropdown = $('

');

          var that = this;
          this.filteredModel.each(function (i) {
            var item = $('
' + i.get('place_name') + '
');
            item.click(that.setPlace);
            dropdown.append(item);
          });
          this.$el.empty().append(this.menuItem).append(dropdown);
        } else {
          this.$el.empty();
        }
      },
      setPlace:function (evt) {
        // find related model
        var model = this.model.findWhere({place_name:$(evt.target).text()});
        // show the localization marker on the map
        var view = new GeoLocatePlace({model:model}).render();

        return evt.preventDefault();
      },
      enableMenu:function () {
        this.menuItem.removeClass('disabled');
      },
      disableMenu:function () {
        this.menuItem.addClass('disabled');
      },
      updateFilter:function (model) {
        this.filteredModel.reset(this.model.filter(function (m) {
          return !m.hasLocation();
        }));
      }
    }),

    // view shows containers on the map
    Containers = Backbone.View.extend({
      initialize:function () {
        _.bindAll(this, 'render', 'removeMarkers', 'updateFilter', 'updateMarkerBindings', 'movePlace');

        this.filteredModel = new collection.Containers();
        this.filteredModel.on('reset', this.render);
        this.model.on({
          reset:this.updateFilter,
          request:this.showLoading
        });
        vent.on('geoLocatePlace:placementStarted', this.removeMarkers);
        vent.on('geoLocatePlace:placementCanceled', this.render);
        appState.filterDate.on('change', this.updateFilter);
        appState.places.on('change', this.updateFilter);

        this.markerLayerGroup = null;
      },
      render:function () {
        $("#loading").hide();

        this.removeMarkers();

        //add the new pins
        var updateMarkerBindings = this.updateMarkerBindings;
        var markerArray = this.filteredModel.map(function (m) {
          var place = appState.places.get(m.get('place_id'));
          return L.marker({lat:place.get('lat'), lng:place.get('lng')})
            .bindPopup('' + place.get('place_name') + '
' +
            '' + moment(m.get('time_from')).tz('Europe/Prague').format('H:mm') + ' - ' + moment(m.get('time_to')).tz('Europe/Prague').format('H:mm') + '
' +
            'upravit ', {closeButton:false})
            .on('popupopen', updateMarkerBindings);
        });
        this.markerLayerGroup = L.layerGroup(markerArray).addTo(map);

        return this;
      },
      showLoading:function () {
        $('#loading').show();
      },
      removeMarkers:function () {
        if (this.markerLayerGroup) {
          //clear the current pins
          map.removeLayer(this.markerLayerGroup);
          this.markerLayerGroup = null;
        }
      },
      // updates collection of shown models by filtering date and location
      updateFilter:function () {
        this.filteredModel.reset(this.model.filter(function (m) {
          // return containers for current day
          return moment(m.get('time_from')).isSame(appState.filterDate.get('filter_date'), 'day') &&
            // which are not yet removed
            moment().isBefore(m.get('time_to')) &&
            // and with location specified
            appState.places.get(m.get('place_id')).hasLocation();
        }));
      },
      updateMarkerBindings:function () {
        $('#movePlaceButton').click(this.movePlace);
      },
      movePlace:function (evt) {
        // find related model
        var model = appState.places.findWhere({place_name:$(evt.target).siblings().first().text()});
        // show the localization marker on the map
        var view = new GeoLocatePlace({model:model}).render();

        return evt.preventDefault();
      }
    }),

    // view controls filtering of containers by day
    ContainerFilter = Backbone.View.extend({
      initialize:function () {
        _.bindAll(this, 'render', 'setPrev', 'setNext', 'enableFilter', 'disableFilter');

        this.model.on('change', this.render);
        this.disabled = false;

        // create menu items and register callbacks
        $('

')
          .click(this.setPrev)
          .appendTo(this.$el);
        this.$el.append('

');
        $('

')
          .click(this.setNext)
          .appendTo(this.$el);

        // disable / enable filter on unknown place location
        vent.on('geoLocatePlace:placementStarted', this.disableFilter);
        vent.on('geoLocatePlace:placementCanceled', this.enableFilter);
        vent.on('geoLocatePlace:placementFinished', this.enableFilter);

        // customize moment.js to show days only (not time) in calendar()
        moment.lang('cs', {
          'calendar':{
            sameDay:"[dnes]",
            nextDay:'[zítra]',
            nextWeek:function () {
              switch (this.day()) {
                case 0:
                  return '[v neděli]';
                case 1:
                case 2:
                  return '[v] dddd';
                case 3:
                  return '[ve středu]';
                case 4:
                  return '[ve čtvrtek]';
                case 5:
                  return '[v pátek]';
                case 6:
                  return '[v sobotu]';
              }
            },
            lastDay:'[včera]',
            lastWeek:function () {
              switch (this.day()) {
                case 0:
                  return '[minulou neděli]';
                case 1:
                case 2:
                  return '[minulé] dddd';
                case 3:
                  return '[minulou středu]';
                case 4:
                case 5:
                  return '[minulý] dddd';
                case 6:
                  return '[minulou sobotu]';
              }
            },
            sameElse:"L"
          }
        });
      },
      render:function () {
        this.$('.navbar-text').text(this.model.get('filter_date').calendar());
        return this;
      },
      setPrev:function (e) {
        if (!this.disabled) {
          // update filter day
          if (moment().isBefore(this.model.get('filter_date'), 'day')) {
            // subtract one day from filter day
            this.model.set('filter_date', moment(this.model.get('filter_date')).subtract('days', 1));
          }

          // update button visibility
          if (!moment().isBefore(this.model.get('filter_date'), 'day')) {
            this.$('.container-filter-prev').addClass('disabled');
          }
        }

        return e.preventDefault();
      },
      setNext:function (e) {
        if (!this.disabled) {
          if (moment().isSame(this.model.get('filter_date'), 'day')) {
            // if filter day is today enable back button
            this.$('.container-filter-prev').removeClass('disabled');
          }
          this.model.set('filter_date', moment(this.model.get('filter_date')).add('days', 1));
        }

        return e.preventDefault();
      },
      // function enables filter buttons
      enableFilter:function () {
        this.disabled = false;
        // check if Prev button can be enabled
        if (moment().isBefore(this.model.get('filter_date'), 'day')) {
          this.$('.container-filter-prev').removeClass('disabled');
        }
        // enable Next button
        this.$('.container-filter-next').removeClass('disabled');
      },
      // function disables filter buttons
      disableFilter:function () {
        this.disabled = true;
        this.$('.container-filter-prev').addClass('disabled');
        this.$('.container-filter-next').addClass('disabled');
      }
    })
  ;

  return {
    GeoLocatePlace: GeoLocatePlace,
    UnknownPlaces: UnknownPlaces,
    Containers: Containers,
    ContainerFilter: ContainerFilter
  };

});<commit_msg>Fixed error which prevented edit of place location when all places were located<commit_after>define([
  'jquery',
  'underscore',
  'backbone',
  'geo-util',
  'map',
  'collection',
  'app-state',
  'moment-timezone',
  'moment-timezone-data',
  'moment-lang-cs'
], function ($, _, Backbone, geoUtil, map, collection, appState, moment) {

  "use strict";

  var
    // instantiate global event handler
    vent = _.extend({}, Backbone.Events),

    // view shows marker on the map and asks user to place it to correct location
    GeoLocatePlace = Backbone.View.extend({
      initialize:function () {
        _.bindAll(this, 'render', 'addMarker', 'afterMarkerDrag',
          'updateMarkerBindings', 'unknownPlaced', 'unknownNotPlaced');

        //clear pins on the map
        vent.trigger('geoLocatePlace:placementStarted');
      },
      render: function() {
        if (!this.model.hasLocation()) {
          // try to geocode the location
          geoUtil.geoLocate(this.model.get('place_name'), this.addMarker);
        } else {
          this.addMarker([this.model.get('lat'), this.model.get('lng')]);
        }

        return this;
      },
      addMarker: function(loc) {
        // add pin and show info message
        this.marker = L.marker(loc, {draggable:true})
          .bindPopup('
Umístěte mne na místo ' + this.model.get('place_name') + '

<button id="setPlaceOkButton" type="button" class="btn btn-primary btn-sm btn-block"">Hotovo</button><button id="setPlaceCancelButton" type="button" class="btn btn-link btn-sm btn-block"">Zrušit</button>', {closeButton:false})
          .on('dragend', this.afterMarkerDrag)
          .on('popupopen', this.updateMarkerBindings)
          .addTo(map)
          .openPopup();
        this.afterMarkerDrag();
      },
      // function opens marker popup and binds click actions on buttons
      afterMarkerDrag:function () {
        this.marker.openPopup();
      },
      updateMarkerBindings:function () {
        $('#setPlaceOkButton').click(this.unknownPlaced);
        $('#setPlaceCancelButton').click(this.unknownNotPlaced);
      },
      // function is called whenever user confirms placement of unknown place
      unknownPlaced:function (e) {
        this.model.save({
          lat:this.marker.getLatLng().lat,
          lng:this.marker.getLatLng().lng
        }, {wait:true});
        map.removeLayer(this.marker);
        vent.trigger('geoLocatePlace:placementFinished');

        return e.preventDefault();
      },
      // function is called whenever user cancels placement of unknown place
      unknownNotPlaced:function (e) {
        map.removeLayer(this.marker);
        vent.trigger('geoLocatePlace:placementCanceled');

        return e.preventDefault();
      }
    }),

    // view shows marker to localize unknown place and submits it to server
    UnknownPlaces = Backbone.View.extend({
      initialize:function () {
        _.bindAll(this, 'render', 'setPlace', 'enableMenu', 'disableMenu', 'updateFilter');

        this.filteredModel = new collection.Places();
        this.filteredModel.on('reset', this.render);
        this.model.on({
          reset:this.updateFilter,
          change:this.updateFilter
        });
        vent.on('geoLocatePlace:placementStarted', this.disableMenu);
        vent.on('geoLocatePlace:placementFinished', this.enableMenu);
        vent.on('geoLocatePlace:placementCanceled', this.enableMenu);
      },
      render:function () {
        if (this.filteredModel.size() > 0) {
          this.menuItem = $('' +
            '  Neznámá místa ' +
            '' + this.filteredModel.size() + ' ');
          // create items of dropdown menu
          var dropdown = $('

');

          var that = this;
          this.filteredModel.each(function (i) {
            var item = $('
' + i.get('place_name') + '
');
            item.click(that.setPlace);
            dropdown.append(item);
          });
          this.$el.empty().append(this.menuItem).append(dropdown);
        } else {
          this.$el.empty();
        }
      },
      setPlace:function (evt) {
        // find related model
        var model = this.model.findWhere({place_name:$(evt.target).text()});
        // show the localization marker on the map
        var view = new GeoLocatePlace({model:model}).render();

        return evt.preventDefault();
      },
      enableMenu:function () {
        if (this.menuItem) {
          this.menuItem.removeClass('disabled');
        }
      },
      disableMenu:function () {
        if (this.menuItem) {
          this.menuItem.addClass('disabled');
        }
      },
      updateFilter:function (model) {
        this.filteredModel.reset(this.model.filter(function (m) {
          return !m.hasLocation();
        }));
      }
    }),

    // view shows containers on the map
    Containers = Backbone.View.extend({
      initialize:function () {
        _.bindAll(this, 'render', 'removeMarkers', 'updateFilter', 'updateMarkerBindings', 'movePlace');

        this.filteredModel = new collection.Containers();
        this.filteredModel.on('reset', this.render);
        this.model.on({
          reset:this.updateFilter,
          request:this.showLoading
        });
        vent.on('geoLocatePlace:placementStarted', this.removeMarkers);
        vent.on('geoLocatePlace:placementCanceled', this.render);
        appState.filterDate.on('change', this.updateFilter);
        appState.places.on('change', this.updateFilter);

        this.markerLayerGroup = null;
      },
      render:function () {
        $("#loading").hide();

        this.removeMarkers();

        //add the new pins
        var updateMarkerBindings = this.updateMarkerBindings;
        var markerArray = this.filteredModel.map(function (m) {
          var place = appState.places.get(m.get('place_id'));
          return L.marker({lat:place.get('lat'), lng:place.get('lng')})
            .bindPopup('' + place.get('place_name') + '
' +
            '' + moment(m.get('time_from')).tz('Europe/Prague').format('H:mm') + ' - ' + moment(m.get('time_to')).tz('Europe/Prague').format('H:mm') + '
' +
            'upravit ', {closeButton:false})
            .on('popupopen', updateMarkerBindings);
        });
        this.markerLayerGroup = L.layerGroup(markerArray).addTo(map);

        return this;
      },
      showLoading:function () {
        $('#loading').show();
      },
      removeMarkers:function () {
        if (this.markerLayerGroup) {
          //clear the current pins
          map.removeLayer(this.markerLayerGroup);
          this.markerLayerGroup = null;
        }
      },
      // updates collection of shown models by filtering date and location
      updateFilter:function () {
        this.filteredModel.reset(this.model.filter(function (m) {
          // return containers for current day
          return moment(m.get('time_from')).isSame(appState.filterDate.get('filter_date'), 'day') &&
            // which are not yet removed
            moment().isBefore(m.get('time_to')) &&
            // and with location specified
            appState.places.get(m.get('place_id')).hasLocation();
        }));
      },
      updateMarkerBindings:function () {
        $('#movePlaceButton').click(this.movePlace);
      },
      movePlace:function (evt) {
        // find related model
        var model = appState.places.findWhere({place_name:$(evt.target).siblings().first().text()});
        // show the localization marker on the map
        var view = new GeoLocatePlace({model:model}).render();

        return evt.preventDefault();
      }
    }),

    // view controls filtering of containers by day
    ContainerFilter = Backbone.View.extend({
      initialize:function () {
        _.bindAll(this, 'render', 'setPrev', 'setNext', 'enableFilter', 'disableFilter');

        this.model.on('change', this.render);
        this.disabled = false;

        // create menu items and register callbacks
        $('

')
          .click(this.setPrev)
          .appendTo(this.$el);
        this.$el.append('

');
        $('

')
          .click(this.setNext)
          .appendTo(this.$el);

        // disable / enable filter on unknown place location
        vent.on('geoLocatePlace:placementStarted', this.disableFilter);
        vent.on('geoLocatePlace:placementCanceled', this.enableFilter);
        vent.on('geoLocatePlace:placementFinished', this.enableFilter);

        // customize moment.js to show days only (not time) in calendar()
        moment.lang('cs', {
          'calendar':{
            sameDay:"[dnes]",
            nextDay:'[zítra]',
            nextWeek:function () {
              switch (this.day()) {
                case 0:
                  return '[v neděli]';
                case 1:
                case 2:
                  return '[v] dddd';
                case 3:
                  return '[ve středu]';
                case 4:
                  return '[ve čtvrtek]';
                case 5:
                  return '[v pátek]';
                case 6:
                  return '[v sobotu]';
              }
            },
            lastDay:'[včera]',
            lastWeek:function () {
              switch (this.day()) {
                case 0:
                  return '[minulou neděli]';
                case 1:
                case 2:
                  return '[minulé] dddd';
                case 3:
                  return '[minulou středu]';
                case 4:
                case 5:
                  return '[minulý] dddd';
                case 6:
                  return '[minulou sobotu]';
              }
            },
            sameElse:"L"
          }
        });
      },
      render:function () {
        this.$('.navbar-text').text(this.model.get('filter_date').calendar());
        return this;
      },
      setPrev:function (e) {
        if (!this.disabled) {
          // update filter day
          if (moment().isBefore(this.model.get('filter_date'), 'day')) {
            // subtract one day from filter day
            this.model.set('filter_date', moment(this.model.get('filter_date')).subtract('days', 1));
          }

          // update button visibility
          if (!moment().isBefore(this.model.get('filter_date'), 'day')) {
            this.$('.container-filter-prev').addClass('disabled');
          }
        }

        return e.preventDefault();
      },
      setNext:function (e) {
        if (!this.disabled) {
          if (moment().isSame(this.model.get('filter_date'), 'day')) {
            // if filter day is today enable back button
            this.$('.container-filter-prev').removeClass('disabled');
          }
          this.model.set('filter_date', moment(this.model.get('filter_date')).add('days', 1));
        }

        return e.preventDefault();
      },
      // function enables filter buttons
      enableFilter:function () {
        this.disabled = false;
        // check if Prev button can be enabled
        if (moment().isBefore(this.model.get('filter_date'), 'day')) {
          this.$('.container-filter-prev').removeClass('disabled');
        }
        // enable Next button
        this.$('.container-filter-next').removeClass('disabled');
      },
      // function disables filter buttons
      disableFilter:function () {
        this.disabled = true;
        this.$('.container-filter-prev').addClass('disabled');
        this.$('.container-filter-next').addClass('disabled');
      }
    })
  ;

  return {
    GeoLocatePlace: GeoLocatePlace,
    UnknownPlaces: UnknownPlaces,
    Containers: Containers,
    ContainerFilter: ContainerFilter
  };

});<|endoftext|>


<commit_before>
	game.GameTimerManager = Object.extend({
		init: function(x, y, settings) {
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();
		this.paused = false;
		this.alwaysUpdate = true;
	},
			update: function(){
				this.now = new Date().getTime();
				this.goldTimerCheck();
				this.creepTimerCheck();

				return true;
			},

			goldTimerCheck: function(){
					if(Math.round(this.now/1000) % 20 ===0 && (this.now - this.lastCreep >= 1000)){
					game.data.gold += (game.data.exp1+1);
					console.log("Current gold: " + game.data.gold);
				}
			},

			creepTimerCheck: function(){
				if(Math.round(this.now/1000) % 10 ===0 && (this.now - this.lastCreep >= 1000)){
					this.lastCreep = this.now;
					var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
					me.game.world.addChild(creepe, 5);
				}
			}

	});

	game.HeroDeathManager = Object.extend({
		init: function(x, y, settings){
			this.alwaysUpdate = true;
		},

		update: function(){
					if(game.data.player.dead){
					me.game.world.removeChild(game.data.player);
					me.state.current().resetPlayer(10, 0);
				}
				return true;
		}
	});

	game.ExperienceManager = Object.extend({
		init: function(x, y, settings){
			this.alwaysUpdate = true;
			this.gameover = false;
		},

		update: function(){
			if (game.data.win === true && !this.gameover){
				this.gameOver(true);
			}else if(game.data.win === false && !this.gameover){

				this.gameOver(false);
			}

			return true;
		},

		gameOver: function(win){
			if (win){
				game.data.exp += 10;
			}else{
				game.data.exp += 1;
			}
			console.log(game.data.exp);
			this.gameover = true;
			me.save.exp = game.data.exp;
			me.save.exp2 = 4;
		}

	});

	game.SpendGold = Object.extend({
		init: function(x, y, settings){
			this.now = new Date().getTime();
			this.lastBuy = new Date().getTime();
			this.paused = false;
			this.alwaysUpdate = true;
			this.updateWhenPaused = true;
			this.buying = false;
		},

		update: function(){
			this.now = new Date().getTime();

			if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >=1000){
				this.lastBuy = this.now;
				if(!this.buying){
					this.startBuying();

			}else{
				this.stopBuying();

			}
		}
			return true;
		},

		startBuying: function(){
			this.buying = true;
			game.data.pausePos = me.game.viewport.localToWorld(0, 0);
			game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
			game.data.buyscreen.updateWhenPaused=true;
			game.data.buyscreen.setOpacity(0.8);
			me.game.world.addChild(game.data.buyscreen, 34);
			game.data.player.body.setVelocity(0, 0);
			me.state.pause(me.state.PLAY);
			me.input.bindKey(me.input.KEY.F1, "F1", true);
			me.input.bindKey(me.input.KEY.F2, "F2", true);
			me.input.bindKey(me.input.KEY.F3, "F3", true);
			me.input.bindKey(me.input.KEY.F4, "F4", true);
			me.input.bindKey(me.input.KEY.F5, "F5", true);
			me.input.bindKey(me.input.KEY.F6, "F6", true);
			this.setBuyText();
		},

		setBuyText: function(){
		 game.data.buytext = new (me.Renderable.extend({

		 	init: function(){
		 		console.log("init");
		 		this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]);
		 		this.font = new me.Font("Arial", 26, "white");
		 		this.updateWhenPaused = true;
		 		this.alwaysUpdate = true;
		 	},

		 	draw: function(renderer){
		 		this.font.draw(renderer.getContext(), "PRESS F1-F6 to buy, F5 TO BUY, B TO EXIT. Current Gold: " + game.data.gold, this.pos.x, this.pos.y);
		 		this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + " Cost: " + ((game.data.skill1+1)*10), this.pos.x, this.pos.y + 40);
		 		this.font.draw(renderer.getContext(), "Skill 2: Run Faster! Current Level: " + game.data.skill2 + " Cost: " + ((game.data.skill2+1)*10), this.pos.x, this.pos.y + 80);
		 		this.font.draw(renderer.getContext(), "Skill 3: Increase Health. Current Level: " + game.data.skill3 + " Cost: " + ((game.data.skill3+1)*10), this.pos.x, this.pos.y + 120);
		 		this.font.draw(renderer.getContext(), "Q Ability: Speed Burst. Current Level: " + game.data.ability1 + " Cost: " + ((game.data.ability1+1)*10), this.pos.x, this.pos.y + 160);
		 		this.font.draw(renderer.getContext(), "W Ability: Eat Your Creep For Health: " + game.data.ability2 + " Cost: " + ((game.data.ability2+1)*10), this.pos.x, this.pos.y + 200);
		 		this.font.draw(renderer.getContext(), "E Ability: Throw Your Spear: " + game.data.ability3 + " Cost: " + ((game.data.ability3+1)*10), this.pos.x, this.pos.y + 240);
		 	},

		 }));
me.game.world.addChild(game.data.buytext, 35);
		},

		stopBuying: function(){
			this.buying = false;
			me.state.resume(me.state.PLAY);
			game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
			me.game.world.removeChild(game.data.buyscreen);
			me.input.unbindKey(me.input.KEY.F1, "F1", true);
			me.input.unbindKey(me.input.KEY.F2, "F2", true);
			me.input.unbindKey(me.input.KEY.F3, "F3", true);
			me.input.unbindKey(me.input.KEY.F4, "F4", true);
			me.input.unbindKey(me.input.KEY.F5, "F5", true);
			me.input.unbindKey(me.input.KEY.F6, "F6", true);
			me.game.world.removeChild(game.data.buytext);

		}

	});

<commit_msg>video 50 making skills and abilitys for the player<commit_after>
	game.GameTimerManager = Object.extend({
		init: function(x, y, settings) {
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();
		this.paused = false;
		this.alwaysUpdate = true;
	},
			update: function(){
				this.now = new Date().getTime();
				this.goldTimerCheck();
				this.creepTimerCheck();

				return true;
			},

			goldTimerCheck: function(){
					if(Math.round(this.now/1000) % 20 ===0 && (this.now - this.lastCreep >= 1000)){
					game.data.gold += (game.data.exp1+1);
					console.log("Current gold: " + game.data.gold);
				}
			},

			creepTimerCheck: function(){
				if(Math.round(this.now/1000) % 10 ===0 && (this.now - this.lastCreep >= 1000)){
					this.lastCreep = this.now;
					var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
					me.game.world.addChild(creepe, 5);
				}
			}

	});

	game.HeroDeathManager = Object.extend({
		init: function(x, y, settings){
			this.alwaysUpdate = true;
		},

		update: function(){
					if(game.data.player.dead){
					me.game.world.removeChild(game.data.player);
					me.state.current().resetPlayer(10, 0);
				}
				return true;
		}
	});

	game.ExperienceManager = Object.extend({
		init: function(x, y, settings){
			this.alwaysUpdate = true;
			this.gameover = false;
		},

		update: function(){
			if (game.data.win === true && !this.gameover){
				this.gameOver(true);
			}else if(game.data.win === false && !this.gameover){

				this.gameOver(false);
			}

			return true;
		},

		gameOver: function(win){
			if (win){
				game.data.exp += 10;
			}else{
				game.data.exp += 1;
			}
			console.log(game.data.exp);
			this.gameover = true;
			me.save.exp = game.data.exp;
			me.save.exp2 = 4;
		}

	});

	game.SpendGold = Object.extend({
		init: function(x, y, settings){
			this.now = new Date().getTime();
			this.lastBuy = new Date().getTime();
			this.paused = false;
			this.alwaysUpdate = true;
			this.updateWhenPaused = true;
			this.buying = false;
		},

		update: function(){
			this.now = new Date().getTime();

			if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >=1000){
				this.lastBuy = this.now;
				if(!this.buying){
					this.startBuying();

			}else{
				this.stopBuying();

			}
		}
			this.checkBuyKeys();

			return true;
		},

		startBuying: function(){
			this.buying = true;
			game.data.pausePos = me.game.viewport.localToWorld(0, 0);
			game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
			game.data.buyscreen.updateWhenPaused=true;
			game.data.buyscreen.setOpacity(0.8);
			me.game.world.addChild(game.data.buyscreen, 34);
			game.data.player.body.setVelocity(0, 0);
			me.state.pause(me.state.PLAY);
			me.input.bindKey(me.input.KEY.F1, "F1", true);
			me.input.bindKey(me.input.KEY.F2, "F2", true);
			me.input.bindKey(me.input.KEY.F3, "F3", true);
			me.input.bindKey(me.input.KEY.F4, "F4", true);
			me.input.bindKey(me.input.KEY.F5, "F5", true);
			me.input.bindKey(me.input.KEY.F6, "F6", true);
			this.setBuyText();
		},

		setBuyText: function(){
		 game.data.buytext = new (me.Renderable.extend({

		 	init: function(){
		 		console.log("init");
		 		this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]);
		 		this.font = new me.Font("Arial", 26, "white");
		 		this.updateWhenPaused = true;
		 		this.alwaysUpdate = true;
		 	},

		 	draw: function(renderer){
		 		this.font.draw(renderer.getContext(), "PRESS F1-F6 to buy, F5 TO BUY, B TO EXIT. Current Gold: " + game.data.gold, this.pos.x, this.pos.y);
		 		this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + " Cost: " + ((game.data.skill1+1)*10), this.pos.x, this.pos.y + 40);
		 		this.font.draw(renderer.getContext(), "Skill 2: Run Faster! Current Level: " + game.data.skill2 + " Cost: " + ((game.data.skill2+1)*10), this.pos.x, this.pos.y + 80);
		 		this.font.draw(renderer.getContext(), "Skill 3: Increase Health. Current Level: " + game.data.skill3 + " Cost: " + ((game.data.skill3+1)*10), this.pos.x, this.pos.y + 120);
		 		this.font.draw(renderer.getContext(), "Q Ability: Speed Burst. Current Level: " + game.data.ability1 + " Cost: " + ((game.data.ability1+1)*10), this.pos.x, this.pos.y + 160);
		 		this.font.draw(renderer.getContext(), "W Ability: Eat Your Creep For Health: " + game.data.ability2 + " Cost: " + ((game.data.ability2+1)*10), this.pos.x, this.pos.y + 200);
		 		this.font.draw(renderer.getContext(), "E Ability: Throw Your Spear: " + game.data.ability3 + " Cost: " + ((game.data.ability3+1)*10), this.pos.x, this.pos.y + 240);
		 	},

		 }));
me.game.world.addChild(game.data.buytext, 35);
		},

		stopBuying: function(){
			this.buying = false;
			me.state.resume(me.state.PLAY);
			game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
			me.game.world.removeChild(game.data.buyscreen);
			me.input.unbindKey(me.input.KEY.F1, "F1", true);
			me.input.unbindKey(me.input.KEY.F2, "F2", true);
			me.input.unbindKey(me.input.KEY.F3, "F3", true);
			me.input.unbindKey(me.input.KEY.F4, "F4", true);
			me.input.unbindKey(me.input.KEY.F5, "F5", true);
			me.input.unbindKey(me.input.KEY.F6, "F6", true);
			me.game.world.removeChild(game.data.buytext);

		},

		checkBuyKeys: function(){
			if(me.input.isKeyPressed("F1")){
				if(this.checkCost(1)){
					this.makePurchase(1);
				}
			}else if(me.input.isKeyPressed("F2")){
				if(this.checkCost(2)){
					this.makePurchase(2);
				}
			}else if(me.input.isKeyPressed("F3")){
				if(this.checkCost(3)){
					this.makePurchase(3);
				}
			}else if(me.input.isKeyPressed("F4")){
				if(this.checkCost(4)){
					this.makePurchase(4);
				}
			}else if(me.input.isKeyPressed("F5")){
				if(this.checkCost(5)){
					this.makePurchase(5);
				}
			}else if(me.input.isKeyPressed("F6")){
				if(this.checkCost(6)){
					this.makePurchase(6);
				}
			}
		},

		checkCost: function(skill1){
			if(skill===1 && (game.data.gold >= ((game.data.skill1+1)*10))){
				return true;
			}		else if(skill===2 && (game.data.gold >= ((game.data.skill2+1)*10))){
				return true;
			}		else if(skill===3 && (game.data.gold >= ((game.data.skill3+1)*10))){
				return true;
			}			  else if(skill===4 && (game.data.gold >= ((game.data.ability1+1)*10))){
				return true;
			}		else if(skill===5 && (game.data.gold >= ((game.data.ability2+1)*10))){
				return true;
			}			else if(skill===6 && (game.data.gold >= ((game.data.ability3+1)*10))){
				return true;
			}else{
				return false;
			}
		},

		makePurchase: function(skill){
			if(skill === 1){
			game.data.gold -= ((game.data.skill1 +1)* 10);
			game.data.skill1 += 1;
			game.data.playerAttack += 1;
		}else if(skill ===2){
			game.data.gold -= ((game.data.skill2 +1)* 10);
			game.data.skill2 += 1;
		}else if(skill ===3){
			game.data.gold -= ((game.data.skill3 +1)* 10);
			game.data.skill3 += 1;
		}else if(skill ===4){
			game.data.gold -= ((game.data.ability1 +1)* 10);
			game.data.ability1 += 1;
		}else if(skill ===5){
			game.data.gold -= ((game.data.ability2 +1)* 10);
			game.data.ability2 += 1;
		}else if(skill ===6){
			game.data.gold -= ((game.data.ability3 +1)* 10);
			game.data.ability3 += 1;
		}
	  }

	});

<|endoftext|>


<commit_before>game.GameTimerManager = Object.extend({
	init: function(x,y,settings){
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();
		this.paused = false;
		this.alwaysUpdate = true;
	},

	update: function (){
		this.now = new Date().getTime();
		this.goldTimerCheck();
		this.creepTimerCheck();

		return true;
	},

	goldTimerCheck: function(){
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
			game.data.gold += 1;

		}
	},

	creepTimerCheck: function(){
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
			this.lastCreep = this.now;
			var creepe = me.pool.pull("EnemyCreep", 1000, 0,{});
				me.game.world.addChild(creepe, 5);
		}
	}
});

game.HeroDeathManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;
	},

	update: function(){
		if(game.data.player.dead) {
			me.game.world.removeChild(game.data.player);
			me.state.current().resetPlayer(10,0);
		}

		return true;
	}
});

game.ExperienceManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;
		this.gameover = false;
	},
	update: function(){
		if(game.data.win === true && !this.gameOver){
			this.gameOver(true);
		}else if (game.data.win === false && !this.gameOver) {
			this.gameOver = false;
		}

		return true;
	},

	gameOver: function(win){
		if(win){
			game.data.exp += 10;
		}
		else{
			game.data.exp += 1;
		}
		this.gameover = true;
		me.save.exp = game.data.exp;
	}
});

game.SpendGold = Object.extend({
	init: function(x,y,settings){
		this.now = new Date().getTime();
		this.lastBuy = new Date().getTime();
		this.paused = false;
		this.alwaysUpdate = true;
	},

	update: function(){
		return true;
	}
});
<commit_msg>VIDEO 47 woot got that extra credit thoe<commit_after>game.GameTimerManager = Object.extend({
	init: function(x,y,settings){
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();
		this.paused = false;
		this.alwaysUpdate = true;
	},

	update: function (){
		this.now = new Date().getTime();
		this.goldTimerCheck();
		this.creepTimerCheck();

		return true;
	},

	goldTimerCheck: function(){
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
			game.data.gold += 1;

		}
	},

	creepTimerCheck: function(){
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
			this.lastCreep = this.now;
			var creepe = me.pool.pull("EnemyCreep", 1000, 0,{});
				me.game.world.addChild(creepe, 5);
		}
	}
});

game.HeroDeathManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;
	},

	update: function(){
		if(game.data.player.dead) {
			me.game.world.removeChild(game.data.player);
			me.state.current().resetPlayer(10,0);
		}

		return true;
	}
});

game.ExperienceManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;
		this.gameover = false;
	},
	update: function(){
		if(game.data.win === true && !this.gameOver){
			this.gameOver(true);
		}else if (game.data.win === false && !this.gameOver) {
			this.gameOver = false;
		}

		return true;
	},

	gameOver: function(win){
		if(win){
			game.data.exp += 10;
		}
		else{
			game.data.exp += 1;
		}
		this.gameover = true;
		me.save.exp = game.data.exp;
	}
});

game.SpendGold = Object.extend({
	init: function(x,y,settings){
		this.now = new Date().getTime();
		this.lastBuy = new Date().getTime();
		this.paused = false;
		this.alwaysUpdate = true;
		this.updateWhenPaused = true;
		this.buying = false;
	},

	update: function(){
		this.now = new Date().getTime();
		if(me.input.isKeyPressed("buy") && this.now - this.lastBuy >=1000){
			this.lastBuy = this.now;
			if(!this.buying){
				this.startBuying();
			}else{
				this.stopBuying();
			}

		}

		return true;
	},
	startBuying: function(){
		this.buying = true;
		me.state.pause(me.state.Play);
		game.data.pausePos = me.game.viewport.localToWorld(0,0);
		game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
		game.data.buyscreen.updateWhenPaused = true;
		game.data.buyscreen.setOpacity(0.8);
		me.game.world.addChild(game.data.buyscreen, 34);
		game.data.player.body.setVelocity(0,0);
	},

	stopBuying: function(){
		this.buying = false;
		me.state.resume(me.state.PLAY);
		game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
		me.game.world.removeChild(game.data.buyscreen);
	}
});
<|endoftext|>


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

CLASS({
  name: 'LeafDataView',
  package: 'foam.ui',
  extendsModel: 'foam.patterns.ChildTreeTrait',

  documentation: function() {/* For Views that use $$DOC{ref:'.data'},
    but do not pass it along to any children, use this trait.
  */},

  imports: ['data$ as dataImport$'],

  properties: [
    {
      name: 'dataImport',
      documentation: function() {/* Handles the incoming data from the import
        context, and may be ignored if data is directly set. */},
      postSet: function(old, nu) {
        if ( this.isImportEnabled_ && ! equals(this.data, nu) ) {
          this.isContextChange_ = true;
          this.data = nu;
          this.isContextChange_ = false;
        }
      }
    },
    {
      name: 'data',
      documentation: function() {/* The actual data used by the view. May be set
        directly to override the context import. Children will see changes to this
        data through the context. Override $$DOC{ref:'.onDataChange'}
        instead of using a postSet here. */},
      postSet: function(old, nu) {
        this.onDataChange(old, nu);
      }
    },
    {
      model_: 'BooleanProperty',
      name: 'isContextChange_',
      defaultValue: false,
      transient: true,
      hidden: true
    },
    {
      model_: 'BooleanProperty',
      name: 'isImportEnabled_',
      defaultValue: true,
      hidden: true
    },

  ],

  methods: {
    onDataChange: function(old, nu) { /* React to a change to $$DOC{ref:'.data'}.
      Don't forget to call this.SUPER(old,nu) in your implementation. */
      this.isImportEnabled_ = this.isImportEnabled_ && this.isContextChange_;
      if ( this.isImportEnabled_ && !equals(this.dataImport, nu) ) {
        this.dataImport = nu;
      }
    },
  }

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

CLASS({
  name: 'LeafDataView',
  package: 'foam.ui',
  extendsModel: 'foam.patterns.ChildTreeTrait',

  documentation: function() {/* For Views that use $$DOC{ref:'.data'},
    but do not pass it along to any children, use this trait.
  */},

  imports: ['data$'],

  properties: [
    {
      name: 'data',
      documentation: function() {/* The actual data used by the view. May be set
        directly to override the context import. Children will see changes to this
        data through the context. Override $$DOC{ref:'.onDataChange'}
        instead of using a postSet here. */},
      postSet: function(old, nu) {
        this.onDataChange(old, nu);
      }
    }
  ],

  methods: {
    onDataChange: function(old, nu) { /* React to a change to $$DOC{ref:'.data'}.
      Don't forget to call this.SUPER(old,nu) in your implementation. */
    }
  }

});
<|endoftext|>


<commit_before>$(document).ready(function(){
  setTimeout(function(){
    $('.results-table h4').each(function(i){
      function getText(file,self) {
        $.ajax({
          url : file,
          context: self,
          dataType: "text",
          success : function (data) {
            self.parent().find(".text").html(data);
          }
        })
      }
      if ($(this).html().includes('User Agent')) {
        var filename = '/static/results-text/user-agent.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('HTTP_ACCEPT Headers')) {
        var filename = '/static/results-text/http-accept-headers.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Browser Plugin')) {
        var filename = '/static/results-text/browser-plugin-details.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('AudioContext')) {
        var filename = '/static/results-text/audiocontext.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Cookies Enabled')) {
        var filename = '/static/results-text/cookies-enabled.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Device Memory')) {
        var filename = '/static/results-text/device-memory.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('DNT Header')) {
        var filename = '/static/results-text/dnt-header.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Hardware Concurrency')) {
        var filename = '/static/results-text/hardware-concurrency.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Hash of canvas fingerprint')) {
        var filename = '/static/results-text/hash-of-canvas.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Hash of WebGL fingerprint')) {
        var filename = '/static/results-text/hash-of-webgl.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Limited supercookie ')) {
        var filename = '/static/results-text/limited-super-cookie.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Platform')) {
        var filename = '/static/results-text/platform.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Screen Size')) {
        var filename = '/static/results-text/screen-size.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('System Fonts')) {
        var filename = '/static/results-text/system-fonts.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Time Zone')) {
        var filename = '/static/results-text/time-zone.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Time Zone Offset')) {
        var filename = '/static/results-text/time-zone-offset.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Touch Support')) {
        var filename = '/static/results-text/touch-support.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('User Agent')) {
        var filename = '/static/results-text/user-agent.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('WebGL Vendor')) {
        var filename = '/static/results-text/webgl-vendor.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
    });
    $('.detailed').hide();
    $('#default-button').addClass('active');
    $('#default-button').on( 'click', function(e) {
      $('#default-button').addClass('active');
      $('#detailed-button').removeClass('active');
      $('.detailed').hide();
    });
    $('#detailed-button').on( 'click', function(e) {
      $('#detailed-button').addClass('active');
      $('#default-button').removeClass('active');
      $('.detailed').show();
    });
   // smaller phone, make table of contents (see results template)
     $('select').selectmenu({
           'change': function () {
          var val = $( "#characteristic option:selected" ).val();
          console.log('val='+val);
          window.location.href = val;
        }
      });
  }, 2000);

});
<commit_msg>making detailed the "default" view<commit_after>$(document).ready(function(){
  setTimeout(function(){
    $('.results-table h4').each(function(i){
      function getText(file,self) {
        $.ajax({
          url : file,
          context: self,
          dataType: "text",
          success : function (data) {
            self.parent().find(".text").html(data);
          }
        })
      }
      if ($(this).html().includes('User Agent')) {
        var filename = '/static/results-text/user-agent.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('HTTP_ACCEPT Headers')) {
        var filename = '/static/results-text/http-accept-headers.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Browser Plugin')) {
        var filename = '/static/results-text/browser-plugin-details.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('AudioContext')) {
        var filename = '/static/results-text/audiocontext.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Cookies Enabled')) {
        var filename = '/static/results-text/cookies-enabled.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Device Memory')) {
        var filename = '/static/results-text/device-memory.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('DNT Header')) {
        var filename = '/static/results-text/dnt-header.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Hardware Concurrency')) {
        var filename = '/static/results-text/hardware-concurrency.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Hash of canvas fingerprint')) {
        var filename = '/static/results-text/hash-of-canvas.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Hash of WebGL fingerprint')) {
        var filename = '/static/results-text/hash-of-webgl.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Limited supercookie ')) {
        var filename = '/static/results-text/limited-super-cookie.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Platform')) {
        var filename = '/static/results-text/platform.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Screen Size')) {
        var filename = '/static/results-text/screen-size.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('System Fonts')) {
        var filename = '/static/results-text/system-fonts.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Time Zone')) {
        var filename = '/static/results-text/time-zone.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Time Zone Offset')) {
        var filename = '/static/results-text/time-zone-offset.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('Touch Support')) {
        var filename = '/static/results-text/touch-support.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('User Agent')) {
        var filename = '/static/results-text/user-agent.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
      if ($(this).html().includes('WebGL Vendor')) {
        var filename = '/static/results-text/webgl-vendor.txt';
        var selfname = $(this);
        getText(filename, selfname);
      }
    });
    $('#default-button').on( 'click', function(e) {
      $('#default-button').addClass('active');
      $('#detailed-button').removeClass('active');
      $('.detailed').hide();
    });
    $('#detailed-button').addClass('active');
    $('#detailed-button').on( 'click', function(e) {
      $('#detailed-button').addClass('active');
      $('#default-button').removeClass('active');
      $('.detailed').show();
    });
   // smaller phone, make table of contents (see results template)
     $('select').selectmenu({
           'change': function () {
          var val = $( "#characteristic option:selected" ).val();
          console.log('val='+val);
          window.location.href = val;
        }
      });
  }, 2000);

});
<|endoftext|>


<commit_before>/**
 * Accordion module.
 * @module foundation.accordion
 * @requires foundation.util.keyboard
 * @requires foundation.util.animationFrame
 */
!function($) {
  'use strict';

  /**
   * Creates a new instance of an accordion.
   * @class
   * @fires Accordion#init
   * @param {jQuery} element - jQuery object to make into an accordion.
   */
  function Accordion(element, options){
    this.$element = element;
    this.options = $.extend({}, Accordion.defaults, this.$element.data(), options);

    this._init();
    /**
     * Fires when the plugin has been successfuly initialized.
     * @event Accordion#init
     */
    Foundation.registerPlugin(this);
    Foundation.Keyboard.register('Accordion', {
      'ENTER': 'toggle',
      'SPACE': 'toggle',
      'ARROW_DOWN': 'next',
      'ARROW_UP': 'previous'
    });
  }

  Accordion.defaults = {
    slideSpeed: 250,
    multiExpand: false,
    allowAllClosed: false
  };

  /**
   * Initializes the accordion by animating the preset active pane(s).
   * @private
   */
  Accordion.prototype._init = function() {
    this.$element.attr('role', 'tablist');
    this.$tabs = this.$element.children('li');
    this.$tabs.each(function(idx, el){

      var $el = $(el),
          $content = $el.find('[data-tab-content]'),
          id = $content[0].id || Foundation.GetYoDigits(6, 'accordion'),
          linkId = el.id || id + '-label';

      $el.find('a:first').attr({
        'aria-controls': id,
        'role': 'tab',
        'id': linkId,
        'aria-expanded': false,
        'aria-selected': false
      });
      $content.attr({'role': 'tabpanel', 'aria-labelledby': linkId, 'aria-hidden': true, 'id': id});
    });
    var $initActive = this.$element.find('.is-active').children('[data-tab-content]');
    if($initActive.length){
      this.down($initActive, true);
    }
    this._events();
  };

  /**
   * Adds event handlers for items within the accordion.
   * @private
   */
  Accordion.prototype._events = function() {
    var _this = this;

    this.$tabs.each(function(){
      var $elem = $(this);
      var $tabContent = $elem.children('[data-tab-content]');
      if ($tabContent.length) {
        $elem.children('a').off('click.zf.accordion keydown.zf.accordion')
               .on('click.zf.accordion', function(e){
        // $(this).children('a').on('click.zf.accordion', function(e) {
          e.preventDefault();
          if ($elem.hasClass('is-active')) {
            if(_this.options.allowAllClosed || $elem.siblings().hasClass('is-active')){
              _this.up($tabContent);
            }
          }
          else {
            _this.down($tabContent);
          }
        }).on('keydown.zf.accordion', function(e){
          Foundation.Keyboard.handleKey(e, _this, {
            toggle: function() {
              _this.toggle($tabContent);
            },
            next: function() {
              $elem.next().find('a').focus().trigger('click.zf.accordion');
            },
            previous: function() {
              $elem.prev().find('a').focus().trigger('click.zf.accordion');
            },
            handled: function() {
              e.preventDefault();
              e.stopPropagation();
            }
          });
        });
      }
    });
  };
  Accordion.prototype.toggle = function($target){
    if($target.parent().hasClass('is-active')){
      if(this.options.allowAllClosed || $target.parent().siblings().hasClass('is-active')){
        this.up($target);
      }else{ return; }
    }else{
      this.down($target);
    }
  };
  /**
   * Opens the accordion tab defined by `$target`.
   * @param {jQuery} $target - Accordion tab to open.
   * @fires Accordion#down
   */
  Accordion.prototype.down = function($target, firstTime) {
    var _this = this;
    if(!this.options.multiExpand && !firstTime){
      var $currentActive = this.$element.find('.is-active').children('[data-tab-content]');
      if($currentActive.length){
        this.up($currentActive);
      }
    }

    $target
      .attr('aria-hidden', false)
      .parent('[data-tab-content]')
      .addBack()
      .parent().addClass('is-active');

    Foundation.Move(_this.options.slideSpeed, $target, function(){
      $target.slideDown(_this.options.slideSpeed);
    });

    if(!firstTime){
      Foundation._reflow(this.$element.attr('data-accordion'));
    }
    $('#' + $target.attr('aria-labelledby')).attr({
      'aria-expanded': true,
      'aria-selected': true
    })
    /**
     * Fires when the tab is done opening.
     * @event Accordion#down
     */
    this.$element.trigger('down.zf.accordion', [$target]);
  };

  /**
   * Closes the tab defined by `$target`.
   * @param {jQuery} $target - Accordion tab to close.
   * @fires Accordion#up
   */
  Accordion.prototype.up = function($target) {
    var $aunts = $target.parent().siblings(),
        _this = this;
    var canClose = this.options.multiExpand ? $aunts.hasClass('is-active') : $target.parent().hasClass('is-active');

    if(!this.options.allowAllClosed && !canClose){
      return;
    }

    Foundation.Move(this.options.slideSpeed, $target, function(){
      $target.slideUp(_this.options.slideSpeed)
    });

    $target.attr('aria-hidden', true)
           .parent().removeClass('is-active');

    $('#' + $target.attr('aria-labelledby')).attr({
     'aria-expanded': false,
     'aria-selected': false
    })

    /**
     * Fires when the tab is done collapsing up.
     * @event Accordion#up
     */
    this.$element.trigger('up.zf.accordion', [$target]);
  };

  /**
   * Destroys an instance of an accordion.
   * @fires Accordion#destroyed
   */
  Accordion.prototype.destroy = function() {
    this.$element.find('[data-tab-content]').slideUp(0).css('display', '');
    this.$element.find('a').off('.zf.accordion');

    /**
     * Fires when the plugin has been destroyed.
     * @event Accordion#destroyed
     */
    // this.$element.trigger('destroyed.zf.accordion');
    Foundation.unregisterPlugin(this);
  }

  Foundation.plugin(Accordion);
}(jQuery);
<commit_msg>adds missing ; to accordion<commit_after>/**
 * Accordion module.
 * @module foundation.accordion
 * @requires foundation.util.keyboard
 * @requires foundation.util.animationFrame
 */
!function($) {
  'use strict';

  /**
   * Creates a new instance of an accordion.
   * @class
   * @fires Accordion#init
   * @param {jQuery} element - jQuery object to make into an accordion.
   */
  function Accordion(element, options){
    this.$element = element;
    this.options = $.extend({}, Accordion.defaults, this.$element.data(), options);

    this._init();
    /**
     * Fires when the plugin has been successfuly initialized.
     * @event Accordion#init
     */
    Foundation.registerPlugin(this);
    Foundation.Keyboard.register('Accordion', {
      'ENTER': 'toggle',
      'SPACE': 'toggle',
      'ARROW_DOWN': 'next',
      'ARROW_UP': 'previous'
    });
  }

  Accordion.defaults = {
    slideSpeed: 250,
    multiExpand: false,
    allowAllClosed: false
  };

  /**
   * Initializes the accordion by animating the preset active pane(s).
   * @private
   */
  Accordion.prototype._init = function() {
    this.$element.attr('role', 'tablist');
    this.$tabs = this.$element.children('li');
    this.$tabs.each(function(idx, el){

      var $el = $(el),
          $content = $el.find('[data-tab-content]'),
          id = $content[0].id || Foundation.GetYoDigits(6, 'accordion'),
          linkId = el.id || id + '-label';

      $el.find('a:first').attr({
        'aria-controls': id,
        'role': 'tab',
        'id': linkId,
        'aria-expanded': false,
        'aria-selected': false
      });
      $content.attr({'role': 'tabpanel', 'aria-labelledby': linkId, 'aria-hidden': true, 'id': id});
    });
    var $initActive = this.$element.find('.is-active').children('[data-tab-content]');
    if($initActive.length){
      this.down($initActive, true);
    }
    this._events();
  };

  /**
   * Adds event handlers for items within the accordion.
   * @private
   */
  Accordion.prototype._events = function() {
    var _this = this;

    this.$tabs.each(function(){
      var $elem = $(this);
      var $tabContent = $elem.children('[data-tab-content]');
      if ($tabContent.length) {
        $elem.children('a').off('click.zf.accordion keydown.zf.accordion')
               .on('click.zf.accordion', function(e){
        // $(this).children('a').on('click.zf.accordion', function(e) {
          e.preventDefault();
          if ($elem.hasClass('is-active')) {
            if(_this.options.allowAllClosed || $elem.siblings().hasClass('is-active')){
              _this.up($tabContent);
            }
          }
          else {
            _this.down($tabContent);
          }
        }).on('keydown.zf.accordion', function(e){
          Foundation.Keyboard.handleKey(e, _this, {
            toggle: function() {
              _this.toggle($tabContent);
            },
            next: function() {
              $elem.next().find('a').focus().trigger('click.zf.accordion');
            },
            previous: function() {
              $elem.prev().find('a').focus().trigger('click.zf.accordion');
            },
            handled: function() {
              e.preventDefault();
              e.stopPropagation();
            }
          });
        });
      }
    });
  };
  Accordion.prototype.toggle = function($target){
    if($target.parent().hasClass('is-active')){
      if(this.options.allowAllClosed || $target.parent().siblings().hasClass('is-active')){
        this.up($target);
      }else{ return; }
    }else{
      this.down($target);
    }
  };
  /**
   * Opens the accordion tab defined by `$target`.
   * @param {jQuery} $target - Accordion tab to open.
   * @fires Accordion#down
   */
  Accordion.prototype.down = function($target, firstTime) {
    var _this = this;
    if(!this.options.multiExpand && !firstTime){
      var $currentActive = this.$element.find('.is-active').children('[data-tab-content]');
      if($currentActive.length){
        this.up($currentActive);
      }
    }

    $target
      .attr('aria-hidden', false)
      .parent('[data-tab-content]')
      .addBack()
      .parent().addClass('is-active');

    Foundation.Move(_this.options.slideSpeed, $target, function(){
      $target.slideDown(_this.options.slideSpeed);
    });

    if(!firstTime){
      Foundation._reflow(this.$element.attr('data-accordion'));
    }
    $('#' + $target.attr('aria-labelledby')).attr({
      'aria-expanded': true,
      'aria-selected': true
    });
    /**
     * Fires when the tab is done opening.
     * @event Accordion#down
     */
    this.$element.trigger('down.zf.accordion', [$target]);
  };

  /**
   * Closes the tab defined by `$target`.
   * @param {jQuery} $target - Accordion tab to close.
   * @fires Accordion#up
   */
  Accordion.prototype.up = function($target) {
    var $aunts = $target.parent().siblings(),
        _this = this;
    var canClose = this.options.multiExpand ? $aunts.hasClass('is-active') : $target.parent().hasClass('is-active');

    if(!this.options.allowAllClosed && !canClose){
      return;
    }

    Foundation.Move(this.options.slideSpeed, $target, function(){
      $target.slideUp(_this.options.slideSpeed);
    });

    $target.attr('aria-hidden', true)
           .parent().removeClass('is-active');

    $('#' + $target.attr('aria-labelledby')).attr({
     'aria-expanded': false,
     'aria-selected': false
   });

    /**
     * Fires when the tab is done collapsing up.
     * @event Accordion#up
     */
    this.$element.trigger('up.zf.accordion', [$target]);
  };

  /**
   * Destroys an instance of an accordion.
   * @fires Accordion#destroyed
   */
  Accordion.prototype.destroy = function() {
    this.$element.find('[data-tab-content]').slideUp(0).css('display', '');
    this.$element.find('a').off('.zf.accordion');

    /**
     * Fires when the plugin has been destroyed.
     * @event Accordion#destroyed
     */
    // this.$element.trigger('destroyed.zf.accordion');
    Foundation.unregisterPlugin(this);
  };

  Foundation.plugin(Accordion);
}(jQuery);
<|endoftext|>


<commit_before>import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import moment from 'moment';

moduleForComponent( 'sl-date-time', 'Unit - component: sl-date-time' );

test( 'Default class names are present', function( assert ) {
    this.subject({ timezone: 'America/Chicago' });

    assert.ok(
        this.$().hasClass( 'sl-datetime' ),
        'Default rendered component has class "sl-datetime"'
    );
});

test( 'Attribute "datetime" is properly set', function( assert ) {
    this.subject({
        timezone : 'America/Chicago',
        value    : new Date( 2015, 0, 1 )
    });

    assert.equal(
        this.$().attr( 'datetime' ),
        '2015-01-01 00:00 CST',
        '"datetime" attribute is expected value'
    );
});

test( 'Format "date" results in correctly formatted value', function( assert ) {
    var formattedValue = '2015-01-01',
        component      = this.subject({
            format   : 'date',
            timezone : 'America/Chicago',
            value    : new Date( 2015, 0, 1 )
        });

    assert.equal(
        component.get( 'formattedValue' ),
        formattedValue,
        '"date" formatted date is expected value'
    );

    assert.equal(
        Ember.$.trim( this.$().text() ),
        formattedValue,
        'Rendered component text is expected formatted value'
    );
});

test( 'Format "relative" results in correctly formatted value', function( assert ) {
    var formattedValue = 'a year ago',
        component      = this.subject({
            format   : 'relative',
            timezone : 'America/Chicago',
            value    : moment().subtract( 1, 'year' )
        });

    assert.equal(
        component.get( 'formattedValue' ),
        formattedValue,
        '"relative" formatted date is expected value'
    );

    assert.equal(
        Ember.$.trim( this.$().text() ),
        formattedValue,
        'Rendered component text is expected formatted value'
    );
});

test( 'Format "datetime" results in correctly formatted value', function( assert ) {
    var formattedValue = 'Thursday, January 1st 2015, 12:00 AM CST',
        component      = this.subject({
            format   : 'datetime',
            timezone : 'America/Chicago',
            value    : new Date( 2015, 0, 1 )
        });

    assert.equal(
        component.get( 'formattedValue' ),
        formattedValue,
        '"datetime" formatted date is expected value'
    );

    assert.equal(
        Ember.$.trim( this.$().text() ),
        formattedValue,
        'Rendered component text is expected formatted value'
    );
});

test( 'Computed momentValue is set and updated correctly', function( assert ) {
    var component = this.subject({
        timezone : 'America/Chicago',
        value    : new Date( 2015, 0, 1 )
    });

    assert.equal(
        component.get( 'momentValue' ).calendar(),
        '01/01/2015',
        'Initial momentValue is expected value'
    );

    Ember.run( () => {
        component.set( 'value', new Date( 2015, 1, 15 ) );
    });
    assert.equal(
        component.get( 'momentValue' ).calendar(),
        '02/15/2015',
        'Updated momentValue is expected value'
    );
});

test( 'Computed timezoneString is set and updated correctly', function( assert ) {
    var component = this.subject({
        timezone : 'America/Chicago',
        value    : new Date( 2015, 0, 1 )
    });

    console.log( component.get( 'timezoneString' ) );

    assert.equal(
        component.get( 'timezoneString' ),
        'CST',
        'Initial timezoneString is expected value'
    );

    Ember.run( () => {
        component.set( 'timezone', 'America/Los_Angeles' );
    });
    assert.equal(
        component.get( 'timezoneString' ),
        'PST',
        'Updated timezoneString is expected value'
    );
});

test( '"title" property is an alias to "datetime" value', function( assert ) {
    var component = this.subject({ timezone: 'America/Chicago' });

    assert.equal(
        component.get( 'title' ),
        component.get( 'datetime' ),
        '"title" property is aliased to "datetime" property'
    );
});
<commit_msg>Remove console.log<commit_after>import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import moment from 'moment';

moduleForComponent( 'sl-date-time', 'Unit - component: sl-date-time' );

test( 'Default class names are present', function( assert ) {
    this.subject({ timezone: 'America/Chicago' });

    assert.ok(
        this.$().hasClass( 'sl-datetime' ),
        'Default rendered component has class "sl-datetime"'
    );
});

test( 'Attribute "datetime" is properly set', function( assert ) {
    this.subject({
        timezone : 'America/Chicago',
        value    : new Date( 2015, 0, 1 )
    });

    assert.equal(
        this.$().attr( 'datetime' ),
        '2015-01-01 00:00 CST',
        '"datetime" attribute is expected value'
    );
});

test( 'Format "date" results in correctly formatted value', function( assert ) {
    var formattedValue = '2015-01-01',
        component      = this.subject({
            format   : 'date',
            timezone : 'America/Chicago',
            value    : new Date( 2015, 0, 1 )
        });

    assert.equal(
        component.get( 'formattedValue' ),
        formattedValue,
        '"date" formatted date is expected value'
    );

    assert.equal(
        Ember.$.trim( this.$().text() ),
        formattedValue,
        'Rendered component text is expected formatted value'
    );
});

test( 'Format "relative" results in correctly formatted value', function( assert ) {
    var formattedValue = 'a year ago',
        component      = this.subject({
            format   : 'relative',
            timezone : 'America/Chicago',
            value    : moment().subtract( 1, 'year' )
        });

    assert.equal(
        component.get( 'formattedValue' ),
        formattedValue,
        '"relative" formatted date is expected value'
    );

    assert.equal(
        Ember.$.trim( this.$().text() ),
        formattedValue,
        'Rendered component text is expected formatted value'
    );
});

test( 'Format "datetime" results in correctly formatted value', function( assert ) {
    var formattedValue = 'Thursday, January 1st 2015, 12:00 AM CST',
        component      = this.subject({
            format   : 'datetime',
            timezone : 'America/Chicago',
            value    : new Date( 2015, 0, 1 )
        });

    assert.equal(
        component.get( 'formattedValue' ),
        formattedValue,
        '"datetime" formatted date is expected value'
    );

    assert.equal(
        Ember.$.trim( this.$().text() ),
        formattedValue,
        'Rendered component text is expected formatted value'
    );
});

test( 'Computed momentValue is set and updated correctly', function( assert ) {
    var component = this.subject({
        timezone : 'America/Chicago',
        value    : new Date( 2015, 0, 1 )
    });

    assert.equal(
        component.get( 'momentValue' ).calendar(),
        '01/01/2015',
        'Initial momentValue is expected value'
    );

    Ember.run( () => {
        component.set( 'value', new Date( 2015, 1, 15 ) );
    });
    assert.equal(
        component.get( 'momentValue' ).calendar(),
        '02/15/2015',
        'Updated momentValue is expected value'
    );
});

test( 'Computed timezoneString is set and updated correctly', function( assert ) {
    var component = this.subject({
        timezone : 'America/Chicago',
        value    : new Date( 2015, 0, 1 )
    });

    assert.equal(
        component.get( 'timezoneString' ),
        'CST',
        'Initial timezoneString is expected value'
    );

    Ember.run( () => {
        component.set( 'timezone', 'America/Los_Angeles' );
    });
    assert.equal(
        component.get( 'timezoneString' ),
        'PST',
        'Updated timezoneString is expected value'
    );
});

test( '"title" property is an alias to "datetime" value', function( assert ) {
    var component = this.subject({ timezone: 'America/Chicago' });

    assert.equal(
        component.get( 'title' ),
        component.get( 'datetime' ),
        '"title" property is aliased to "datetime" property'
    );
});
<|endoftext|>