<commit_before>// LV TRUCKS MAP - map-related Javascripts

// Initialize map & set initial location / view
var map = L.mapbox.map('map')
    .setView([36.1665, -115.1479], 14)  // This will be overridden later when map bounds are set based on available markers.
    .addLayer(L.mapbox.tileLayer('louh.map-vio2jxma', {
        detectRetina: true,
        retinaVersion: 'louh.map-2lywy8ei'
    }))

// Generate center offset amounts for different views
var centerOffsetH = 0,
    centerOffsetV = 0

if ($('#truck-data').is(':visible')) {
    centerOffsetH = ($(window).width() - $('#truck-data').width()) / 2
}

/*
if ($('#truck-data').is(':visible')) {
    centerOffsetH = $('#truck-data').width()
} else {
    centerOffsetV = $(window).height() / 4
}

// See here for source and discussion of following mixin
// https://github.com/Leaflet/Leaflet/issues/859
MapCenterOffsetMixin = {
    UIOffset: [centerOffsetH, centerOffsetV], // x, y
    getBounds: function(){
        var a=this.getPixelBounds(),
            b=this.unproject(new L.Point(a.min.x+this.UIOffset[0],a.max.y+this.UIOffset[1]), this._zoom,!0),
            c=this.unproject(new L.Point(a.max.x,a.min.y),this._zoom,!0);
            return new L.LatLngBounds(b,c)
    },
    _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
        var targetPoint = this.project(newCenter, newCenter).subtract([this.UIOffset[0]/2, this.UIOffset[1]/2]),
            newCenter = this.unproject(targetPoint, newZoom);
        var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
        return this.project(latlng, newZoom)._subtract(topLeft);
    },
    _getCenterLayerPoint: function () {
        return this.containerPointToLayerPoint(this.getSize().divideBy(2).add([this.UIOffset[0]/2, this.UIOffset[1]/2]));
    },
    _resetView: function (a, b, c, d) {
        var e = this._zoom !== b;
        // Change the center
        var targetPoint = this.project(a, b).subtract([this.UIOffset[0] / 2, this.UIOffset[1]/2]),
            a = this.unproject(targetPoint, b);
        d || (this.fire("movestart"), e && this.fire("zoomstart")), this._zoom = b, this._initialTopLeftPoint = this._getNewTopLeftPoint(a);
        if (!c) L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
        else {
            var f = L.DomUtil.getPosition(this._mapPane);
            this._initialTopLeftPoint._add(f)
        }
        this._tileLayersToLoad = this._tileLayersNum, this.fire("viewreset", {
            hard: !c
        }), this.fire("move"), (e || d) && this.fire("zoomend"), this.fire("moveend"), this._loaded || (this._loaded = !0, this.fire("load"))
    }
}

L.Map.include(MapCenterOffsetMixin);
*/

// Map imagery attribution
// Note that mapbox.js provides its own separate attribution, which I don't know how to edit, so I've hidden it with CSS (super hacky!)
var control = L.control.attribution({
    prefix: 'Map imagery by MapBox. Data © OpenStreetMap contributors.'
}).addTo(map)

// Set up truck icon
var truckMarker = L.icon({
    iconUrl: 'img/marker-truck.svg',

    iconSize:     [70, 60], // size of the icon
    iconAnchor:   [35, 50], // point of the icon which will correspond to marker's location
    popupAnchor:  [3, -55]  // point from which the popup should open relative to the iconAnchor
})

var truckMarkerOff = L.icon({
    iconUrl: 'img/marker-truck-off.svg',

    iconSize:     [70, 60],
    iconAnchor:   [35, 50],
    popupAnchor:  [3, -55]
})

// Get data
var data = document.data()

// This information is now also available back in main.js
var locations = data.locations // this is a GeoJSON format
var trucks = data.trucks
var calendar = data.calendar

// Populate map with locations
var markers = L.mapbox.markerLayer(locations, {
    filter: function (feature) {
        return true
        // disabled active filter
        // return feature.properties.active === true
    }
}).eachLayer(function (marker) {

    // set options here directly on the marker object
    // marker.options.icon = truckMarkerOff  // set this to be off by default
    marker.options.riseOnHover = true

    // shorthand for where things are stored in the GeoJSON
    var markerID = marker.feature.id

    for (i = 0; i < calendar.now.length; i++) {
        if (calendar.now[i].at == markerID ) {
            for (j =0; j < trucks.length; j++) {
                if (trucks[j].id == calendar.now[i].truck) {
                    marker.truck = trucks[j]
                    break
                }
            }
            marker.calendar = calendar.now[i]
            break
        }
    }

    // Popup construction and marker on
    var popupHTML = 'No truck at ' + marker.feature.properties.name + '
' + marker.feature.properties.address
    if (marker.truck) {
        var popupHTML = '' + marker.truck.name + ' is at ' + marker.feature.properties.name + '
' + marker.feature.properties.address + '
until ' + marker.calendar.until

        // Turn on marker
        // marker.options.icon = truckMarker
        marker.feature.properties['marker-color'] = '#f93'
    }

    marker.bindPopup(popupHTML, {
        closeButton: false,
        minWidth: 200,
        autoPanPadding: [20, 40],
        closeOnClick: true,
        keepInView: true
    })

    // Center marker on click
    marker.on('click', function (e) {
        map.panTo(marker.getLatLng())
    })

}).addTo(map)

// Set the bounding area for the map
map.fitBounds(markers.getBounds().pad(0.5), {
    paddingTopLeft: [centerOffsetH, centerOffsetV]
})
map.setMaxBounds(markers.getBounds().pad(6))

// Open popups on mouseover (test)
markers.on('mouseover', function (e) {
    e.layer.openPopup()
})

// GEOLOCATE!
// This uses the HTML5 geolocation API, which is available on
// most mobile browsers and modern browsers, but not in Internet Explorer
//
// See this chart of compatibility for details:
// http://caniuse.com/#feat=geolocation
if (navigator.geolocation) {
    map.locate()
}
// Once we've got a position, add a marker.
map.on('locationfound', function (e) {
    map.markerLayer.setGeoJSON({
        type: 'Feature',
        geometry: {
            type: 'Point',
            coordinates: [e.latlng.lng, e.latlng.lat]
        },
        properties: {
            'title': 'You are here',
            'marker-size': 'large',
            'marker-color': '#cd0000',
            'marker-symbol': 'star-stroked'
        }
    })
})

// Popups test
/*
markers.on('click',function (e) {
    e.layer.unbindPopup();

    var mPopup = $('#m-popup').html()
    var popupObject = {}

    var i = 1

    var feature = e.layer.feature;
    popupObject.location = feature.properties.name
    popupObject.address = feature.properties.address
    popupObject.name = trucks[i].name
    popupObject.until = trucks[i].until

    $('#popup-layer').html(Mustache.render(mPopup, popupObject))
    $('#popup').fadeIn(200)
});
// Clear the tooltip when map is clicked
map.on('click',function (e) {
    $('#popup').fadeOut(200)
});
*/<commit_msg>mobile tweaks.<commit_after>// LV TRUCKS MAP - map-related Javascripts

// Initialize map & set initial location / view
var map = L.mapbox.map('map')
    .setView([36.1665, -115.1479], 14)  // This will be overridden later when map bounds are set based on available markers.
    .addLayer(L.mapbox.tileLayer('louh.map-vio2jxma', {
        detectRetina: true,
        retinaVersion: 'louh.map-2lywy8ei'
    }))

// Generate center offset amounts for different views
var centerOffsetH = 0,
    centerOffsetV = 0

if ($('#truck-data').is(':visible')) {
    centerOffsetH = ($(window).width() - $('#truck-data').width()) / 2
}

/*
if ($('#truck-data').is(':visible')) {
    centerOffsetH = $('#truck-data').width()
} else {
    centerOffsetV = $(window).height() / 4
}

// See here for source and discussion of following mixin
// https://github.com/Leaflet/Leaflet/issues/859
MapCenterOffsetMixin = {
    UIOffset: [centerOffsetH, centerOffsetV], // x, y
    getBounds: function(){
        var a=this.getPixelBounds(),
            b=this.unproject(new L.Point(a.min.x+this.UIOffset[0],a.max.y+this.UIOffset[1]), this._zoom,!0),
            c=this.unproject(new L.Point(a.max.x,a.min.y),this._zoom,!0);
            return new L.LatLngBounds(b,c)
    },
    _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
        var targetPoint = this.project(newCenter, newCenter).subtract([this.UIOffset[0]/2, this.UIOffset[1]/2]),
            newCenter = this.unproject(targetPoint, newZoom);
        var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
        return this.project(latlng, newZoom)._subtract(topLeft);
    },
    _getCenterLayerPoint: function () {
        return this.containerPointToLayerPoint(this.getSize().divideBy(2).add([this.UIOffset[0]/2, this.UIOffset[1]/2]));
    },
    _resetView: function (a, b, c, d) {
        var e = this._zoom !== b;
        // Change the center
        var targetPoint = this.project(a, b).subtract([this.UIOffset[0] / 2, this.UIOffset[1]/2]),
            a = this.unproject(targetPoint, b);
        d || (this.fire("movestart"), e && this.fire("zoomstart")), this._zoom = b, this._initialTopLeftPoint = this._getNewTopLeftPoint(a);
        if (!c) L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
        else {
            var f = L.DomUtil.getPosition(this._mapPane);
            this._initialTopLeftPoint._add(f)
        }
        this._tileLayersToLoad = this._tileLayersNum, this.fire("viewreset", {
            hard: !c
        }), this.fire("move"), (e || d) && this.fire("zoomend"), this.fire("moveend"), this._loaded || (this._loaded = !0, this.fire("load"))
    }
}

L.Map.include(MapCenterOffsetMixin);
*/

// Map imagery attribution
// Note that mapbox.js provides its own separate attribution, which I don't know how to edit, so I've hidden it with CSS (super hacky!)
var control = L.control.attribution({
    prefix: 'Map imagery by MapBox. Data © OpenStreetMap contributors.'
}).addTo(map)

// Set up truck icon
var truckMarker = L.icon({
    iconUrl: 'img/marker-truck.svg',

    iconSize:     [70, 60], // size of the icon
    iconAnchor:   [35, 50], // point of the icon which will correspond to marker's location
    popupAnchor:  [3, -55]  // point from which the popup should open relative to the iconAnchor
})

var truckMarkerOff = L.icon({
    iconUrl: 'img/marker-truck-off.svg',

    iconSize:     [70, 60],
    iconAnchor:   [35, 50],
    popupAnchor:  [3, -55]
})

// Get data
var data = document.data()

// This information is now also available back in main.js
var locations = data.locations // this is a GeoJSON format
var trucks = data.trucks
var calendar = data.calendar

// Populate map with locations
var markers = L.mapbox.markerLayer(locations, {
    filter: function (feature) {
        return true
        // disabled active filter
        // return feature.properties.active === true
    }
}).eachLayer(function (marker) {

    // set options here directly on the marker object
    // marker.options.icon = truckMarkerOff  // set this to be off by default
    marker.options.riseOnHover = true

    // shorthand for where things are stored in the GeoJSON
    var markerID = marker.feature.id

    for (i = 0; i < calendar.now.length; i++) {
        if (calendar.now[i].at == markerID ) {
            for (j =0; j < trucks.length; j++) {
                if (trucks[j].id == calendar.now[i].truck) {
                    marker.truck = trucks[j]
                    break
                }
            }
            marker.calendar = calendar.now[i]
            break
        }
    }

    // Popup construction and marker on
    var popupHTML = 'No truck at ' + marker.feature.properties.name + '
' + marker.feature.properties.address
    if (marker.truck) {
        var popupHTML = '' + marker.truck.name + ' is at ' + marker.feature.properties.name + '
' + marker.feature.properties.address + '
until ' + marker.calendar.until

        // Turn on marker
        // marker.options.icon = truckMarker
        marker.feature.properties['marker-color'] = '#f93'
    }

    marker.bindPopup(popupHTML, {
        closeButton: false,
        minWidth: 200,
        autoPanPadding: [20, 40]
    })

    // Center marker on click
    marker.on('click', function (e) {
        map.panTo(marker.getLatLng())
    })

}).addTo(map)

// Set the bounding area for the map
map.fitBounds(markers.getBounds().pad(0.5), {
    paddingTopLeft: [centerOffsetH, centerOffsetV]
})
map.setMaxBounds(markers.getBounds().pad(6))

// Open popups on mouseover (test)
markers.on('mouseover', function (e) {
    e.layer.openPopup()
})

// GEOLOCATE!
// This uses the HTML5 geolocation API, which is available on
// most mobile browsers and modern browsers, but not in Internet Explorer
//
// See this chart of compatibility for details:
// http://caniuse.com/#feat=geolocation
if (navigator.geolocation) {
    map.locate()
}
// Once we've got a position, add a marker.
map.on('locationfound', function (e) {
    map.markerLayer.setGeoJSON({
        type: 'Feature',
        geometry: {
            type: 'Point',
            coordinates: [e.latlng.lng, e.latlng.lat]
        },
        properties: {
            'title': 'You are here',
            'marker-size': 'large',
            'marker-color': '#cd0000',
            'marker-symbol': 'star-stroked'
        }
    })
})

// Popups test
/*
markers.on('click',function (e) {
    e.layer.unbindPopup();

    var mPopup = $('#m-popup').html()
    var popupObject = {}

    var i = 1

    var feature = e.layer.feature;
    popupObject.location = feature.properties.name
    popupObject.address = feature.properties.address
    popupObject.name = trucks[i].name
    popupObject.until = trucks[i].until

    $('#popup-layer').html(Mustache.render(mPopup, popupObject))
    $('#popup').fadeIn(200)
});
// Clear the tooltip when map is clicked
map.on('click',function (e) {
    $('#popup').fadeOut(200)
});
*/<|endoftext|>


<commit_before>(function ($, dc) {
  "use strict";

  $(function gdprBanner() {
    if (!dc.hasItem("gdpr-accept")) {
      var gdpr = $("
").on("click", ".gdpr-close", function(e) {
        dc.setItem("gdpr-accept", "yes");
        $(document.body).removeClass("with-gdpr");
        gdpr.remove();
      }).append("").
        append("
Our site uses cookies for analytics. If you're unsure about it, take a look at our privacy policy.
");

      $(document.body).addClass("with-gdpr").find("header").append(gdpr);
      dc.setItem("gdpr-accept", "yes");
    }
  });

})(jQuery, docCookies);
<commit_msg>Add `rel="noopener noreferrer"` to external links on GDPR banner<commit_after>(function ($, dc) {
  "use strict";

  $(function gdprBanner() {
    if (!dc.hasItem("gdpr-accept")) {
      var gdpr = $("
").on("click", ".gdpr-close", function(e) {
        dc.setItem("gdpr-accept", "yes");
        $(document.body).removeClass("with-gdpr");
        gdpr.remove();
      }).append("").
        append("
Our site uses cookies for analytics. If you're unsure about it, take a look at our privacy policy.
");

      $(document.body).addClass("with-gdpr").find("header").append(gdpr);
      dc.setItem("gdpr-accept", "yes");
    }
  });

})(jQuery, docCookies);
<|endoftext|>


<commit_before>var tmsFolder = 'file:///Users/daveism/curtms/';
var dataFolder = './data/';
var dataFolder = 'https://raw.githubusercontent.com/daveism/cr-quick/gh-pages/data/';

var Date_WMS1 = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-swir-threshold?AOI_ID=327", {
  layers: 'SWIR-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var Date_WMS2 = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-swir-allchange?AOI_ID=328", {
  layers: 'SWIR-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var Date_WMS3 = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-swir-allchange?AOI_ID=329", {
  layers: 'SWIR-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var swirwms = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-swir-allchange?AOI_ID=290", {
  layers: 'swir-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var ndviwms = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-ndvi?AOI_ID=290", {
  layers: 'ndvi-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var ndmiwms = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-ndmi?AOI_ID=290", {
  layers: 'ndmi-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var basicMap = L.tileLayer('http://api.tiles.mapbox.com/v3/daveism.oo0p88l4/{z}/{x}/{y}.png', {
  attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA',
  maxZoom: 15
})

var image = L.tileLayer('http://api.tiles.mapbox.com/v3/daveism.oo0o5k97/{z}/{x}/{y}.png', {
  attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA',
  maxZoom: 15
})

var ndvi = L.tileLayer(tmsFolder + 'ndvi_tms/{z}/{x}/{y}.png', {
  attribution: 'Landsat FACT',
  tms:true,
  maxZoom: 15,
  opacity: 0.65
})

var ndmi = L.tileLayer(tmsFolder + 'ndmi_tms/{z}/{x}/{y}.png', {
  attribution: 'Landsat FACT',
  tms:true,
  maxZoom: 15,
  opacity: 0.65
})

var swir = L.tileLayer(tmsFolder + 'swir_tms/{z}/{x}/{y}.png', {
  attribution: 'Landsat FACT',
  tms:true,
  maxZoom: 15,
  opacity: 0.65
});

var baseMaps = {
  "map": basicMap,
  "sat": image
};

var map = L.map('map',{
  center: [36.730,-81.859],
  zoom: 13,
  layers: [image],
  crs: 	L.CRS.EPSG900913
});

var overlayMaps = {
  "NDVI": ndvi,
  "NDMI": ndmi,
  "SWIR": swir,
  "SWIR(wms)":swirwms,
  "NDMI(wms)":ndmiwms,
  "NDVI(wms)":ndviwms,
  "datewms1":Date_WMS1,
  "datewms2":Date_WMS2,
  "datewms3":Date_WMS3
};
var doAnimate;
$("input[value=doAnimate]").click(function( event ) {
  if(doAnimate){
    doAnimate = false;
  }else{
    doAnimate = true;
    map.addLayer(Date_WMS1);
  }

  cnt=2;
  maxCnt=3;

  (function next() {
      if (!doAnimate) return;
      setTimeout(function() {
            if(cnt===1){
              map.removeLayer(Date_WMS3)
              map.removeLayer(Date_WMS2)
              map.addLayer(Date_WMS1)
            }
            if(cnt===2){
              map.removeLayer(Date_WMS1)
              map.removeLayer(Date_WMS3)
              map.addLayer(Date_WMS2)
            }
            if(cnt===3){
              map.removeLayer(Date_WMS1)
              map.removeLayer(Date_WMS2)
              map.addLayer(Date_WMS3)
            }
            cnt++;
            if(cnt===maxCnt){cnt=1}
          next();
      }, 3000);
  })();
});

$( "input[type=checkbox]" ).click(function( event ) {
  layerClicked = window[event.target.value];
  if (map.hasLayer(layerClicked)) {
    map.removeLayer(layerClicked);
  }
  else{
    map.addLayer(layerClicked);
  } ;
});

//change geosjson layer
$( "#changeLyr[type=button]" ).click(function( event ) {
  if (map.hasLayer(geojsonLayer)) {
    map.removeLayer(geojsonLayer);
  }
  else{
    map.addLayer(geojsonLayer);
  } ;
});

//base map toggle
$( ".btn-group label" ).click(function( event ) {
  if(this.id == 'basesat'){
    map.addLayer(image);
    map.removeLayer(basicMap);
  }
  if(this.id == 'basemap'){
    basicMap.addTo(map);
    map.addLayer(basicMap);
    map.removeLayer(image);
  }
});

var changeCount = 0
var curpoint = 0
var geoJSON = '';
var geojsonLayer;

$.getJSON(dataFolder + "swir_areas.geojson", function(response) {
  console.log("response", response);
  geojsonLayer = new L.GeoJSON(response);
  geojsonLayer.addTo(map);
  geoJSON = response;
  changeCount = geoJSON.features.length;
  map.removeLayer(geojsonLayer);
});

var getNextChange = function(){
  if(curpoint=>changeCount){
    curpoint++;
    $("#currval").html('Change Feauture:  ' + curpoint)
    var centroidPt = turf.centroid(geoJSON.features[curpoint]);
    console.log(JSON.stringify(centroidPt))
    map.setView([ centroidPt.geometry.coordinates[1] , centroidPt.geometry.coordinates[0]],15);
  }
}

var getPevChange = function(){
  if(curpoint >=  0){
    curpoint--;
    $("#currval").html('Change Feauture:  ' + curpoint)
    var area = turf.area(geoJSON.features[curpoint]);
    var centroidPt = turf.centroid(geoJSON.features[curpoint]);
    console.log(JSON.stringify(centroidPt))
    console.log(area);
    map.setView([ centroidPt.geometry.coordinates[1] , centroidPt.geometry.coordinates[0]],15);
  }
}

//$("input[value=Date_WMS3]").click()
<commit_msg>skip small change areas<commit_after>var tmsFolder = 'file:///Users/daveism/curtms/';
var dataFolder = './data/';
var dataFolder = 'https://raw.githubusercontent.com/daveism/cr-quick/gh-pages/data/';

var Date_WMS1 = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-swir-threshold?AOI_ID=327", {
  layers: 'SWIR-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var Date_WMS2 = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-swir-allchange?AOI_ID=328", {
  layers: 'SWIR-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var Date_WMS3 = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-swir-allchange?AOI_ID=329", {
  layers: 'SWIR-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var swirwms = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-swir-allchange?AOI_ID=290", {
  layers: 'swir-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var ndviwms = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-ndvi?AOI_ID=290", {
  layers: 'ndvi-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var ndmiwms = L.tileLayer.wms("http://landsatfact-data-dev.nemac.org/lsf-cr-ndmi?AOI_ID=290", {
  layers: 'ndmi-archiveCloudGap',
  format: 'image/png',
  transparent: true,
  attribution: 'Landsat FACT',
  maxZoom: 15
});

var basicMap = L.tileLayer('http://api.tiles.mapbox.com/v3/daveism.oo0p88l4/{z}/{x}/{y}.png', {
  attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA',
  maxZoom: 15
})

var image = L.tileLayer('http://api.tiles.mapbox.com/v3/daveism.oo0o5k97/{z}/{x}/{y}.png', {
  attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA',
  maxZoom: 15
})

var ndvi = L.tileLayer(tmsFolder + 'ndvi_tms/{z}/{x}/{y}.png', {
  attribution: 'Landsat FACT',
  tms:true,
  maxZoom: 15,
  opacity: 0.65
})

var ndmi = L.tileLayer(tmsFolder + 'ndmi_tms/{z}/{x}/{y}.png', {
  attribution: 'Landsat FACT',
  tms:true,
  maxZoom: 15,
  opacity: 0.65
})

var swir = L.tileLayer(tmsFolder + 'swir_tms/{z}/{x}/{y}.png', {
  attribution: 'Landsat FACT',
  tms:true,
  maxZoom: 15,
  opacity: 0.65
});

var baseMaps = {
  "map": basicMap,
  "sat": image
};

var map = L.map('map',{
  center: [36.730,-81.859],
  zoom: 13,
  layers: [image],
  crs: 	L.CRS.EPSG900913
});

var overlayMaps = {
  "NDVI": ndvi,
  "NDMI": ndmi,
  "SWIR": swir,
  "SWIR(wms)":swirwms,
  "NDMI(wms)":ndmiwms,
  "NDVI(wms)":ndviwms,
  "datewms1":Date_WMS1,
  "datewms2":Date_WMS2,
  "datewms3":Date_WMS3
};
var doAnimate;
$("input[value=doAnimate]").click(function( event ) {
  if(doAnimate){
    doAnimate = false;
  }else{
    doAnimate = true;
    map.addLayer(Date_WMS1);
  }

  cnt=2;
  maxCnt=3;

  (function next() {
      if (!doAnimate) return;
      setTimeout(function() {
            if(cnt===1){
              map.removeLayer(Date_WMS3)
              map.removeLayer(Date_WMS2)
              map.addLayer(Date_WMS1)
            }
            if(cnt===2){
              map.removeLayer(Date_WMS1)
              map.removeLayer(Date_WMS3)
              map.addLayer(Date_WMS2)
            }
            if(cnt===3){
              map.removeLayer(Date_WMS1)
              map.removeLayer(Date_WMS2)
              map.addLayer(Date_WMS3)
            }
            cnt++;
            if(cnt===maxCnt){cnt=1}
          next();
      }, 3000);
  })();
});

$( "input[type=checkbox]" ).click(function( event ) {
  layerClicked = window[event.target.value];
  if (map.hasLayer(layerClicked)) {
    map.removeLayer(layerClicked);
  }
  else{
    map.addLayer(layerClicked);
  } ;
});

//change geosjson layer
$( "#changeLyr[type=button]" ).click(function( event ) {
  if (map.hasLayer(geojsonLayer)) {
    map.removeLayer(geojsonLayer);
  }
  else{
    map.addLayer(geojsonLayer);
  } ;
});

//base map toggle
$( ".btn-group label" ).click(function( event ) {
  if(this.id == 'basesat'){
    map.addLayer(image);
    map.removeLayer(basicMap);
  }
  if(this.id == 'basemap'){
    basicMap.addTo(map);
    map.addLayer(basicMap);
    map.removeLayer(image);
  }
});

var changeCount = 0
var curpoint = 0
var geoJSON = '';
var geojsonLayer;

$.getJSON(dataFolder + "swir_areas.geojson", function(response) {
  console.log("response", response);
  geojsonLayer = new L.GeoJSON(response);
  geojsonLayer.addTo(map);
  geoJSON = response;
  changeCount = geoJSON.features.length;
  map.removeLayer(geojsonLayer);
});

var getNextChange = function(){
  if(curpoint=>changeCount){
    curpoint++;
    $("#currval").html('Change Feauture:  ' + curpoint)
    areaPush();
    var centroidPt = turf.centroid(geoJSON.features[curpoint]);
    console.log(JSON.stringify(centroidPt))
    map.setView([ centroidPt.geometry.coordinates[1] , centroidPt.geometry.coordinates[0]],15);
  }
}

var getPevChange = function(){
  if(curpoint >=  0){
    curpoint--;
    $("#currval").html('Change Feauture:  ' + curpoint)

    areaPop();
    var centroidPt = turf.centroid(geoJSON.features[curpoint]);
    console.log(JSON.stringify(centroidPt))
    map.setView([ centroidPt.geometry.coordinates[1] , centroidPt.geometry.coordinates[0]],15);
  }
}

var areaPush = function(){
  var area = turf.area(geoJSON.features[curpoint]);
  console.log(area);
  if(area<3001){
    curpoint++;
    areaPush()
  }
}

var areaPop = function(){
  var area = turf.area(geoJSON.features[curpoint]);
  console.log(area);
  if(area<3001){
    curpoint--;
    areaPush()
  }
}
//$("input[value=Date_WMS3]").click()
<|endoftext|>


<commit_before>

function getposts(){
	console.log("getposts running...");
	console.log($("#blog").children().length);
	if ($("#blog").children().length<2){
		$("#left").hide();
		console.log("hiding left button");
		$("#right").hide();
		console.log("hiding right button");

		$.getJSON('entries.json', function(data){
			for (var i in data.entries){
				$("#blog").append("

"+data.entries[i].date+"

"+data.entries[i].title+"

"+data.entries[i].text+"

");
				}
		 });
			$("#blog").hide();
		console.log("hiding blog");
		}
}

function pager(change){
	console.log("pager running...");
	page+=change;
	var posts=$("#blog").childNodes;
	for (post in posts){
		$(post).hide();
	}
	for (i=0;i<=4;i++){
		$(posts[page*5+i]).show();
		console.log("we should show post #"+page*5);
	}
	if (page ==0){
		$("#left").hide();
	}else{
		$("#left").show();
	}
	if (page ==ceil(c.length/5)) {
		$("#right").hide();
	}else{
		$("#right").show();
	}
}

function displayBlog(){
	console.log("displayBlog running...");
	$("#blog").show();
	console.log("show blog");
	pager(0);

}<commit_msg>test 0847<commit_after>

function getposts(){
	console.log("getposts running...");
	console.log($("#blog").children().length);
	if ($("#blog").children().length<2){
		$("#left").hide();
		console.log("hiding left button");
		$("#right").hide();
		console.log("hiding right button");
		$("#blog").hide();
		console.log("hiding blog");
		$.getJSON('entries.json', function(data){
			for (var i in data.entries){
				$("#blog").append("

"+data.entries[i].date+"

"+data.entries[i].title+"

"+data.entries[i].text+"

");
				}
		 });
	}
}

function pager(change){
	console.log("pager running...");
	page+=change;
	var posts=$("#blog").childNodes;
	for (post in posts){
		$(post).hide();
	}
	for (i=0;i<=4;i++){
		$(posts[page*5+i]).show();
		console.log("we should show post #"+page*5);
	}
	if (page ==0){
		$("#left").hide();
	}else{
		$("#left").show();
	}
	if (page ==ceil(c.length/5)) {
		$("#right").hide();
	}else{
		$("#right").show();
	}
}

function displayBlog(){
	console.log("displayBlog running...");
	$("#blog").show();
	console.log("show blog");
	pager(0);

}<|endoftext|>


<commit_before>$(document).ready(function() {

    if ($('.addon-validator-suite').length) {
        initValidator();
    }

});

function initValidator() {

    function inherit(OtherClass, constructor) {
        var NewClass = function() {
            OtherClass.apply(this, arguments);
            if (typeof constructor !== 'undefined') {
                constructor.apply(this, arguments);
            }
        }
        $.extend(NewClass.prototype, OtherClass.prototype);
        return NewClass;
    }

    function emptyFn() {
        return null;
    }

    function ResultsTier($suite, tierId, options) {
        if (typeof options === 'undefined')
            options = {}
        if (typeof options.app === 'undefined')
            options.app = null;
        if (typeof options.testsWereRun === 'undefined')
            options.testsWereRun = true;
        this.$results = $('.results', $suite);
        this.app = options.app;
        this.testsWereRun = options.testsWereRun;
        this.counts = {error: 0, warning: 0};
        this.tierId = tierId;
        this.$suite = $suite;
        this.$dom = $('#suite-results-tier-' + tierId, $suite);
        if (!this.$dom.length) {
            this.$dom = this.createDom();
            this.$results.append(this.$dom);
        }
        this.$tierResults = $('.tier-results', this.$dom);
        this.wakeUp();
        // this.$results.append($tier);
    }

    ResultsTier.prototype.tallyMsgType = function(type_) {
        if (type_ == 'notice') type_ = 'warning';
        this.counts[type_] += 1;
    };

    ResultsTier.prototype.createDom = function() {
        var $tier = $($('.template', this.$suite).html());
        $tier.attr('id', 'suite-results-tier-' + this.tierId);
        return $tier;
    }

    ResultsTier.prototype.summarize = function() {
        var sm = resultSummary(this.counts.error, this.counts.warning),
            resultClass, summaryMsg;
        $('.result-summary', this.$dom).css('visibility', 'visible')
                                       .empty().text(sm);
        if (this.counts.error) {
            resultClass = 'tests-failed';
        } else if (this.counts.warning) {
            resultClass = 'tests-passed-warnings';
        } else {
            if (this.testsWereRun) {
                summaryMsg = gettext('All tests passed successfully.');
                resultClass = 'tests-passed';
            } else {
                summaryMsg = gettext('These tests were not run.');
                resultClass = 'tests-notrun';
                // No summary since no tests were run:
                $('.result-summary', this.$dom).html(' ');
            }
            this.$tierResults.append('' + summaryMsg + '');
        }
        this.$tierResults.removeClass('ajax-loading', 'tests-failed',
                                      'tests-passed', 'tests-passed-warnings',
                                      'tests-notrun')
                         .addClass(resultClass);
        if ($('.test-tier', this.$suite).length)
            this.topSummary();
    };

    ResultsTier.prototype.topSummary = function() {
        var $top = $('[class~="test-tier"]' +
                     '[data-tier="' + this.tierId + '"]', this.$suite),
            summaryMsg = resultSummary(this.counts.error, this.counts.warning);

        $('.tier-summary', $top).text(summaryMsg);
        $top.removeClass('ajax-loading', 'tests-failed', 'tests-passed',
                         'tests-notrun');
        if (this.counts.error > 0) {
            $top.addClass('tests-failed');
        } else {
            if (this.testsWereRun)
                $top.addClass('tests-passed');
            else
                $top.addClass('tests-notrun');
        }
    };

    ResultsTier.prototype.wakeUp = function() {
        var $title = $('h4', this.$dom),
            changeLink;
        $('.tier-results', this.$dom).empty();
        this.$dom.removeClass('hidden');
        this.$dom.show();
        // this.$dom.css('display', 'display');
        // this.$dom.css('visibility', 'visible');
        if (this.app) {
            // Override the title with a special app/version title
            $title.text(format('{0} {1} {2}',
                               this.app.trans[this.app.guid],
                               this.app.version,
                               gettext('Tests')));
            changeLink = this.app.versionChangeLinks[this.app.guid + ' ' +
                                                     this.app.version];
            if (changeLink) {
                this.$dom.prepend(
                    format('{1}',
                           changeLink,
                           // L10n: Example: Changes in Firefox 5
                           gettext(format('Changes in {0} {1}',
                                          this.app.trans[this.app.guid],
                                          this.app.version.substring(0,1)))));
            }
        } else if (!$title.text()) {
            $title.text(gettext('Tests'));
        }
        $('.tier-results', this.$dom).removeClass('ajax-loading');
    };

    function MsgVisitor(suite, data) {
        this.$suite = suite;
        this.data = data;
        this.$results = $('.results', suite);
        this.msgSet = {};
        this.tiers = {};
        this.appTrans = null;
        this.versionChangeLinks = null;
    }

    MsgVisitor.prototype.createTier = function(tierId, options) {
        if (options && options.app) {
            options.app.trans = this.appTrans;
            options.app.versionChangeLinks = this.versionChangeLinks;
        }
        var tier = new ResultsTier(this.$suite, tierId, options);
        return tier;
    };

    MsgVisitor.prototype.finish = function(msg) {
        var self = this;
        $('.result', this.$suite).each(function(i, res) {
            if (!$('.msg', res).length) {
                // No messages so no tier was created.
                self.getTier($('.tier-results', res).attr('data-tier'));
            }
        });
        $.each(this.tiers, function(tierId, tier) {
            tier.summarize();
        });
    };

    MsgVisitor.prototype.getMsgType = function(msg) {
         return msg['type'];
    };

    MsgVisitor.prototype.getTier = function(tierId, options) {
        if (typeof options === 'undefined')
            options = {app: null};
        if (!options.app
            && this.data.validation.ending_tier
            && this.data.validation.ending_tier < tierId) {
            options.testsWereRun = false;
        }
        if (typeof this.tiers[tierId] === 'undefined')
            this.tiers[tierId] = this.createTier(tierId, options);
        return this.tiers[tierId];
    };

    MsgVisitor.prototype.message = function(msg, options) {
        if (typeof this.msgSet[msg.uid] !== 'undefined')
            return;
        this.msgSet[msg.uid] = true;
        var tier = this.getTier(msg.tier, options),
            msgDiv = $('

'),
            effectiveType = this.getMsgType(msg),
            prefix = effectiveType=='warning' ? gettext('Warning')
                                              : gettext('Error');

        tier.tallyMsgType(effectiveType);
        msgDiv.attr('id', 'v-msg-' + msg.uid);
        msgDiv.addClass('msg-' + effectiveType);
        $('h5', msgDiv).html(msg.message);
        if (typeof(msg.description) === 'undefined' || msg.description === '') {
            msg.description = [];
        } else if (typeof(msg.description) === 'string') {
            // Currently it can be either of these:
            //      descripion: "foo"
            //      description: ["foo", "bar"]
            msg.description = [msg.description];
        }
        $.each(msg.description, function(i, val) {
            msgDiv.append(format('
{0}: {1}
', [prefix, val]));
        });
        if (msg.description.length == 0) {
            msgDiv.append('

');
        }
        if (msg.file) {
            msgDiv.append(this.messageContext(msg));
        }
        $('.tier-results', tier.$dom).append(msgDiv);
    };

    MsgVisitor.prototype.messageContext = function(msg) {
        var ctxFile = msg.file, ctxDiv, code, lines, innerCode;
        if (typeof(ctxFile) === 'string') {
            ctxFile = [ctxFile];
        }
        // e.g. ["silvermelxt_1.3.5.xpi",
        //       "chrome/silvermelxt.jar"]
        ctxFile = joinPaths(ctxFile);
        ctxDiv = $(format('
' +
                          '
{0}

', [ctxFile]));
        if (msg.context) {
            code = $('

');
            lines = $('

');
            code.append(lines);
            innerCode = $('

');
            code.append(innerCode);
            msg.context = formatCodeIndentation(msg.context);
            $.each(msg.context, function(n, c) {
                lines.append(
                    $(format('
{0}
', [msg.line + n])));
                innerCode.append(
                    $(format('
{0}
', [c])));
            });
            ctxDiv.append(code);
        }
        return ctxDiv;
    };

    var CompatMsgVisitor = inherit(MsgVisitor, function(suite, data) {
        this.appTrans = JSON.parse(this.$results.attr('data-app-trans'));
        this.versionChangeLinks = JSON.parse(this.$results.attr('data-version-change-links'));
    });

    CompatMsgVisitor.prototype.finish = function(msg) {
        MsgVisitor.prototype.finish.apply(this, arguments);
        // Since results are more dynamic on the compatibility page,
        // hide tiers without messages.
        $('.result', this.$suite).each(function(i, res) {
            if (!$('.msg', res).length)
                $(res).hide();
        });
    };

    CompatMsgVisitor.prototype.getMsgType = function(msg) {
         return msg.compatibility_type ? msg.compatibility_type: msg['type'];
    };

    CompatMsgVisitor.prototype.message = function(msg) {
        var self = this;
        if (msg.for_appversions) {
            eachAppVer(msg.for_appversions, function(guid, version, id) {
                var app = {guid: guid, version: version, id: id};
                msg.tier = id;  // change the tier to match app/version
                MsgVisitor.prototype.message.apply(self, [msg, {app: app}]);
            });
        } else {
            MsgVisitor.prototype.message.apply(this, arguments);
        }
    };

    function buildResults(suite, data) {
        var vis,
            validation = data.validation,
            summaryTxt;

        if ($('.results', suite).hasClass('compatibility-results'))
            vis = new CompatMsgVisitor(suite, data);
        else
            vis = new MsgVisitor(suite, data);
        $.each(validation.messages, function(i, msg) {
            vis.message(msg);
        });
        vis.finish();

        if (validation.errors > 0) {
            summaryTxt = gettext('Add-on failed validation.');
        } else {
            summaryTxt = gettext('Add-on passed validation.');
        }
        $('.suite-summary span', suite).text(summaryTxt);
        $('.suite-summary', suite).show();
    }

    function eachAppVer(appVer, visit) {
        // Iterates an application/version map and calls
        // visit(gui, version, key) for each item.
        //
        // e.g. {'{ec8030f7-c20a-464f-9b0e-13a3a9e97384}':["4.0b1"]}
        // ->
        //      visit('{ec8030f7-c20a-464f-9b0e-13a3a9e97384}',
        //            "4.0b1",
        //            'ec8030f7-c20a-464f-9b0e-13a3a9e97384-40b1')
        if (appVer) {
            $.each(appVer, function(guid, all_versions) {
                $.each(all_versions, function(i, version) {
                    var key = (guid + '-' + version).replace(/[^a-z0-9_-]+/gi, '');
                    visit(guid, version, key);
                });
            });
        }
    }

    function resultSummary(numErrors, numWarnings) {
        // e.g. '1 error, 3 warnings'
        var errors = format(ngettext('{0} error', '{0} errors',
                                     numErrors),
                            [numErrors]),
            warnings = format(ngettext('{0} warning', '{0} warnings',
                                       numWarnings),
                              [numWarnings]);
        return format('{0}, {1}', errors, warnings);
    }

    function joinPaths(parts) {
        var p = '';
        $.each(parts, function(i, part) {
            if (!part || typeof(part) !== 'string') {
                // Might be null or empty string.
                return;
            }
            if (p.length) {
                p += '/';
                if (part.substring(0,1) === '/') {
                    // Prevent double slashes.
                    part = part.substring(1);
                }
            }
            p += part;
        });
        return p;
    }

    function formatCodeIndentation(lines) {
        var indent = null;
        $.each(lines, function(i, code) {
            if (code === null) {
                code = ''; // blank line
            }
            lines[i] = code;
            var m = code.length - code.replace(/^\s+/, '').length;
            if (indent === null) {
                indent = m;
            }
            // Look for the smallest common indent of white space.
            if (m < indent) {
                indent = m;
            }
        });
        $.each(lines, function(i, code) {
            if (indent > 0) {
                // Dedent all code to common level.
                code = code.substring(indent);
                lines[i] = code;
            }
            var n = code.search(/[^\s]/); // first non-space char
            if (n > 0) {
                lines[i] = '';
                // Add back the original indentation.
                for (var x=0; x<n; x++) {
                    lines[i] += ' ';
                }
                lines[i] += $.trim(code);
            }
        });
        return lines;
    }

    $('.addon-validator-suite').live('validate', function(e) {
        var el = $(this),
            url = el.attr('data-validateurl');

        $('.test-tier,.tier-results', el).addClass('ajax-loading');

        $.ajax({type: 'POST',
                url: url,
                data: {},
                success: function(data) {
                    if (data.validation == '') {
                        // Note: traceback is in data.error
                        data.validation = {
                            ending_tier: 1,
                            messages: [{
                                'type':'error',
                                message: gettext('Error'),
                                description: [
                                    gettext('Validation task could not ' +
                                            'complete or completed with ' +
                                            'errors')],
                                tier: 1,
                                uid: '__global_error__'
                            }]
                        };
                    }
                    buildResults(el, data);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    buildResults(el, {
                        validation: {
                            ending_tier: 1,
                            messages: [{
                                'type':'error',
                                message: gettext('Error'),
                                description: [gettext('Internal server error')],
                                tier: 1,
                                uid: '__global_error__'
                            }]
                        }
                    });
                },
                dataType: 'json'
        });
    });

    // Validate when the page loads.
    $('#addon-validator-suite').trigger('validate');

};<commit_msg>Minor code cleanup<commit_after>$(document).ready(function() {

    if ($('.addon-validator-suite').length) {
        initValidator();
    }

});

function initValidator() {

    function inherit(OtherClass, constructor) {
        var NewClass = function() {
            OtherClass.apply(this, arguments);
            if (typeof constructor !== 'undefined') {
                constructor.apply(this, arguments);
            }
        }
        $.extend(NewClass.prototype, OtherClass.prototype);
        return NewClass;
    }

    function emptyFn() {
        return null;
    }

    function ResultsTier($suite, tierId, options) {
        if (typeof options === 'undefined')
            options = {}
        if (typeof options.app === 'undefined')
            options.app = null;
        if (typeof options.testsWereRun === 'undefined')
            options.testsWereRun = true;
        this.$results = $('.results', $suite);
        this.app = options.app;
        this.testsWereRun = options.testsWereRun;
        this.counts = {error: 0, warning: 0};
        this.tierId = tierId;
        this.$suite = $suite;
        this.$dom = $('#suite-results-tier-' + tierId, $suite);
        if (!this.$dom.length) {
            this.$dom = this.createDom();
            this.$results.append(this.$dom);
        }
        this.$tierResults = $('.tier-results', this.$dom);
        this.wakeUp();
    }

    ResultsTier.prototype.tallyMsgType = function(type_) {
        if (type_ == 'notice') type_ = 'warning';
        this.counts[type_] += 1;
    };

    ResultsTier.prototype.createDom = function() {
        var $tier = $($('.template', this.$suite).html());
        $tier.attr('id', 'suite-results-tier-' + this.tierId);
        return $tier;
    }

    ResultsTier.prototype.summarize = function() {
        var sm = resultSummary(this.counts.error, this.counts.warning),
            resultClass, summaryMsg;
        $('.result-summary', this.$dom).css('visibility', 'visible')
                                       .empty().text(sm);
        if (this.counts.error) {
            resultClass = 'tests-failed';
        } else if (this.counts.warning) {
            resultClass = 'tests-passed-warnings';
        } else {
            if (this.testsWereRun) {
                summaryMsg = gettext('All tests passed successfully.');
                resultClass = 'tests-passed';
            } else {
                summaryMsg = gettext('These tests were not run.');
                resultClass = 'tests-notrun';
                // No summary since no tests were run:
                $('.result-summary', this.$dom).html(' ');
            }
            this.$tierResults.append('' + summaryMsg + '');
        }
        this.$tierResults.removeClass('ajax-loading', 'tests-failed',
                                      'tests-passed', 'tests-passed-warnings',
                                      'tests-notrun')
                         .addClass(resultClass);
        if ($('.test-tier', this.$suite).length)
            this.topSummary();
    };

    ResultsTier.prototype.topSummary = function() {
        var $top = $('[class~="test-tier"]' +
                     '[data-tier="' + this.tierId + '"]', this.$suite),
            summaryMsg = resultSummary(this.counts.error, this.counts.warning);

        $('.tier-summary', $top).text(summaryMsg);
        $top.removeClass('ajax-loading', 'tests-failed', 'tests-passed',
                         'tests-notrun');
        if (this.counts.error > 0) {
            $top.addClass('tests-failed');
        } else {
            if (this.testsWereRun)
                $top.addClass('tests-passed');
            else
                $top.addClass('tests-notrun');
        }
    };

    ResultsTier.prototype.wakeUp = function() {
        var $title = $('h4', this.$dom),
            changeLink;
        $('.tier-results', this.$dom).empty();
        this.$dom.removeClass('hidden');
        this.$dom.show();
        if (this.app) {
            // Override the title with a special app/version title
            $title.text(format('{0} {1} {2}',
                               this.app.trans[this.app.guid],
                               this.app.version,
                               gettext('Tests')));
            changeLink = this.app.versionChangeLinks[this.app.guid + ' ' +
                                                     this.app.version];
            if (changeLink) {
                this.$dom.prepend(
                    format('{1}',
                           changeLink,
                           // L10n: Example: Changes in Firefox 5
                           gettext(format('Changes in {0} {1}',
                                          this.app.trans[this.app.guid],
                                          this.app.version.substring(0,1)))));
            }
        } else if (!$title.text()) {
            $title.text(gettext('Tests'));
        }
        $('.tier-results', this.$dom).removeClass('ajax-loading');
    };

    function MsgVisitor(suite, data) {
        this.$suite = suite;
        this.data = data;
        this.$results = $('.results', suite);
        this.msgSet = {};
        this.tiers = {};
        this.appTrans = null;
        this.versionChangeLinks = null;
    }

    MsgVisitor.prototype.createTier = function(tierId, options) {
        if (options && options.app) {
            options.app.trans = this.appTrans;
            options.app.versionChangeLinks = this.versionChangeLinks;
        }
        var tier = new ResultsTier(this.$suite, tierId, options);
        return tier;
    };

    MsgVisitor.prototype.finish = function(msg) {
        var self = this;
        $('.result', this.$suite).each(function(i, res) {
            if (!$('.msg', res).length) {
                // No messages so no tier was created.
                self.getTier($('.tier-results', res).attr('data-tier'));
            }
        });
        $.each(this.tiers, function(tierId, tier) {
            tier.summarize();
        });
    };

    MsgVisitor.prototype.getMsgType = function(msg) {
         return msg['type'];
    };

    MsgVisitor.prototype.getTier = function(tierId, options) {
        if (typeof options === 'undefined')
            options = {app: null};
        if (!options.app
            && this.data.validation.ending_tier
            && this.data.validation.ending_tier < tierId) {
            options.testsWereRun = false;
        }
        if (typeof this.tiers[tierId] === 'undefined')
            this.tiers[tierId] = this.createTier(tierId, options);
        return this.tiers[tierId];
    };

    MsgVisitor.prototype.message = function(msg, options) {
        if (typeof this.msgSet[msg.uid] !== 'undefined')
            return;
        this.msgSet[msg.uid] = true;
        var tier = this.getTier(msg.tier, options),
            msgDiv = $('

'),
            effectiveType = this.getMsgType(msg),
            prefix = effectiveType=='warning' ? gettext('Warning')
                                              : gettext('Error');

        tier.tallyMsgType(effectiveType);
        msgDiv.attr('id', 'v-msg-' + msg.uid);
        msgDiv.addClass('msg-' + effectiveType);
        $('h5', msgDiv).html(msg.message);
        if (typeof(msg.description) === 'undefined' || msg.description === '') {
            msg.description = [];
        } else if (typeof(msg.description) === 'string') {
            // Currently it can be either of these:
            //      descripion: "foo"
            //      description: ["foo", "bar"]
            msg.description = [msg.description];
        }
        $.each(msg.description, function(i, val) {
            msgDiv.append(format('
{0}: {1}
', [prefix, val]));
        });
        if (msg.description.length == 0) {
            msgDiv.append('

');
        }
        if (msg.file) {
            msgDiv.append(this.messageContext(msg));
        }
        $('.tier-results', tier.$dom).append(msgDiv);
    };

    MsgVisitor.prototype.messageContext = function(msg) {
        var ctxFile = msg.file, ctxDiv, code, lines, innerCode;
        if (typeof(ctxFile) === 'string') {
            ctxFile = [ctxFile];
        }
        // e.g. ["silvermelxt_1.3.5.xpi", "chrome/silvermelxt.jar"]
        ctxFile = joinPaths(ctxFile);
        ctxDiv = $(format('
' +
                          '
{0}

', [ctxFile]));
        if (msg.context) {
            code = $('

');
            lines = $('

');
            code.append(lines);
            innerCode = $('

');
            code.append(innerCode);
            msg.context = formatCodeIndentation(msg.context);
            $.each(msg.context, function(n, c) {
                lines.append($(format('
{0}
', [msg.line + n])));
                innerCode.append($(format('
{0}
', [c])));
            });
            ctxDiv.append(code);
        }
        return ctxDiv;
    };

    var CompatMsgVisitor = inherit(MsgVisitor, function(suite, data) {
        this.appTrans = JSON.parse(this.$results.attr('data-app-trans'));
        this.versionChangeLinks = JSON.parse(this.$results.attr('data-version-change-links'));
    });

    CompatMsgVisitor.prototype.finish = function(msg) {
        MsgVisitor.prototype.finish.apply(this, arguments);
        // Since results are more dynamic on the compatibility page,
        // hide tiers without messages.
        $('.result', this.$suite).each(function(i, res) {
            if (!$('.msg', res).length)
                $(res).hide();
        });
    };

    CompatMsgVisitor.prototype.getMsgType = function(msg) {
         return msg.compatibility_type ? msg.compatibility_type: msg['type'];
    };

    CompatMsgVisitor.prototype.message = function(msg) {
        var self = this;
        if (msg.for_appversions) {
            eachAppVer(msg.for_appversions, function(guid, version, id) {
                var app = {guid: guid, version: version, id: id};
                msg.tier = id;  // change the tier to match app/version
                MsgVisitor.prototype.message.apply(self, [msg, {app: app}]);
            });
        } else {
            MsgVisitor.prototype.message.apply(this, arguments);
        }
    };

    function buildResults(suite, data) {
        var vis,
            validation = data.validation,
            summaryTxt;

        if ($('.results', suite).hasClass('compatibility-results'))
            vis = new CompatMsgVisitor(suite, data);
        else
            vis = new MsgVisitor(suite, data);
        $.each(validation.messages, function(i, msg) {
            vis.message(msg);
        });
        vis.finish();

        if (validation.errors > 0) {
            summaryTxt = gettext('Add-on failed validation.');
        } else {
            summaryTxt = gettext('Add-on passed validation.');
        }
        $('.suite-summary span', suite).text(summaryTxt);
        $('.suite-summary', suite).show();
    }

    function eachAppVer(appVer, visit) {
        // Iterates an application/version map and calls
        // visit(gui, version, key) for each item.
        //
        // e.g. {'{ec8030f7-c20a-464f-9b0e-13a3a9e97384}':["4.0b1"]}
        // ->
        //      visit('{ec8030f7-c20a-464f-9b0e-13a3a9e97384}',
        //            "4.0b1",
        //            'ec8030f7-c20a-464f-9b0e-13a3a9e97384-40b1')
        if (appVer) {
            $.each(appVer, function(guid, all_versions) {
                $.each(all_versions, function(i, version) {
                    var key = (guid + '-' + version).replace(/[^a-z0-9_-]+/gi, '');
                    visit(guid, version, key);
                });
            });
        }
    }

    function resultSummary(numErrors, numWarnings) {
        // e.g. '1 error, 3 warnings'
        var errors = format(ngettext('{0} error', '{0} errors', numErrors),
                            [numErrors]),
            warnings = format(ngettext('{0} warning', '{0} warnings', numWarnings),
                              [numWarnings]);
        return format('{0}, {1}', errors, warnings);
    }

    function joinPaths(parts) {
        var p = '';
        $.each(parts, function(i, part) {
            if (!part || typeof(part) !== 'string') {
                // Might be null or empty string.
                return;
            }
            if (p.length) {
                p += '/';
                if (part.substring(0,1) === '/') {
                    // Prevent double slashes.
                    part = part.substring(1);
                }
            }
            p += part;
        });
        return p;
    }

    function formatCodeIndentation(lines) {
        var indent = null;
        $.each(lines, function(i, code) {
            if (code === null) {
                code = ''; // blank line
            }
            lines[i] = code;
            var m = code.length - code.replace(/^\s+/, '').length;
            if (indent === null) {
                indent = m;
            }
            // Look for the smallest common indent of white space.
            if (m < indent) {
                indent = m;
            }
        });
        $.each(lines, function(i, code) {
            if (indent > 0) {
                // Dedent all code to common level.
                code = code.substring(indent);
                lines[i] = code;
            }
            var n = code.search(/[^\s]/); // first non-space char
            if (n > 0) {
                lines[i] = '';
                // Add back the original indentation.
                for (var x=0; x<n; x++) {
                    lines[i] += ' ';
                }
                lines[i] += $.trim(code);
            }
        });
        return lines;
    }

    $('.addon-validator-suite').live('validate', function(e) {
        var el = $(this),
            url = el.attr('data-validateurl');

        $('.test-tier,.tier-results', el).addClass('ajax-loading');

        $.ajax({type: 'POST',
                url: url,
                data: {},
                success: function(data) {
                    if (data.validation == '') {
                        // Note: traceback is in data.error
                        data.validation = {
                            ending_tier: 1,
                            messages: [{
                                'type':'error',
                                message: gettext('Error'),
                                description: [
                                    gettext('Validation task could not ' +
                                            'complete or completed with ' +
                                            'errors')],
                                tier: 1,
                                uid: '__global_error__'
                            }]
                        };
                    }
                    buildResults(el, data);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    buildResults(el, {
                        validation: {
                            ending_tier: 1,
                            messages: [{
                                'type':'error',
                                message: gettext('Error'),
                                description: [gettext('Internal server error')],
                                tier: 1,
                                uid: '__global_error__'
                            }]
                        }
                    });
                },
                dataType: 'json'
        });
    });

    // Validate when the page loads.
    $('#addon-validator-suite').trigger('validate');

};<|endoftext|>


<commit_before>var width = 960;
var mapHeight= 480;

var projection = d3.geo.mercator()
	.scale((width + 1) / 2 / Math.PI)
	.precision(.01);

var path = d3.geo.path()
	.projection(projection);

var zoom = d3.behavior.zoom()
	.translate(projection.translate())
	.scale(projection.scale())
	.on("zoom", function() {
		projection.translate(d3.event.translate).scale(d3.event.scale);
		svg.selectAll("path").attr("d", path);
	});

var svg = d3.select("#mapArea").append("svg")
	.attr("width", width)
	.attr("height", mapHeight)
	.attr("id", "map")
	.call(zoom);

svg.append("rect")
	.attr("id", "bg")
	.attr("width", width)
	.attr("height", mapHeight);

showBgMap("backgroundMap", "data/external/ne_110m_coastline.json");

var svgmap_drag = d3.behavior.drag()
	.origin(function(d) { return d; })
	.on("dragstart", dragstarted)
	.on("drag", dragmove);

var svgmap_resize = d3.behavior.drag()
	.on("dragstart", dragresizestarted)
	.on("drag", dragresize);

function dragstarted() {
	d3.event.sourceEvent.stopPropagation();
}

function dragmove(d) {
	d.x += d3.event ? d3.event.dx : 0;
	d.y += d3.event ? d3.event.dy : 0;
	d3.selectAll("#externalSvg, #resizeHandle")
		.style("margin-left", d.x+"px")
		.style("margin-top",+ d.y+"px");
}

function showBgMap(id, filePath) {
	d3.json(filePath, function(error, world) {

		svg.append("g")
			.attr("id", id)
				.selectAll(".subunit")
			.data(world.features)
			.enter()
				.append("path")
				.attr("class", function(d) {
					return "subunit-boundary subunit " + d.properties.adm0_a3;
				})
				.attr("d", path);

		initExternalSvgMap();
	});
}

var svgMap = null;
var isLoading;

function initExternalSvgMap() {
	$('#externalSvg, #resizeHandle').remove();
	if (svgMap) {
		svgMap = null;
	}
	isLoading = false;
	helper.classed("hidden", true);
}

function loadExternalSvgForYear(year) {
	if (!isLoading) {
		isLoading = true;
		d3.json("gateway.php?getSvg&year="+year+"&ignored="+slider.datum().ignoredMaps.join(",")+"", function(error, incompleteMapInfo) {
			var mapFileName = incompleteMapInfo.fileName;
			if (mapFileName) {
				if (!svgMap || svgMap.datum().fileName !== mapFileName) {
					initExternalSvgMap();

					d3.xml("cache/svg/"+mapFileName, "image/svg+xml", function(xml) {
						svgMap = d3.select(d3.select("#mapArea").node().appendChild(document.importNode(xml.documentElement, true)))
							.attr("name", mapFileName)
							.attr("id", "externalSvg")
							.classed("externalSvg", true);

						svgMap
							.datum({
								id: incompleteMapInfo.id,
								fileName: incompleteMapInfo.fileName,
								x: 0,
								y: 0,
								width:  parseInt(svgMap.attr("width")),
								height: parseInt(svgMap.attr("height"))
							});

						dragmove.call(svgMap.node(), svgMap.datum());

						d3.select("#mapArea")
							.append("svg")
							.attr("id", "resizeHandle")
							.style("left", 200 + svgMap.datum().width  - 16)
							.style("top",        svgMap.datum().height - 16)
							.attr("width",  16)
							.attr("height", 16)
							.call(svgmap_resize)
							.append("rect")
								.attr("x", 0)
								.attr("y", 0)
								.attr("width", 16)
								.attr("height", 16);

						initHelper();
						activateHelperNextStep();

						isLoading = false;
					});
				}
			}
			else {
				initExternalSvgMap();
			}
		});
	}
}

function onTerritoryMouseover() {
	d3.select(this).classed("hovered", true);
}

function onTerritoryMouseout() {
	d3.select(this).classed("hovered", false);
}

function dragresizestarted() {
	d3.event.sourceEvent.stopPropagation();
}

function dragresize(){
	svgMap.datum().width += d3.event.dx;
	svgMap.datum().height += d3.event.dy;

	d3.select("#externalSvg")
		.style("width", svgMap.datum().width+"px")
		.style("height", svgMap.datum().height+"px");

	d3.select("#resizeHandle")
		.style("left", (200 + svgMap.datum().width - 16)+"px")
		.style("top",  (svgMap.datum().height - 16 )+"px");
}<commit_msg>Refactor resize handler size and positionning<commit_after>var width = 960;
var mapHeight= 480;
var resizeHandleSize = 16;

var projection = d3.geo.mercator()
	.scale((width + 1) / 2 / Math.PI)
	.precision(.01);

var path = d3.geo.path()
	.projection(projection);

var zoom = d3.behavior.zoom()
	.translate(projection.translate())
	.scale(projection.scale())
	.on("zoom", function() {
		projection.translate(d3.event.translate).scale(d3.event.scale);
		svg.selectAll("path").attr("d", path);
	});

var svg = d3.select("#mapArea").append("svg")
	.attr("width", width)
	.attr("height", mapHeight)
	.attr("id", "map")
	.call(zoom);

svg.append("rect")
	.attr("id", "bg")
	.attr("width", width)
	.attr("height", mapHeight);

showBgMap("backgroundMap", "data/external/ne_110m_coastline.json");

var svgmap_drag = d3.behavior.drag()
	.origin(function(d) { return d; })
	.on("dragstart", dragstarted)
	.on("drag", dragmove);

var svgmap_resize = d3.behavior.drag()
	.on("dragstart", dragresizestarted)
	.on("drag", dragresize);

function dragstarted() {
	d3.event.sourceEvent.stopPropagation();
}

function dragmove(d) {
	d.x += d3.event ? d3.event.dx : 0;
	d.y += d3.event ? d3.event.dy : 0;
	d3.selectAll("#externalSvg, #resizeHandle")
		.style("margin-left", d.x+"px")
		.style("margin-top",+ d.y+"px");
}

function showBgMap(id, filePath) {
	d3.json(filePath, function(error, world) {

		svg.append("g")
			.attr("id", id)
				.selectAll(".subunit")
			.data(world.features)
			.enter()
				.append("path")
				.attr("class", function(d) {
					return "subunit-boundary subunit " + d.properties.adm0_a3;
				})
				.attr("d", path);

		initExternalSvgMap();
	});
}

var svgMap = null;
var isLoading;

function initExternalSvgMap() {
	$('#externalSvg, #resizeHandle').remove();
	if (svgMap) {
		svgMap = null;
	}
	isLoading = false;
	helper.classed("hidden", true);
}

function loadExternalSvgForYear(year) {
	if (!isLoading) {
		isLoading = true;
		d3.json("gateway.php?getSvg&year="+year+"&ignored="+slider.datum().ignoredMaps.join(",")+"", function(error, incompleteMapInfo) {
			var mapFileName = incompleteMapInfo.fileName;
			if (mapFileName) {
				if (!svgMap || svgMap.datum().fileName !== mapFileName) {
					initExternalSvgMap();

					d3.xml("cache/svg/"+mapFileName, "image/svg+xml", function(xml) {
						svgMap = d3.select(d3.select("#mapArea").node().appendChild(document.importNode(xml.documentElement, true)))
							.attr("name", mapFileName)
							.attr("id", "externalSvg")
							.classed("externalSvg", true);

						svgMap
							.datum({
								id: incompleteMapInfo.id,
								fileName: incompleteMapInfo.fileName,
								x: 0,
								y: 0,
								width:  parseInt(svgMap.attr("width")),
								height: parseInt(svgMap.attr("height"))
							});

						dragmove.call(svgMap.node(), svgMap.datum());

						d3.select("#mapArea")
							.append("svg")
								.attr("id", "resizeHandle")
								.attr("width",  resizeHandleSize)
								.attr("height", resizeHandleSize)
								.call(svgmap_resize)
								.append("rect")
									.attr("x", 0)
									.attr("y", 0)
									.attr("width",  resizeHandleSize)
									.attr("height", resizeHandleSize);

						dragresize.call(d3.select('#resizeHandle').node());

						initHelper();
						activateHelperNextStep();

						isLoading = false;
					});
				}
			}
			else {
				initExternalSvgMap();
			}
		});
	}
}

function onTerritoryMouseover() {
	d3.select(this).classed("hovered", true);
}

function onTerritoryMouseout() {
	d3.select(this).classed("hovered", false);
}

function dragresizestarted() {
	d3.event.sourceEvent.stopPropagation();
}

function dragresize(){
	svgMap.datum().width  += d3.event ? d3.event.dx : 0;
	svgMap.datum().height += d3.event ? d3.event.dy : 0;

	d3.select("#externalSvg")
		.style("width",  svgMap.datum().width +"px")
		.style("height", svgMap.datum().height+"px");

	d3.select(this)
		.style("left", (200 + svgMap.datum().width  - resizeHandleSize)+"px")
		.style("top",  (      svgMap.datum().height - resizeHandleSize)+"px");
}<|endoftext|>


<commit_before>$(document).ready(function(getblog){
	function getblog(){
		$.getJSON("entries.json", function(data){
			alert(data.start.count);
		});
	}
<commit_msg>Check 4<commit_after>$(document).ready(function(getblog){
	function getblog(){
		$.getJSON("entries.json", function(data){
			alert(data.start.count);
		});
});
<|endoftext|>


<commit_before>$(document).ready(getposts);
function getposts(){

    $.getJSON('entries.json', function(data) {
		$.each(data.entries.reverse(), function(key, val) {
                var output="
";
				    output+="
" + val.date +"
";
				    output+="
" + val.title +"
";
				    output+="
" + val.text +"
";
				    output+="
";
					output+="
";

				$("#blog").append(output);
				$('#blog').paginate({itemsPerPage: 1});
      	});
    });
}<commit_msg>JSON to 2<commit_after>$(document).ready(getposts);
function getposts(){

    $.getJSON('entries.json', function(data) {
		$.each(data.entries.reverse(), function(key, val) {
                var output="
";
				    output+="
" + val.date +"
";
				    output+="
" + val.title +"
";
				    output+="
" + val.text +"
";
				    output+="
";
					output+="
";

				$("#blog").append(output);
				$('#blog').paginate({itemsPerPage: 2});
      	});
    });
}<|endoftext|>


<commit_before>var Map;
require('tile');

Map = function () {
    var map;

    map = [];

    this.setMap = function (newMap) {
        map = newMap;
    };

    this.getMap = function () {
        return map;
    }

    this.getView = function (x, y, width, height) {
        var view, i;
        view = map.slice(y, y + height);
        width += x;
        for (i = height; i--;) {
            view[i] = view[i].slice(x, width);
        }
        return view;
    };

    this.randomMap = function (width, height) {
        var i, j, row, random;
        map = [];
        for (i = height; i--;) {
            row = [];
            for (j = width; j--;) {
                random = Math.round(Math.random() * 155) + 50;
                row.push(new Tile(Math.floor(Math.random() * 3)));
            }
            map.push(row);
        }
    };
};<commit_msg>removed an unused variable "random" from the method randomMap<commit_after>var Map;
require('tile');

Map = function () {
    var map;

    map = [];

    this.setMap = function (newMap) {
        map = newMap;
    };

    this.getMap = function () {
        return map;
    }

    this.getView = function (x, y, width, height) {
        var view, i;
        view = map.slice(y, y + height);
        width += x;
        for (i = height; i--;) {
            view[i] = view[i].slice(x, width);
        }
        return view;
    };

    this.randomMap = function (width, height) {
        var i, j, row;
        map = [];
        for (i = height; i--;) {
            row = [];
            for (j = width; j--;) {
                row.push(new Tile(Math.floor(Math.random() * 3)));
            }
            map.push(row);
        }
    };
};<|endoftext|>


<commit_before>$(document).ready(function(){
    $('#studentid').focus();
    var timeout;
    var l;
    var working = false;
    handleresponse = function (msg) {
        console.log(msg);
        l.stop();
        working = false;
        $('#studentid').val('').focus();
        var level='danger';
        var title='Uh-Oh...';
        var description='There may be a problem with your account. Please contact an administrator if this keeps happening.';
        if(msg.code=="checkin"){
            level='success';
            title=msg.name+',';
            description='you are now checked in. Don\'t forget to check out when the meeting is over!';
        }
        if(msg.code=="checkout"){
            level='success';
            title=msg.name+',';
            description='you have checked out. You now have '+msg.hours+' hours.';
        }
        if(msg.code=="exceed"){
            level='warning';
            description='You\'ve been checked in too long! Hours from the last session will not be counted. Input again if you need to be checked in.';
        }
        if(msg.code=="false"){
            description='The entered ID is either too short or too nonexistant.';
        }
        $('#alertbox').html('
'+title+' '+description+'
');
        $('#alertbox').fadeIn(200);
        timeout=setTimeout(function(){$('#alertbox').fadeOut(100);},3000);
    }
    $('#checkin').click(function () {
        if(!working){
            l = Ladda.create(this);
            l.start();
            working = true;
            clearTimeout(timeout);
            $('#alertbox').fadeOut(100);
            var studentid=$('#studentid').val();
            $.ajax({
                type: "GET",
                url: '?p=json&r=checkin&d='+studentid
            }).done(handleresponse).fail(function(){console.log('Something has gone very wrong')});
        }
    });
    $("#studentid").keyup(function(event){
        if(event.keyCode == 13){
            $("#checkin").click();
        }
    });
    var timer = countdown(new Date(2015, 1, 17), function(ts) {
        document.getElementById('clock').innerHTML = ts.toString();
    }, countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
});
<commit_msg>Change count down timing<commit_after>$(document).ready(function(){
    $('#studentid').focus();
    var timeout;
    var l;
    var working = false;
    handleresponse = function (msg) {
        console.log(msg);
        l.stop();
        working = false;
        $('#studentid').val('').focus();
        var level='danger';
        var title='Uh-Oh...';
        var description='There may be a problem with your account. Please contact an administrator if this keeps happening.';
        if(msg.code=="checkin"){
            level='success';
            title=msg.name+',';
            description='you are now checked in. Don\'t forget to check out when the meeting is over!';
        }
        if(msg.code=="checkout"){
            level='success';
            title=msg.name+',';
            description='you have checked out. You now have '+msg.hours+' hours.';
        }
        if(msg.code=="exceed"){
            level='warning';
            description='You\'ve been checked in too long! Hours from the last session will not be counted. Input again if you need to be checked in.';
        }
        if(msg.code=="false"){
            description='The entered ID is either too short or too nonexistant.';
        }
        $('#alertbox').html('
'+title+' '+description+'
');
        $('#alertbox').fadeIn(200);
        timeout=setTimeout(function(){$('#alertbox').fadeOut(100);},3000);
    }
    $('#checkin').click(function () {
        if(!working){
            l = Ladda.create(this);
            l.start();
            working = true;
            clearTimeout(timeout);
            $('#alertbox').fadeOut(100);
            var studentid=$('#studentid').val();
            $.ajax({
                type: "GET",
                url: '?p=json&r=checkin&d='+studentid
            }).done(handleresponse).fail(function(){console.log('Something has gone very wrong')});
        }
    });
    $("#studentid").keyup(function(event){
        if(event.keyCode == 13){
            $("#checkin").click();
        }
    });
    var timer = countdown(new Date(2015, 1, 17, 20, 0, 0, 0), function(ts) {
        document.getElementById('clock').innerHTML = ts.toString();
    }, countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
});
<|endoftext|>


<commit_before>$(document).ready(function(){
    $('#studentid').focus();
    var timeout;
    var l;
    var working = false;
    handleresponse = function (msg) {
        console.log(msg);
        l.stop();
        working = false;
        $('#studentid').val('').focus();
        var level='danger';
        var title='Uh-Oh...';
        var description='There may be a problem with your account. Please contact an administrator if this keeps happening.';
        if(msg.code=="checkin"){
            level='success';
            title=msg.name+',';
            description='you are now checked in. Don\'t forget to check out when the meeting is over!';
        }
        if(msg.code=="checkout"){
            level='success';
            title=msg.name+',';
            description='you have checked out. You now have '+msg.hours+' hours.';
        }
        if(msg.code=="exceed"){
            level='warning';
            description='You\'ve been checked in too long! Hours from the last session will not be counted. Input again if you need to be checked in.';
        }
        if(msg.code=="false"){
            description='The entered ID is either too short or too nonexistant.';
        }
        $('#alertbox').html('
'+title+' '+description+'
');
        $('#alertbox').fadeIn(200);
        timeout=setTimeout(function(){$('#alertbox').fadeOut(100);},3000);
    }
    $('#checkin').click(function () {
        if(!working){
            l = Ladda.create(this);
            l.start();
            working = true;
            clearTimeout(timeout);
            $('#alertbox').fadeOut(100);
            var studentid=$('#studentid').val();
            $.ajax({
                type: "GET",
                url: '?p=json&r=checkin&d='+studentid
            }).done(handleresponse).fail(function(){console.log('Something has gone very wrong')});
        }
    });
    $("#studentid").keyup(function(event){
        if(event.keyCode == 13){
            $("#checkin").click();
        }
    });
    var FlipClockCss = document.createElement("link");
    FlipClockCss.rel = "stylesheet";
    FlipClockCss.href = "assets/css/flipclock.css";
    document.head.appendChild(FlipClockCss);
    var clock = $('#clock').FlipClock({
        autostart: false,
        countdown: true,
        clockFace: 'DailyCounter'
    });
    clock.setTime(new Date(2015, 2, 17));
    clock.start();
});
<commit_msg>fix count down date<commit_after>$(document).ready(function(){
    $('#studentid').focus();
    var timeout;
    var l;
    var working = false;
    handleresponse = function (msg) {
        console.log(msg);
        l.stop();
        working = false;
        $('#studentid').val('').focus();
        var level='danger';
        var title='Uh-Oh...';
        var description='There may be a problem with your account. Please contact an administrator if this keeps happening.';
        if(msg.code=="checkin"){
            level='success';
            title=msg.name+',';
            description='you are now checked in. Don\'t forget to check out when the meeting is over!';
        }
        if(msg.code=="checkout"){
            level='success';
            title=msg.name+',';
            description='you have checked out. You now have '+msg.hours+' hours.';
        }
        if(msg.code=="exceed"){
            level='warning';
            description='You\'ve been checked in too long! Hours from the last session will not be counted. Input again if you need to be checked in.';
        }
        if(msg.code=="false"){
            description='The entered ID is either too short or too nonexistant.';
        }
        $('#alertbox').html('
'+title+' '+description+'
');
        $('#alertbox').fadeIn(200);
        timeout=setTimeout(function(){$('#alertbox').fadeOut(100);},3000);
    }
    $('#checkin').click(function () {
        if(!working){
            l = Ladda.create(this);
            l.start();
            working = true;
            clearTimeout(timeout);
            $('#alertbox').fadeOut(100);
            var studentid=$('#studentid').val();
            $.ajax({
                type: "GET",
                url: '?p=json&r=checkin&d='+studentid
            }).done(handleresponse).fail(function(){console.log('Something has gone very wrong')});
        }
    });
    $("#studentid").keyup(function(event){
        if(event.keyCode == 13){
            $("#checkin").click();
        }
    });
    var FlipClockCss = document.createElement("link");
    FlipClockCss.rel = "stylesheet";
    FlipClockCss.href = "assets/css/flipclock.css";
    document.head.appendChild(FlipClockCss);
    var clock = $('#clock').FlipClock({
        autostart: false,
        countdown: true,
        clockFace: 'DailyCounter'
    });
    var millisecondsUntil = new Date(2015, 2, 17).getTime() - Date.UTC();
    clock.setTime(millisecondsUntil);
    clock.start();
});
<|endoftext|>


<commit_before>'use strict'

const canvasApi = require('../canvasApi')
require('colors')
const log = require('../server/init/logging')

function isInScope (msg) {
  var affArray = msg.affiliation
  return affArray && (affArray.includes('employee') || affArray.includes('student'))
}

function convertToCanvasUser (msg) {
  log.info('\nConverting the user-type message to canvasApi format for: ' + msg.username + ' ' + msg.kthid, ' msg affiliation ', msg.affiliation)

  if (msg.username && (msg.given_name || msg.family_name) && msg.kthid) {
    let user = {
      pseudonym: {
        unique_id: `${msg.username}@kth.se`, // CSVs analogi av 'login_id'
        sis_user_id: msg.kthid // CSVs analogi av 'user_id' needed for enrollments
      },
      user: {
        'name': `${msg.given_name} ${msg.family_name}`
      }
    }
    return user
  } else {
    return
  }
}

function createOrUpdate (user) {
  return canvasApi.getUser(user.pseudonym.sis_user_id)
        .then(userFromCanvas => {
          log.info('found user in canvas', userFromCanvas)
          log.info('update the user with new values: ', user)
          return userFromCanvas
        })
        .then(userFromCanvas => canvasApi.updateUser(user, userFromCanvas.id))
        .catch(e => {
          if (e.statusCode === 404) {
            log.info('user doesnt exist in canvas. Trying to create it.', user)
            return canvasApi.createUser(user)
            .then(res => {
              log.info('Success! User created', res)
              return res
            })
          } else {
            throw e
          }
        })
}

module.exports = function (msg) {
  if (!isInScope(msg)) {
    log.info('\nUser is not an employee and not a student, out of the affilication scope. Skipping user ' + msg.username + ' ' + msg.kthid + ' with affiliation ' + msg.affiliation)
    return Promise.resolve('User not in affiliation scope...')
  }

  let user = convertToCanvasUser(msg)

  if (!user) {
    log.info('\nIncomplete fields to create user in canvas, skipping. Probably,it is missing a name(given_name, family_name) or a username or kth_id.....', msg)
    return Promise.resolve('Some of required users fields are missing (a name(given_name, family_name) or a username or kth_id), skipping message')
  }

  return createOrUpdate(user)
}
<commit_msg>refactor handleUserMessage<commit_after>'use strict'

const canvasApi = require('../canvasApi')
require('colors')
const log = require('../server/init/logging')

function isInScope (msg) {
  var affArray = msg.affiliation
  const result = affArray && (affArray.includes('employee') || affArray.includes('student'))
  if (!result) {
    log.info('\nUser is not an employee and not a student, out of the affilication scope. User ' + msg.username + ' ' + msg.kthid + ' with affiliation ' + msg.affiliation)
  }
  return result
}

function convertToCanvasUser (msg) {
  log.info('\nConverting the user-type message to canvasApi format for: ' + msg.username + ' ' + msg.kthid, ' msg affiliation ', msg.affiliation)

  if (msg.username && (msg.given_name || msg.family_name) && msg.kthid) {
    let user = {
      pseudonym: {
        unique_id: `${msg.username}@kth.se`, // CSVs analogi av 'login_id'
        sis_user_id: msg.kthid // CSVs analogi av 'user_id' needed for enrollments
      },
      user: {
        'name': `${msg.given_name} ${msg.family_name}`
      }
    }
    return user
  } else {
    log.info('\nIncomplete fields to create user in canvas, skipping. Probably,it is missing a name(given_name, family_name) or a username or kth_id.....', msg)
    return
  }
}

function createOrUpdate (user) {
  return canvasApi.getUser(user.pseudonym.sis_user_id)
        .then(userFromCanvas => {
          log.info('found user in canvas', userFromCanvas)
          log.info('update the user with new values: ', user)
          return userFromCanvas
        })
        .then(userFromCanvas => canvasApi.updateUser(user, userFromCanvas.id))
        .catch(e => {
          if (e.statusCode === 404) {
            log.info('user doesnt exist in canvas. Create it.', user)
            return canvasApi.createUser(user)
            .then(res => {
              log.info('Success! User created', res)
              return res
            })
          } else {
            throw e
          }
        })
}

module.exports = function (msg) {
  const user = convertToCanvasUser(msg)

  if (isInScope(msg) && user) {
    return createOrUpdate(user)
    .then(user => msg)
  } else {
    return Promise.resolve(msg)
  }
}
<|endoftext|>


<commit_before>(function ($, window, document, undefined) {

  'use strict';

/*
* d3
*/
// stage
var w = window,
    windowWidth = w.innerWidth,
    windowHeight = w.innerHeight;

var width = windowWidth,
    height = windowHeight;

// globe
var globe = {type: 'Sphere'},
    velocity = 0.005,
    radius = Math.sqrt(width*height)/2,
    scale = radius;

// colors
var color = {
  bright: '#fff',
  dark: '#263238'
};

// JSONP data stuff
var dataISS = null,
    urlISS = 'http://api.open-notify.org/iss-now.json?callback=?',
    latISS = null,
    lonISS = null,
    tick = 0;

// create CANVAS tag
var canvas = d3.select('.draw')
  .append('canvas')
  .attr('width', width)
  .attr('height', height)
  .attr('class', 'globe');

var context = canvas.node().getContext('2d');

// choose geo projection type
var projection = d3.geo.orthographic()
  // .translate([width/2, height/2])
  .translate([width/2, height + height/6])
  .scale(scale)
  .clipAngle(90)
  .precision(0.5);

// create geographic shapes from projection and context
var geoPath = d3.geo.path()
  .projection(projection)
  .context(context);

// get data from local JSON for globe
d3.json('assets/json/world-110m.json', function(error, dataWorld) {
    if (error) {
      throw error;
    }

    var land = topojson.feature(dataWorld, dataWorld.objects.land);
    var borders = topojson.mesh(dataWorld, dataWorld.objects.countries, function(a, b) { return a != b; });

    // Get API from open-notify.org every 5 seconds and
    // write to local storage with sessionStorage.
    // Project the data and rotate, too.
    setInterval(function() {
      console.log('update sessionStorage from open notify API');

      $.getJSON(urlISS, function(storedData) {
        sessionStorage.setItem('storedData', JSON.stringify(storedData));
      });

      // get data from local storage
      dataISS = JSON.parse(sessionStorage.getItem('storedData'));
        latISS = dataISS.iss_position.latitude;
        lonISS = dataISS.iss_position.longitude;

      console.log(dataISS);

      projection.rotate([lonISS, latISS, 0]); // test rotation
      // projection.rotate([-velocity * elapsed, 0, 90]); // test rotation

      // don't draw rectangle
      context.clearRect(0, 0, width, height);

      // outline and fill globe
      context.beginPath();
      geoPath(globe);
      context.fillStyle = color.dark;
      context.fill();
      context.lineWidth = 2;
      context.strokeStyle = color.dark;
      context.stroke();

      // fill landmass
      context.beginPath();
      geoPath(land);
      context.fillStyle = color.bright;
      context.fill();
      context.lineWidth = 1;
      context.strokeStyle = color.dark;
      context.stroke();

      // draw lines of country borders
      context.beginPath();
      geoPath(borders);
      context.lineWidth = 0.5;
      context.strokeStyle = color.dark;
      context.stroke();
    }, 5000);

    // d3.timer(function(elapsed) {

    // });
});

// console.log(dataISS);

})(jQuery, window, document);
<commit_msg>now the earth turns correctly from ISS position, with bearing<commit_after>(function ($, d3, window, document, undefined) {

  'use strict';

/*
* d3
*/
// stage
var w = window,
    windowWidth = w.innerWidth,
    windowHeight = w.innerHeight;

var width = windowWidth,
    height = windowHeight;

// globe
var globe = {type: 'Sphere'},
    circle = {type: "GeometryCollection", geometries: 'circles'},
    velocity = 0.005,
    // radius = Math.sqrt(width*height)/3,
    radius = Math.sqrt(width*height)/2,
    scale = radius,
    distance = 2;

// colors
var color = {
  bright: '#fff',
  darkest: '#263238',
  dark: '#999'
};

// JSONP data stuff
var dataISS = null,
    urlISS = 'http://api.open-notify.org/iss-now.json?callback=?',
    latISS = null,
    lonISS = null,
    latISSPast = 0,
    lonISSPast = 0,
    rotationISS = 90,
    rotationISSPast = 0,
    tick = 0;

// create CANVAS tag
var canvas = d3.select('.draw')
  .append('canvas')
  .attr('width', width)
  .attr('height', height)
  .attr('class', 'draw-globe');

var context = canvas.node().getContext('2d');

// // choose geo projection type
// var projection = d3.geo.satellite()
//   .distance(distance)
//   .scale(scale*2)
//   .tilt(40)
//   // .center([0, -7])
//   // .translate([width/2, height/2])
//   // .translate([width/2, height + height/8])
//   .clipAngle(Math.acos(1 / distance) * 180 / Math.PI - 1e-6)
//   .precision(0.5);

// choose geo projection type
var projection = d3.geo.orthographic()
  // .center([50,50])
  .translate([width/2, height/2])
  // .translate([width/2, height + height/6])
  .scale(scale)
  .clipAngle(90)
  .precision(0.5);

// create geographic shapes from projection and context
var geoPath = d3.geo.path()
  .projection(projection)
  .context(context);

// get data from local JSON for globe
d3.json('assets/json/world-110m.json', function(error, dataWorld) {
    if (error) {
      throw error;
    }

    getDataISS();

    var land = topojson.feature(dataWorld, dataWorld.objects.land);
    var borders = topojson.mesh(dataWorld, dataWorld.objects.countries, function(a, b) { return a != b; });

    // Get API from open-notify.org every 5 seconds and
    // write to local storage with sessionStorage.
    // Project the data and rotate, too.
    setInterval(function() {
      console.log('update sessionStorage from open notify API');
      // console.log(lonISSPast);
      latISSPast = latISS;
      lonISSPast = lonISS;
      rotationISSPast = rotationISS;
      // console.log(lonISS);
      getDataISS();

      // var geoCircle = d3.geo.circle()
      //   .origin([lonISS, latISS])
      //   .angle(500);
      // var geoCircles = [geoCircle()];

      // bearing
      // http://www.movable-type.co.uk/scripts/latlong.html
      // https://github.com/chrisveness/geodesy
      var posISS = new LatLon(latISS, lonISS);
      var posISSPast = new LatLon(latISSPast, lonISSPast);
      var bearing = posISS.bearingTo(posISSPast);
      console.log('LatLon degrees: ' + latISS + ', ' + lonISS);
      console.log('LatLon: ' + posISS);
      console.log('LatLon past: ' + posISSPast);
      console.log('Bearing: ' + bearing);

      // d3.timer(function(elapsed) {
      //   d3.transition()
      //     .duration(4999)
      //     .ease('linear')
      //     .tween('rotate', function () {
            // projection.rotate([52.5167, 13.3833, 0]); // -> Berlin Coords
            projection.rotate([lonISS, latISS, bearing]); // test rotation
            // projection.rotate([-velocity * elapsed, 0, 90]); // test rotation

            // don't draw rectangle
            context.clearRect(0, 0, width, height);

            // outline and fill globe
            context.beginPath();
            geoPath(globe);
            context.fillStyle = color.dark;
            context.fill();
            context.lineWidth = 2;
            context.strokeStyle = color.dark;
            context.stroke();

            // fill landmass
            context.beginPath();
            geoPath(land);
            context.fillStyle = color.bright;
            context.fill();
            context.lineWidth = 1;
            context.strokeStyle = color.dark;
            context.stroke();

            // draw lines of country borders
            context.beginPath();
            geoPath(borders);
            context.lineWidth = 0.5;
            context.strokeStyle = color.dark;
            context.stroke();

            // context.beginPath();
            // path({type: "GeometryCollection", geometries: geoCircles});
            // context.fillStyle = color.dark;
            // context.fill();
            // context.lineWidth = 0.5;
            // context.strokeStyle = color.dark;
            // context.stroke();

      //   }); // END transition
      // }); // END timer
    }, 5000); // END setInterval

});

function getDataISS () {
  $.getJSON(urlISS, function(storedData) {
    sessionStorage.setItem('storedData', JSON.stringify(storedData));
  });

  // get data from local storage
  dataISS = JSON.parse(sessionStorage.getItem('storedData'));
      lonISS = dataISS.iss_position.longitude * -1;
      latISS = dataISS.iss_position.latitude * -1;
    // lonISS = -121 * -1;
    // latISS = 35.5 * -1;
}

})(jQuery, d3, window, document);
<|endoftext|>