<commit_before>console.log('poi-begin');
var map, filter, mapOptions, mapBounds, markerBounds, poiIndexed, catIndexed, iconAnchor, infoWindow;
iconAnchor = new google.maps.Point(5, 33);
function indexPOIData() {
	var i, len;
	poiIndexed = {};
	for (i = 0, len = poi.length; i < len; i++) {
		poiIndexed[poi[i].id] = poi[i];
	}
	catIndexed = {};
	for (i = 0, len = cat.length; i < len; i++) {
		catIndexed[cat[i].id] = cat[i];
	}
}
function setupPOILists() {
	var i, len;
	var markup = '';
	for (i = 0; i < cat.length; i++) {
		markup += markupCategoryList(cat[i]);
	}
	$(".poi-categories").append(markup);
	$(".poi-category label").click(function(event) {
		var catID, filterIndex
		catElement = $(this).closest(".poi-category");
		catID = catElement.attr("data-cat-id");
		if (catID === "") {
			filter = [];
			$(".poi-category ul").slideDown();// show all lists
		} else {
			catElement.siblings(".poi-category").find("ul").slideUp();
			$("ul", catElement).slideDown();// show this list
		$(".poi-category[data-cat-id=" + catID + "]").slideDown
			filter = [catID];
		}
		infoWindow.close();
		placeMarkers();
		if (catID === "") {
			map.panTo(mapOptions.center);
			map.setZoom(mapOptions.zoom);
		}
	});
	$(".poi-category ul").mCustomScrollbar({
		scrollButtons: {
			enable: true
		}
	});
	$(".poi-category li").click(function(event) {
		var poi = poiIndexed[$(this).attr("data-poi-id")];
		map.panTo(poi.marker.getPosition());
		if (filter && filter.length && filter.indexOf(poi.cat_id) === -1) {
			filter = [poi.cat_id];
			placeMarkers();
		}
		showPOIInfo(poi);
	});
}
function markupCategoryList(cat) {
	var markup, i, len, address, symbolPath;
	symbolPath = cat.icon.replace(/\/marker-/, '/symbol-');
	//console.log(symbolPath);
	markup = '
'
			+ '' + cat.name + ''
			+ '
';
	for (i = 0, len = poi.length; i < len; i++) {
		if (poi[i].cat_id == cat.id) {
			markup += '
' + poi[i].name + '
';
		}
	}
	markup += '
'
		+ '
';

	return markup;
}
function showPOIInfo(poi) {
	var content, linkName, $header, mapTop;
	content = '
'
		+ '
'+poi['name']+'
';
	if (poi['description']) {
		content += '
' + poi['description'] + '
';
	}
	content += '
'+poi['address'] + '
'
		+ poi['city'] + ', ' + poi['state'] + ' ' + poi['zip']
		+ '
'
		+ '
';
	if (poi['phone']) {
		content += poi['phone'];
		if (poi['url']) content += '
';
	}
	if (poi['url']) {
		linkName = poi['url'].replace(/^https?:\/\/|\/$/g, '');
		if (linkName.indexOf('playavista.com') === 0) {
			linkName = linkName.replace(/^.*\//, '');
		}
		content += ''+linkName+'';
	}
	content += '
' // .contact
		+ '
'; // .poi-info
	infoWindow.setContent(content);
	infoWindow.open(map, poi.marker);
	$header = $("header");
	mapTop = $("#map-canvas").offset().top - $header.height() - $header.position().top;
	if ($(document.body).scrollTop() > mapTop) {
		$(document.body).animate({scrollTop: mapTop}, 300);
	}
}
function placeMarkers(forceFit) {
	var i, len, isMatch, position, markerOptions;
	markerBounds = new google.maps.LatLngBounds();
	for (i = 0, len = poi.length; i < len; i++) {
		isMatch = (
			!filter
			|| (
				typeof filter == "object"
				&& (
					!filter.length
					|| filter.indexOf(poi[i].cat_id) !== -1
				)
			)
			|| (
				(
					typeof filter == "string"
					|| typeof filter == "number"
				)
				&& poi[i].id == filter
			)
		);
		if (typeof poi[i].marker !== "undefined") {
			if (isMatch) {
				poi[i].marker.setMap(map);
				markerBounds.extend(poi[i].marker.getPosition());
			} else {
				poi[i].marker.setMap(null);
			}
		} else if(isMatch) {
			if (Number(poi[i].lat) && Number(poi[i].lng)) {
				var poiCat = catIndexed[poi[i].cat_id];
				position = new google.maps.LatLng(poi[i].lat, poi[i].lng);
				markerOptions = {
					position: position,
					map: map,
					title: poi[i].name
				};
				if (poiCat) {
					markerOptions.icon = {
						url: poiCat.icon,
						anchor: iconAnchor
					};
				}
				poi[i].marker = new google.maps.Marker(markerOptions);

				google.maps.event.addListener(poi[i].marker, 'click', (function(i) { return function() {
					showPOIInfo(poi[i]);
				}})(i));
				// google.maps.addListener(poi[i].marker, 'click', function(event) {
				// 	address = poi[i].address + '
' + poi[i].city + ', ' + poi[i].state + ' ' + poi[i].zip;
				// 	markup = '
' + poi[i].name + '

' + address + '
';
				// 	// show markup in infowindow
				// });
				markerBounds.extend(position);
			}
		}
	}
	mapBounds = map.getBounds();
	if (forceFit || (mapBounds && !mapBounds.intersects(markerBounds))) {
		if (markerBounds.toString() != "((1, 180), (-1, -180))") {
			map.fitBounds(markerBounds);
		}
	}
}
function initMap() {
	mapOptions = {
		zoom: 14,
		center: new google.maps.LatLng(0, 0),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		styles: [
			{
				"featureType": "administrative.locality",
				"elementType": "labels",
				"stylers": [
					{ "visibility": "off" }
				]
			},
			{
				"featureType": "administrative.neighborhood",
				"elementType": "labels",
				"stylers": [
					{ "visibility": "off" }
				]
			},
			{
				"featureType": "poi.sports_complex",
				"elementType": "labels",
				"stylers": [
					{ "visibility": "off" }
				]
			},
			{
				"featureType": "transit.station.airport",
				"elementType": "labels",
				"stylers": [
					{ "visibility": "off" }
				]
			}
		]
	};
	if (center_lat && center_lng) {
		mapOptions.center = new google.maps.LatLng(center_lat, center_lng)
	}
	map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

	filter = [];

	infoWindow = new google.maps.InfoWindow();
	placeMarkers(!center_lat || !center_lng);
	setupPOILists();
	$("#menu-item-26").addClass("current-menu-item");// FIXME: demo only
	console.log('poi-fixme');
}
indexPOIData();
google.maps.event.addDomListener(window, 'load', initMap);

<commit_msg>turned off slide up/down<commit_after>var map, filter, mapOptions, mapBounds, markerBounds, poiIndexed, catIndexed, iconAnchor, infoWindow;
iconAnchor = new google.maps.Point(5, 33);
function indexPOIData() {
	var i, len;
	poiIndexed = {};
	for (i = 0, len = poi.length; i < len; i++) {
		poiIndexed[poi[i].id] = poi[i];
	}
	catIndexed = {};
	for (i = 0, len = cat.length; i < len; i++) {
		catIndexed[cat[i].id] = cat[i];
	}
}
function setupPOILists() {
	var i, len;
	var markup = '';
	for (i = 0; i < cat.length; i++) {
		markup += markupCategoryList(cat[i]);
	}
	$(".poi-categories").append(markup);
	$(".poi-category label").click(function(event) {
		var catID, filterIndex
		catElement = $(this).closest(".poi-category");
		catID = catElement.attr("data-cat-id");
		if (catID === "") {
			filter = [];

			// these 3 commented out lines control the POI slide up/down
			// we need to make them controllable (on/off) from the backend
			// 12/17 --ps

			//$(".poi-category ul").slideDown();// show all lists
		} else {
			//catElement.siblings(".poi-category").find("ul").slideUp();
			//$("ul", catElement).slideDown();// show this list
		$(".poi-category[data-cat-id=" + catID + "]").slideDown
			filter = [catID];
		}
		infoWindow.close();
		placeMarkers();
		if (catID === "") {
			map.panTo(mapOptions.center);
			map.setZoom(mapOptions.zoom);
		}
	});
	$(".poi-category ul").mCustomScrollbar({
		scrollButtons: {
			enable: true
		}
	});
	$(".poi-category li").click(function(event) {
		var poi = poiIndexed[$(this).attr("data-poi-id")];
		map.panTo(poi.marker.getPosition());
		if (filter && filter.length && filter.indexOf(poi.cat_id) === -1) {
			filter = [poi.cat_id];
			placeMarkers();
		}
		showPOIInfo(poi);
	});
}
function markupCategoryList(cat) {
	var markup, i, len, address, symbolPath;
	symbolPath = cat.icon.replace(/\/marker-/, '/symbol-');
	markup = '
'
			+ '' + cat.name + ''
			+ '
';
	for (i = 0, len = poi.length; i < len; i++) {
		if (poi[i].cat_id == cat.id) {
			markup += '
' + poi[i].name + '
';
		}
	}
	markup += '
'
		+ '
';

	return markup;
}
function showPOIInfo(poi) {
	var content, linkName, $header, mapTop;
	content = '
'
		+ '
'+poi['name']+'
';
	if (poi['description']) {
		content += '
' + poi['description'] + '
';
	}
	content += '
'+poi['address'] + '
'
		+ poi['city'] + ', ' + poi['state'] + ' ' + poi['zip']
		+ '
'
		+ '
';
	if (poi['phone']) {
		content += poi['phone'];
		if (poi['url']) content += '
';
	}
	if (poi['url']) {
		linkName = poi['url'].replace(/^https?:\/\/|\/$/g, '');
		if (linkName.indexOf('playavista.com') === 0) {
			linkName = linkName.replace(/^.*\//, '');
		}
		content += ''+linkName+'';
	}
	content += '
' // .contact
		+ '
'; // .poi-info
	infoWindow.setContent(content);
	infoWindow.open(map, poi.marker);
	$header = $("header");
	mapTop = $("#map-canvas").offset().top - $header.height() - $header.position().top;
	if ($(document.body).scrollTop() > mapTop) {
		$(document.body).animate({scrollTop: mapTop}, 300);
	}
}
function placeMarkers(forceFit) {
	var i, len, isMatch, position, markerOptions;
	markerBounds = new google.maps.LatLngBounds();
	for (i = 0, len = poi.length; i < len; i++) {
		isMatch = (
			!filter
			|| (
				typeof filter == "object"
				&& (
					!filter.length
					|| filter.indexOf(poi[i].cat_id) !== -1
				)
			)
			|| (
				(
					typeof filter == "string"
					|| typeof filter == "number"
				)
				&& poi[i].id == filter
			)
		);
		if (typeof poi[i].marker !== "undefined") {
			if (isMatch) {
				poi[i].marker.setMap(map);
				markerBounds.extend(poi[i].marker.getPosition());
			} else {
				poi[i].marker.setMap(null);
			}
		} else if(isMatch) {
			if (Number(poi[i].lat) && Number(poi[i].lng)) {
				var poiCat = catIndexed[poi[i].cat_id];
				position = new google.maps.LatLng(poi[i].lat, poi[i].lng);
				markerOptions = {
					position: position,
					map: map,
					title: poi[i].name
				};
				if (poiCat) {
					markerOptions.icon = {
						url: poiCat.icon,
						anchor: iconAnchor
					};
				}
				poi[i].marker = new google.maps.Marker(markerOptions);

				google.maps.event.addListener(poi[i].marker, 'click', (function(i) { return function() {
					showPOIInfo(poi[i]);
				}})(i));
				// google.maps.addListener(poi[i].marker, 'click', function(event) {
				// 	address = poi[i].address + '
' + poi[i].city + ', ' + poi[i].state + ' ' + poi[i].zip;
				// 	markup = '
' + poi[i].name + '

' + address + '
';
				// 	// show markup in infowindow
				// });
				markerBounds.extend(position);
			}
		}
	}
	mapBounds = map.getBounds();
	if (forceFit || (mapBounds && !mapBounds.intersects(markerBounds))) {
		if (markerBounds.toString() != "((1, 180), (-1, -180))") {
			map.fitBounds(markerBounds);
		}
	}
}
function initMap() {
	mapOptions = {
		zoom: 14,
		center: new google.maps.LatLng(0, 0),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		styles: [
			{
				"featureType": "administrative.locality",
				"elementType": "labels",
				"stylers": [
					{ "visibility": "off" }
				]
			},
			{
				"featureType": "administrative.neighborhood",
				"elementType": "labels",
				"stylers": [
					{ "visibility": "off" }
				]
			},
			{
				"featureType": "poi.sports_complex",
				"elementType": "labels",
				"stylers": [
					{ "visibility": "off" }
				]
			},
			{
				"featureType": "transit.station.airport",
				"elementType": "labels",
				"stylers": [
					{ "visibility": "off" }
				]
			}
		]
	};
	if (center_lat && center_lng) {
		mapOptions.center = new google.maps.LatLng(center_lat, center_lng)
	}
	map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

	filter = [];

	infoWindow = new google.maps.InfoWindow();
	placeMarkers(!center_lat || !center_lng);
	setupPOILists();
	$("#menu-item-26").addClass("current-menu-item");// FIXME: demo only
}
indexPOIData();
google.maps.event.addDomListener(window, 'load', initMap);

<|endoftext|>


<commit_before>'use strict';

// RequestAnimationFrame
(function() {
  var lastTime = 0;
  var vendors = ['webkit', 'moz'];
  for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
    window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
    window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
  }

  if (!window.requestAnimationFrame){
    window.requestAnimationFrame = function(callback) {
      var currTime = new Date().getTime();
      var timeToCall = Math.max(0, 16 - (currTime - lastTime));
      var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
      lastTime = currTime + timeToCall;
      return id;
    };
  }

  if (!window.cancelAnimationFrame){
    window.cancelAnimationFrame = function(id) {
      clearTimeout(id);
    };
  }

}());

var App = {};

//  App
(function($){
  var startHeight = $(window).height();

  App.lastScroll = 0;

  App.init = function(){

    App.menuColor();
    App.logo();
    App.menu();
    App.coverHeight();
    App.homePhotoHover();
    App.snapHeader();
    App.fixieText();

    $('body#place').each(function(){
      $(window).scrollTop(0);
    });

  };

  App.coverHeight = function(){
    $('#cover').height(startHeight);
  };

  App.menu = function(){
    // Menu
    $('#menu-icon, #menu .close').off('click.menu').on('click.menu', function(e){
      e.preventDefault();
      $('#menu').toggleClass('open');
    });
  };

  App.menuColor = function(){
    if($(window).scrollTop() > startHeight) {
      $('#menu-icon').removeClass('white').addClass('black');
    } else {
      $('#menu-icon').addClass('white').removeClass('black');
    }

    window.requestAnimationFrame( App.menuColor );
  };

  App.logo = function() {
    // Logo
    var $logo = $('#logo');

    $('#cover').fadeTo(0, 0.01);

    $logo.each(function(){
      var randomLogo = _.random(1, 10),
          imageUrl = ['img/logos/logo_'+ randomLogo +'.png', 'img/logos-hd/logo_'+ randomLogo +'.png'];

      $.preload(imageUrl[0]).then(function(){
        return $.preload(imageUrl[1]);
      })
      .then(function() {
        return $logo.removeClass('hide').fadeOut(0).promise();
      }).then(function(){
        return $logo.addClass('logo_' + randomLogo).promise();
      }).then(function(){
        setTimeout(function(){

          // $logo.fadeIn(300);

          $('#cover').fadeIn(400);
      	  $('#logo').delay(800).fadeIn(400);

        }, 300);
      });

    });
  };

  App.homePhotoHover = function(){
    // Home Photo Hover
    $('#main .company').each(function(index){
      var $this = $(this),
          photoHover = $this.data('photo');
      if (photoHover) {
        $this.off('mouseenter.photoHover').on('mouseenter.photoHover', function(e){
          console.log(e);
          var offset = {top: e.clientY, left: e.clientX},
              imageUrl = 'img/photo-hover/' + photoHover;

          $.preload(imageUrl).done(function(){
            var $photo = $('<img>', {id: 'photo-hover-' + index ,src:imageUrl, 'class': 'photo-hover'});
            $photo.css({
              top: (offset.top),
              left: (offset.left),
              display: 'none'
            });
            $this.data('photo-index', 'photo-hover-' + index);
            $('#main').append($photo);
            $photo.fadeIn('fast');
          });
        }).off('mouseleave.photoHover').on('mouseleave.photoHover', function(){
          var $this = $(this),
              photoIndex = $this.data('photo-index');

          if (photoIndex) {
            $('#'+photoIndex).fadeOut('fast').promise().then(function(){
              $('#'+photoIndex).remove();
            });
          }
        });
      }
    });
  };

  App.snapHeader = function(){
    var scroll = $(window).scrollTop();
    App.currentScroll = scroll;
    App.scrollDirection = App.currentScroll > App.lastScroll;

    if((scroll < startHeight) && scroll > 0 && scroll < (startHeight - 10)) {
      if (App.scrollDirection) {
        if (!App.animatingScroll) App.animateScrollTo(startHeight + 10);
      }
    }

    App.lastScroll = scroll;

    window.requestAnimationFrame( App.snapHeader );
  };

  App.animateScrollTo = function(to){
    App.animatingScroll = true;
    return $('html, body').animate({scrollTop:to}, {duration: '300', queue: false}).promise().then(function(){
      App.animatingScroll = false;
    });
  };

  App.fixieText = function() {
    var $textContainers = $('.fixie-text-container');

    $textContainers.each(function () {
      var $this = $(this),
          $window = $(window),
          relativeTop = $this.offset().top - $window.scrollTop(),
          relativeBottom = (relativeTop + $this.height() - 20),
          $text = $('.fixie-text', $this);

      if ($this.hasClass('gone')) {
        var textRelativeTop_ = $text.offset().top - $window.scrollTop();

        if (textRelativeTop_ >= 30) {
          $text.css({
            'position': 'fixed',
            'top': '30px',
            'left': $text.offset().left,
            'width': $text.css('width')
          });

          $this.removeClass('gone');
        }

      } else {
        if (relativeTop <= 30) {
          $text.css({
            'position': 'fixed',
            'top': '30px',
            'left': $text.offset().left,
            'width': $text.css('width')
          });
        }

        if (relativeTop > 30) {
          $text.css({
            'position': 'relative',
            'top': 'auto',
            'left': 'auto',
            'width': ''
          });
        }

        if ((relativeBottom - 30) <= $text.height()) {
          var textRelativeTop = $text.offset().top - $window.scrollTop();
          $this.css({
            'position': 'relative'
          });
          $text.css({
            'position': 'absolute',
            'top': textRelativeTop - relativeTop,
            'left': $text.offset().left - $this.offset().left
          });

          $this.addClass('gone');
        }
      }

    });

    window.requestAnimationFrame( App.fixieText );
  };

  App.buildMap = function(){
      // Basic options for a simple Google Map
      // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
      var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 15,
        scrollwheel: false,

        // The latitude and longitude to center the map (always required)
        // center: new google.maps.LatLng(40.6700, -73.9400), // New York
        center: new google.maps.LatLng(-23.529246, -46.636655), // New York

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        styles: [{
          'featureType':'landscape',
          'stylers':[
            {'saturation':-100},
            {'lightness':65},
            {'visibility':'on'}
          ]
        },{
          'featureType':'poi',
          'stylers':[
            {'saturation':-100},
            {'lightness':51},
            {'visibility':'simplified'}
          ]
        },{
          'featureType':'road.highway',
          'stylers':[
            {'saturation':-100},
            {'visibility':'simplified'}
          ]
        },{
          'featureType':'road.arterial',
          'stylers':[
            {'saturation':-100},
            {'lightness':30},
            {'visibility':'on'}
          ]
        },{
          'featureType':'road.local',
          'stylers':[
            {'saturation':-100},
            {'lightness':40},
            {'visibility':'on'}
          ]
        },{
          'featureType':'transit',
          'stylers':[
            {'saturation':-100},
            {'visibility':'simplified'}
          ]
        },{
          'featureType':'administrative.province',
          'stylers':[
            {'visibility':'off'}
          ]
        },{
          'featureType':'water',
          'elementType':'labels',
          'stylers':[
            {'visibility':'on'},
            {'lightness':-25},
            {'saturation':-100}
          ]
        },{
          'featureType':'water',
          'elementType':'geometry',
          'stylers':[
            {'hue':'#ffff00'},
            {'lightness':-25},
            {'saturation':-97}
          ]
        }]
      };
      // Get the HTML DOM element that will contain your map
      // We are using a div with id='map' seen below in the <body>
      var mapElement = document.getElementById('map-container');

      // Create the Google Map using our element and options defined above
      var map = new google.maps.Map(mapElement, mapOptions);

      var pinIcon = {
          path: 'M71.5,39c0,12.15-22,44-22,44s-22-31.85-22-44c0-12.151,9.849-22,22-22C61.65,17,71.5,26.849,71.5,39  z',
          fillColor: 'black',
          fillOpacity: 1,
          scale: 1,
          strokeColor: 'black',
          strokeWeight: 1
        };

      // Let's also add a marker while we're at it
      var marker = new google.maps.Marker({
          // position: new google.maps.LatLng(40.6700, -73.9400),
          position: new google.maps.LatLng(-23.529246, -46.636655),
          icon: pinIcon,
          map: map
      });

      console.log();
  };

  App.init();
  google.maps.event.addDomListener(window, 'load', App.buildMap);
})(jQuery);
<commit_msg>fade da capa<commit_after>'use strict';

// RequestAnimationFrame
(function() {
  var lastTime = 0;
  var vendors = ['webkit', 'moz'];
  for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
    window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
    window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
  }

  if (!window.requestAnimationFrame){
    window.requestAnimationFrame = function(callback) {
      var currTime = new Date().getTime();
      var timeToCall = Math.max(0, 16 - (currTime - lastTime));
      var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
      lastTime = currTime + timeToCall;
      return id;
    };
  }

  if (!window.cancelAnimationFrame){
    window.cancelAnimationFrame = function(id) {
      clearTimeout(id);
    };
  }

}());

var App = {};

//  App
(function($){
  var startHeight = $(window).height();

  App.lastScroll = 0;

  App.init = function(){

    App.menuColor();
    App.logo();
    App.menu();
    App.coverHeight();
    App.homePhotoHover();
    App.snapHeader();
    App.fixieText();

    $('body#place').each(function(){
      $(window).scrollTop(0);
    });

  };

  App.coverHeight = function(){
    $('#cover').height(startHeight);
  };

  App.menu = function(){
    // Menu
    $('#menu-icon, #menu .close').off('click.menu').on('click.menu', function(e){
      e.preventDefault();
      $('#menu').toggleClass('open');
    });
  };

  App.menuColor = function(){
    if($(window).scrollTop() > startHeight) {
      $('#menu-icon').removeClass('white').addClass('black');
    } else {
      $('#menu-icon').addClass('white').removeClass('black');
    }

    window.requestAnimationFrame( App.menuColor );
  };

  App.logo = function() {
    // Logo
    var $logo = $('#logo');

    $('#cover').fadeTo(0,0);
    $('#cover').delay(600).fadeTo(400,1);

    $logo.each(function(){
      var randomLogo = _.random(1, 10),
          imageUrl = ['img/logos/logo_'+ randomLogo +'.png', 'img/logos-hd/logo_'+ randomLogo +'.png'];

      $.preload(imageUrl[0]).then(function(){
        return $.preload(imageUrl[1]);
      })
      .then(function() {
        return $logo.removeClass('hide').fadeOut(0).promise();
      }).then(function(){
        return $logo.addClass('logo_' + randomLogo).promise();
      }).then(function(){
        setTimeout(function(){

          $logo.fadeIn(400);

        }, 800);
      });

    });
  };

  App.homePhotoHover = function(){
    // Home Photo Hover
    $('#main .company').each(function(index){
      var $this = $(this),
          photoHover = $this.data('photo');
      if (photoHover) {
        $this.off('mouseenter.photoHover').on('mouseenter.photoHover', function(e){
          console.log(e);
          var offset = {top: e.clientY, left: e.clientX},
              imageUrl = 'img/photo-hover/' + photoHover;

          $.preload(imageUrl).done(function(){
            var $photo = $('<img>', {id: 'photo-hover-' + index ,src:imageUrl, 'class': 'photo-hover'});
            $photo.css({
              top: (offset.top),
              left: (offset.left),
              display: 'none'
            });
            $this.data('photo-index', 'photo-hover-' + index);
            $('#main').append($photo);
            $photo.fadeIn('fast');
          });
        }).off('mouseleave.photoHover').on('mouseleave.photoHover', function(){
          var $this = $(this),
              photoIndex = $this.data('photo-index');

          if (photoIndex) {
            $('#'+photoIndex).fadeOut('fast').promise().then(function(){
              $('#'+photoIndex).remove();
            });
          }
        });
      }
    });
  };

  App.snapHeader = function(){
    var scroll = $(window).scrollTop();
    App.currentScroll = scroll;
    App.scrollDirection = App.currentScroll > App.lastScroll;

    if((scroll < startHeight) && scroll > 0 && scroll < (startHeight - 10)) {
      if (App.scrollDirection) {
        if (!App.animatingScroll) App.animateScrollTo(startHeight + 10);
      }
    }

    App.lastScroll = scroll;

    window.requestAnimationFrame( App.snapHeader );
  };

  App.animateScrollTo = function(to){
    App.animatingScroll = true;
    return $('html, body').animate({scrollTop:to}, {duration: '300', queue: false}).promise().then(function(){
      App.animatingScroll = false;
    });
  };

  App.fixieText = function() {
    var $textContainers = $('.fixie-text-container');

    $textContainers.each(function () {
      var $this = $(this),
          $window = $(window),
          relativeTop = $this.offset().top - $window.scrollTop(),
          relativeBottom = (relativeTop + $this.height() - 20),
          $text = $('.fixie-text', $this);

      if ($this.hasClass('gone')) {
        var textRelativeTop_ = $text.offset().top - $window.scrollTop();

        if (textRelativeTop_ >= 30) {
          $text.css({
            'position': 'fixed',
            'top': '30px',
            'left': $text.offset().left,
            'width': $text.css('width')
          });

          $this.removeClass('gone');
        }

      } else {
        if (relativeTop <= 30) {
          $text.css({
            'position': 'fixed',
            'top': '30px',
            'left': $text.offset().left,
            'width': $text.css('width')
          });
        }

        if (relativeTop > 30) {
          $text.css({
            'position': 'relative',
            'top': 'auto',
            'left': 'auto',
            'width': ''
          });
        }

        if ((relativeBottom - 30) <= $text.height()) {
          var textRelativeTop = $text.offset().top - $window.scrollTop();
          $this.css({
            'position': 'relative'
          });
          $text.css({
            'position': 'absolute',
            'top': textRelativeTop - relativeTop,
            'left': $text.offset().left - $this.offset().left
          });

          $this.addClass('gone');
        }
      }

    });

    window.requestAnimationFrame( App.fixieText );
  };

  App.buildMap = function(){
      // Basic options for a simple Google Map
      // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
      var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 15,
        scrollwheel: false,

        // The latitude and longitude to center the map (always required)
        // center: new google.maps.LatLng(40.6700, -73.9400), // New York
        center: new google.maps.LatLng(-23.529246, -46.636655), // New York

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        styles: [{
          'featureType':'landscape',
          'stylers':[
            {'saturation':-100},
            {'lightness':65},
            {'visibility':'on'}
          ]
        },{
          'featureType':'poi',
          'stylers':[
            {'saturation':-100},
            {'lightness':51},
            {'visibility':'simplified'}
          ]
        },{
          'featureType':'road.highway',
          'stylers':[
            {'saturation':-100},
            {'visibility':'simplified'}
          ]
        },{
          'featureType':'road.arterial',
          'stylers':[
            {'saturation':-100},
            {'lightness':30},
            {'visibility':'on'}
          ]
        },{
          'featureType':'road.local',
          'stylers':[
            {'saturation':-100},
            {'lightness':40},
            {'visibility':'on'}
          ]
        },{
          'featureType':'transit',
          'stylers':[
            {'saturation':-100},
            {'visibility':'simplified'}
          ]
        },{
          'featureType':'administrative.province',
          'stylers':[
            {'visibility':'off'}
          ]
        },{
          'featureType':'water',
          'elementType':'labels',
          'stylers':[
            {'visibility':'on'},
            {'lightness':-25},
            {'saturation':-100}
          ]
        },{
          'featureType':'water',
          'elementType':'geometry',
          'stylers':[
            {'hue':'#ffff00'},
            {'lightness':-25},
            {'saturation':-97}
          ]
        }]
      };
      // Get the HTML DOM element that will contain your map
      // We are using a div with id='map' seen below in the <body>
      var mapElement = document.getElementById('map-container');

      // Create the Google Map using our element and options defined above
      var map = new google.maps.Map(mapElement, mapOptions);

      var pinIcon = {
          path: 'M71.5,39c0,12.15-22,44-22,44s-22-31.85-22-44c0-12.151,9.849-22,22-22C61.65,17,71.5,26.849,71.5,39  z',
          fillColor: 'black',
          fillOpacity: 1,
          scale: 1,
          strokeColor: 'black',
          strokeWeight: 1
        };

      // Let's also add a marker while we're at it
      var marker = new google.maps.Marker({
          // position: new google.maps.LatLng(40.6700, -73.9400),
          position: new google.maps.LatLng(-23.529246, -46.636655),
          icon: pinIcon,
          map: map
      });

      console.log();
  };

  App.init();
  google.maps.event.addDomListener(window, 'load', App.buildMap);
})(jQuery);
<|endoftext|>


<commit_before>
var translation = {
    first: "|< Premier",
    previous: "< Précédent",
    random: "N'importe",
    next: "Prochain >",
    last: "Dernier >|"
};

var t = "assets/";

var strips = [
    "slogan.png",
    "bd-en-ligne.png",
    "l-austerite.png",
    "la-pub.png",
    "du-boulot.png",
    "charlie.png",
    "un-cafe.png",
    "fiat-luxe.png",
    "c-ta-crere.png",
    "time-out.png",
    "je-like-pas.png",
    "de-pis-en-pis.png",
    "toune.png",
    "le-futur-ete.png",
    "c-est_pas_gai.png",
    "le-truc.png",
    "fin-de-partie.png",
    "don-de-soi.png",
    "festival.png",
    "infortunes-du-rire.png",
    "cuisses.png",
    "sante.png",
    "automobilistes.png",
    "but-d-jouet.png",
    "qui-rira-le-dernier.png",
    "cadeau.png",
    "universel.png",
    "exil.png",
    "mise-a-jour.png",
    "presentations.png",
    "pornophiles.png",
    "faux-departs.png",
    "zero-probleme.png",
    "tribut.png",
    "chocolat.png",
    "la-joke.png"
];

var prevBtn = document.querySelectorAll(".prev"),
    nextBtn = document.querySelectorAll(".next"),
    firstBtn = document.querySelectorAll(".first"),
    lastBtn = document.querySelectorAll(".last"),
    randomBtn = document.querySelectorAll(".random"),
    preloadFirst = document.querySelector(".preload__first"),
    preloadPrevious = document.querySelector(".preload__previous"),
    preloadRandom = document.querySelector(".preload__random"),
    preloadNext = document.querySelector(".preload__next"),
    preloadLast = document.querySelector(".preload__last");
    prevBtn[0].innerHTML = translation.previous, nextBtn[0].innerHTML = translation.next, firstBtn[0].innerHTML = translation.first, lastBtn[0].innerHTML = translation.last, randomBtn[0].innerHTML = translation.random,
    function() {
        var initialURL = location.pathname;
        var e = strips.length - 1,
            r = strips.indexOf(initialURL.slice(1) + '.png'),
            o = document.querySelector("#comic"),
            l = function(strips, t) {
                for (var e = strips.length; e > 0;) e--, strips[e].addEventListener("click", t)
            },
            i = function() {
                r -= 1, 0 > r && (r = 0), s()
            },
            a = function() {
                r += 1, r > e && (r = e), s()
            },
            u = function() {
                r = 0, s()
            },
            c = function() {
                r = e, s()
            },
            p = function() {
                r = strips.indexOf(preloadRandom.getAttribute("data-file")), randomComic = preCalcRandom(), s();

            };
            if (r < 0) {r = e};
        l(prevBtn, i), l(nextBtn, a), l(firstBtn, u), l(lastBtn, c), l(randomBtn, p);
        var s = function() {
            o.src = t + strips[r];
            currentURL = strips[r].slice(0, -4);
            preload();
            history.pushState(null, null, currentURL);
            // Disable first/last and next/previous if last/first comic
            if (r === e){disableLast()} else {enableLast()};
            if (r === 0){disableFirst()} else {enableFirst()};
        }
        var disableLast = function () {
            var isLastDisabled = document.querySelector('.disable--last');
            if (!isLastDisabled){
                document.querySelector('.controls').classList.add("disable--last");
            };
        };
        var enableLast = function () {
            var isLastDisabled = document.querySelector('.disable--last');
            if (isLastDisabled){
                document.querySelector('.controls').classList.remove("disable--last");
            };
        };
        var disableFirst = function () {
            var isFirstDisabled = document.querySelector('.disable--first');
            if (!isFirstDisabled){
                document.querySelector('.controls').classList.add("disable--first");
            };
        };
        var enableFirst = function () {
            var isFirstDisabled = document.querySelector('.disable--first');
            if (isFirstDisabled){
                document.querySelector('.controls').classList.remove("disable--first");
            };
        };
        var preCalcRandom = function () {
            var rndNum = r;
            while (rndNum == r){
                rndNum = Math.floor(Math.random() * e);
            }
            return rndNum;
        }
        var preload = function() {
            nextComic = r + 1;
            if (nextComic > e) {nextComic = e};
            previousComic = r - 1;
            if (previousComic < 0) {previousComic = 0};
            preloadFirst.src = t + strips[0], preloadPrevious.src = t + strips[previousComic], preloadRandom.src = t + strips[randomComic], preloadRandom.setAttribute("data-file", strips[randomComic]), preloadNext.src = t + strips[nextComic], preloadLast.src = t + strips[e];
        }
        if (r != e){s()};
        var randomComic = preCalcRandom();
        preload();
        window.addEventListener('popstate', function(){
            var currentComic = r;
            var currentURL = location.pathname;
            if (currentURL.slice(1) == '') {
                r = e;
            } else {
                r = strips.indexOf(currentURL.slice(1) + '.png');

            }
            if (r == currentComic) {
                return;
            };

            o.src = t + n[r];
            if (r === e){disableLast()} else {enableLast()};
            if (r === 0){disableFirst()} else {enableFirst()};
        });
    }();
<commit_msg>Replace t variable by folder.<commit_after>
var translation = {
    first: "|< First",
    previous: "< Previous",
    random: "Random",
    next: "Next >",
    last: "Latest >|"
};

var folder = "assets/";

var strips = [
    "slogan.png",
    "bd-en-ligne.png",
    "l-austerite.png",
    "la-pub.png",
    "du-boulot.png",
    "charlie.png",
    "un-cafe.png",
    "fiat-luxe.png",
    "c-ta-crere.png",
    "time-out.png",
    "je-like-pas.png",
    "de-pis-en-pis.png",
    "toune.png",
    "le-futur-ete.png",
    "c-est_pas_gai.png",
    "le-truc.png",
    "fin-de-partie.png",
    "don-de-soi.png",
    "festival.png",
    "infortunes-du-rire.png",
    "cuisses.png",
    "sante.png",
    "automobilistes.png",
    "but-d-jouet.png",
    "qui-rira-le-dernier.png",
    "cadeau.png",
    "universel.png",
    "exil.png",
    "mise-a-jour.png",
    "presentations.png",
    "pornophiles.png",
    "faux-departs.png",
    "zero-probleme.png",
    "tribut.png",
    "chocolat.png",
    "la-joke.png"
];

var prevBtn = document.querySelectorAll(".prev"),
    nextBtn = document.querySelectorAll(".next"),
    firstBtn = document.querySelectorAll(".first"),
    lastBtn = document.querySelectorAll(".last"),
    randomBtn = document.querySelectorAll(".random"),
    preloadFirst = document.querySelector(".preload__first"),
    preloadPrevious = document.querySelector(".preload__previous"),
    preloadRandom = document.querySelector(".preload__random"),
    preloadNext = document.querySelector(".preload__next"),
    preloadLast = document.querySelector(".preload__last");
    prevBtn[0].innerHTML = translation.previous, nextBtn[0].innerHTML = translation.next, firstBtn[0].innerHTML = translation.first, lastBtn[0].innerHTML = translation.last, randomBtn[0].innerHTML = translation.random,
    function() {
        var initialURL = location.pathname;
        var e = strips.length - 1,
            r = strips.indexOf(initialURL.slice(1) + '.png'),
            o = document.querySelector("#comic"),
            l = function(strips, folder) {
                for (var e = strips.length; e > 0;) e--, strips[e].addEventListener("click", folder)
            },
            i = function() {
                r -= 1, 0 > r && (r = 0), s()
            },
            a = function() {
                r += 1, r > e && (r = e), s()
            },
            u = function() {
                r = 0, s()
            },
            c = function() {
                r = e, s()
            },
            p = function() {
                r = strips.indexOf(preloadRandom.getAttribute("data-file")), randomComic = preCalcRandom(), s();

            };
            if (r < 0) {r = e};
        l(prevBtn, i), l(nextBtn, a), l(firstBtn, u), l(lastBtn, c), l(randomBtn, p);
        var s = function() {
            o.src = folder + strips[r];
            currentURL = strips[r].slice(0, -4);
            preload();
            history.pushState(null, null, currentURL);
            // Disable first/last and next/previous if last/first comic
            if (r === e){disableLast()} else {enableLast()};
            if (r === 0){disableFirst()} else {enableFirst()};
        }
        var disableLast = function () {
            var isLastDisabled = document.querySelector('.disable--last');
            if (!isLastDisabled){
                document.querySelector('.controls').classList.add("disable--last");
            };
        };
        var enableLast = function () {
            var isLastDisabled = document.querySelector('.disable--last');
            if (isLastDisabled){
                document.querySelector('.controls').classList.remove("disable--last");
            };
        };
        var disableFirst = function () {
            var isFirstDisabled = document.querySelector('.disable--first');
            if (!isFirstDisabled){
                document.querySelector('.controls').classList.add("disable--first");
            };
        };
        var enableFirst = function () {
            var isFirstDisabled = document.querySelector('.disable--first');
            if (isFirstDisabled){
                document.querySelector('.controls').classList.remove("disable--first");
            };
        };
        var preCalcRandom = function () {
            var rndNum = r;
            while (rndNum == r){
                rndNum = Math.floor(Math.random() * e);
            }
            return rndNum;
        }
        var preload = function() {
            nextComic = r + 1;
            if (nextComic > e) {nextComic = e};
            previousComic = r - 1;
            if (previousComic < 0) {previousComic = 0};
            preloadFirst.src = folder + strips[0], preloadPrevious.src = folder + strips[previousComic], preloadRandom.src = folder + strips[randomComic], preloadRandom.setAttribute("data-file", strips[randomComic]), preloadNext.src = folder + strips[nextComic], preloadLast.src = folder + strips[e];
        }
        if (r != e){s()};
        var randomComic = preCalcRandom();
        preload();
        window.addEventListener('popstate', function(){
            var currentComic = r;
            var currentURL = location.pathname;
            if (currentURL.slice(1) == '') {
                r = e;
            } else {
                r = strips.indexOf(currentURL.slice(1) + '.png');

            }
            if (r == currentComic) {
                return;
            };

            o.src = t + n[r];
            if (r === e){disableLast()} else {enableLast()};
            if (r === 0){disableFirst()} else {enableFirst()};
        });
    }();
<|endoftext|>


<commit_before>const nbt = require('prismarine-nbt')
const { performance } = require('perf_hooks')
const { createDoneTask, createTask } = require('../promise_utils')
const BlockFaces = require('prismarine-world').iterators.BlockFace
const { Vec3 } = require('vec3')

module.exports = inject

function inject (bot) {
  let swingInterval = null
  let waitTimeout = null

  let diggingTask = createDoneTask()

  bot.targetDigBlock = null
  bot.lastDigTime = null

  async function dig (block, forceLook, digFace) {
    if (block === null || block === undefined) {
      throw new Error('dig was called with an undefined or null block')
    }
    if (!digFace || typeof digFace === 'function') {
      digFace = 'auto'
    }

    if (bot.targetDigBlock) bot.stopDigging()

    let diggingFace = 1 // Default (top)

    if (forceLook !== 'ignore') {
      if (digFace?.x || digFace?.y || digFace?.z) {
        // Determine the block face the bot should mine
        if (digFace.x) {
          diggingFace = digFace.x > 0 ? BlockFaces.EAST : BlockFaces.WEST
        } else if (digFace.y) {
          diggingFace = digFace.y > 0 ? BlockFaces.TOP : BlockFaces.BOTTOM
        } else if (digFace.z) {
          diggingFace = digFace.z > 0 ? BlockFaces.SOUTH : BlockFaces.NORTH
        }
        await bot.lookAt(block.position.offset(0.5, 0.5, 0.5).offset(digFace.x * 0.5, digFace.y * 0.5, digFace.z * 0.5), forceLook)
      } else if (digFace === 'raycast') {
        // Check faces that could be seen from the current position. If the delta is smaller then 0.5 that means the
        // bot cam most likely not see the face as the block is 1 block thick
        // this could be false for blocks that have a smaller bounding box then 1x1x1
        const dx = bot.entity.position.x - block.position.x + 0.5
        const dy = bot.entity.position.y - block.position.y - 0.5 + bot.entity.height // -0.5 because the bot position
        // is calculated from the block position that is inside its feet so 0.5 - 1 = -0.5
        const dz = bot.entity.position.z - block.position.z + 0.5
        // Check y first then x and z
        const visibleFaces = {
          y: Math.sign(Math.abs(dy) > 0.5 ? dy : 0),
          x: Math.sign(Math.abs(dx) > 0.5 ? dx : 0),
          z: Math.sign(Math.abs(dz) > 0.5 ? dz : 0)
        }
        const validFaces = []
        for (const i in visibleFaces) {
          if (!visibleFaces[i]) continue // skip as this face is not visible
          // target position on the target block face. -> 0.5 + (current face) * 0.5
          const targetPos = block.position.offset(0.5 + (i === 'x' ? visibleFaces[i] * 0.5 : 0), 0.5 + (i === 'y' ? visibleFaces[i] * 0.5 : 0), 0.5 + (i === 'z' ? visibleFaces[i] * 0.5 : 0))
          const startPos = bot.entity.position.offset(0, bot.entity.height, 0)
          const rayBlock = bot.world.raycast(startPos, targetPos.clone().subtract(startPos).normalize(), 5)
          if (rayBlock) {
            const rayPos = rayBlock.position
            if (rayPos.x === block.position.x && rayPos.y === block.position.y && rayPos.z === block.position.z) {
              // console.info(rayBlock)
              validFaces.push({
                face: rayBlock.face,
                targetPos: rayBlock.intersect
              })
            }
          }
        }
        if (validFaces.length > 0) {
          // Chose closest valid face
          let closest
          let distSqrt = 999
          for (const i in validFaces) {
            const tPos = validFaces[i].targetPos
            const cDist = new Vec3(tPos.x, tPos.y, tPos.z).distanceSquared(bot.entity.position.offset(0, bot.entity.height, 0))
            if (distSqrt > cDist) {
              closest = validFaces[i]
              distSqrt = cDist
            }
          }
          await bot.lookAt(closest.targetPos, forceLook)
          diggingFace = closest.face
        } else {
          // Block is obstructed return error?
          throw new Error('Block not in view')
        }
      } else {
        await bot.lookAt(block.position.offset(0.5, 0.5, 0.5), forceLook)
      }
    }

    diggingTask = createTask()
    bot._client.write('block_dig', {
      status: 0, // start digging
      location: block.position,
      face: diggingFace // default face is 1 (top)
    })
    const waitTime = bot.digTime(block)
    waitTimeout = setTimeout(finishDigging, waitTime)
    bot.targetDigBlock = block
    bot.swingArm()

    swingInterval = setInterval(() => {
      bot.swingArm()
    }, 350)

    function finishDigging () {
      clearInterval(swingInterval)
      clearTimeout(waitTimeout)
      swingInterval = null
      waitTimeout = null
      if (bot.targetDigBlock) {
        bot._client.write('block_dig', {
          status: 2, // finish digging
          location: bot.targetDigBlock.position,
          face: diggingFace // hard coded to always dig from the top
        })
      }
      bot.targetDigBlock = null
      bot.lastDigTime = performance.now()
      bot._updateBlockState(block.position, 0)
    }

    const eventName = `blockUpdate:${block.position}`
    bot.on(eventName, onBlockUpdate)

    bot.stopDigging = () => {
      if (!bot.targetDigBlock) return
      bot.removeListener(eventName, onBlockUpdate)
      clearInterval(swingInterval)
      clearTimeout(waitTimeout)
      swingInterval = null
      waitTimeout = null
      bot._client.write('block_dig', {
        status: 1, // cancel digging
        location: bot.targetDigBlock.position,
        face: 1 // hard coded to always dig from the top
      })
      const block = bot.targetDigBlock
      bot.targetDigBlock = null
      bot.lastDigTime = performance.now()
      bot.emit('diggingAborted', block)
      bot.stopDigging = noop
      diggingTask.cancel(new Error('Digging aborted'))
    }

    function onBlockUpdate (oldBlock, newBlock) {
      // vanilla server never actually interrupt digging, but some server send block update when you start digging
      // so ignore block update if not air
      if (newBlock.type !== 0) return
      bot.removeListener(eventName, onBlockUpdate)
      clearInterval(swingInterval)
      clearTimeout(waitTimeout)
      swingInterval = null
      waitTimeout = null
      bot.targetDigBlock = null
      bot.lastDigTime = performance.now()
      bot.emit('diggingCompleted', newBlock)
      diggingTask.finish()
    }

    await diggingTask.promise
  }

  function canDigBlock (block) {
    return block && block.diggable && block.position.offset(0.5, 0.5, 0.5).distanceTo(bot.entity.position.offset(0, 1.65, 0)) <= 5.1
  }

  function digTime (block) {
    let type = null
    let enchantments = []
    if (bot.heldItem) {
      type = bot.heldItem.type
      if (bot.heldItem.nbt) {
        enchantments = nbt.simplify(bot.heldItem.nbt).Enchantments || nbt.simplify(bot.heldItem.nbt).ench
      }
    }
    const creative = bot.game.gameMode === 'creative'
    return block.digTime(type, creative, bot.entity.isInWater, !bot.entity.onGround, enchantments, bot.entity.effects)
  }

  bot.dig = callbackify(dig)
  bot.stopDigging = noop
  bot.canDigBlock = canDigBlock
  bot.digTime = digTime
}

function callbackify (f) { // specifically for this function because cb could be the non-last parameter
  return function (...args) {
    const cbIndex = typeof args[1] === 'function' ? 1 : (typeof args[2] === 'function' ? 2 : 3)
    const cb = args[cbIndex]

    if (cbIndex === 1) args[1] = true
    else if (typeof args[1] === 'string') args[1] = args[1] === 'ignore' ? args[1] : false
    else args[1] = !!args[1] // coerce to boolean

    return f(...args).then(r => { if (cb) { cb(undefined, r) } return r }, err => { if (cb) { cb(err) } else throw err })
  }
}

function noop (err) {
  if (err) throw err
}
<commit_msg>Prevents exceeding Max Listeners when bot dies simultaneously digging (#1850)<commit_after>const nbt = require('prismarine-nbt')
const { performance } = require('perf_hooks')
const { createDoneTask, createTask } = require('../promise_utils')
const BlockFaces = require('prismarine-world').iterators.BlockFace
const { Vec3 } = require('vec3')

module.exports = inject

function inject (bot) {
  let swingInterval = null
  let waitTimeout = null

  let diggingTask = createDoneTask()

  bot.targetDigBlock = null
  bot.lastDigTime = null

  async function dig (block, forceLook, digFace) {
    if (block === null || block === undefined) {
      throw new Error('dig was called with an undefined or null block')
    }
    if (!digFace || typeof digFace === 'function') {
      digFace = 'auto'
    }

    if (bot.targetDigBlock) bot.stopDigging()

    let diggingFace = 1 // Default (top)

    if (forceLook !== 'ignore') {
      if (digFace?.x || digFace?.y || digFace?.z) {
        // Determine the block face the bot should mine
        if (digFace.x) {
          diggingFace = digFace.x > 0 ? BlockFaces.EAST : BlockFaces.WEST
        } else if (digFace.y) {
          diggingFace = digFace.y > 0 ? BlockFaces.TOP : BlockFaces.BOTTOM
        } else if (digFace.z) {
          diggingFace = digFace.z > 0 ? BlockFaces.SOUTH : BlockFaces.NORTH
        }
        await bot.lookAt(block.position.offset(0.5, 0.5, 0.5).offset(digFace.x * 0.5, digFace.y * 0.5, digFace.z * 0.5), forceLook)
      } else if (digFace === 'raycast') {
        // Check faces that could be seen from the current position. If the delta is smaller then 0.5 that means the
        // bot cam most likely not see the face as the block is 1 block thick
        // this could be false for blocks that have a smaller bounding box then 1x1x1
        const dx = bot.entity.position.x - block.position.x + 0.5
        const dy = bot.entity.position.y - block.position.y - 0.5 + bot.entity.height // -0.5 because the bot position
        // is calculated from the block position that is inside its feet so 0.5 - 1 = -0.5
        const dz = bot.entity.position.z - block.position.z + 0.5
        // Check y first then x and z
        const visibleFaces = {
          y: Math.sign(Math.abs(dy) > 0.5 ? dy : 0),
          x: Math.sign(Math.abs(dx) > 0.5 ? dx : 0),
          z: Math.sign(Math.abs(dz) > 0.5 ? dz : 0)
        }
        const validFaces = []
        for (const i in visibleFaces) {
          if (!visibleFaces[i]) continue // skip as this face is not visible
          // target position on the target block face. -> 0.5 + (current face) * 0.5
          const targetPos = block.position.offset(0.5 + (i === 'x' ? visibleFaces[i] * 0.5 : 0), 0.5 + (i === 'y' ? visibleFaces[i] * 0.5 : 0), 0.5 + (i === 'z' ? visibleFaces[i] * 0.5 : 0))
          const startPos = bot.entity.position.offset(0, bot.entity.height, 0)
          const rayBlock = bot.world.raycast(startPos, targetPos.clone().subtract(startPos).normalize(), 5)
          if (rayBlock) {
            const rayPos = rayBlock.position
            if (rayPos.x === block.position.x && rayPos.y === block.position.y && rayPos.z === block.position.z) {
              // console.info(rayBlock)
              validFaces.push({
                face: rayBlock.face,
                targetPos: rayBlock.intersect
              })
            }
          }
        }
        if (validFaces.length > 0) {
          // Chose closest valid face
          let closest
          let distSqrt = 999
          for (const i in validFaces) {
            const tPos = validFaces[i].targetPos
            const cDist = new Vec3(tPos.x, tPos.y, tPos.z).distanceSquared(bot.entity.position.offset(0, bot.entity.height, 0))
            if (distSqrt > cDist) {
              closest = validFaces[i]
              distSqrt = cDist
            }
          }
          await bot.lookAt(closest.targetPos, forceLook)
          diggingFace = closest.face
        } else {
          // Block is obstructed return error?
          throw new Error('Block not in view')
        }
      } else {
        await bot.lookAt(block.position.offset(0.5, 0.5, 0.5), forceLook)
      }
    }

    diggingTask = createTask()
    bot._client.write('block_dig', {
      status: 0, // start digging
      location: block.position,
      face: diggingFace // default face is 1 (top)
    })
    const waitTime = bot.digTime(block)
    waitTimeout = setTimeout(finishDigging, waitTime)
    bot.targetDigBlock = block
    bot.swingArm()

    swingInterval = setInterval(() => {
      bot.swingArm()
    }, 350)

    function finishDigging () {
      clearInterval(swingInterval)
      clearTimeout(waitTimeout)
      swingInterval = null
      waitTimeout = null
      if (bot.targetDigBlock) {
        bot._client.write('block_dig', {
          status: 2, // finish digging
          location: bot.targetDigBlock.position,
          face: diggingFace // hard coded to always dig from the top
        })
      }
      bot.targetDigBlock = null
      bot.lastDigTime = performance.now()
      bot._updateBlockState(block.position, 0)
    }

    const eventName = `blockUpdate:${block.position}`
    bot.on(eventName, onBlockUpdate)

    bot.stopDigging = () => {
      if (!bot.targetDigBlock) return
      bot.removeListener(eventName, onBlockUpdate)
      clearInterval(swingInterval)
      clearTimeout(waitTimeout)
      swingInterval = null
      waitTimeout = null
      bot._client.write('block_dig', {
        status: 1, // cancel digging
        location: bot.targetDigBlock.position,
        face: 1 // hard coded to always dig from the top
      })
      const block = bot.targetDigBlock
      bot.targetDigBlock = null
      bot.lastDigTime = performance.now()
      bot.emit('diggingAborted', block)
      bot.stopDigging = noop
      diggingTask.cancel(new Error('Digging aborted'))
    }

    function onBlockUpdate (oldBlock, newBlock) {
      // vanilla server never actually interrupt digging, but some server send block update when you start digging
      // so ignore block update if not air
      if (newBlock.type !== 0) return
      bot.removeListener(eventName, onBlockUpdate)
      clearInterval(swingInterval)
      clearTimeout(waitTimeout)
      swingInterval = null
      waitTimeout = null
      bot.targetDigBlock = null
      bot.lastDigTime = performance.now()
      bot.emit('diggingCompleted', newBlock)
      diggingTask.finish()
    }

    await diggingTask.promise
  }

  bot.on('death', () => {
    bot.removeAllListeners('diggingAborted')
    bot.removeAllListeners('diggingCompleted')
    bot.stopDigging()
  })

  function canDigBlock (block) {
    return block && block.diggable && block.position.offset(0.5, 0.5, 0.5).distanceTo(bot.entity.position.offset(0, 1.65, 0)) <= 5.1
  }

  function digTime (block) {
    let type = null
    let enchantments = []
    if (bot.heldItem) {
      type = bot.heldItem.type
      if (bot.heldItem.nbt) {
        enchantments = nbt.simplify(bot.heldItem.nbt).Enchantments || nbt.simplify(bot.heldItem.nbt).ench
      }
    }
    const creative = bot.game.gameMode === 'creative'
    return block.digTime(type, creative, bot.entity.isInWater, !bot.entity.onGround, enchantments, bot.entity.effects)
  }

  bot.dig = callbackify(dig)
  bot.stopDigging = noop
  bot.canDigBlock = canDigBlock
  bot.digTime = digTime
}

function callbackify (f) { // specifically for this function because cb could be the non-last parameter
  return function (...args) {
    const cbIndex = typeof args[1] === 'function' ? 1 : (typeof args[2] === 'function' ? 2 : 3)
    const cb = args[cbIndex]

    if (cbIndex === 1) args[1] = true
    else if (typeof args[1] === 'string') args[1] = args[1] === 'ignore' ? args[1] : false
    else args[1] = !!args[1] // coerce to boolean

    return f(...args).then(r => { if (cb) { cb(undefined, r) } return r }, err => { if (cb) { cb(err) } else throw err })
  }
}

function noop (err) {
  if (err) throw err
}
<|endoftext|>


<commit_before>
// This module exports a factory for creating leaflet geoJSON layer from MBTA geoJSON.
function geoJsonLayer(json) {
  var layer = L.geoJson(json, {
    style: function(feature) {
      return {
        color: feature.properties['COLOR']
      }
    }
  });

  return layer;
}<commit_msg>Show neighborhood name on hover<commit_after>
// This module exports a factory for creating leaflet geoJSON layer from MBTA geoJSON.
function geoJsonLayer(json) {
  var layer = L.geoJson(json, {
    style: function(feature) {
      return {
        color: feature.properties['COLOR']
      }
    },
    onEachFeature: function (feature, layer) {
        layer.on('mouseover', function(){
        	$("#nhood").html(feature.properties.Name)
        })
        layer.on('mouseout', function(){
        	$("#nhood").html("")
        })
    }
  });

  return layer;
}<|endoftext|>


<commit_before>/*
hud.js
------
    This file contains the code for controlling the player
    health HUD. The technique used is "injection", which is
    an extension of the original code. The way it works is
    by creating a new instance of original code and supply it
    with a new name. Simply put, injection is a copy of the
    original but different in the sense of the extra code we
    add. While injecting, we modify the original code. In
    the case of this plugin, we overwrite the draw() function
    of our game. The this.parent() function will point to our
    old draw() function, so everything there is kept. All we
    check for in the new isntance is the presence of a player
    entity, and if true then a HUD is drawn.

    The health HUD consists of two parts: A number and Health bar.

    Number: A function which handles drawing a black, slightly transparent
    rectangle where the health will be visible. Uses the following
    canvas properties to draw the HUD to screen:
        | fillstyle: This property sets the color
        | font: This property sets the font
        | setAlpha(): This property sets the transparency.
            | setalpha = 1: Fully Solid
            | setAlpha = 0: Fully transparent
        | fillRect(): This property draws a rectangle to the screen
          given a given position with a given width + height
        | fillText(): This property draws text on screen at a given positon.

    Bar: A function which draws two rectangles on top of each other. Uses
    the same canvas properties above to draw.

*/

ig.module(
    'plugins.hud.hud'
)
.defines(function() {
    ig.hud = ig.Class.extend({
        // Get the canvas
        canvas  : document.getElementById('canvas'),
        // Check if the canvas is being viewed
        context : canvas.getContext('2d'),

        init: function() {
            ig.Game.inject({
                draw: function() {
                    this.parent();
                    // If there is a player. draw the HUD
                    if(ig.game.getEntitiesByType('EntityPlayer').length  != 0) {
                        if(this.hud && !ig.game.menuVisible) {
                            ig.game.barHud.draw(0, 155);
                            this.hud.number_health();
                            this.hud.bar_health();
                            this.hud.number_mana();
                            this.hud.bar_mana();
                            // this.hud.number_stamina();
                            // this.hud.bar_stamina();
                            // this.hud.number_level();
                            // this.hud.bar_exp();
                        }
                    }
                }
            })
        },

        // ----- Health Meter -----
        number_health: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            if(player.attacking && !this.menuVisible){
                ig.game.attackingAnimation.draw(20, 185);
            }
            else if(!player.attacking && !this.menuVisible){
                ig.game.okayAnimation.draw(20, 185);
            }
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            //context.fillRect (10, 10, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            // (11, 21): x, y position to draw to screen
            context.fillText ('HP: ' + player.health + '/' + player.stats.maxHP, 135, 390); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_health: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.health / player.stats.maxHP, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            //context.fillRect (90, 10, 100, 13);
            // Determine what color of health to draw, Bright red for full, dim red otherwise
            var color = h < 100 ? "rgb(175, 0, 0)" : "rgb(225, 0, 0)";
            //var color = "rgb(200, 0, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;

            // (x, y, .., ..)
            context.fillRect (115, 390, h-6, 8);
            context.setAlpha = 1;
            return null;
        },

        // ----- Mana Meter -----
        number_mana: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            //context.fillRect (10, 25, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('MP: ' + player.tp + '/' + player.stats.maxTP, 135, 430); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_mana: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.tp / player.stats.maxTP, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            //context.fillRect (90, 25, 100, 13);
            // Determine what color of mana to draw, Bright blue for full, dim blue otherwise
            var color = h < 100 ? "rgb(0, 0, 175)" : "rgb(0, 0, 225)";
            //var color = "rgb(0, 0, 200)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (115, 430, h-6, 8);
            context.setAlpha = 1;
            return null;
        },

        // ----- Stamina Meter -----
        number_stamina: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            context.fillRect (10, 40, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('SP: ' + player.stamina + '/' + player.max_stamina, 11, 51); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_stamina: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.stamina / player.max_stamina, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            context.fillRect (90, 40, 100, 13);
            // Determine what color of stamina to draw, Bright green for full, dim green otherwise
            var color = h < 100 ? "rgb(0, 175, 0)" : "rgb(0, 225, 0)";
            //var color = "rgb(0, 200, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (91, 41, h-2, 11);
            context.setAlpha = 1;
            return null;
        },

        // ----- Level/Experience Meter -----
        number_level: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            context.fillRect (10, 55, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('Level: ' + ig.game.LEVEL, 11, 66); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_exp: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(ig.game.EXP.curr / ig.game.EXP.next, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            context.fillRect (90, 55, 100, 13);
            var color = "rgb(200, 200, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (91, 56, h-2, 11);
            context.setAlpha = 1;
            return null;
        },
    });
})
<commit_msg>Adding level up bar<commit_after>/*
hud.js
------
    This file contains the code for controlling the player
    health HUD. The technique used is "injection", which is
    an extension of the original code. The way it works is
    by creating a new instance of original code and supply it
    with a new name. Simply put, injection is a copy of the
    original but different in the sense of the extra code we
    add. While injecting, we modify the original code. In
    the case of this plugin, we overwrite the draw() function
    of our game. The this.parent() function will point to our
    old draw() function, so everything there is kept. All we
    check for in the new isntance is the presence of a player
    entity, and if true then a HUD is drawn.

    The health HUD consists of two parts: A number and Health bar.

    Number: A function which handles drawing a black, slightly transparent
    rectangle where the health will be visible. Uses the following
    canvas properties to draw the HUD to screen:
        | fillstyle: This property sets the color
        | font: This property sets the font
        | setAlpha(): This property sets the transparency.
            | setalpha = 1: Fully Solid
            | setAlpha = 0: Fully transparent
        | fillRect(): This property draws a rectangle to the screen
          given a given position with a given width + height
        | fillText(): This property draws text on screen at a given positon.

    Bar: A function which draws two rectangles on top of each other. Uses
    the same canvas properties above to draw.

*/

ig.module(
    'plugins.hud.hud'
)
.defines(function() {
    ig.hud = ig.Class.extend({
        // Get the canvas
        canvas  : document.getElementById('canvas'),
        // Check if the canvas is being viewed
        context : canvas.getContext('2d'),

        init: function() {
            ig.Game.inject({
                draw: function() {
                    this.parent();
                    // If there is a player. draw the HUD
                    if(ig.game.getEntitiesByType('EntityPlayer').length  != 0) {
                        if(this.hud && !ig.game.menuVisible) {
                            ig.game.barHud.draw(0, 155);
                            this.hud.number_health();
                            this.hud.bar_health();
                            this.hud.number_mana();
                            this.hud.bar_mana();
                            this.hud.number_level();
                            this.hud.bar_exp();
                        }
                    }
                }
            })
        },

        // ----- Health Meter -----
        number_health: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            if(player.attacking && !this.menuVisible){
                ig.game.attackingAnimation.draw(20, 185);
            }
            else if(!player.attacking && !this.menuVisible){
                ig.game.okayAnimation.draw(20, 185);
            }
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            //context.fillRect (10, 10, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            // (11, 21): x, y position to draw to screen
            context.fillText ('HP: ' + player.health + '/' + player.stats.maxHP, 135, 390); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_health: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.health / player.stats.maxHP, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            //context.fillRect (90, 10, 100, 13);
            // Determine what color of health to draw, Bright red for full, dim red otherwise
            var color = h < 100 ? "rgb(175, 0, 0)" : "rgb(225, 0, 0)";
            //var color = "rgb(200, 0, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;

            // (x, y, .., ..)
            context.fillRect (115, 390, h-6, 8);
            context.setAlpha = 1;
            return null;
        },

        // ----- Mana Meter -----
        number_mana: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            //context.fillRect (10, 25, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('MP: ' + player.tp + '/' + player.stats.maxTP, 135, 415); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_mana: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.tp / player.stats.maxTP, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            //context.fillRect (90, 25, 100, 13);
            // Determine what color of mana to draw, Bright blue for full, dim blue otherwise
            var color = h < 100 ? "rgb(0, 0, 175)" : "rgb(0, 0, 225)";
            //var color = "rgb(0, 0, 200)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (115, 415, h-6, 8);
            context.setAlpha = 1;
            return null;
        },

        // ----- Level/Experience Meter -----
        number_level: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('Level: ' + player.stats.level, 135, 440); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_exp: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(ig.game.levelsCatalog[player.stats.level].expTotal / ig.game.levelsCatalog[player.stats.level].expToNext, ig.game.levelsCatalog[player.stats.level].expToNext);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            var color = "rgb(200, 200, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (115, 440, h-2, 11);
            context.setAlpha = 1;
            return null;
        },
    });
})
<|endoftext|>