<commit_before>/*
*   khrizenriquez <christoferen7@gmail.com>
*/

//'use strict';
var map;
var mapContainer    = document.getElementById('mapContainer');
var mapOptions      = {
    zoomControl: false,
    mapTypeControl: true,
    scaleControl: false,
    streetViewControl: false,
    rotateControl: false,
    center: {
        lat: 14.6586779, lng: -90.5133461
    }, scrollwheel: false,
    zoom: 18
};

var showMarkerInfo = function (element) {
    $('#mapOptions').modal('show');
};

// var options = {
//   enableHighAccuracy: true,
//   timeout: 5000,
//   maximumAge: 0
// };
//
// function success(pos) {
//   var crd = pos.coords;
//
//   console.log('Your current position is:');
//   console.log('Latitude : ' + crd.latitude);
//   console.log('Longitude: ' + crd.longitude);
//   console.log('More or less ' + crd.accuracy + ' meters.');
// };
//
// function error(err) {
//   console.warn('ERROR(' + err.code + '): ' + err.message);
// };
//
// navigator.geolocation.getCurrentPosition(success, error, options);

var initMap = function () {
    var poolLatLng      = new google.maps.LatLng(14.659124, -90.512665);
    var fieldLatLng     = new google.maps.LatLng(14.657474, -90.512412);
    //var cabinLatLng     = new google.maps.LatLng(14.657176, -90.513357);
    var infoWindow = new google.maps.InfoWindow({map: map});
    // Create a map object and specify the DOM element for display.
    map = new google.maps.Map(mapContainer, mapOptions);

    var markerPool = new google.maps.Marker({
        position:   poolLatLng,
        title:      "Piscina"
    });
    var markerField = new google.maps.Marker({
        position:   fieldLatLng,
        title:      "Campo"
    });
    // var markerCabin = new Marker({
    //     map:        map,
    //     position:   new google.maps.LatLng(14.657176, -90.513357),
    //     title:      "Cabañas",
    //     icon: {
    //         path: MAP_PIN,
    // 		fillColor: '#00CCBB',
    // 		fillOpacity: 1,
    // 		strokeColor: '#000',
    // 		strokeWeight: 1
    //     }, map_icon_label: ''
    // });

    var infowindow = new google.maps.InfoWindow({
        content: '
Piscina

Ver más
'
    });
    markerPool.addListener('click', function() {
        infowindow.open(map, markerPool);
    });

    // To add the marker to the map, call setMap();
    //markerPool.setMap(map);
    //markerField.setMap(map);
    //markerCabin.setMap(map);

    // if (navigator.geolocation) {
    //     navigator.geolocation.getCurrentPosition(function(position) {
    //       var pos = {
    //         lat: position.coords.latitude,
    //         lng: position.coords.longitude
    //       };
    //
    //       infoWindow.setPosition(pos);
    //       infoWindow.setContent('Location found.');
    //       map.setCenter(pos);
    //     }, function() {
    //       handleLocationError(true, infoWindow, map.getCenter());
    //     });
    //   } else {
    //     // Browser doesn't support Geolocation
    //     handleLocationError(false, infoWindow, map.getCenter());
    //   }
};

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                        'Error: The Geolocation service failed.' :
                        'Error: Your browser doesn\'t support geolocation.');
}

var loadGoogleMaps = function () {
    var container = '';
    initMap();
};

var drawMarker = function (map, obj) {};
var drawMarkers = function (map, arrObj) {
    var m = map || new google.maps.Map(mapContainer, mapOptions);
    var data = arrObj || [];

    data.some(function (element, index, arr) {
        if (element.isActive) {
            element.locations.some(function (el, ind, ar) {
                console.log(el);
                new Marker({
                    map:        map,
                    position:   new google.maps.LatLng(Number(el.latitude), Number(el.longitude)),
                    title:      element.name,
                    icon: {
                        path: MAP_PIN,
                		fillColor: '#00CCBB',
                		fillOpacity: 1,
                		strokeColor: '#000',
                		strokeWeight: 1
                    }, map_icon_label: ''
                });
            });
        }
    });
};

var fillMapOptions = function () {
    var xhr         = new XMLHttpRequest();
    var container   = document.querySelector('.container-map .optionsContainer #container-map-list-elements');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            var response    = JSON.parse(xhr.responseText);
            container.innerHTML = '';

            response.some(function (element, index, arr) {
                if (element.isActive) {
                    container.innerHTML += "
<input id='element-"+
                    index
                    +"' type='checkbox' value='1' /> "+
                    "" +
                    element.name
                    +"
";
                }
            });

            drawMarkers(map, response);
        }
    };
    xhr.open('GET', 'storage/info.json', true);
    xhr.send(null);
};

document.addEventListener('DOMContentLoaded', function () {  });

window.onload = function() {
    loadGoogleMaps();
    fillMapOptions();
};
<commit_msg>Activando la localización del usuario<commit_after>/*
*   khrizenriquez <christoferen7@gmail.com>
*/

//'use strict';
var map;
var mapContainer    = document.getElementById('mapContainer');
var mapOptions      = {
    zoomControl: false,
    mapTypeControl: true,
    scaleControl: false,
    streetViewControl: false,
    rotateControl: false,
    center: {
        lat: 14.6586779, lng: -90.5133461
    }, scrollwheel: false,
    zoom: 18
};

var showMarkerInfo = function (element) {
    $('#mapOptions').modal('show');
};

// var options = {
//   enableHighAccuracy: true,
//   timeout: 5000,
//   maximumAge: 0
// };
//
// function success(pos) {
//   var crd = pos.coords;
//
//   console.log('Your current position is:');
//   console.log('Latitude : ' + crd.latitude);
//   console.log('Longitude: ' + crd.longitude);
//   console.log('More or less ' + crd.accuracy + ' meters.');
// };
//
// function error(err) {
//   console.warn('ERROR(' + err.code + '): ' + err.message);
// };
//
// navigator.geolocation.getCurrentPosition(success, error, options);

var initMap = function () {
    var poolLatLng      = new google.maps.LatLng(14.659124, -90.512665);
    var fieldLatLng     = new google.maps.LatLng(14.657474, -90.512412);
    //var cabinLatLng     = new google.maps.LatLng(14.657176, -90.513357);
    var infoWindow = new google.maps.InfoWindow({map: map});
    // Create a map object and specify the DOM element for display.
    map = new google.maps.Map(mapContainer, mapOptions);

    var markerPool = new google.maps.Marker({
        position:   poolLatLng,
        title:      "Piscina"
    });
    var markerField = new google.maps.Marker({
        position:   fieldLatLng,
        title:      "Campo"
    });
    // var markerCabin = new Marker({
    //     map:        map,
    //     position:   new google.maps.LatLng(14.657176, -90.513357),
    //     title:      "Cabañas",
    //     icon: {
    //         path: MAP_PIN,
    // 		fillColor: '#00CCBB',
    // 		fillOpacity: 1,
    // 		strokeColor: '#000',
    // 		strokeWeight: 1
    //     }, map_icon_label: ''
    // });

    var infowindow = new google.maps.InfoWindow({
        content: '
Piscina

Ver más
'
    });
    markerPool.addListener('click', function() {
        infowindow.open(map, markerPool);
    });

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };

            new Marker({
                map:        map,
                position:   new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
                title:      "Cabañas",
                icon: {
                    path: MAP_PIN,
            		fillColor: '#00CCBB',
            		fillOpacity: 1,
            		strokeColor: '#000',
            		strokeWeight: 1
                }, map_icon_label: ''
            });
            //map.setCenter(pos);
        }, function() {
            console.log('No compartio su ubicación');
        });
    } else {
        // Browser doesn't support Geolocation
        alert('Tú navegador no soporta la funcionalidad de geolocalización');
    }
};

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                        'Error: The Geolocation service failed.' :
                        'Error: Your browser doesn\'t support geolocation.');
}

var loadGoogleMaps = function () {
    var container = '';
    initMap();
};

var drawMarker = function (map, obj) {};
var drawMarkers = function (map, arrObj) {
    var m = map || new google.maps.Map(mapContainer, mapOptions);
    var data = arrObj || [];

    data.some(function (element, index, arr) {
        if (element.isActive) {
            element.locations.some(function (el, ind, ar) {
                console.log(el);
                new Marker({
                    map:        map,
                    position:   new google.maps.LatLng(Number(el.latitude), Number(el.longitude)),
                    title:      element.name,
                    icon: {
                        path: MAP_PIN,
                		fillColor: '#00CCBB',
                		fillOpacity: 1,
                		strokeColor: '#000',
                		strokeWeight: 1
                    }, map_icon_label: ''
                });
            });
        }
    });
};

var fillMapOptions = function () {
    var xhr         = new XMLHttpRequest();
    var container   = document.querySelector('.container-map .optionsContainer #container-map-list-elements');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            var response    = JSON.parse(xhr.responseText);
            container.innerHTML = '';

            response.some(function (element, index, arr) {
                if (element.isActive) {
                    container.innerHTML += "
<input id='element-"+
                    index
                    +"' type='checkbox' value='1' /> "+
                    "" +
                    element.name
                    +"
";
                }
            });

            drawMarkers(map, response);
        }
    };
    xhr.open('GET', 'storage/info.json', true);
    xhr.send(null);
};

document.addEventListener('DOMContentLoaded', function () {  });

window.onload = function() {
    loadGoogleMaps();
    fillMapOptions();
};
<|endoftext|>


<commit_before>var app = angular.module('demo', []);

app.config(function ($routeProvider) {
  $routeProvider
  .when('/map', {
  templateUrl:'map.html'
  })
  .when('/ad', {
    templateUrl:'mac.html'
  })
  .when('/game', {
    templateUrl:'game.html'
  })
  .when('/trailler', {
    templateUrl:'trailler.html'
  })
  .when('/macys', {
    templateUrl:'macys.html'
  })
  .otherwise({
    templateUrl:'dashboard.html'
  });
});

app.controller('MainCtrl', function($scope, $rootScope, $location) {
  $scope.go = function(path,direction) {
      if(direction == 'top' || direction == 'bottom') {
        path = '/dashboard';
      } else if(path=='ad') {
        $scope.nextPage = '/macys';
      } else if(path=='/macys') {
        $scope.nextPage = 'ad';
      } else {
        $scope.nextPage = '/dashboard';
      }
      $scope.direction = direction;
      //$scope.addMov(direction);
      $location.path(path);
  };
  $scope.movs = [];

  /**var fb = new Firebase('https://boiling-fire-1817.firebaseio.com');
  fb.on('value', function(snapshot) {
    $scope.movs = [];
    snapshot.forEach(function(childSnapshot) {
      var childData = childSnapshot.val();
      $scope.movs.push({direction:childData.direction});
    });
  });

  $scope.addMov = function (dir) {
    $scope.movs.push({direction:dir});
    fb.push({direction:dir});
  };
  **/

});

$(document).ready(function () {
  Kinect.connect("http://localhost", 8181);
  engagedUser = null;

  sensor = Kinect.sensor(Kinect.DEFAULT_SENSOR_NAME, function (sensorToConfig, isConnected) {
                if (isConnected) {
                    // Determine what is the engagement state upon connection
                    sensorToConfig.getConfig(function (data) {
                        var engagedUserId = findEngagedUser(data[Kinect.INTERACTION_STREAM_NAME].userStates);

                        updateUserState(true, engagedUserId, sensorToConfig);
                    });
                } else {
                    updateUserState(false, engagedUser, sensorToConfig);
                }
            });

  // Get the id of the engaged user, if present, or null if there is no engaged user
  function findEngagedUser(userStates) {
      var engagedUserId = null;

      for (var i = 0; i < userStates.length; ++i) {
          var entry = userStates[i];
          if (entry.userState == "engaged") {
              engagedUserId = entry.id;
              break;
          }
      }
      console.log("engagedUserId")
      console.log(engagedUserId);

      return engagedUserId;
  };
  var delayedConfigTimeoutId = null;
            function updateUserState(newIsSensorConnected, newEngagedUser, sensorToConfig) {
                var hasEngagedUser = engagedUser != null;
                var newHasEngagedUser = newEngagedUser != null;

                // If there's a pending configuration change when state changes again, cancel previous timeout
                if (delayedConfigTimeoutId != null) {
                    clearTimeout(delayedConfigTimeoutId);
                    delayedConfigTimeoutId = null;
                }

                if ((isSensorConnected != newIsSensorConnected) || (engagedUser != newEngagedUser)) {
                    if (newIsSensorConnected) {

                        var immediateConfig = {};
                        var delayedConfig = {};
                        immediateConfig[Kinect.INTERACTION_STREAM_NAME] = { "enabled": true };
                        immediateConfig[Kinect.USERVIEWER_STREAM_NAME] = { "resolution": streamImageResolution };
                        immediateConfig[Kinect.BACKGROUNDREMOVAL_STREAM_NAME] = { "resolution": streamImageResolution };

                        setCursorVisibility(newHasEngagedUser);
                        setCanvasVisibility(userViewerCanvasElement, !newHasEngagedUser);
                        setCanvasVisibility(backgroundRemovalCanvasElement, newHasEngagedUser);

                        if (newHasEngagedUser) {
                            immediateConfig[Kinect.BACKGROUNDREMOVAL_STREAM_NAME].enabled = true;
                            immediateConfig[Kinect.BACKGROUNDREMOVAL_STREAM_NAME].trackingId = newEngagedUser;

                            delayedConfig[Kinect.USERVIEWER_STREAM_NAME] = { "enabled": false };
                        } else {
                            immediateConfig[Kinect.USERVIEWER_STREAM_NAME].enabled = true;

                            if (hasEngagedUser) {
                                delayedConfig[Kinect.BACKGROUNDREMOVAL_STREAM_NAME] = { "enabled": false };
                            }
                        }

                        // Perform immediate configuration
                        sensorToConfig.postConfig(immediateConfig, configError);

                        // schedule delayed configuration for 2 seconds later
                        if (!isEmptyObject(delayedConfig)) {
                            delayedConfigTimeoutId = setTimeout(function () {
                                sensorToConfig.postConfig(delayedConfig, configError);
                                delayedConfigTimeoutId = null;
                            }, 2000);
                        }
                    } else {
                        setCursorVisibility(false);
                        setCanvasVisibility(userViewerCanvasElement, false);
                        setCanvasVisibility(backgroundRemovalCanvasElement, false);
                    }
                }

                isSensorConnected = newIsSensorConnected;
                engagedUser = newEngagedUser;

                resetHidePanelTimeout();
            };

});

<commit_msg>Sensor Handling<commit_after>var app = angular.module('demo', []);

app.config(function ($routeProvider) {
  $routeProvider
  .when('/map', {
  templateUrl:'map.html'
  })
  .when('/ad', {
    templateUrl:'mac.html'
  })
  .when('/game', {
    templateUrl:'game.html'
  })
  .when('/trailler', {
    templateUrl:'trailler.html'
  })
  .when('/macys', {
    templateUrl:'macys.html'
  })
  .otherwise({
    templateUrl:'dashboard.html'
  });
});

app.controller('MainCtrl', function($scope, $rootScope, $location) {
  $scope.go = function(path,direction) {
      if(direction == 'top' || direction == 'bottom') {
        path = '/dashboard';
      } else if(path=='ad') {
        $scope.nextPage = '/macys';
      } else if(path=='/macys') {
        $scope.nextPage = 'ad';
      } else {
        $scope.nextPage = '/dashboard';
      }
      $scope.direction = direction;
      //$scope.addMov(direction);
      $location.path(path);
  };
  $scope.movs = [];

  /**var fb = new Firebase('https://boiling-fire-1817.firebaseio.com');
  fb.on('value', function(snapshot) {
    $scope.movs = [];
    snapshot.forEach(function(childSnapshot) {
      var childData = childSnapshot.val();
      $scope.movs.push({direction:childData.direction});
    });
  });

  $scope.addMov = function (dir) {
    $scope.movs.push({direction:dir});
    fb.push({direction:dir});
  };
  **/

});

$(document).ready(function () {
  Kinect.connect("localhost", 8181);
  engagedUser = null;

  sensor = Kinect.sensor(Kinect.DEFAULT_SENSOR_NAME, function (sensorToConfig, isConnected) {
                if (isConnected) {
                    // Determine what is the engagement state upon connection
                    sensorToConfig.getConfig(function (data) {
                        var engagedUserId = findEngagedUser(data[Kinect.INTERACTION_STREAM_NAME].userStates);

                        updateUserState(true, engagedUserId, sensorToConfig);
                    });
                } else {
                    updateUserState(false, engagedUser, sensorToConfig);
                }
            });

  // Get the id of the engaged user, if present, or null if there is no engaged user
  function findEngagedUser(userStates) {
      var engagedUserId = null;

      for (var i = 0; i < userStates.length; ++i) {
          var entry = userStates[i];
          if (entry.userState == "engaged") {
              engagedUserId = entry.id;
              break;
          }
      }
      console.log("engagedUserId")
      console.log(engagedUserId);

      return engagedUserId;
  };
  var delayedConfigTimeoutId = null;
            function updateUserState(newIsSensorConnected, newEngagedUser, sensorToConfig) {
                var hasEngagedUser = engagedUser != null;
                var newHasEngagedUser = newEngagedUser != null;

                // If there's a pending configuration change when state changes again, cancel previous timeout
                if (delayedConfigTimeoutId != null) {
                    clearTimeout(delayedConfigTimeoutId);
                    delayedConfigTimeoutId = null;
                }

                if ((isSensorConnected != newIsSensorConnected) || (engagedUser != newEngagedUser)) {
                    if (newIsSensorConnected) {

                        var immediateConfig = {};
                        var delayedConfig = {};
                        immediateConfig[Kinect.INTERACTION_STREAM_NAME] = { "enabled": true };
                        immediateConfig[Kinect.USERVIEWER_STREAM_NAME] = { "resolution": streamImageResolution };
                        immediateConfig[Kinect.BACKGROUNDREMOVAL_STREAM_NAME] = { "resolution": streamImageResolution };

                        setCursorVisibility(newHasEngagedUser);
                        setCanvasVisibility(userViewerCanvasElement, !newHasEngagedUser);
                        setCanvasVisibility(backgroundRemovalCanvasElement, newHasEngagedUser);

                        if (newHasEngagedUser) {
                            immediateConfig[Kinect.BACKGROUNDREMOVAL_STREAM_NAME].enabled = true;
                            immediateConfig[Kinect.BACKGROUNDREMOVAL_STREAM_NAME].trackingId = newEngagedUser;

                            delayedConfig[Kinect.USERVIEWER_STREAM_NAME] = { "enabled": false };
                        } else {
                            immediateConfig[Kinect.USERVIEWER_STREAM_NAME].enabled = true;

                            if (hasEngagedUser) {
                                delayedConfig[Kinect.BACKGROUNDREMOVAL_STREAM_NAME] = { "enabled": false };
                            }
                        }

                        // Perform immediate configuration
                        sensorToConfig.postConfig(immediateConfig, configError);

                        // schedule delayed configuration for 2 seconds later
                        if (!isEmptyObject(delayedConfig)) {
                            delayedConfigTimeoutId = setTimeout(function () {
                                sensorToConfig.postConfig(delayedConfig, configError);
                                delayedConfigTimeoutId = null;
                            }, 2000);
                        }
                    } else {
                        setCursorVisibility(false);
                        setCanvasVisibility(userViewerCanvasElement, false);
                        setCanvasVisibility(backgroundRemovalCanvasElement, false);
                    }
                }

                isSensorConnected = newIsSensorConnected;
                engagedUser = newEngagedUser;

                resetHidePanelTimeout();
            };

});

<|endoftext|>


<commit_before>/*global MozSmsFilter*/
$(function() {
  'use strict';

  /*
  function logObject(obj) {
    $("#response").append("
 New Object: " + obj);
    Object.keys(obj).forEach(function (key) {
      $("#response").append("
 " + key + ": " + obj[key]);
    });
  }
  */
  function logMsg(msg) {
    [
      'type', 'id', 'threadId', 'body', 'delivery', 'deliveryStatus', 'read'
    , 'receiver', 'sender', 'timestamp', 'messageClass'
    ].forEach(function (key) {
      $("#response").append("
 " + key + ": " + msg[key]);
    });
  }

  $('form#sms-form').on("submit", function (ev) {
    $("#response").html("submit form");
    ev.preventDefault();
    ev.stopPropagation();

	//var crypto = crypto.subtle;
	var message = $('[name=msg]').val();

	var pwUtf8 = new TextEncoder().encode(message);
	var pwHash = crypto.subtle.digest('SHA-256', pwUtf8);

	var iv = crypto.getRandomValues(new Uint8Array(20));
	var alg = { name: 'AES-GCM', iv: iv };
	var key = crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']);

	var cryptedMessage = crypto.subtle.encrypt(alg, key, cryptedMessage);

	var decryptedMessage = crypto.subtle.decrypt(alg, key, data);

    var msg = decryptedMessage
      , phone = $('[name=phone]').val()
      , request;

    $("#response").html("got values");

    request = navigator.mozMobileMessage.send(phone, msg);
    $("#response").html("tried to send message");

    $("#response").html("iterate through requests");
    request.onsuccess = function () {
      window.thing = this;
      console.error(this.result);
      $("#response").html("Sent to
" + this.result);
      logMsg(this.result);
    };
    request.onerror = function () {
      window.thing = this;
      console.error(this.error.name);
      console.error(this.error.message);
      $("#response").html(this.error.name + ':' + this.error.message);
    };
    //});
  });

  function showMessages(id) {
    var filter = new MozSmsFilter() // https://developer.mozilla.org/en-US/docs/Web/API/MozSmsFilter
      , cursor
      ;

    filter.read = false;
    if ('undefined' !== typeof id) {
      filter.threadId = id;
    }

    // Get the messages from the latest to the first
    cursor = navigator.mozMobileMessage.getMessages(filter, true);

    cursor.onsuccess = function () {
      logMsg(this.result);
      /*
      var message = this.result
        , time = message.timestamp.toDateString()
        ;

      console.log(time + ': ' + (message.body || message.subject)); // SMS || MMS
      $("#response").append("
Got new message [" + time + "]"
        + "
" + (message.body || message.subject)
        + "
"
      );

      if (!this.done) {
        this.continue();
      }
      */
    };
  }

  // 'received' seems to only activate after a message is sent
  navigator.mozMobileMessage.addEventListener('received', function (msg) {
    // https://developer.mozilla.org/en-US/docs/Web/API/MozSmsMessage
    $("#response").html("Got a message");
    $("#response").append("
" + msg);
    logMsg(msg);

    showMessages(msg.id);
  });

  navigator.mozSetMessageHandler("alarm", function (mozAlarm) {
    // var directive = alorms[mozAlarm.data.id]; doStuff(directive);
    $("#alarms").append("
Alarm Fired: " + new Date().toString().replace(/GMT.*/, ''));
      //+ " : " + JSON.stringify(mozAlarm.data) + "
");
    showMessages();
    //setAlarm(7 * 1000);
    setAlarm(7 * 60 * 1000);
  });

  function setAlarm(offset) {
    var alarmId
      , date
      , request
      ;

    $("#response").append("

 setting alarm for " + (offset / 1000) + "s in the future");
    date = new Date(Date.now() + offset);
    $("#response").append("
 will fire at " + " for " + date.toString().replace(/GMT.*/, ''));

    // Set an alarm and store it's id
    //request = navigator.mozAlarms.add(date, "ignoreTimezone", { foo: "bar" });
    request = navigator.mozAlarms.add(date, "honorTimezone", { foo: "bar" });

    request.onsuccess = function () {
      // alarms[this.result] = { type: 'thingy', params: ['do', 'stuff'] };
      alarmId = this.result;
      if (this.result) {
        $("#response").append("
 set alarm " + this.result + " for " + date.toString().replace(/GMT.*/, ''));
      } else {
        $("#response").append("

 error setting alarm: " + this.error);
      }
    };

    // ...

    // Later on, removing the alarm if it exists
    if (alarmId) {
      navigator.mozAlarms.remove(alarmId);
    }
  }

  if (!navigator.mozHasPendingMessage("alarm")) {
    setAlarm(5 * 1000);
  }
});
<commit_msg>fix decrypt bug<commit_after>/*global MozSmsFilter*/
$(function() {
  'use strict';

  /*
  function logObject(obj) {
    $("#response").append("
 New Object: " + obj);
    Object.keys(obj).forEach(function (key) {
      $("#response").append("
 " + key + ": " + obj[key]);
    });
  }
  */
  function logMsg(msg) {
    [
      'type', 'id', 'threadId', 'body', 'delivery', 'deliveryStatus', 'read'
    , 'receiver', 'sender', 'timestamp', 'messageClass'
    ].forEach(function (key) {
      $("#response").append("
 " + key + ": " + msg[key]);
    });
  }

  $('form#sms-form').on("submit", function (ev) {
    $("#response").html("submit form");
    ev.preventDefault();
    ev.stopPropagation();

	// Encryption
	var message = $('[name=msg]').val();

	var pwUtf8 = new TextEncoder().encode(message);
	var pwHash = crypto.subtle.digest('SHA-256', pwUtf8);

	var iv = crypto.getRandomValues(new Uint8Array(20));
	var alg = { name: 'AES-GCM', iv: iv };
	var key = crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']);

	var cryptedMessage = crypto.subtle.encrypt(alg, key, ptUtf8);

	// decryption
	var decryptedMessage = crypto.subtle.decrypt(alg, key, cryptedMessage);

    var msg = decryptedMessage
      , phone = $('[name=phone]').val()
      , request;

    $("#response").html("got values");

    request = navigator.mozMobileMessage.send(phone, msg);
    $("#response").html("tried to send message");

    $("#response").html("iterate through requests");
    request.onsuccess = function () {
      window.thing = this;
      console.error(this.result);
      $("#response").html("Sent to
" + this.result);
      logMsg(this.result);
    };
    request.onerror = function () {
      window.thing = this;
      console.error(this.error.name);
      console.error(this.error.message);
      $("#response").html(this.error.name + ':' + this.error.message);
    };
    //});
  });

  function showMessages(id) {
    var filter = new MozSmsFilter() // https://developer.mozilla.org/en-US/docs/Web/API/MozSmsFilter
      , cursor
      ;

    filter.read = false;
    if ('undefined' !== typeof id) {
      filter.threadId = id;
    }

    // Get the messages from the latest to the first
    cursor = navigator.mozMobileMessage.getMessages(filter, true);

    cursor.onsuccess = function () {
      logMsg(this.result);
      /*
      var message = this.result
        , time = message.timestamp.toDateString()
        ;

      console.log(time + ': ' + (message.body || message.subject)); // SMS || MMS
      $("#response").append("
Got new message [" + time + "]"
        + "
" + (message.body || message.subject)
        + "
"
      );

      if (!this.done) {
        this.continue();
      }
      */
    };
  }

  // 'received' seems to only activate after a message is sent
  navigator.mozMobileMessage.addEventListener('received', function (msg) {
    // https://developer.mozilla.org/en-US/docs/Web/API/MozSmsMessage
    $("#response").html("Got a message");
    $("#response").append("
" + msg);
    logMsg(msg);

    showMessages(msg.id);
  });

  navigator.mozSetMessageHandler("alarm", function (mozAlarm) {
    // var directive = alorms[mozAlarm.data.id]; doStuff(directive);
    $("#alarms").append("
Alarm Fired: " + new Date().toString().replace(/GMT.*/, ''));
      //+ " : " + JSON.stringify(mozAlarm.data) + "
");
    showMessages();
    //setAlarm(7 * 1000);
    setAlarm(7 * 60 * 1000);
  });

  function setAlarm(offset) {
    var alarmId
      , date
      , request
      ;

    $("#response").append("

 setting alarm for " + (offset / 1000) + "s in the future");
    date = new Date(Date.now() + offset);
    $("#response").append("
 will fire at " + " for " + date.toString().replace(/GMT.*/, ''));

    // Set an alarm and store it's id
    //request = navigator.mozAlarms.add(date, "ignoreTimezone", { foo: "bar" });
    request = navigator.mozAlarms.add(date, "honorTimezone", { foo: "bar" });

    request.onsuccess = function () {
      // alarms[this.result] = { type: 'thingy', params: ['do', 'stuff'] };
      alarmId = this.result;
      if (this.result) {
        $("#response").append("
 set alarm " + this.result + " for " + date.toString().replace(/GMT.*/, ''));
      } else {
        $("#response").append("

 error setting alarm: " + this.error);
      }
    };

    // ...

    // Later on, removing the alarm if it exists
    if (alarmId) {
      navigator.mozAlarms.remove(alarmId);
    }
  }

  if (!navigator.mozHasPendingMessage("alarm")) {
    setAlarm(5 * 1000);
  }
});
<|endoftext|>


<commit_before>(function($) {

	$.fn.shopaholic = function(params) {
		var options = $.extend({
			data: '/data/items.json' //This line adding another parameter to the options... ```expands``` it
		}, params);
		var Super = this;
		var jsonData = {};
		var items = {};
		var models = {
			item: function(item) {
				return '
' +
						'
' +
							'
' +
								'' +
							'
' +
							'
' + item.name + '+
' +
						'
' +
					'
';
			}
		}

		var render = {
			items: function(data){ //Renders Items
				$.each( data.items, function( key, value ) {
					$(Super).append(models.item(value));
				});
				$('a.button').click(function(){ //Adds click handler
					render.cart.add($(this).data('id'));
				})

			},
			desc: function(data){ //Renders Description
				options.header.append(''); //Add image
				options.header.append('
' + data.name + '
'); //Add name
				options.header.append('
' + data.description + '
');//Add description

				$('head').append('<title>' + data.name + '</title>'); //Add name
			},
			cart: {

				list: function(){ //Returns array of items.
					return JSON.parse(localStorage.get('cart'));
				},

				add: function(id){ //Added id.
					var temp = JSON.parse(localStorage.getItem('cart'));
					if(!Array.isArray(temp)) temp = [];
					temp.push(id.toString());
					localStorage.setItem('cart', JSON.stringify(temp));
				},

				remove: function(id){ //Removes id.
					var temp = JSON.parse(localStorage['cart']);
					var index = temp.indexOf(id.toString());
					if(index > -1){
						temp = temp.splice(index, 1);
						localStorage.setItem('cart', JSON.stringify(temp));
					}
				},

				clear: function(){ //Clears shopping cart.
					localStorage.setItem('cart', []);
				}
			}
		}

		$.getJSON( 'data/items.json', function( data ) {
			$.each( data.items, function( key, value ) {
				items[value.id] = value //Reversing list to object
			});

			jsonData = data; //Saving data
			render.desc(data); //Rendering description
			render.items(data); //Rendering items
		})
		.fail(function(error){
			console.log(error)
		})
	};

}(jQuery));<commit_msg>Moved local storate methods to db var. Added button modifier.<commit_after>(function($) {

	$.fn.shopaholic = function(params) {
		var options = $.extend({
			data: '/data/items.json' //This line adding another parameter to the options... ```expands``` it
		}, params);
		var Super = this;
		var jsonData = {};
		var items = {};
		var models = {
			item: function(item) {
				var text = db.in(item.id) ? '‒' : '+';
				var colour = db.in(item.id) ? 'red' : '';

				return '
' +
						'
' +
							'
' +
								'' +
							'
' +
							'
' + item.name + '' + text + '
' +
						'
' +
					'
';
			}
		};

		var db = {

			list: function(){ //Returns array of items.
				return JSON.parse(localStorage.get('cart') || "[]");
			},

			add: function(id){ //Added id.
				var temp = JSON.parse(localStorage.getItem('cart')) || [];
				// if(!Array.isArray(temp)) temp = []; //SAVE FOR LATER
				var index = temp.indexOf(id.toString());
				if(index === -1){
					temp.push(id.toString());
					localStorage.setItem('cart', JSON.stringify(temp));
				}

			},

			in: function(id){
				var temp = JSON.parse(localStorage.getItem('cart')) || [];
				var index = temp.indexOf(id.toString());
				if(index !== -1){
					return true;
				}
				return false;
			},

			remove: function(id){ //Removes id.
				var temp = JSON.parse(localStorage['cart']);
				var index = temp.indexOf(id.toString());
				if(index !== -1){
					temp.splice(index, 1);
					localStorage.setItem('cart', JSON.stringify(temp));
				}
			},

			clear: function(){ //Clears shopping cart.
				localStorage.setItem('cart', []);
			}
		};

		var render = {
			items: function(data){ //Renders Items
				$.each( data.items, function( key, value ) {
					$(Super).append(models.item(value));
				});
				$('a.button').click(function(){ //Adds click handler
					var id = $(this).data('id');
					if(id){
						render.button(this, id);
					}
				})

			},
			desc: function(data){ //Renders Description
				options.header.append(''); //Add image
				options.header.append('
' + data.name + '
'); //Add name
				options.header.append('
' + data.description + '
');//Add description

				$('head').append('<title>' + data.name + '</title>'); //Add title
			},
			button: function(button, id){
				if(!db.in(id)){
					db.add(id); //Adds item to list

					$(button).addClass('red');//Change the colour.
					$(button).text('‒');//Changes the text.

				}else{
					db.remove(id);

					$(button).removeClass('red'); //Change the colour.
					$(button).text('+'); //Changes the text.
				}
			},
			cart: function(){

			}

		}

		$.getJSON( 'data/items.json', function( data ) {
			$.each( data.items, function( key, value ) {
				items[value.id] = value //Reversing list to object
			});

			jsonData = data; //Saving data

			render.desc(data); //Rendering description
			render.items(data); //Rendering items
		})
		.fail(function(error){
			console.log(error)
		})
	};

}(jQuery));<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------------------*/
/* CONTROLLER */

// map in global scope for access
var map;

function initMap() {
	// Create a new map object and add to #map div
	map = new google.maps.Map(document.getElementById('map'), initOptions);

	// add search box
	addSearchBox();
}

function addSearchBox() {
	// create new search box object and assign to #searchbox <input>
	var input = document.getElementById('searchbox');
	// (searchBox in global scope)
	searchBox = new google.maps.places.SearchBox(input);

	// move search box to top left of map (COMMENTED OUT FOR NOW)
	// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

	// bias searchbox results towards current map bounds
	map.addListener('bounds_changed', function() {
		searchBox.setBounds(map.getBounds());
	});

	addSearchListener(searchBox);
}

function addSearchListener(searchBox) {
	// listen for user selecting place
	searchBox.addListener('places_changed', function() {
		// getPlaces() return an ARRAY of possible matches
		// so "li" returns array of possibles
		var places = searchBox.getPlaces();
		// just select 1st place in array
		var place = places[0];

		// create new marker
		var newMarkOptions = {
			map : map,
			title : place.formatted_address,
			position : place.geometry.location
		};
		addMarker(newMarkOptions);

		// centre screen on marker
		var bounds = new google.maps.LatLngBounds();
		if (place.geometry.viewport) {
            // Only geocodes have viewport.
            bounds.union(place.geometry.viewport);
        }
        else {
            bounds.extend(place.geometry.location);
        }

		// fit map to bounds selected by place search
		map.fitBounds(bounds);
		// set zoom to street level
		map.setZoom(15);

		// get stop/search data from api
		getStopsData();
	});
}

function addMarker(markerOptions) {
	marker = new google.maps.Marker(markerOptions);
	var marker = new google.maps.Marker(markerOptions);

	// add info window for each stop

	// format date/time
	var date = new Date(stop.datetime);
	var formattedDate = date.toString();

	var infoContent = "
"
							+ '
' + formattedDate + '
'
					   		+ '
' + stop.legislation + '
'
					   		+ '
' + stop.gender + ', ' + stop.age_range + ', ' + stop.self_defined_ethnicity + '
'
					   		+ '
' + 'result: ' + stop.outcome + '
'
					   	+ '
';

	// test
	console.log(infoContent);

	var infowindow = new google.maps.InfoWindow({
		content: infoContent
	});
	marker.addListener('click', function() {
		infowindow.open(map, marker);
	})
};

function getStopsData() {
	// get current bounds from getBounds object
	var current_bounds = map.getBounds();
	var min_lat = current_bounds.R.R;
	var min_lng = current_bounds.j.j;
	var max_lat = current_bounds.R.j;
	var max_lng = current_bounds.j.R;

	// get police.uk stop-search data for current bounds (https://data.police.uk/docs/method/stops-street/)
	var poly_1 = min_lat.toString() + ',' + min_lng.toString() + ':';
	var poly_2 = min_lat.toString() + ',' + max_lng.toString() + ':';
	var poly_3 = max_lat.toString() + ',' + max_lng.toString(); // 4th poly not required as per documentation
	var query = 'https://data.police.uk/api/stops-street?poly=' + poly_1 + poly_2 + poly_3;
	var stops;

	var request = new XMLHttpRequest();
	request.open("GET", query); // async by default
	request.addEventListener("load", function() {
		// once loaded, do this..

		stops = JSON.parse(request.responseText);

		// test
		// console.log(stops);

		addStopsMarkers(stops);
	});
	request.send(null);
}

function addStopsMarkers(stops) {
	//test
	console.log(stops);
	for (stop of stops) {
		// test
		console.log(stop);
		var markerOptions = {};
		markerOptions.position = {
			lat: Number(stop.location.latitude),
			lng: Number(stop.location.longitude)
		};
		markerOptions.animation = google.maps.Animation.DROP;
		markerOptions.map = map;
		addMarker(markerOptions);

	}
}

/*-----------------------------------------------------------------------------------------*/
/* MODEL */

var initOptions = {
	center : {lat : 53.328, lng: -3.101995},
	zoom : 8
};

/*---------------------------------------------------------------------------------------*/
/* VIEW */

initMap();

/*---------------------------------*/
/* TEST: can we use this later for recalculating not just when user searches,
	   but when user moves map bounds? */
map.addListener('bounds_changed', function() {
	console.log(searchBox.getBounds());
})
<commit_msg>move call to addSearchBox() out of initMap()<commit_after>/*-----------------------------------------------------------------------------------------*/
/* CONTROLLER */

// map in global scope for access
var map;

function initMap() {
	// Create a new map object and add to #map div
	map = new google.maps.Map(document.getElementById('map'), initOptions);
}

function addSearchBox() {
	// create new search box object and assign to #searchbox <input>
	var input = document.getElementById('searchbox');
	// (searchBox in global scope)
	searchBox = new google.maps.places.SearchBox(input);

	// move search box to top left of map (COMMENTED OUT FOR NOW)
	// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

	// bias searchbox results towards current map bounds
	map.addListener('bounds_changed', function() {
		searchBox.setBounds(map.getBounds());
	});

	addSearchListener(searchBox);
}

function addSearchListener(searchBox) {
	// listen for user selecting place
	searchBox.addListener('places_changed', function() {
		// getPlaces() return an ARRAY of possible matches
		// so "li" returns array of possibles
		var places = searchBox.getPlaces();
		// just select 1st place in array
		var place = places[0];

		// create new marker
		var newMarkOptions = {
			map : map,
			title : place.formatted_address,
			position : place.geometry.location
		};
		addMarker(newMarkOptions);

		// centre screen on marker
		var bounds = new google.maps.LatLngBounds();
		if (place.geometry.viewport) {
            // Only geocodes have viewport.
            bounds.union(place.geometry.viewport);
        }
        else {
            bounds.extend(place.geometry.location);
        }

		// fit map to bounds selected by place search
		map.fitBounds(bounds);
		// set zoom to street level
		map.setZoom(15);

		// get stop/search data from api
		getStopsData();
	});
}

function addMarker(markerOptions) {
	marker = new google.maps.Marker(markerOptions);
	var marker = new google.maps.Marker(markerOptions);

	// add info window for each stop

	// format date/time
	var date = new Date(stop.datetime);
	var formattedDate = date.toString();

	var infoContent = "
"
							+ '
' + formattedDate + '
'
					   		+ '
' + stop.legislation + '
'
					   		+ '
' + stop.gender + ', ' + stop.age_range + ', ' + stop.self_defined_ethnicity + '
'
					   		+ '
' + 'result: ' + stop.outcome + '
'
					   	+ '
';

	// test
	console.log(infoContent);

	var infowindow = new google.maps.InfoWindow({
		content: infoContent
	});
	marker.addListener('click', function() {
		infowindow.open(map, marker);
	})
};

function getStopsData() {
	// get current bounds from getBounds object
	var current_bounds = map.getBounds();
	var min_lat = current_bounds.R.R;
	var min_lng = current_bounds.j.j;
	var max_lat = current_bounds.R.j;
	var max_lng = current_bounds.j.R;

	// get police.uk stop-search data for current bounds (https://data.police.uk/docs/method/stops-street/)
	var poly_1 = min_lat.toString() + ',' + min_lng.toString() + ':';
	var poly_2 = min_lat.toString() + ',' + max_lng.toString() + ':';
	var poly_3 = max_lat.toString() + ',' + max_lng.toString(); // 4th poly not required as per documentation
	var query = 'https://data.police.uk/api/stops-street?poly=' + poly_1 + poly_2 + poly_3;
	var stops;

	var request = new XMLHttpRequest();
	request.open("GET", query); // async by default
	request.addEventListener("load", function() {
		// once loaded, do this..

		stops = JSON.parse(request.responseText);

		// test
		// console.log(stops);

		addStopsMarkers(stops);
	});
	request.send(null);
}

function addStopsMarkers(stops) {
	//test
	console.log(stops);
	for (stop of stops) {
		// test
		console.log(stop);
		var markerOptions = {};
		markerOptions.position = {
			lat: Number(stop.location.latitude),
			lng: Number(stop.location.longitude)
		};
		markerOptions.animation = google.maps.Animation.DROP;
		markerOptions.map = map;
		addMarker(markerOptions);

	}
}

/*-----------------------------------------------------------------------------------------*/
/* MODEL */

var initOptions = {
	center : {lat : 53.328, lng: -3.101995},
	zoom : 8
};

/*---------------------------------------------------------------------------------------*/
/* VIEW */

initMap();
addSearchBox();

/*---------------------------------*/
/* TEST: can we use this later for recalculating not just when user searches,
	   but when user moves map bounds? */
map.addListener('bounds_changed', function() {
	console.log(searchBox.getBounds());
})
<|endoftext|>


<commit_before>// TODO split osm-pbf-leaflet into separate projects
//require('osm-pbf-leaflet');
require('../node_modules/osm-pbf-leaflet/lib/OSMReader.js');
require('../node_modules/osm-pbf-leaflet/lib/leaflet-osm.js');
require('leaflet-tilelayer-vector');
require('../lib/leaflet-plugins/Permalink.js');
require('../lib/leaflet-plugins/Permalink.Layer.js');
require('../lib/Leaflet.zoomslider/src/L.Control.Zoomslider.js');
require('./L.Control.Zoomslider-patch.js');
require('../lib/Leaflet.zoomdisplay/leaflet.zoomdisplay.js');
require('./Control.Progress');
//require('./Control.ZoomInfo.js');
require('./PbfWorker.js');
require('./Path._updatePathViewport.js');

var popup = require('./popup.js');
var miniMap = require('./minimap.js');

var map;
var baseLayer;
var emptyBaseLayer;
var vectorTileLayer;
var tileDebugLayer;
var layerControl;
var visibility = 'visible';
var baseLayerActive = null;
var landuse = true;

/**
 * Changes the visibility for all features (supporting hover only)
 *
 * @param {string} 'visible' | 'hidden'
 */
var updateVisibility = function(aVisibility) {
    var container = map.getRenderer(vectorTileLayer)._container;

    visibility = aVisibility;
    if (visibility === 'hidden') {
        activateBaseLayer();
    } else {
        restoreBaseLayer();
    }

    if (L.Path.CANVAS) {
        container.style.visibility = aVisibility;
    } else {
        // does not work as expected in Chrome (v26):
        // when svg root is hidden, setting visible on child has no effect
        //map._pathRoot.setAttribute('visibility', visibility);
        var children = container.childNodes;
        for (var i = 0; i < children.length; i++) {
            setPathVisibility(children[i], aVisibility);
        }
        container.setAttribute('pointer-events', 'painted');
    }
};

var activateBaseLayer = function() {
    baseLayerActive = map.hasLayer(baseLayer);
    if (!baseLayerActive) {
        map.addLayer(baseLayer);
        map.removeLayer(emptyBaseLayer);
    }
};

var restoreBaseLayer = function() {
    if (baseLayerActive !== null && !baseLayerActive) {
        map.removeLayer(baseLayer);
        map.addLayer(emptyBaseLayer);
    }
};

var setPathVisibility = function(pathEle, aVisibility) {
    if (pathEle) {
        pathEle.setAttribute('visibility', aVisibility);
    }
};

var showLanduse = function(aLanduse) {
    landuse = aLanduse;
    vectorTileLayer.redraw();
};

function init() {

    // enlarge vector clip bounds, restricted by tile bounds,
    // see Path._updatePathViewport.js
    L.Path.CLIP_PADDING = 1;

    map = L.map('map', {
        minZoom: 5,
        maxZoom: 19,
        // disable keyboard, L.Map.Keyboard._onMouseDown slow (?)
        keyboard: false,
        // disable force/kinetic dragging, not recognizable with many vectors, sometimes too fast
        inertia: false,
        // ignored by MiniMap > reset setView in minimap.js
        //reset: true,
        //animate: false
    });
    map.setView([52.4859, -1.88935], 16);
    //map.addControl(new L.Control.ZoomInfo());

    emptyBaseLayer = L.layerGroup();
    baseLayer = new L.OSM.Mapnik({
        attribution: 'map © OpenStreetMap contributors'
    });

    var colors = {
        // Leaflet colors (http://leafletjs.com/examples/geojson.html)
        polygon: '#b0de5c',
        line: '#0033ff',
        point: '#ff7800',
        hover: 'red'
    };

    var pointStyle = {
        radius: 4,
        fillColor: colors.point,
        color: "#000",
        weight: 1,
        opacity: 1,
        fillOpacity: 0.8
    };
    var lineStyle = {
        weight: 4,
        opacity: 0.7,
        color: colors.line
    };
    var polygonStyle = {
        weight: 2,
        color: "#999",
        opacity: 1,
        fillColor: colors.polygon,
        fillOpacity: 0.5
    };
    var styles = {
        node: pointStyle,
        way: lineStyle,
        area: polygonStyle
    };

    var getHoverStyle = function(layer) {
        return {
            weight: layer.options.weight + 1,
            color: colors.hover,
            fillColor: colors.hover
        };
    };
    var bindHover = function(feature, layer) {
        layer.on('mouseover', function(evt) {
            if (!this.defaultOptions) {
                this.defaultOptions = this.options;
            }
            this.setStyle(getHoverStyle(this));
            setPathVisibility(this._path, 'visible');

            // lazy label binding for better performance
            // (registering less events + creating less objects on tile load)
            var popupContent = popup.getFeatureInfoHtml(this.feature);
            if (!this._label) {
                this.bindLabel(popupContent);
                this._showLabel(evt);
            }
        }, layer);
        layer.on('mouseout', function(evt) {
            // TODO resetStyle for L.OSM.DataLayer? (has styles instead of style)
            //layer.resetStyle(evt.target);
            L.Util.extend(this.options, this.defaultOptions);
            this.setStyle(this.options);
            setPathVisibility(this._path, 'inherit');
        }, layer);
    };

    var bindPopup = function(feature, layer) {
        layer.on('click', function(evt) {
            // lazy popup binding for better performance
            // (registering less events + creating less objects on tile load)
            var popupContent = popup.getFeatureInfoHtml(this.feature);
            this.bindPopup(popupContent, {offset:new L.Point(0,0)});
            this._openPopup(evt);
        }, layer);
    };

    function allKeys(tags, start) {
        for (key in tags) {
            if (!(start === key.substr(0, start.length))) {
                return false;
            }
        }
        return true;
    }

    // true keeps feature, false discards
    var filter = function(feature) {
        var tags = feature.tags,
            noTags = Object.keys(tags).length === 0;
        return (map.getZoom() >= 17
            || !(noTags || tags.building || allKeys(tags, 'building') || allKeys(tags, 'roof:')
                || allKeys(tags, 'addr:') || tags.natural === 'tree' || tags.highway === 'street_lamp'
                || tags.barrier === 'fence' || tags['building:demolished'] === 'yes'))
            && (map.getZoom() >= 15 || !(feature.type === 'node') || tags.place)
            && (landuse || !(feature.area && (tags.landuse || tags.natural || tags.leisure)));
    };

    var vectorOptions = {
        filter: filter,
        styles: styles,
        onEachFeature: function(feature, layer) {
            bindHover(feature, layer);
            bindPopup(feature, layer);
            layer.on('add', function(evt) {
                setPathVisibility(evt.target._container, visibility);
            });
        }
    };

    var tileOptions = {
        // remove tiles outside viewport
        unloadInvisibleTiles: true,
        // no tile loading while panning, too slow with large vector tiles
        updateWhenIdle: true,
        // unique feature key function, for filtering duplicate features contained in multiple tiles
        unique: function(feature) {
            return feature.type.substr(0,1) + feature.id;
        },
        // factory function for creating the actual vector layer, default is L.geoJson
        // PBF parsing done in worker, use default layer here to avoid dependency in main bundle
        //layerFactory: L.osmPbf
        layerFactory: function(data, options) {
            return new L.OSM.DataLayer(data, options);
        },
        ajax: L.Request.binaryGet,
        // web worker
        workerFactory: L.pbfWorker,
        //workerFactory: L.noWorker,
        // fixed zoom level 13 for Mapsplit tiles (resize all other levels)
        serverZooms: [13],
        minZoom: 13,
        maxZoom: 19,
        attribution: 'data © OpenStreetMap contributors, '
            + 'licensed under ODbL'
    };

    vectorTileLayer = new L.TileLayer.Vector.Unclipped("tiles/{x}_{y}.pbf", tileOptions, vectorOptions);
    /*
    vectorTileLayer.on('loading', function() {
        console.time('load');
        timer.reset();
    });
    vectorTileLayer.on('load', function() {
        console.timeEnd('load');
        timer.report();
        //var tilesKeys = Object.keys(vectorTileLayer._tiles);
        //console.log('_tiles (' + tilesKeys.length + '): ' + tilesKeys);
    });
    map.on('moveend', function() {
        console.log('----- moveend -----');
    });
    */

    // hack for Path_updatePathViewport.js
    map._vectorTileLayer = vectorTileLayer;

    map.addControl(new L.Control.Progress(vectorTileLayer, {div: 'progress-container'}));
    map.addLayer(vectorTileLayer);

    var progressLayer = new L.TileLayer.Progress(vectorTileLayer).addTo(map);
    var debugLayer = new L.TileLayer.Debug(vectorTileLayer);

    layerControl = L.control.layers({
        'OSM Mapnik': baseLayer,
        'no base layer': emptyBaseLayer
    }, {
        'Vector Tiles': vectorTileLayer,
        'Loading Tiles': progressLayer,
        'Debug': debugLayer
    }).addTo(map);
    baseLayer.addTo(map);

    map.addControl(new L.Control.Permalink({
        text: 'Permalink',
        layers: layerControl
    }));

    // MiniMap (overview map)
    miniMap.init(map);

    /*
    // debug layer, from:
    // http://blog.mathieu-leplatre.info/leaflet-tiles-in-lambert-93-projection-2154.html
    tileDebugLayer = L.tileLayer.canvas();
    tileDebugLayer.drawTile = function(canvas, tilePoint, zoom) {
        var ctx = canvas.getContext('2d');
        ctx.strokeStyle = ctx.fillStyle = "red";
        ctx.rect(0,0, 256,256);
        ctx.stroke();
        ctx.fillText('' + tilePoint.x + '_' + tilePoint.y,5,10);
    };
    map.addLayer(tileDebugLayer);
    */
}

init();

exports.updateVisibility = updateVisibility;
exports.showLanduse = showLanduse;
exports.map = map;
exports.activateBaseLayer = activateBaseLayer;
exports.restoreBaseLayer = restoreBaseLayer;
<commit_msg>update pointer events<commit_after>// TODO split osm-pbf-leaflet into separate projects
//require('osm-pbf-leaflet');
require('../node_modules/osm-pbf-leaflet/lib/OSMReader.js');
require('../node_modules/osm-pbf-leaflet/lib/leaflet-osm.js');
require('leaflet-tilelayer-vector');
require('../lib/leaflet-plugins/Permalink.js');
require('../lib/leaflet-plugins/Permalink.Layer.js');
require('../lib/Leaflet.zoomslider/src/L.Control.Zoomslider.js');
require('./L.Control.Zoomslider-patch.js');
require('../lib/Leaflet.zoomdisplay/leaflet.zoomdisplay.js');
require('./Control.Progress');
//require('./Control.ZoomInfo.js');
require('./PbfWorker.js');
require('./Path._updatePathViewport.js');

var popup = require('./popup.js');
var miniMap = require('./minimap.js');

var map;
var baseLayer;
var emptyBaseLayer;
var vectorTileLayer;
var tileDebugLayer;
var layerControl;
var visibility = 'visible';
var baseLayerActive = null;
var landuse = true;

/**
 * Changes the visibility for all features (supporting hover only)
 *
 * @param {string} 'visible' | 'hidden'
 */
var updateVisibility = function(aVisibility) {
    var container = map.getRenderer(vectorTileLayer)._container;

    visibility = aVisibility;
    if (visibility === 'hidden') {
        activateBaseLayer();
    } else {
        restoreBaseLayer();
    }

    if (L.Path.CANVAS) {
        container.style.visibility = aVisibility;
    } else {
        // does not work as expected in Chrome (v26):
        // when svg root is hidden, setting visible on child has no effect
        //map._pathRoot.setAttribute('visibility', visibility);
        var children = container.childNodes;
        for (var i = 0; i < children.length; i++) {
            setPathVisibility(children[i], aVisibility);
        }
    }
};

var activateBaseLayer = function() {
    baseLayerActive = map.hasLayer(baseLayer);
    if (!baseLayerActive) {
        map.addLayer(baseLayer);
        map.removeLayer(emptyBaseLayer);
    }
};

var restoreBaseLayer = function() {
    if (baseLayerActive !== null && !baseLayerActive) {
        map.removeLayer(baseLayer);
        map.addLayer(emptyBaseLayer);
    }
};

var setPathVisibility = function(pathEle, aVisibility) {
    if (pathEle) {
        pathEle.setAttribute('visibility', aVisibility);
    }
};

var showLanduse = function(aLanduse) {
    landuse = aLanduse;
    vectorTileLayer.redraw();
};

function init() {

    // enlarge vector clip bounds, restricted by tile bounds,
    // see Path._updatePathViewport.js
    L.Path.CLIP_PADDING = 1;

    map = L.map('map', {
        minZoom: 5,
        maxZoom: 19,
        // disable keyboard, L.Map.Keyboard._onMouseDown slow (?)
        keyboard: false,
        // disable force/kinetic dragging, not recognizable with many vectors, sometimes too fast
        inertia: false,
        // ignored by MiniMap > reset setView in minimap.js
        //reset: true,
        //animate: false
    });
    map.setView([52.4859, -1.88935], 16);
    //map.addControl(new L.Control.ZoomInfo());

    emptyBaseLayer = L.layerGroup();
    baseLayer = new L.OSM.Mapnik({
        attribution: 'map © OpenStreetMap contributors'
    });

    var colors = {
        // Leaflet colors (http://leafletjs.com/examples/geojson.html)
        polygon: '#b0de5c',
        line: '#0033ff',
        point: '#ff7800',
        hover: 'red'
    };

    var pointStyle = {
        radius: 4,
        fillColor: colors.point,
        color: "#000",
        weight: 1,
        opacity: 1,
        fillOpacity: 0.8,
        pointerEvents: 'painted'
    };
    var lineStyle = {
        weight: 4,
        opacity: 0.7,
        color: colors.line,
        pointerEvents: 'painted'
    };
    var polygonStyle = {
        weight: 2,
        color: "#999",
        opacity: 1,
        fillColor: colors.polygon,
        fillOpacity: 0.5,
        pointerEvents: 'painted'
    };
    var styles = {
        node: pointStyle,
        way: lineStyle,
        area: polygonStyle
    };

    var getHoverStyle = function(layer) {
        return {
            weight: layer.options.weight + 1,
            color: colors.hover,
            fillColor: colors.hover
        };
    };
    var bindHover = function(feature, layer) {
        layer.on('mouseover', function(evt) {
            if (!this.defaultOptions) {
                this.defaultOptions = this.options;
            }
            this.setStyle(getHoverStyle(this));
            setPathVisibility(this._path, 'visible');

            // lazy label binding for better performance
            // (registering less events + creating less objects on tile load)
            var popupContent = popup.getFeatureInfoHtml(this.feature);
            if (!this._label) {
                this.bindLabel(popupContent);
                this._showLabel(evt);
            }
        }, layer);
        layer.on('mouseout', function(evt) {
            // TODO resetStyle for L.OSM.DataLayer? (has styles instead of style)
            //layer.resetStyle(evt.target);
            L.Util.extend(this.options, this.defaultOptions);
            this.setStyle(this.options);
            setPathVisibility(this._path, 'inherit');
        }, layer);
    };

    var bindPopup = function(feature, layer) {
        layer.on('click', function(evt) {
            // lazy popup binding for better performance
            // (registering less events + creating less objects on tile load)
            var popupContent = popup.getFeatureInfoHtml(this.feature);
            this.bindPopup(popupContent, {offset:new L.Point(0,0)});
            this._openPopup(evt);
        }, layer);
    };

    function allKeys(tags, start) {
        for (key in tags) {
            if (!(start === key.substr(0, start.length))) {
                return false;
            }
        }
        return true;
    }

    // true keeps feature, false discards
    var filter = function(feature) {
        var tags = feature.tags,
            noTags = Object.keys(tags).length === 0;
        return (map.getZoom() >= 17
            || !(noTags || tags.building || allKeys(tags, 'building') || allKeys(tags, 'roof:')
                || allKeys(tags, 'addr:') || tags.natural === 'tree' || tags.highway === 'street_lamp'
                || tags.barrier === 'fence' || tags['building:demolished'] === 'yes'))
            && (map.getZoom() >= 15 || !(feature.type === 'node') || tags.place)
            && (landuse || !(feature.area && (tags.landuse || tags.natural || tags.leisure)));
    };

    var vectorOptions = {
        filter: filter,
        styles: styles,
        onEachFeature: function(feature, layer) {
            bindHover(feature, layer);
            bindPopup(feature, layer);
            layer.on('add', function(evt) {
                setPathVisibility(evt.target._container, visibility);
            });
        }
    };

    var tileOptions = {
        // remove tiles outside viewport
        unloadInvisibleTiles: true,
        // no tile loading while panning, too slow with large vector tiles
        updateWhenIdle: true,
        // unique feature key function, for filtering duplicate features contained in multiple tiles
        unique: function(feature) {
            return feature.type.substr(0,1) + feature.id;
        },
        // factory function for creating the actual vector layer, default is L.geoJson
        // PBF parsing done in worker, use default layer here to avoid dependency in main bundle
        //layerFactory: L.osmPbf
        layerFactory: function(data, options) {
            return new L.OSM.DataLayer(data, options);
        },
        ajax: L.Request.binaryGet,
        // web worker
        workerFactory: L.pbfWorker,
        //workerFactory: L.noWorker,
        // fixed zoom level 13 for Mapsplit tiles (resize all other levels)
        serverZooms: [13],
        minZoom: 13,
        maxZoom: 19,
        attribution: 'data © OpenStreetMap contributors, '
            + 'licensed under ODbL'
    };

    vectorTileLayer = new L.TileLayer.Vector.Unclipped("tiles/{x}_{y}.pbf", tileOptions, vectorOptions);
    /*
    vectorTileLayer.on('loading', function() {
        console.time('load');
        timer.reset();
    });
    vectorTileLayer.on('load', function() {
        console.timeEnd('load');
        timer.report();
        //var tilesKeys = Object.keys(vectorTileLayer._tiles);
        //console.log('_tiles (' + tilesKeys.length + '): ' + tilesKeys);
    });
    map.on('moveend', function() {
        console.log('----- moveend -----');
    });
    */

    // hack for Path_updatePathViewport.js
    map._vectorTileLayer = vectorTileLayer;

    map.addControl(new L.Control.Progress(vectorTileLayer, {div: 'progress-container'}));
    map.addLayer(vectorTileLayer);

    var progressLayer = new L.TileLayer.Progress(vectorTileLayer).addTo(map);
    var debugLayer = new L.TileLayer.Debug(vectorTileLayer);

    layerControl = L.control.layers({
        'OSM Mapnik': baseLayer,
        'no base layer': emptyBaseLayer
    }, {
        'Vector Tiles': vectorTileLayer,
        'Loading Tiles': progressLayer,
        'Debug': debugLayer
    }).addTo(map);
    baseLayer.addTo(map);

    map.addControl(new L.Control.Permalink({
        text: 'Permalink',
        layers: layerControl
    }));

    // MiniMap (overview map)
    miniMap.init(map);

    /*
    // debug layer, from:
    // http://blog.mathieu-leplatre.info/leaflet-tiles-in-lambert-93-projection-2154.html
    tileDebugLayer = L.tileLayer.canvas();
    tileDebugLayer.drawTile = function(canvas, tilePoint, zoom) {
        var ctx = canvas.getContext('2d');
        ctx.strokeStyle = ctx.fillStyle = "red";
        ctx.rect(0,0, 256,256);
        ctx.stroke();
        ctx.fillText('' + tilePoint.x + '_' + tilePoint.y,5,10);
    };
    map.addLayer(tileDebugLayer);
    */
}

init();

exports.updateVisibility = updateVisibility;
exports.showLanduse = showLanduse;
exports.map = map;
exports.activateBaseLayer = activateBaseLayer;
exports.restoreBaseLayer = restoreBaseLayer;
<|endoftext|>


<commit_before>// Nav.js
// Shows nested navs smoothly when main nav links are clicked or hovered over

var timeoutId = 0;
var thisNav;
var isDone;
var isTabOpen = false;

function showNav() {
	isDone = false;
	thisNav.css('z-index', 100).slideDown(300, function() {isDone = true;});
	isTabOpen = true;
}

function hideNav() {
	isDone = false;
	thisNav.css('z-index', 50).slideUp(200, function() {isDone = true;});
}

function clickToggle() {
	if(isDone == true) {
		$(this).next().slideToggle(300);
		return false;
	}
}

// Disable default show on hover from css
$('body').removeClass('no-javascript');

// Show nested nav on hover, and hide nested nav on mouse leave
$('.nav-link').on({
	mouseenter: function() {
		thisNav = $(this).children('ul');
		if (isTabOpen == true) {
			timeoutId = setTimeout(showNav, 200);
		} else {
			timeoutId = setTimeout(showNav, 0);
		}
		isTabOpen = true;
	},
	mouseleave: function() {
		clearTimeout(timeoutId);
		hideNav();
	}
});

// Alternatively toggles nested nav on click (this is for mobile)
$('.nav-link > a').on('click', clickToggle);

//Prevent nav link from opening
$('.nav-link > a').click (function (e) {
        e.preventDefault();
        return false;
    }
);

// $('#myElement').mousedown(function() {
//     timeoutId = setTimeout(myFunction, 1000);
// }).bind('mouseup mouseleave', function() {
//     clearTimeout(timeoutId);
// });<commit_msg>Finish nav.js<commit_after>// Nav.js
// Shows nested navs smoothly when main nav links are clicked or hovered over

var timeoutId = 0;
var thisNav;
var isDone;
var isTabOpen = false;

function showNav() {
	isDone = false;
	thisNav.css('z-index', 100).slideDown(300, function() {isDone = true;});
	isTabOpen = true;
}

function hideNav() {
	isDone = false;
	thisNav.css('z-index', 50).slideUp(200, function() {isDone = true;});
}

function clickToggle() {
	if(isDone == true) {
		$(this).next().slideToggle(300);
		return false;
	}
}

// Disable default show on hover from css
$('body').removeClass('no-javascript');

// Show nested nav on hover, and hide nested nav on mouse leave
$('.nav-link').on({
	mouseenter: function() {
		thisNav = $(this).children('ul');
		if (isTabOpen == true) {
			timeoutId = setTimeout(showNav, 150);
		} else {
			timeoutId = setTimeout(showNav, 0);
		}
		isTabOpen = true;
	},
	mouseleave: function() {
		clearTimeout(timeoutId);
		hideNav();
	}
});

// Alternatively toggles nested nav on click (this is for mobile)
$('.nav-link > a').on('click', clickToggle);

//Prevent nav link from opening
$('.nav-link > a').click (function (e) {
        e.preventDefault();
        return false;
    }
);

// $('#myElement').mousedown(function() {
//     timeoutId = setTimeout(myFunction, 1000);
// }).bind('mouseup mouseleave', function() {
//     clearTimeout(timeoutId);
// });<|endoftext|>


<commit_before>'use strict';

function rpg_npc_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 20;
    properties['height-half'] = properties['height'] / 2;
    properties['team'] = properties['team'] !== void 0
      ? properties['team']
      : 1;
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 20;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    properties['stats'] = properties['stats'] || {};
      properties['stats']['health'] = properties['stats']['health'] || {};
        properties['stats']['health']['current'] = properties['stats']['health']['current'] !== void 0
          ? properties['stats']['health']['current']
          : 1;
        properties['stats']['health']['max'] = properties['stats']['health']['max'] || 1;

    properties['selected'] = properties['selected'] || void 0;
    properties['spellbook'] = properties['spellbook'] || {};

    rpg_npcs.push(properties);
}

function rpg_npc_handle(){
    for(var npc in rpg_npcs){
        if(rpg_npcs[npc]['selected'] === void 0){
            continue;
        }

        for(var spell in rpg_npcs[npc]['spellbook']){
            if(rpg_npcs[npc]['spellbook'][spell]['current'] < rpg_npcs[npc]['spellbook'][spell]['reload']){
                rpg_npcs[npc]['spellbook'][spell]['current'] += 1;
                continue;
            }

            if(rpg_npcs[npc]['selected'] !== spell){
                continue;
            }

            rpg_npcs[npc]['spellbook'][spell]['current'] = 0;

            // Create NPC-created particle.
            var speeds = math_movement_speed(
              rpg_npcs[npc]['x'],
              rpg_npcs[npc]['y'],
              rpg_player['x'],
              rpg_player['y']
            );
            var particle = {};
            for(var property in rpg_npcs[npc]['spellbook'][spell]){
                particle[property] = rpg_npcs[npc]['spellbook'][spell][property];
            }
            particle['dx'] = rpg_player['x'] > rpg_npcs[npc]['x'] ? speeds[0] : -speeds[0];
            particle['dy'] = rpg_player['y'] > rpg_npcs[npc]['y'] ? speeds[1] : -speeds[1];
            particle['owner'] = npc;
            particle['x'] = rpg_npcs[npc]['x'];
            particle['y'] = rpg_npcs[npc]['y'];

            rpg_particle_create(particle);
            break;
        }
    }
}

function rpg_particle_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['damage'] = properties['damage'] || 0;
    properties['dx'] = properties['dx'] || 0;
    properties['dy'] = properties['dy'] || 0;
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 10;
    properties['height-half'] = properties['height'] / 2;
    properties['lifespan'] = properties['lifespan'] !== void 0
      ? properties['lifespan']
      : 10;
    properties['owner'] = properties['owner'] !== void 0
      ? properties['owner']
      : -1;
    properties['speed-x'] = properties['speed-x'] !== void 0
      ? properties['speed-x']
      : 1;
    properties['speed-y'] = properties['speed-y'] !== void 0
      ? properties['speed-y']
      : 1;
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 10;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_particles.push(properties);
}

function rpg_particle_handle(){
    particleloop:
    for(var particle in rpg_particles){
        rpg_particles[particle]['x'] += rpg_particles[particle]['dx'] * rpg_particles[particle]['speed-x'];
        rpg_particles[particle]['y'] += rpg_particles[particle]['dy'] * rpg_particles[particle]['speed-y'];

        if(rpg_particles[particle]['lifespan'] < 0){
            rpg_particles.splice(
              particle,
              1
            );
            continue;
        }
        rpg_particles[particle]['lifespan'] -= 1;

        for(var object in rpg_world_dynamic){
            if(!rpg_world_dynamic[object]['collision']
              || rpg_particles[particle]['x'] <= rpg_world_dynamic[object]['x']
              || rpg_particles[particle]['x'] >= rpg_world_dynamic[object]['x'] + rpg_world_dynamic[object]['width']
              || rpg_particles[particle]['y'] <= rpg_world_dynamic[object]['y']
              || rpg_particles[particle]['y'] >= rpg_world_dynamic[object]['y'] + rpg_world_dynamic[object]['height']){
                continue;
            }

            rpg_particles.splice(
              particle,
              1
            );
            continue particleloop;
        }

        // Handle particles not owned by player.
        if(rpg_particles[particle]['owner'] > -1){
            if(rpg_particles[particle]['x'] > rpg_player['x'] - rpg_player['width-half']
              && rpg_particles[particle]['x'] < rpg_player['x'] + rpg_player['width-half']
              && rpg_particles[particle]['y'] > rpg_player['y'] - rpg_player['height-half']
              && rpg_particles[particle]['y'] < rpg_player['y'] + rpg_player['height-half']){
                rpg_player_affect(
                  'health',
                  rpg_particles[particle]['damage']
                );

                rpg_particles.splice(
                  particle,
                  1
                );
            }

            continue;
        }

        // Handle particles owned by player.
        for(var npc in rpg_npcs){
            if(rpg_npcs[npc]['team'] === 0
              || rpg_particles[particle]['x'] <= rpg_npcs[npc]['x'] - rpg_npcs[npc]['width'] / 2
              || rpg_particles[particle]['x'] >= rpg_npcs[npc]['x'] + rpg_npcs[npc]['width'] / 2
              || rpg_particles[particle]['y'] <= rpg_npcs[npc]['y'] - rpg_npcs[npc]['height'] / 2
              || rpg_particles[particle]['y'] >= rpg_npcs[npc]['y'] + rpg_npcs[npc]['height'] / 2){
                continue;
            }

            rpg_npcs[npc]['stats']['health']['current'] -= rpg_particles[particle]['damage'];
            if(rpg_npcs[npc]['stats']['health']['current'] <= 0){
                rpg_npcs.splice(
                  npc,
                  1
                );
            }

            rpg_particles.splice(
              particle,
              1
            );
            continue particleloop;
        }
    }
}

function rpg_player_affect(stat, effect){
    rpg_player['stats'][stat]['current'] -= effect;
    if(rpg_player['stats'][stat]['current'] <= 0){
        rpg_player['stats'][stat]['current'] = 0;

        if(stat === 'health'){
            rpg_player['dead'] = true;
        }

    }else if(rpg_player['stats'][stat]['current'] >= rpg_player['stats'][stat]['max']){
        rpg_player['stats'][stat]['current'] = rpg_player['stats'][stat]['max'];
        rpg_player['stats'][stat]['regeneration']['current'] = 0;
    }
}

function rpg_player_create(properties){
    properties = properties || {};

    properties['dead'] = false;
    properties['equipment'] = properties['equipment'] || {
      'feet': void 0,
      'head': void 0,
      'off-hand': void 0,
      'legs': void 0,
      'main-hand': void 0,
      'neck': void 0,
      'torso': void 0,
    };
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 34;
    properties['height-half'] = properties['height'] / 2;
    properties['inventory'] = properties['inventory'] || [];
    properties['selected'] = properties['selected'] || 1;
    properties['spellbar'] = properties['spellbar'] || {
      0: void 0,
      1: void 0,
      2: void 0,
      3: void 0,
      4: void 0,
      5: void 0,
      6: void 0,
      7: void 0,
      8: void 0,
      9: void 0,
    };
    properties['spellbook'] = properties['spellbook'] || {};
    properties['stats'] = properties['stats'] || {};
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 23;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;
    properties['y-velocity'] = properties['y-velocity'] || 0;

    rpg_player = properties;
}

function rpg_player_handle(){
    if(rpg_player['dead']){
        return;
    }

    // Regenerate player health and mana.
    if(rpg_player['stats']['health']['current'] < rpg_player['stats']['health']['max']){
        rpg_player['stats']['health']['regeneration']['current'] += 1;
        if(rpg_player['stats']['health']['regeneration']['current'] >= rpg_player['stats']['health']['regeneration']['max']){
            rpg_player['stats']['health']['current'] += 1;
            rpg_player['stats']['health']['regeneration']['current'] = 0;
        }
    }

    if(rpg_player['stats']['mana']['current'] < rpg_player['stats']['mana']['max']){
        rpg_player['stats']['mana']['regeneration']['current'] += 1;
        if(rpg_player['stats']['mana']['regeneration']['current'] >= rpg_player['stats']['mana']['regeneration']['max']){
            rpg_player['stats']['mana']['current'] += 1;
            rpg_player['stats']['mana']['regeneration']['current'] = 0;
        }
    }

    // Update player spells.
    for(var spell in rpg_player['spellbook']){
        if(rpg_player['spellbook'][spell]['current'] < rpg_player['spellbook'][spell]['reload']){
            rpg_player['spellbook'][spell]['current'] += 1;
        }
    }

    // Check if player wants to fire selected spell
    //   and fire it if they do and it can be fired.
    var selected = rpg_player['spellbook'][rpg_player['spellbar'][rpg_player['selected']]];

    if(mouse_lock_x > -1
      && selected['current'] >= selected['reload']
      && rpg_player['stats'][selected['costs']]['current'] >= selected['cost']){
        selected['current'] = 0;
        rpg_player['stats'][selected['costs']]['current'] = Math.max(
          rpg_player['stats'][selected['costs']]['current'] - selected['cost'],
          0
        );

        // Handle particle-creating spells.
        if(selected['type'] === 'particle'){
            var speeds = math_movement_speed(
              rpg_player['x'],
              rpg_player['y'],
              rpg_player['x'] + mouse_x - canvas_x,
              rpg_player['y'] + mouse_y - canvas_y
            );
            var particle = {};
            for(var property in selected['particle']){
                particle[property] = selected['particle'][property];
            }
            particle['dx'] = mouse_x > canvas_x ? speeds[0] : -speeds[0];
            particle['dy'] = mouse_y > canvas_y ? speeds[1] : -speeds[1];
            particle['x'] = rpg_player['x'];
            particle['y'] = rpg_player['y'];

            rpg_particle_create(particle);

        }else if(selected['type'] === 'stat'){
            rpg_player_affect(
              selected['effect']['stat'],
              selected['effect']['damage']
            );

        }else if(selected['type'] === 'world-dynamic'){
            var worlddynamic = {};
            for(var property in selected['world-dynamic']){
                worlddynamic[property] = selected['world-dynamic'][property];
            }
            worlddynamic['x'] = rpg_player['x'] + mouse_x - canvas_x;
            worlddynamic['y'] = rpg_player['y'] + mouse_y - canvas_y;

            rpg_world_dynamic_create(worlddynamic);
        }
    }
}

function rpg_spell_select(id){
    if(id < 1){
        id = 10;

    }else if(id > 10){
        id = 1;
    }

    rpg_player['selected'] = id;
    document.getElementById('canvas').style.cursor =
      rpg_player['spellbook'][rpg_player['spellbar'][id]]['cursor'] || 'auto';
}

function rpg_world_dynamic_create(properties){
    properties = properties || {};

    properties['collision'] = properties['collision'] === void 0;
    properties['color'] = properties['color'] || '#fff';
    properties['effect'] = properties['effect'] || {};
    properties['effect-stat'] = properties['effect-stat'] || 'health';
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 25;
    properties['type'] = properties['type'] || 'stone';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 25;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_world_dynamic.push(properties);
}

var rpg_npcs = [];
var rpg_particles = [];
var rpg_player = {};
var rpg_ui = 0;
var rpg_world_dynamic = [];
var rpg_world_static = [];
<commit_msg>made spellcasting cost use rpg_player_affect()<commit_after>'use strict';

function rpg_npc_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 20;
    properties['height-half'] = properties['height'] / 2;
    properties['team'] = properties['team'] !== void 0
      ? properties['team']
      : 1;
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 20;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    properties['stats'] = properties['stats'] || {};
      properties['stats']['health'] = properties['stats']['health'] || {};
        properties['stats']['health']['current'] = properties['stats']['health']['current'] !== void 0
          ? properties['stats']['health']['current']
          : 1;
        properties['stats']['health']['max'] = properties['stats']['health']['max'] || 1;

    properties['selected'] = properties['selected'] || void 0;
    properties['spellbook'] = properties['spellbook'] || {};

    rpg_npcs.push(properties);
}

function rpg_npc_handle(){
    for(var npc in rpg_npcs){
        if(rpg_npcs[npc]['selected'] === void 0){
            continue;
        }

        for(var spell in rpg_npcs[npc]['spellbook']){
            if(rpg_npcs[npc]['spellbook'][spell]['current'] < rpg_npcs[npc]['spellbook'][spell]['reload']){
                rpg_npcs[npc]['spellbook'][spell]['current'] += 1;
                continue;
            }

            if(rpg_npcs[npc]['selected'] !== spell){
                continue;
            }

            rpg_npcs[npc]['spellbook'][spell]['current'] = 0;

            // Create NPC-created particle.
            var speeds = math_movement_speed(
              rpg_npcs[npc]['x'],
              rpg_npcs[npc]['y'],
              rpg_player['x'],
              rpg_player['y']
            );
            var particle = {};
            for(var property in rpg_npcs[npc]['spellbook'][spell]){
                particle[property] = rpg_npcs[npc]['spellbook'][spell][property];
            }
            particle['dx'] = rpg_player['x'] > rpg_npcs[npc]['x'] ? speeds[0] : -speeds[0];
            particle['dy'] = rpg_player['y'] > rpg_npcs[npc]['y'] ? speeds[1] : -speeds[1];
            particle['owner'] = npc;
            particle['x'] = rpg_npcs[npc]['x'];
            particle['y'] = rpg_npcs[npc]['y'];

            rpg_particle_create(particle);
            break;
        }
    }
}

function rpg_particle_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['damage'] = properties['damage'] || 0;
    properties['dx'] = properties['dx'] || 0;
    properties['dy'] = properties['dy'] || 0;
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 10;
    properties['height-half'] = properties['height'] / 2;
    properties['lifespan'] = properties['lifespan'] !== void 0
      ? properties['lifespan']
      : 10;
    properties['owner'] = properties['owner'] !== void 0
      ? properties['owner']
      : -1;
    properties['speed-x'] = properties['speed-x'] !== void 0
      ? properties['speed-x']
      : 1;
    properties['speed-y'] = properties['speed-y'] !== void 0
      ? properties['speed-y']
      : 1;
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 10;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_particles.push(properties);
}

function rpg_particle_handle(){
    particleloop:
    for(var particle in rpg_particles){
        rpg_particles[particle]['x'] += rpg_particles[particle]['dx'] * rpg_particles[particle]['speed-x'];
        rpg_particles[particle]['y'] += rpg_particles[particle]['dy'] * rpg_particles[particle]['speed-y'];

        if(rpg_particles[particle]['lifespan'] < 0){
            rpg_particles.splice(
              particle,
              1
            );
            continue;
        }
        rpg_particles[particle]['lifespan'] -= 1;

        for(var object in rpg_world_dynamic){
            if(!rpg_world_dynamic[object]['collision']
              || rpg_particles[particle]['x'] <= rpg_world_dynamic[object]['x']
              || rpg_particles[particle]['x'] >= rpg_world_dynamic[object]['x'] + rpg_world_dynamic[object]['width']
              || rpg_particles[particle]['y'] <= rpg_world_dynamic[object]['y']
              || rpg_particles[particle]['y'] >= rpg_world_dynamic[object]['y'] + rpg_world_dynamic[object]['height']){
                continue;
            }

            rpg_particles.splice(
              particle,
              1
            );
            continue particleloop;
        }

        // Handle particles not owned by player.
        if(rpg_particles[particle]['owner'] > -1){
            if(rpg_particles[particle]['x'] > rpg_player['x'] - rpg_player['width-half']
              && rpg_particles[particle]['x'] < rpg_player['x'] + rpg_player['width-half']
              && rpg_particles[particle]['y'] > rpg_player['y'] - rpg_player['height-half']
              && rpg_particles[particle]['y'] < rpg_player['y'] + rpg_player['height-half']){
                rpg_player_affect(
                  'health',
                  rpg_particles[particle]['damage']
                );

                rpg_particles.splice(
                  particle,
                  1
                );
            }

            continue;
        }

        // Handle particles owned by player.
        for(var npc in rpg_npcs){
            if(rpg_npcs[npc]['team'] === 0
              || rpg_particles[particle]['x'] <= rpg_npcs[npc]['x'] - rpg_npcs[npc]['width'] / 2
              || rpg_particles[particle]['x'] >= rpg_npcs[npc]['x'] + rpg_npcs[npc]['width'] / 2
              || rpg_particles[particle]['y'] <= rpg_npcs[npc]['y'] - rpg_npcs[npc]['height'] / 2
              || rpg_particles[particle]['y'] >= rpg_npcs[npc]['y'] + rpg_npcs[npc]['height'] / 2){
                continue;
            }

            rpg_npcs[npc]['stats']['health']['current'] -= rpg_particles[particle]['damage'];
            if(rpg_npcs[npc]['stats']['health']['current'] <= 0){
                rpg_npcs.splice(
                  npc,
                  1
                );
            }

            rpg_particles.splice(
              particle,
              1
            );
            continue particleloop;
        }
    }
}

function rpg_player_affect(stat, effect){
    rpg_player['stats'][stat]['current'] -= effect;
    if(rpg_player['stats'][stat]['current'] <= 0){
        rpg_player['stats'][stat]['current'] = 0;

        if(stat === 'health'){
            rpg_player['dead'] = true;
        }

    }else if(rpg_player['stats'][stat]['current'] >= rpg_player['stats'][stat]['max']){
        rpg_player['stats'][stat]['current'] = rpg_player['stats'][stat]['max'];
        rpg_player['stats'][stat]['regeneration']['current'] = 0;
    }
}

function rpg_player_create(properties){
    properties = properties || {};

    properties['dead'] = false;
    properties['equipment'] = properties['equipment'] || {
      'feet': void 0,
      'head': void 0,
      'off-hand': void 0,
      'legs': void 0,
      'main-hand': void 0,
      'neck': void 0,
      'torso': void 0,
    };
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 34;
    properties['height-half'] = properties['height'] / 2;
    properties['inventory'] = properties['inventory'] || [];
    properties['selected'] = properties['selected'] || 1;
    properties['spellbar'] = properties['spellbar'] || {
      0: void 0,
      1: void 0,
      2: void 0,
      3: void 0,
      4: void 0,
      5: void 0,
      6: void 0,
      7: void 0,
      8: void 0,
      9: void 0,
    };
    properties['spellbook'] = properties['spellbook'] || {};
    properties['stats'] = properties['stats'] || {};
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 23;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;
    properties['y-velocity'] = properties['y-velocity'] || 0;

    rpg_player = properties;
}

function rpg_player_handle(){
    if(rpg_player['dead']){
        return;
    }

    // Regenerate player health and mana.
    if(rpg_player['stats']['health']['current'] < rpg_player['stats']['health']['max']){
        rpg_player['stats']['health']['regeneration']['current'] += 1;
        if(rpg_player['stats']['health']['regeneration']['current'] >= rpg_player['stats']['health']['regeneration']['max']){
            rpg_player['stats']['health']['current'] += 1;
            rpg_player['stats']['health']['regeneration']['current'] = 0;
        }
    }

    if(rpg_player['stats']['mana']['current'] < rpg_player['stats']['mana']['max']){
        rpg_player['stats']['mana']['regeneration']['current'] += 1;
        if(rpg_player['stats']['mana']['regeneration']['current'] >= rpg_player['stats']['mana']['regeneration']['max']){
            rpg_player['stats']['mana']['current'] += 1;
            rpg_player['stats']['mana']['regeneration']['current'] = 0;
        }
    }

    // Update player spells.
    for(var spell in rpg_player['spellbook']){
        if(rpg_player['spellbook'][spell]['current'] < rpg_player['spellbook'][spell]['reload']){
            rpg_player['spellbook'][spell]['current'] += 1;
        }
    }

    // Check if player wants to fire selected spell
    //   and fire it if they do and it can be fired.
    var selected = rpg_player['spellbook'][rpg_player['spellbar'][rpg_player['selected']]];

    if(mouse_lock_x > -1
      && selected['current'] >= selected['reload']
      && rpg_player['stats'][selected['costs']]['current'] >= selected['cost']){
        selected['current'] = 0;
        rpg_player_affect(
          selected['costs'],
          selected['cost']
        );

        // Handle particle-creating spells.
        if(selected['type'] === 'particle'){
            var speeds = math_movement_speed(
              rpg_player['x'],
              rpg_player['y'],
              rpg_player['x'] + mouse_x - canvas_x,
              rpg_player['y'] + mouse_y - canvas_y
            );
            var particle = {};
            for(var property in selected['particle']){
                particle[property] = selected['particle'][property];
            }
            particle['dx'] = mouse_x > canvas_x ? speeds[0] : -speeds[0];
            particle['dy'] = mouse_y > canvas_y ? speeds[1] : -speeds[1];
            particle['x'] = rpg_player['x'];
            particle['y'] = rpg_player['y'];

            rpg_particle_create(particle);

        }else if(selected['type'] === 'stat'){
            rpg_player_affect(
              selected['effect']['stat'],
              selected['effect']['damage']
            );

        }else if(selected['type'] === 'world-dynamic'){
            var worlddynamic = {};
            for(var property in selected['world-dynamic']){
                worlddynamic[property] = selected['world-dynamic'][property];
            }
            worlddynamic['x'] = rpg_player['x'] + mouse_x - canvas_x;
            worlddynamic['y'] = rpg_player['y'] + mouse_y - canvas_y;

            rpg_world_dynamic_create(worlddynamic);
        }
    }
}

function rpg_spell_select(id){
    if(id < 1){
        id = 10;

    }else if(id > 10){
        id = 1;
    }

    rpg_player['selected'] = id;
    document.getElementById('canvas').style.cursor =
      rpg_player['spellbook'][rpg_player['spellbar'][id]]['cursor'] || 'auto';
}

function rpg_world_dynamic_create(properties){
    properties = properties || {};

    properties['collision'] = properties['collision'] === void 0;
    properties['color'] = properties['color'] || '#fff';
    properties['effect'] = properties['effect'] || {};
    properties['effect-stat'] = properties['effect-stat'] || 'health';
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 25;
    properties['type'] = properties['type'] || 'stone';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 25;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_world_dynamic.push(properties);
}

var rpg_npcs = [];
var rpg_particles = [];
var rpg_player = {};
var rpg_ui = 0;
var rpg_world_dynamic = [];
var rpg_world_static = [];
<|endoftext|>