<commit_before>/*
 * Copyright 2013 Thomas Dy, Philip Cheang under the terms of the
 * MIT license found at http://sakay.ph/LICENSE
 */
var map = L.map('map');
map.addLayer(new L.Google('ROADMAP'));

otp.metadata.then(function(data) {
  map.setView([data.centerLatitude, data.centerLongitude], 12);
});

var progress = new Ractive({
  el: '#progress',
  template: '#progressWidgetTemplate'
})
progress.setLoading = function(loading) {
  this.set('loading', loading);
}

var search = new Ractive({
  el: '#search',
  template: '#searchTemplate',
  data: {
    targets: {
      mode: 'TRANSIT,WALK'
    }
  }
});
search.layer = L.layerGroup([]).addTo(map);

search.addInput = function(id, target) {
  var input = document.getElementById(id);
  var searchBox = new google.maps.places.SearchBox(input);

  google.maps.event.addListener(searchBox, 'places_changed', function() {
    search.layer.clearLayers();
    var places = searchBox.getPlaces();
    if(places.length > 0) {
      var place = places[0];
      var latlng = g2lLatLng(place.geometry.location);
      var marker = L.marker(latlng);
      var popup = new Popup(marker);
      marker.addTo(search.layer);
      setTimeout(function() {
        map.setView(latlng, 14);
      }, 0);
      search.setTarget(target, latlng, true);
    }
    viewMode("map");
  });

  // sorry thomas, I'll clean this up

  search.on('go', function() {
    search.layer.clearLayers();
    var places = searchBox.getPlaces();
    if(places.length > 0) {
      var place = places[0];
      var latlng = g2lLatLng(place.geometry.location);
      var marker = L.marker(latlng);
      var popup = new Popup(marker);
      marker.addTo(search.layer);
      setTimeout(function() {
        map.setView(latlng, 14);
      }, 0);
      search.setTarget(target, latlng, true);
    }
    viewMode("map")
  });

  map.on('moveend', function() {
    var bounds = l2gBounds(map.getBounds());
    searchBox.setBounds(bounds);
  });
}

search.setTarget = function(name, latlng, address) {
  var a = name;
  var b = "to";
  if(a == "to") {
    b = "from";
  }

  var targets = search.get('targets');

  var marker;
  if(targets[a]) {
    marker = targets[a];
    marker.setLatLng(latlng);
    marker.unbindPopup();
  }
  else {
    marker = L.marker(latlng);
  }

  var popup = new Popup(marker);

  if(!targets[a]) {
    marker.addTo(map);
    targets[a] = marker;
  }

  if(!address) {
    geocoder.fromLatLng(latlng).then(function(data) {
      var address = data[0].formatted_address;
      document.getElementById(a).value = address;
    });
  }

  if(targets[b]) {
    if(targets[b].getLatLng() == latlng) { // handle setting start as destination
      map.removeLayer(targets[b]);
      targets[b] = null;
    }
  }
  search.update('targets');
  map.closePopup();
}

search.observe('targets', function(targets) {
  if(!targets.from || !targets.to) return;
  var self = this;
  progress.setLoading(true);

  if(sakay.canLog()) {
    var fromName = document.getElementById('from').value;
    var toName = document.getElementById('to').value;

    sakay.log(fromName, targets.from.getLatLng(), toName, targets.to.getLatLng());
  }

  otp.route(
    targets.from.getLatLng(),
    targets.to.getLatLng(),
    targets.mode
  )
  .then(function(data) {
    router.reset();
    if(data.plan) {
      var results = data.plan.itineraries;
      results.forEach(function(itinerary) {
        itinerary.legs = itinerary.legs.filter(function(leg) {
          // because these really aren't that worth it to display
          return leg.duration > 60000;
        }).filter(function(leg) {
          // because OTP sometimes gives bus routes that are non-sensical
          return leg.mode == "WALK" || leg.distance >= 500;
        });

        var incomplete = false;
        itinerary.fare = 0;
        itinerary.legs.forEach(function(leg) {
          leg.points = decodePoints(leg.legGeometry.points);
          if(leg.mode == 'BUS' && leg.routeId.indexOf('PUJ') >= 0) {
            leg.mode = 'JEEP';
          }
          leg.className = leg.mode.toLowerCase();

          if(leg.mode == 'RAIL') {
            leg.route = leg.route.replace("-", " ");
            leg.className = "rail "+leg.route.replace(" ", "").toLowerCase();
          }

          if(leg.routeId == "ROUTE_880872") {
            incomplete = true;
          }

          leg.fare = calculateFare(leg);
          if(leg.fare) {
            itinerary.fare += leg.fare;
            leg.fare = formatFare(leg.fare);
          }
        });

        if(itinerary.fare == 0) {
          itinerary.fare = undefined;
        }
        else {
          itinerary.fare = formatFare(itinerary.fare, incomplete);
        }
      });
      router.set('results', results);
      router.set('selected', -1);
      router.set('selected', 0);
    }
    else {
      router.set('results', null);
      itinerary.set('current', null);
    }
  })
  .fin(function() {
    progress.setLoading(false);
  });
});

search.on({
  swap: function(event) {
    var targets = this.get('targets');
    var tmp = targets.from;
    targets.from = targets.to;
    targets.to = tmp;

    var fromInput = document.getElementById('from');
    var toInput = document.getElementById('to');
    tmp = fromInput.value;
    fromInput.value = toInput.value;
    toInput.value = tmp;
    this.update('targets');
  },
});

search.addInput('from', 'from');
search.addInput('to', 'to');

var TrackModal = (function() {
  var _class = Ractive.extend({
    template: '#trackWidgetTemplate',
    append: true,
    data: {
      disallowTracking: !sakay.canLog()
    },
    init: function() {
      var modalStyle = this.el.style;
      modalStyle.width = '500px';
      modalStyle.margin = "0 0 0 "+(-this.el.clientWidth / 2)+"px";
      this.observe('disallowTracking', function(val) {
        sakay.setCanLog(!val);
      });
    }
  });

  return function() {
    var modal = picoModal({
      content: document.getElementById('trackingInfo').innerHTML,
      modalStyles: {}
    });
    return new _class({
      el: modal.modalElem
    });
  }
})();

var SendModal = (function() {
  var _class = Ractive.extend({
    template: '#modalTemplate',
    init: function(options) {
      var self = this;
      var modalStyle = self.el.style;
      modalStyle.width = 'auto';
      modalStyle.margin = "0 0 0 "+(-self.el.clientWidth / 2)+"px";
      this.on({
        send: function() {
          this.set('sending', true);
          sakay.send(self.get('number'), itinerary.get('current')).then(function() {
            options.modal.close();
            picoModal({
              content: "Your message will be sent in a short while.",
            });
          });
        }
      });
    }
  });

  return function(itinerary) {
    var modal = picoModal({
      closeButton: false,
    });
    return new _class({
      el: modal.modalElem,
      modal: modal
    });
  }
})();

var Popup = (function() {
  var _class = Ractive.extend({
    template: '#popupTemplate',
    init: function() {
      var self = this;

      function setSomething(a, b) {
        return function(event) {
          var latlng = this.get('latlng');
          search.setTarget(a, latlng, false);
        }
      }

      this.on({
        setStart: setSomething('from', 'to'),
        setEnd: setSomething('to', 'from')
      });

      geocoder.fromLatLng(self.get('latlng')).then(function(data) {
        var address = data[0].formatted_address;
        self.set('address', address);
      });
    },
    open: function() {
      map.openPopup(this.el, this.get('latlng'));
    },
    bindTo: function(marker) {
      marker.bindPopup(this.el);
    }
  });
  return function(pos) {
    var latlng = pos;
    if(pos.constructor == L.Marker) {
      latlng = pos.getLatLng();
    }
    var popup = new _class({
      el: document.createElement('div'),
      data: {
        latlng: latlng
      }
    });
    if(pos.constructor == L.Marker) {
      popup.bindTo(pos);
    }
    return popup;
  }
})();

map.on('contextmenu', function(event) {
  var popup = new Popup(event.latlng);
  popup.open();
});

var printView = new Ractive({
  el: '#print',
  template: '#printTemplate',
  data: {
    show: false,
    f: formatDuration,
    formatDirection: function(dir) {
      if(dir == undefined) return '';
      return dir.toLowerCase().replace('_', ' ');
    },
    map: staticMaps
  }
});
printView.on('back', function() {
  printView.set('show', false);
});

var itinerary = new Ractive({
  el: '#itinerary',
  template: '#itineraryTemplate',
  debug: true,
  data: {
    f: formatDuration,
    formatDirection: function(dir) {
      if(dir == undefined) return '';
      return dir.toLowerCase().replace('_', ' ');
    },
    isTransit: function(mode) {
      return mode == 'JEEP' || mode == 'BUS' || mode == 'RAIL';
    },
  }
});
itinerary.markerLayer = L.layerGroup([]).addTo(map);
itinerary.observe('current', function(val, oldVal) {
  printView.set('current', val);
  if(val) {
    itinerary.markerLayer.clearLayers();
    val.legs.forEach(function(leg, index) {
      if(index == 0) return;
      leg.marker = L.marker([leg.from.lat, leg.from.lon]);
      leg.marker.setOpacity(0);
      itinerary.markerLayer.addLayer(leg.marker);
    });
  }
  if(oldVal) {
    oldVal.legs.forEach(function(leg, index) {
      leg.marker = undefined;
    });
  }
});

itinerary.on({
  sendSMS: function() {
    if(itinerary.get('current')) {
      new SendModal();
    }
    else {
      picoModal("Search for a route and we can send the directions to you via SMS.");
    }
  },
  print: function() {
    if(itinerary.get('current')) {
      printView.set('show', true);
    }
    else {
      picoModal("Search for a route first.");
    }
  },
  showSteps: function(event) {
    var path = event.keypath+'.showSteps';
    this.set(path, !this.get(path));
  },
  hover: function(event, index) {
    var leg = this.get('current').legs[index];
    if(event.hover) {
      if(leg.polyline == undefined) {
        leg.polyline = L.polyline(leg.points, {
          color: 'yellow',
          weight: 7
        });
      }
      leg.polyline.addTo(router.layer);
    }
    else {
      map.removeLayer(leg.polyline);
    }
  }
});

var router = new Ractive({
  el: '#routes',
  template: '#routerTemplate',
  debug: true,
  data: {
    f: formatDuration,
  }
});
router.layer = L.layerGroup([]).addTo(map);
router.reset = function() {
  this.layer.clearLayers();
  this.routeLine = L.multiPolyline([]).addTo(this.layer);
}
router.getPoints = function(index) {
  var results = this.get('results');
  var lines = [];
  results[index].legs.forEach(function(leg) {
    lines.push(leg.points);
  });
  return lines;
}
router.showRoute = function(index) {
  this.routeLine.setLatLngs(this.getPoints(index));
  this.unhighlightRoute(index);
  map.fitBounds(this.routeLine.getBounds(), { paddingTopLeft: [300, 10], paddingBottomRight: [10, 10] });
}
router.highlightRoute = function(index) {
  var route = this.get('results')[index];
  if(route.polyline == undefined) {
    route.polyline = L.multiPolyline(this.getPoints(index), {
      color: 'red'
    });
  }
  route.polyline.addTo(this.layer);
}
router.unhighlightRoute = function(index) {
  var polyline = this.get('results')[index].polyline;
  if(this.layer.hasLayer(polyline)) {
    this.layer.removeLayer(polyline);
  }
}

router.observe('selected', function(val) {
  if(val == undefined || val < 0) return;
  var results = this.get('results');
  itinerary.set('current', results[val]);
  this.showRoute(val);
});

router.on({
  select: function(event, index) {
    this.set('selected', index);
  },
  hover: function(event, index) {
    if(index != this.get('selected')) {
      if(event.hover) {
        this.highlightRoute(index);
      }
      else {
        this.unhighlightRoute(index);
      }
    }
  }
});

<commit_msg>Call the browser's print dialog<commit_after>/*
 * Copyright 2013 Thomas Dy, Philip Cheang under the terms of the
 * MIT license found at http://sakay.ph/LICENSE
 */
var map = L.map('map');
map.addLayer(new L.Google('ROADMAP'));

otp.metadata.then(function(data) {
  map.setView([data.centerLatitude, data.centerLongitude], 12);
});

var progress = new Ractive({
  el: '#progress',
  template: '#progressWidgetTemplate'
})
progress.setLoading = function(loading) {
  this.set('loading', loading);
}

var search = new Ractive({
  el: '#search',
  template: '#searchTemplate',
  data: {
    targets: {
      mode: 'TRANSIT,WALK'
    }
  }
});
search.layer = L.layerGroup([]).addTo(map);

search.addInput = function(id, target) {
  var input = document.getElementById(id);
  var searchBox = new google.maps.places.SearchBox(input);

  google.maps.event.addListener(searchBox, 'places_changed', function() {
    search.layer.clearLayers();
    var places = searchBox.getPlaces();
    if(places.length > 0) {
      var place = places[0];
      var latlng = g2lLatLng(place.geometry.location);
      var marker = L.marker(latlng);
      var popup = new Popup(marker);
      marker.addTo(search.layer);
      setTimeout(function() {
        map.setView(latlng, 14);
      }, 0);
      search.setTarget(target, latlng, true);
    }
    viewMode("map");
  });

  // sorry thomas, I'll clean this up

  search.on('go', function() {
    search.layer.clearLayers();
    var places = searchBox.getPlaces();
    if(places.length > 0) {
      var place = places[0];
      var latlng = g2lLatLng(place.geometry.location);
      var marker = L.marker(latlng);
      var popup = new Popup(marker);
      marker.addTo(search.layer);
      setTimeout(function() {
        map.setView(latlng, 14);
      }, 0);
      search.setTarget(target, latlng, true);
    }
    viewMode("map")
  });

  map.on('moveend', function() {
    var bounds = l2gBounds(map.getBounds());
    searchBox.setBounds(bounds);
  });
}

search.setTarget = function(name, latlng, address) {
  var a = name;
  var b = "to";
  if(a == "to") {
    b = "from";
  }

  var targets = search.get('targets');

  var marker;
  if(targets[a]) {
    marker = targets[a];
    marker.setLatLng(latlng);
    marker.unbindPopup();
  }
  else {
    marker = L.marker(latlng);
  }

  var popup = new Popup(marker);

  if(!targets[a]) {
    marker.addTo(map);
    targets[a] = marker;
  }

  if(!address) {
    geocoder.fromLatLng(latlng).then(function(data) {
      var address = data[0].formatted_address;
      document.getElementById(a).value = address;
    });
  }

  if(targets[b]) {
    if(targets[b].getLatLng() == latlng) { // handle setting start as destination
      map.removeLayer(targets[b]);
      targets[b] = null;
    }
  }
  search.update('targets');
  map.closePopup();
}

search.observe('targets', function(targets) {
  if(!targets.from || !targets.to) return;
  var self = this;
  progress.setLoading(true);

  if(sakay.canLog()) {
    var fromName = document.getElementById('from').value;
    var toName = document.getElementById('to').value;

    sakay.log(fromName, targets.from.getLatLng(), toName, targets.to.getLatLng());
  }

  otp.route(
    targets.from.getLatLng(),
    targets.to.getLatLng(),
    targets.mode
  )
  .then(function(data) {
    router.reset();
    if(data.plan) {
      var results = data.plan.itineraries;
      results.forEach(function(itinerary) {
        itinerary.legs = itinerary.legs.filter(function(leg) {
          // because these really aren't that worth it to display
          return leg.duration > 60000;
        }).filter(function(leg) {
          // because OTP sometimes gives bus routes that are non-sensical
          return leg.mode == "WALK" || leg.distance >= 500;
        });

        var incomplete = false;
        itinerary.fare = 0;
        itinerary.legs.forEach(function(leg) {
          leg.points = decodePoints(leg.legGeometry.points);
          if(leg.mode == 'BUS' && leg.routeId.indexOf('PUJ') >= 0) {
            leg.mode = 'JEEP';
          }
          leg.className = leg.mode.toLowerCase();

          if(leg.mode == 'RAIL') {
            leg.route = leg.route.replace("-", " ");
            leg.className = "rail "+leg.route.replace(" ", "").toLowerCase();
          }

          if(leg.routeId == "ROUTE_880872") {
            incomplete = true;
          }

          leg.fare = calculateFare(leg);
          if(leg.fare) {
            itinerary.fare += leg.fare;
            leg.fare = formatFare(leg.fare);
          }
        });

        if(itinerary.fare == 0) {
          itinerary.fare = undefined;
        }
        else {
          itinerary.fare = formatFare(itinerary.fare, incomplete);
        }
      });
      router.set('results', results);
      router.set('selected', -1);
      router.set('selected', 0);
    }
    else {
      router.set('results', null);
      itinerary.set('current', null);
    }
  })
  .fin(function() {
    progress.setLoading(false);
  });
});

search.on({
  swap: function(event) {
    var targets = this.get('targets');
    var tmp = targets.from;
    targets.from = targets.to;
    targets.to = tmp;

    var fromInput = document.getElementById('from');
    var toInput = document.getElementById('to');
    tmp = fromInput.value;
    fromInput.value = toInput.value;
    toInput.value = tmp;
    this.update('targets');
  },
});

search.addInput('from', 'from');
search.addInput('to', 'to');

var TrackModal = (function() {
  var _class = Ractive.extend({
    template: '#trackWidgetTemplate',
    append: true,
    data: {
      disallowTracking: !sakay.canLog()
    },
    init: function() {
      var modalStyle = this.el.style;
      modalStyle.width = '500px';
      modalStyle.margin = "0 0 0 "+(-this.el.clientWidth / 2)+"px";
      this.observe('disallowTracking', function(val) {
        sakay.setCanLog(!val);
      });
    }
  });

  return function() {
    var modal = picoModal({
      content: document.getElementById('trackingInfo').innerHTML,
      modalStyles: {}
    });
    return new _class({
      el: modal.modalElem
    });
  }
})();

var SendModal = (function() {
  var _class = Ractive.extend({
    template: '#modalTemplate',
    init: function(options) {
      var self = this;
      var modalStyle = self.el.style;
      modalStyle.width = 'auto';
      modalStyle.margin = "0 0 0 "+(-self.el.clientWidth / 2)+"px";
      this.on({
        send: function() {
          this.set('sending', true);
          sakay.send(self.get('number'), itinerary.get('current')).then(function() {
            options.modal.close();
            picoModal({
              content: "Your message will be sent in a short while.",
            });
          });
        }
      });
    }
  });

  return function(itinerary) {
    var modal = picoModal({
      closeButton: false,
    });
    return new _class({
      el: modal.modalElem,
      modal: modal
    });
  }
})();

var Popup = (function() {
  var _class = Ractive.extend({
    template: '#popupTemplate',
    init: function() {
      var self = this;

      function setSomething(a, b) {
        return function(event) {
          var latlng = this.get('latlng');
          search.setTarget(a, latlng, false);
        }
      }

      this.on({
        setStart: setSomething('from', 'to'),
        setEnd: setSomething('to', 'from')
      });

      geocoder.fromLatLng(self.get('latlng')).then(function(data) {
        var address = data[0].formatted_address;
        self.set('address', address);
      });
    },
    open: function() {
      map.openPopup(this.el, this.get('latlng'));
    },
    bindTo: function(marker) {
      marker.bindPopup(this.el);
    }
  });
  return function(pos) {
    var latlng = pos;
    if(pos.constructor == L.Marker) {
      latlng = pos.getLatLng();
    }
    var popup = new _class({
      el: document.createElement('div'),
      data: {
        latlng: latlng
      }
    });
    if(pos.constructor == L.Marker) {
      popup.bindTo(pos);
    }
    return popup;
  }
})();

map.on('contextmenu', function(event) {
  var popup = new Popup(event.latlng);
  popup.open();
});

var printView = new Ractive({
  el: '#print',
  template: '#printTemplate',
  data: {
    show: false,
    f: formatDuration,
    formatDirection: function(dir) {
      if(dir == undefined) return '';
      return dir.toLowerCase().replace('_', ' ');
    },
    map: staticMaps
  }
});
printView.on('back', function() {
  printView.set('show', false);
});

var itinerary = new Ractive({
  el: '#itinerary',
  template: '#itineraryTemplate',
  debug: true,
  data: {
    f: formatDuration,
    formatDirection: function(dir) {
      if(dir == undefined) return '';
      return dir.toLowerCase().replace('_', ' ');
    },
    isTransit: function(mode) {
      return mode == 'JEEP' || mode == 'BUS' || mode == 'RAIL';
    },
  }
});
itinerary.markerLayer = L.layerGroup([]).addTo(map);
itinerary.observe('current', function(val, oldVal) {
  printView.set('current', val);
  if(val) {
    itinerary.markerLayer.clearLayers();
    val.legs.forEach(function(leg, index) {
      if(index == 0) return;
      leg.marker = L.marker([leg.from.lat, leg.from.lon]);
      leg.marker.setOpacity(0);
      itinerary.markerLayer.addLayer(leg.marker);
    });
  }
  if(oldVal) {
    oldVal.legs.forEach(function(leg, index) {
      leg.marker = undefined;
    });
  }
});

itinerary.on({
  sendSMS: function() {
    if(itinerary.get('current')) {
      new SendModal();
    }
    else {
      picoModal("Search for a route and we can send the directions to you via SMS.");
    }
  },
  print: function() {
    if(itinerary.get('current')) {
      printView.set('show', true);
      window.print();
    }
    else {
      picoModal("Search for a route first.");
    }
  },
  showSteps: function(event) {
    var path = event.keypath+'.showSteps';
    this.set(path, !this.get(path));
  },
  hover: function(event, index) {
    var leg = this.get('current').legs[index];
    if(event.hover) {
      if(leg.polyline == undefined) {
        leg.polyline = L.polyline(leg.points, {
          color: 'yellow',
          weight: 7
        });
      }
      leg.polyline.addTo(router.layer);
    }
    else {
      map.removeLayer(leg.polyline);
    }
  }
});

var router = new Ractive({
  el: '#routes',
  template: '#routerTemplate',
  debug: true,
  data: {
    f: formatDuration,
  }
});
router.layer = L.layerGroup([]).addTo(map);
router.reset = function() {
  this.layer.clearLayers();
  this.routeLine = L.multiPolyline([]).addTo(this.layer);
}
router.getPoints = function(index) {
  var results = this.get('results');
  var lines = [];
  results[index].legs.forEach(function(leg) {
    lines.push(leg.points);
  });
  return lines;
}
router.showRoute = function(index) {
  this.routeLine.setLatLngs(this.getPoints(index));
  this.unhighlightRoute(index);
  map.fitBounds(this.routeLine.getBounds(), { paddingTopLeft: [300, 10], paddingBottomRight: [10, 10] });
}
router.highlightRoute = function(index) {
  var route = this.get('results')[index];
  if(route.polyline == undefined) {
    route.polyline = L.multiPolyline(this.getPoints(index), {
      color: 'red'
    });
  }
  route.polyline.addTo(this.layer);
}
router.unhighlightRoute = function(index) {
  var polyline = this.get('results')[index].polyline;
  if(this.layer.hasLayer(polyline)) {
    this.layer.removeLayer(polyline);
  }
}

router.observe('selected', function(val) {
  if(val == undefined || val < 0) return;
  var results = this.get('results');
  itinerary.set('current', results[val]);
  this.showRoute(val);
});

router.on({
  select: function(event, index) {
    this.set('selected', index);
  },
  hover: function(event, index) {
    if(index != this.get('selected')) {
      if(event.hover) {
        this.highlightRoute(index);
      }
      else {
        this.unhighlightRoute(index);
      }
    }
  }
});

<|endoftext|>


<commit_before>function init() {
    window.addEventListener('scroll', function(e){
        var distanceY = window.pageYOffset || document.documentElement.scrollTop,
            shrinkOn = 100,
            header = document.querySelector(".site-nav");
        if (distanceY > shrinkOn) {
            classie.add(header,"smaller");
        } else {
            if (classie.has(header,"smaller")) {
                classie.remove(header,"smaller");
            }
        }
    });
}

$(document).ready(function(){
    $('#pull').click(function(){
        id = document.querySelector(".site-nav #navigation a");
        if (classie.has(id,"display")) {
            classie.remove(id,"display");
        } else {
            classie.add(id,"display");
        }
    });
});

window.onload = init();
<commit_msg>Update nav.js<commit_after>function init() {
    window.addEventListener('scroll', function(e){
        var distanceY = window.pageYOffset || document.documentElement.scrollTop,
            shrinkOn = 100,
            header = document.querySelector(".site-nav");
        if (distanceY > shrinkOn) {
            classie.add(header,"smaller");
        } else {
            if (classie.has(header,"smaller")) {
                classie.remove(header,"smaller");
            }
        }
    });
}

$(document).ready(function(){
    $('#pull').click(function(){
        id = document.querySelector(".site-nav #navigation a");
        if (classie.has(id,"display-none")) {
            classie.remove(id,"display-none");
        } else {
            classie.add(id,"display-none");
        }
    });
});

window.onload = init();
<|endoftext|>


<commit_before>/**
 * UCSC Xena Client
 * http://xena.ucsc.edu
 *
 * Navigation component.
 *
 * This is a light wrapper component around React Toolbox's AppBar component.
 */

import {GENESETS_VIEWER_URL} from "./views/GeneSetViewDialog";

// Core dependencies, components
var React = require('react');
var ReactDOM = require('react-dom');
var _ = require('./underscore_ext').default;
import AppBar from 'react-toolbox/lib/app_bar';
import Navigation from 'react-toolbox/lib/navigation';
import {ThemeProvider} from 'react-css-themr';
import Link from 'react-toolbox/lib/link';
import {Menu, MenuItem} from 'react-toolbox/lib/menu';
import {Button} from 'react-toolbox/lib/button';
var navTheme = require('./navTheme');
var BookmarkMenu = require('./views/BookmarkMenu');
var {servers: {localHub}} = require('./defaultServers');

// Styles
var compStyles = require('./nav.module.css');

// Images
import logoSantaCruzImg from '../images/logoSantaCruz.png';
import logoSantaCruz2xImg from '../images/logoSantaCruz@2x.png';
import logoSantaCruz3xImg from '../images/logoSantaCruz@3x.png';

// Locals
var links = [
	{label: 'Data Sets', nav: 'datapages'},
	{label: 'Visualization', nav: 'heatmap'},
	{label: 'Transcripts', nav: 'transcripts'},
	{label: 'Data Hubs', nav: 'hub'},
	{label: 'View My Data', nav: 'datapages', params: {addHub: localHub, host: localHub}},
];

var helproot = 'https://ucsc-xena.gitbook.io/project/';

var helpLink = {
	href: helproot,
	label: 'Help',
	target: '_blank'
};

var geneSetsLink = { //eslint-disable-line no-unused-vars
    href: GENESETS_VIEWER_URL,
    label: 'Gene Sets',
    target: '_blank'
};

var pythonLink = {
    href: helproot + 'overview-of-features/accessing-data-through-python',
    label: 'Python',
    target: '_blank'
};

var active = (l, activeLink) => l.nav === activeLink;

class MoreToolsMenu extends React.Component {
	state = {
		anchorEl: null,
	};

	onClick = event => {
		this.setState({ anchorEl: event.currentTarget });
	};

	handleClose = () => {
		this.setState({ anchorEl: null });
	};

	handleSelect = (url) => {
		window.open(url);
	};

	render() {
		let {anchorEl} = this.state;

		return (

					<Button
						onClick={this.onClick}>
						More Tools
					</Button>
					<Menu position='topLeft'
						active={Boolean(anchorEl)}
						onHide={this.handleClose}
						className={compStyles.menu}
					>
						<MenuItem onClick={this.handleSelect.bind(this, pythonLink.href)} caption={pythonLink.label}/>
						{/*<MenuItem onClick={this.handleSelect.bind(this, geneSetsLink.href)} caption={geneSetsLink.label}/>*/}
					 </Menu>

		);
	}
}

class XenaNav extends React.Component {
	render() {
		let {isPublic, activeLink, getState, onImport} = this.props;
		let routes = _.map(links, l => {
			var {nav, params, ...others} = l,
			onClick = nav ? () => this.props.onNavigate(nav, params) : undefined;
			return {...others, onClick, active: active(l, activeLink)};
		});
		let logoSrcSet = `${logoSantaCruz2xImg} 2x, ${logoSantaCruz3xImg} 3x`;
		return (
			<AppBar className={compStyles.NavAppBar}>

				<Navigation type="horizontal" routes={routes}>
					{getState ? <BookmarkMenu isPublic={isPublic} getState={getState} onImport={onImport}/> : null}
					<Link {...helpLink} />
					<MoreToolsMenu/>
				</Navigation>
			</AppBar>
		);
	}
}

class ThemedNav extends React.Component {
	render() {
		return (
			<ThemeProvider theme={navTheme}>
				<XenaNav {...this.props}/>
			</ThemeProvider>);
	}
}

var nav = document.getElementById('navMenuMain');

export default props => ReactDOM.render(<ThemedNav {...props} />, nav);
<commit_msg>Revert "Comment out geneset viewer."<commit_after>/**
 * UCSC Xena Client
 * http://xena.ucsc.edu
 *
 * Navigation component.
 *
 * This is a light wrapper component around React Toolbox's AppBar component.
 */

import {GENESETS_VIEWER_URL} from "./views/GeneSetViewDialog";

// Core dependencies, components
var React = require('react');
var ReactDOM = require('react-dom');
var _ = require('./underscore_ext').default;
import AppBar from 'react-toolbox/lib/app_bar';
import Navigation from 'react-toolbox/lib/navigation';
import {ThemeProvider} from 'react-css-themr';
import Link from 'react-toolbox/lib/link';
import {Menu, MenuItem} from 'react-toolbox/lib/menu';
import {Button} from 'react-toolbox/lib/button';
var navTheme = require('./navTheme');
var BookmarkMenu = require('./views/BookmarkMenu');
var {servers: {localHub}} = require('./defaultServers');

// Styles
var compStyles = require('./nav.module.css');

// Images
import logoSantaCruzImg from '../images/logoSantaCruz.png';
import logoSantaCruz2xImg from '../images/logoSantaCruz@2x.png';
import logoSantaCruz3xImg from '../images/logoSantaCruz@3x.png';

// Locals
var links = [
	{label: 'Data Sets', nav: 'datapages'},
	{label: 'Visualization', nav: 'heatmap'},
	{label: 'Transcripts', nav: 'transcripts'},
	{label: 'Data Hubs', nav: 'hub'},
	{label: 'View My Data', nav: 'datapages', params: {addHub: localHub, host: localHub}},
];

var helproot = 'https://ucsc-xena.gitbook.io/project/';

var helpLink = {
	href: helproot,
	label: 'Help',
	target: '_blank'
};

var geneSetsLink = {
    href: GENESETS_VIEWER_URL,
    label: 'Gene Sets',
    target: '_blank'
};

var pythonLink = {
    href: helproot + 'overview-of-features/accessing-data-through-python',
    label: 'Python',
    target: '_blank'
};

var active = (l, activeLink) => l.nav === activeLink;

class MoreToolsMenu extends React.Component {
	state = {
		anchorEl: null,
	};

	onClick = event => {
		this.setState({ anchorEl: event.currentTarget });
	};

	handleClose = () => {
		this.setState({ anchorEl: null });
	};

	handleSelect = (url) => {
		window.open(url);
	};

	render() {
		let {anchorEl} = this.state;

		return (

					<Button
						onClick={this.onClick}>
						More Tools
					</Button>
					<Menu position='topLeft'
						active={Boolean(anchorEl)}
						onHide={this.handleClose}
						className={compStyles.menu}
					>
						<MenuItem onClick={this.handleSelect.bind(this, pythonLink.href)} caption={pythonLink.label}/>
						<MenuItem onClick={this.handleSelect.bind(this, geneSetsLink.href)} caption={geneSetsLink.label}/>
					 </Menu>

		);
	}
}

class XenaNav extends React.Component {
	render() {
		let {isPublic, activeLink, getState, onImport} = this.props;
		let routes = _.map(links, l => {
			var {nav, params, ...others} = l,
			onClick = nav ? () => this.props.onNavigate(nav, params) : undefined;
			return {...others, onClick, active: active(l, activeLink)};
		});
		let logoSrcSet = `${logoSantaCruz2xImg} 2x, ${logoSantaCruz3xImg} 3x`;
		return (
			<AppBar className={compStyles.NavAppBar}>

				<Navigation type="horizontal" routes={routes}>
					{getState ? <BookmarkMenu isPublic={isPublic} getState={getState} onImport={onImport}/> : null}
					<Link {...helpLink} />
					<MoreToolsMenu/>
				</Navigation>
			</AppBar>
		);
	}
}

class ThemedNav extends React.Component {
	render() {
		return (
			<ThemeProvider theme={navTheme}>
				<XenaNav {...this.props}/>
			</ThemeProvider>);
	}
}

var nav = document.getElementById('navMenuMain');

export default props => ReactDOM.render(<ThemedNav {...props} />, nav);
<|endoftext|>


<commit_before>function LotteryItem(object, tickets)
{
    var _object = object;
    var _tickets = parseInt(tickets);

    if (_.isNaN(_tickets))
        _tickets = 0;

    this.GetObject = function() { return _object; };
    this.GetTickets = function() { return _tickets; };
    this.CanUseTicket = function() { return _tickets > 0; };
    this.UseTicket = function()
    {
        if (_tickets > 0)
            _tickets--;
        return _tickets;
    };
}

function Lottery(existing)
{
    var _items = [];
    var _totalTickets = 0;

    //HACK
    this.GetItems = function() { return _items; };

    this.AddItem = function(object, tickets)
    {
        var item = new LotteryItem(object, tickets);

        //If tickets are invalid
        if (item.GetTickets() <= 0)
            return false; //Don't add it

        _totalTickets += item.GetTickets();
        _items.push(item);
        return true;
    };

    this.GetTotalTickets = function() { return _totalTickets; };

    this.Draw = function()
    {
        var ticket = Math.min(_totalTickets - 1, Math.round(Math.random()*_totalTickets));
        console.log(_totalTickets + ", " + ticket);
        var currentTicket = 0;
        var drawnItem = null;
        _items = _.filter(_items, function(item)
        {
            if (_.isNull(drawnItem) && currentTicket + item.GetTickets() >= ticket && item.CanUseTicket())
            {
                var remaining = item.UseTicket();
                drawnItem = item.GetObject();
                _totalTickets--;
                return remaining > 0;
            }
            currentTicket += item.GetTickets();
            return true;
        }, this);

        return drawnItem;
    };

    if (_.isObject(existing) && _.isFunction(existing.GetItems))
    {
        _.each(existing.GetItems(), function(item)
        {
            if (_.isFunction(item.GetObject) && _.isFunction(item.GetTickets))
                this.AddItem(item.GetObject(), item.GetTickets());
        }, this);
    }
}

$(function()
{
    var diceNumbers =
    {
        2: 1,
        3: 2,
        4: 3,
        5: 4,
        6: 5,
        7: 6,
        8: 5,
        9: 4,
        10: 3,
        11: 2,
        12: 1
    };

    var baseLottery = new Lottery();

    _.each(diceNumbers, function(tickets, result)
    {
        baseLottery.AddItem(result, tickets);
    });

    var currentLottery = new Lottery();

    var resultDiv = $("#result");
    var visualizeDiv = $("#visualize");

    var rollButton = $("#roll");
    var resetButton = $("#reset");

    var showVisualier = true;
    ToggleVisualizer();

    function ToggleVisualizer()
    {
        showVisualier = !showVisualier;
        visualizeDiv.css("display", showVisualier ? "inline" : "none");
    }

    $(document).keydown(function(event)
    {
        console.log(event.which);
        if (event.which == 86) //v.
            ToggleVisualizer();
        else if (event.which == 32)
            rollButton.click();
        else if (event.which == 82)
            resetButton.click();
    });

    function DrawVisualizer()
    {
        visualizeDiv.html("");
        _.each(currentLottery.GetItems(), function(item)
        {
            visualizeDiv.append(item.GetObject() + ": " + item.GetTickets() + "
");
        });
    }

    function ResetRolls()
    {
        currentLottery = new Lottery(baseLottery);
        DrawVisualizer();
    }

    function RollDice()
    {
        if (currentLottery.GetTotalTickets() <= 0)
            ResetRolls();

        var roll = currentLottery.Draw();

        var date = new Date();

        resultDiv.text("Result: " + roll + " - " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());

        DrawVisualizer();
    }

    rollButton.click(RollDice);
    resetButton.click(function()
    {
        ResetRolls();
        RollDice();
        resultDiv.append(" - Reset.");
    });

    rollButton.click();
});

<commit_msg>Removed debug logging.<commit_after>function LotteryItem(object, tickets)
{
    var _object = object;
    var _tickets = parseInt(tickets);

    if (_.isNaN(_tickets))
        _tickets = 0;

    this.GetObject = function() { return _object; };
    this.GetTickets = function() { return _tickets; };
    this.CanUseTicket = function() { return _tickets > 0; };
    this.UseTicket = function()
    {
        if (_tickets > 0)
            _tickets--;
        return _tickets;
    };
}

function Lottery(existing)
{
    var _items = [];
    var _totalTickets = 0;

    //HACK
    this.GetItems = function() { return _items; };

    this.AddItem = function(object, tickets)
    {
        var item = new LotteryItem(object, tickets);

        //If tickets are invalid
        if (item.GetTickets() <= 0)
            return false; //Don't add it

        _totalTickets += item.GetTickets();
        _items.push(item);
        return true;
    };

    this.GetTotalTickets = function() { return _totalTickets; };

    this.Draw = function()
    {
        var ticket = Math.min(_totalTickets - 1, Math.round(Math.random()*_totalTickets));
        var currentTicket = 0;
        var drawnItem = null;
        _items = _.filter(_items, function(item)
        {
            if (_.isNull(drawnItem) && currentTicket + item.GetTickets() >= ticket && item.CanUseTicket())
            {
                var remaining = item.UseTicket();
                drawnItem = item.GetObject();
                _totalTickets--;
                return remaining > 0;
            }
            currentTicket += item.GetTickets();
            return true;
        }, this);

        return drawnItem;
    };

    if (_.isObject(existing) && _.isFunction(existing.GetItems))
    {
        _.each(existing.GetItems(), function(item)
        {
            if (_.isFunction(item.GetObject) && _.isFunction(item.GetTickets))
                this.AddItem(item.GetObject(), item.GetTickets());
        }, this);
    }
}

$(function()
{
    var diceNumbers =
    {
        2: 1,
        3: 2,
        4: 3,
        5: 4,
        6: 5,
        7: 6,
        8: 5,
        9: 4,
        10: 3,
        11: 2,
        12: 1
    };

    var baseLottery = new Lottery();

    _.each(diceNumbers, function(tickets, result)
    {
        baseLottery.AddItem(result, tickets);
    });

    var currentLottery = new Lottery();

    var resultDiv = $("#result");
    var visualizeDiv = $("#visualize");

    var rollButton = $("#roll");
    var resetButton = $("#reset");

    var showVisualier = true;
    ToggleVisualizer();

    function ToggleVisualizer()
    {
        showVisualier = !showVisualier;
        visualizeDiv.css("display", showVisualier ? "inline" : "none");
    }

    $(document).keydown(function(event)
    {
        if (event.which == 86) //v.
            ToggleVisualizer();
        else if (event.which == 32)
            rollButton.click();
        else if (event.which == 82)
            resetButton.click();
    });

    function DrawVisualizer()
    {
        visualizeDiv.html("");
        _.each(currentLottery.GetItems(), function(item)
        {
            visualizeDiv.append(item.GetObject() + ": " + item.GetTickets() + "
");
        });
    }

    function ResetRolls()
    {
        currentLottery = new Lottery(baseLottery);
        DrawVisualizer();
    }

    function RollDice()
    {
        if (currentLottery.GetTotalTickets() <= 0)
            ResetRolls();

        var roll = currentLottery.Draw();

        var date = new Date();

        resultDiv.text("Result: " + roll + " - " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());

        DrawVisualizer();
    }

    rollButton.click(RollDice);
    resetButton.click(function()
    {
        ResetRolls();
        RollDice();
        resultDiv.append(" - Reset.");
    });

    rollButton.click();
});

<|endoftext|>


<commit_before>'use strict';

function rpg_character_affect(character, stat, effect){
    rpg_characters[character]['stats'][stat]['current'] -= effect;
    if(rpg_characters[character]['stats'][stat]['current'] <= 0){
        rpg_characters[character]['stats'][stat]['current'] = 0;

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

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

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

    properties['color'] = properties['color'] || '#fff';
    properties['dead'] = false;
    properties['equipment'] = properties['equipment'] || {
      'feet': void 0,
      'head': void 0,
      'legs': void 0,
      'main-hand': void 0,
      'neck': void 0,
      'off-hand': void 0,
      'torso': void 0,
    };
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 20;
    properties['height-half'] = properties['height'] / 2;
    properties['inventory'] = properties['inventory'] || [];
    properties['player'] = properties['player'] || false;
    properties['selected'] = properties['selected'] || 0;
    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['x-velocity'] = properties['x-velocity'] || 0;
    properties['y'] = properties['y'] || 0;
    properties['y-velocity'] = properties['y-velocity'] || 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;

    rpg_characters.push(properties);
}

function rpg_character_handle(){
    for(var character in rpg_characters){
        if(rpg_characters[character]['dead']){
            continue;
        }

        // Regenerate character stats.
        for(var stat in rpg_characters[character]['stats']){
            if(rpg_characters[character]['stats'][stat]['regeneration'] === void 0
              || rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
                continue;
            }

            rpg_characters[character]['stats'][stat]['regeneration']['current'] += 1;
            if(rpg_characters[character]['stats'][stat]['regeneration']['current'] >= rpg_characters[character]['stats'][stat]['regeneration']['max']){
                rpg_characters[character]['stats'][stat]['current'] += 1;
                rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
            }
        }

        // Handle character inventory.
        for(var item in rpg_characters[character]['inventory']){
            var selected = rpg_characters[character]['inventory'][item];

            if(selected['current'] < selected['reload']){
                selected['current'] += 1;
                continue;
            }

            if(rpg_characters[character]['selected'] != item){
                continue;
            }

            if(selected['cost'] !== 0
              && rpg_characters[character]['stats'][selected['costs']]['current'] < selected['cost']){
                continue;
            }

            var dx = 0;
            var dy = 0;
            var speeds = 0;
            var target_x = 0;
            var target_y = 0;

            if(character === '0'){
                if(mouse_lock_x < 0){
                    continue;
                }

                target_x = rpg_characters[character]['x'] + mouse_x - canvas_x;
                target_y = rpg_characters[character]['y'] + mouse_y - canvas_y;

                speeds = math_movement_speed(
                  rpg_characters[character]['x'],
                  rpg_characters[character]['y'],
                  target_x,
                  target_y
                );

                dx = mouse_x > canvas_x ? speeds[0] : -speeds[0];
                dy = mouse_y > canvas_y ? speeds[1] : -speeds[1];

            }else{
                speeds = math_movement_speed(
                  rpg_characters[character]['x'],
                  rpg_characters[character]['y'],
                  rpg_characters[0]['x'],
                  rpg_characters[0]['y']
                );

                dx = rpg_characters[0]['x'] > rpg_characters[character]['x'] ? speeds[0] : -speeds[0];
                dy = rpg_characters[0]['y'] > rpg_characters[character]['y'] ? speeds[1] : -speeds[1];
            }

            selected['current'] = 0;
            rpg_character_affect(
              character,
              selected['costs'],
              selected['cost']
            );

            // Handle particle-creating spells.
            if(selected['type'] === 'particle'){
                var particle = {};
                for(var property in selected['particle']){
                    particle[property] = selected['particle'][property];
                }
                particle['dx'] = dx;
                particle['dy'] = dy;
                particle['owner'] = character;
                particle['x'] = rpg_characters[character]['x'];
                particle['y'] = rpg_characters[character]['y'];

                rpg_particle_create(particle);

            }else if(selected['type'] === 'stat'){
                rpg_character_affect(
                  character,
                  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'] = Math.round(target_x - 12.5);
                worlddynamic['y'] = Math.round(target_y - 12.5);

                rpg_world_dynamic_create(worlddynamic);
            }

            break;
        }
    }
}

function rpg_item_create(properties, type){
    properties = properties || {};
    type = type || 'any';

    properties['equipped'] = properties['equipped'] || false;
    properties['owner'] = properties['owner'] || 'player';

    rpg_items.push(properties);
}

function rpg_item_select(character, id){
    character = character || 0;

    var length = rpg_characters[character]['inventory'].length - 1;
    if(id < 0){
        id = length;

    }else if(id > length){
        id = 0;
    }

    rpg_characters[character]['selected'] = id;

    if(character === 0){
        document.getElementById('canvas').style.cursor =
          rpg_characters[0]['inventory'][id]['cursor'] || 'auto';
    }
}

function rpg_item_toggle(id){
    if(rpg_items[id]['owner'] === false){
        return;
    }

    // Toggle item on character.
    rpg_items[id]['equipped'] = !rpg_items[id]['equipped'];
}

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['stat'] = properties['stat'] || 'health';
    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 collisions with characters.
        for(var character in rpg_characters){
            if(rpg_particles[particle]['owner'] == character
              || rpg_particles[particle]['x'] <= rpg_characters[character]['x'] - rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['x'] >= rpg_characters[character]['x'] + rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['y'] <= rpg_characters[character]['y'] - rpg_characters[character]['height'] / 2
              || rpg_particles[particle]['y'] >= rpg_characters[character]['y'] + rpg_characters[character]['height'] / 2){
                continue;
            }

            rpg_character_affect(
              character,
              rpg_particles[particle]['stat'],
              rpg_particles[particle]['damage']
            );

            rpg_particles.splice(
              particle,
              1
            );

            continue particleloop;
        }
    }
}

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_characters = [];
var rpg_items = [];
var rpg_particles = [];
var rpg_world_dynamic = [];
var rpg_world_static = [];
<commit_msg>moved items to characters, added rpg_item_create() usage, improved character stat defaults<commit_after>'use strict';

function rpg_character_affect(character, stat, effect){
    rpg_characters[character]['stats'][stat]['current'] -= effect;
    if(rpg_characters[character]['stats'][stat]['current'] <= 0){
        rpg_characters[character]['stats'][stat]['current'] = 0;

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

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

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

    properties['color'] = properties['color'] || '#fff';
    properties['dead'] = false;
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 20;
    properties['height-half'] = properties['height'] / 2;
    properties['inventory'] = properties['inventory'] || [];
    properties['player'] = properties['player'] || false;
    properties['selected'] = properties['selected'] || 0;
    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['x-velocity'] = properties['x-velocity'] || 0;
    properties['y'] = properties['y'] || 0;
    properties['y-velocity'] = properties['y-velocity'] || 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']
          : 10;
        properties['stats']['health']['max'] = properties['stats']['health']['max'] || properties['stats']['health']['current'];
        properties['stats']['health']['regeneration'] = properties['stats']['health']['regeneration'] || {};
          properties['stats']['health']['regeneration']['current'] = properties['stats']['health']['regeneration']['current'] !== void 0
            ? properties['stats']['health']['regeneration']['current']
            : 0;
          properties['stats']['health']['regeneration']['max'] = properties['stats']['health']['regeneration']['max'] || 1000;
      properties['stats']['mana'] = properties['stats']['mana'] || {};
        properties['stats']['mana']['current'] = properties['stats']['mana']['current'] !== void 0
          ? properties['stats']['mana']['current']
          : 10;
        properties['stats']['mana']['max'] = properties['stats']['mana']['max'] || properties['stats']['mana']['current'];
        properties['stats']['mana']['regeneration'] = properties['stats']['mana']['regeneration'] || {};
          properties['stats']['mana']['regeneration']['current'] = properties['stats']['mana']['regeneration']['current'] !== void 0
            ? properties['stats']['mana']['regeneration']['current']
            : 0;
          properties['stats']['mana']['regeneration']['max'] = properties['stats']['mana']['regeneration']['max'] || 100;

    rpg_characters.push(properties);
}

function rpg_character_handle(){
    for(var character in rpg_characters){
        if(rpg_characters[character]['dead']){
            continue;
        }

        // Regenerate character stats.
        for(var stat in rpg_characters[character]['stats']){
            if(rpg_characters[character]['stats'][stat]['regeneration'] === void 0
              || rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
                continue;
            }

            rpg_characters[character]['stats'][stat]['regeneration']['current'] += 1;
            if(rpg_characters[character]['stats'][stat]['regeneration']['current'] >= rpg_characters[character]['stats'][stat]['regeneration']['max']){
                rpg_characters[character]['stats'][stat]['current'] += 1;
                rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
            }
        }

        // Handle character inventory item spells.
        for(var item in rpg_characters[character]['inventory']){
            var selected = rpg_characters[character]['inventory'][item]['spell'];

            if(selected['reload-current'] < selected['reload']){
                selected['reload-current'] += 1;
                continue;
            }

            if(rpg_characters[character]['selected'] != item){
                continue;
            }

            if(selected['cost'] !== 0
              && rpg_characters[character]['stats'][selected['costs']]['current'] < selected['cost']){
                continue;
            }

            var dx = 0;
            var dy = 0;
            var speeds = 0;
            var target_x = 0;
            var target_y = 0;

            if(character === '0'){
                if(mouse_lock_x < 0){
                    continue;
                }

                target_x = rpg_characters[character]['x'] + mouse_x - canvas_x;
                target_y = rpg_characters[character]['y'] + mouse_y - canvas_y;

                speeds = math_movement_speed(
                  rpg_characters[character]['x'],
                  rpg_characters[character]['y'],
                  target_x,
                  target_y
                );

                dx = mouse_x > canvas_x ? speeds[0] : -speeds[0];
                dy = mouse_y > canvas_y ? speeds[1] : -speeds[1];

            }else{
                speeds = math_movement_speed(
                  rpg_characters[character]['x'],
                  rpg_characters[character]['y'],
                  rpg_characters[0]['x'],
                  rpg_characters[0]['y']
                );

                dx = rpg_characters[0]['x'] > rpg_characters[character]['x'] ? speeds[0] : -speeds[0];
                dy = rpg_characters[0]['y'] > rpg_characters[character]['y'] ? speeds[1] : -speeds[1];
            }

            selected['reload-current'] = 0;
            rpg_character_affect(
              character,
              selected['costs'],
              selected['cost']
            );

            // Handle particle-creating spells.
            if(selected['type'] === 'particle'){
                var particle = {};
                for(var property in selected){
                    particle[property] = selected[property];
                }
                particle['dx'] = dx;
                particle['dy'] = dy;
                particle['owner'] = character;
                particle['x'] = rpg_characters[character]['x'];
                particle['y'] = rpg_characters[character]['y'];

                rpg_particle_create(particle);

            }else if(selected['type'] === 'stat'){
                rpg_character_affect(
                  character,
                  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'] = Math.round(target_x - 12.5);
                worlddynamic['y'] = Math.round(target_y - 12.5);

                rpg_world_dynamic_create(worlddynamic);
            }

            break;
        }
    }
}

function rpg_item_create(properties, type){
    properties = properties || {};
    type = type || 'any';

    properties['cursor'] = properties['cursor'] || 'auto';
    properties['equipped'] = properties['equipped'] || false;
    properties['label'] = properties['label'] || '';
    properties['owner'] = properties['owner'] || 0;
    properties['slot'] = properties['slot'] || 'spellbook';
    properties['spell'] = properties['spell'] || {};
      properties['spell']['cost'] = properties['spell']['cost'] || 0;
      properties['spell']['costs'] = properties['spell']['costs'] || 'mana';
      properties['spell']['color'] = properties['spell']['color'] || '#fff';
      properties['spell']['damage'] = properties['spell']['damage'] || 0;
      properties['spell']['damages'] = properties['spell']['damages'] || 'health';
      properties['spell']['lifespan'] = properties['spell']['lifespan'] || 50;
      properties['spell']['reload'] = properties['spell']['reload'] || 0;
      properties['spell']['reload-current'] = properties['spell']['reload-current'] || properties['spell']['reload'];
      properties['spell']['speed-x'] = properties['spell']['speed-x'] || 5;
      properties['spell']['speed-y'] = properties['spell']['speed-y'] || 5;
      properties['spell']['type'] = properties['spell']['type'] || 'particle';

    return properties;
}

function rpg_item_select(character, id){
    character = character || 0;

    var length = rpg_characters[character]['inventory'].length - 1;
    if(id < 0){
        id = length;

    }else if(id > length){
        id = 0;
    }

    rpg_characters[character]['selected'] = id;

    if(character === 0){
        document.getElementById('canvas').style.cursor =
          rpg_characters[0]['inventory'][id]['cursor'] || 'auto';
    }
}

/*
function rpg_item_toggle(id){
    if(rpg_items[id]['owner'] === false){
        return;
    }

    // Toggle item on character.
    rpg_items[id]['equipped'] = !rpg_items[id]['equipped'];
}
*/

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['stat'] = properties['stat'] || 'health';
    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 collisions with characters.
        for(var character in rpg_characters){
            if(rpg_particles[particle]['owner'] == character
              || rpg_particles[particle]['x'] <= rpg_characters[character]['x'] - rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['x'] >= rpg_characters[character]['x'] + rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['y'] <= rpg_characters[character]['y'] - rpg_characters[character]['height'] / 2
              || rpg_particles[particle]['y'] >= rpg_characters[character]['y'] + rpg_characters[character]['height'] / 2){
                continue;
            }

            rpg_character_affect(
              character,
              rpg_particles[particle]['stat'],
              rpg_particles[particle]['damage']
            );

            rpg_particles.splice(
              particle,
              1
            );

            continue particleloop;
        }
    }
}

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_characters = [];
var rpg_particles = [];
var rpg_world_dynamic = [];
var rpg_world_static = [];
<|endoftext|>


<commit_before>/**
 * jQuery.toTop.js v1.1
 * Developed by: MMK Jony
 * Fork on Github: https://github.com/mmkjony/jQuery.toTop
 **/

!function(o){"use strict";o.fn.toTop=function(t){var i=this,e=o(window),s=o("html, body"),n=o.extend({autohide:!0,offset:420,speed:500,position:!0,right:15,bottom:30},t);i.css({cursor:"pointer"}),n.autohide&&i.css("display","none"),n.position&&i.css({position:"fixed",right:n.right,bottom:n.bottom}),i.click(function(){s.animate({scrollTop:0},n.speed)}),e.scroll(function(){var o=e.scrollTop();n.autohide&&(o>n.offset?i.fadeIn(n.speed):i.fadeOut(n.speed))})}}(jQuery);<commit_msg>Delete top.js<commit_after><|endoftext|>


<commit_before>/*! JSFuck 0.4.0 - http://jsfuck.com */

(function(self){

  var USE_CHAR_CODE = "USE_CHAR_CODE";

  var MIN = 32, MAX = 126;

  var SIMPLE = {
    'false':      '![]',
    'true':       '!![]',
    'undefined':  '[][[]]',
    'NaN':        '+[![]]',
    'Infinity':   '+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]]+[+[]])' // +"1e1000"
  };

  var CONSTRUCTORS = {
    'Array':    '[]',
    'Number':   '(+[])',
    'String':   '([]+[])',
    'Boolean':  '(![])',
    'Function': '[]["filter"]',
    'RegExp':   'Function("return/0/")()'
  };

  var MAPPING = {
    'a':   '(false+"")[1]',
    'b':   '(Function("return{}")()+"")[2]',
    'c':   '([]["filter"]+"")[3]',
    'd':   '(undefined+"")[2]',
    'e':   '(true+"")[3]',
    'f':   '(false+"")[0]',
    'g':   '(false+[0]+String)[20]',
    'h':   '(+(101))["toString"](21)[1]',
    'i':   '([false]+undefined)[10]',
    'j':   '(Function("return{}")()+"")[10]',
    'k':   '(+(20))["toString"](21)',
    'l':   '(false+"")[2]',
    'm':   '(Number+"")[11]',
    'n':   '(undefined+"")[1]',
    'o':   '(true+[]["filter"])[10]',
    'p':   '(+(211))["toString"](31)[1]',
    'q':   '(+(212))["toString"](31)[1]',
    'r':   '(true+"")[1]',
    's':   '(false+"")[3]',
    't':   '(true+"")[0]',
    'u':   '(undefined+"")[0]',
    'v':   '(+(31))["toString"](32)',
    'w':   '(+(32))["toString"](33)',
    'x':   '(+(101))["toString"](34)[1]',
    'y':   '(NaN+[Infinity])[10]',
    'z':   '(+(35))["toString"](36)',

    'A':   '(+false+Array)[10]',
    'B':   '(+false+Boolean)[10]',
    'C':   'Function("return escape")()(("")["italics"]())[2]',
    'D':   'Function("return escape")()([]["filter"])["slice"]("-1")',
    'E':   '(RegExp+"")[12]',
    'F':   '(+false+Function)[10]',
    'G':   '(false+Function("return Date")()())[30]',
    'H':   USE_CHAR_CODE,
    'I':   '(Infinity+"")[0]',
    //'J':   USE_CHAR_CODE,
    'K':   USE_CHAR_CODE,
    'L':   USE_CHAR_CODE,
    'M':   '(true+Function("return Date")()())[30]',
    'N':   '(NaN+"")[0]',
    'O':   '(NaN+Function("return{}")())[11]',
    'P':   USE_CHAR_CODE,
    'Q':   USE_CHAR_CODE,
    'R':   '(+false+RegExp)[10]',
    'S':   '(+false+String)[10]',
    'T':   '(NaN+Function("return Date")()())[30]',
    'U':   '(NaN+Function("return{}")()["toString"]["call"]())[11]',
    'V':   USE_CHAR_CODE,
    'W':   USE_CHAR_CODE,
    'X':   USE_CHAR_CODE,
    'Y':   USE_CHAR_CODE,
    'Z':   USE_CHAR_CODE,

    ' ':   '(NaN+[]["filter"])[11]',
    '!':   USE_CHAR_CODE,
    '"':   '("")["fontcolor"]()[12]',
    '#':   USE_CHAR_CODE,
    '$':   USE_CHAR_CODE,
    '%':   'Function("return escape")()([]["filter"])[20]',
    '&':   USE_CHAR_CODE,
    '\'':  USE_CHAR_CODE,
    '(':   '(false+[]["filter"])[20]',
    ')':   '(true+[]["filter"])[20]',
    '*':   USE_CHAR_CODE,
    '+':   '(+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]])+[])[2]',
    ',':   '[[]]["concat"]([[]])+""',
    '-':   '(+(.+[0000000001])+"")[2]',
    '.':   '(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]',
    '/':   '(false+[+false])["italics"]()[10]',
    ':':   '(RegExp()+"")[3]',
    ';':   USE_CHAR_CODE,
    '<':   '("")["italics"]()[0]',
    '=':   '("")["fontcolor"]()[11]',
    '>':   '("")["italics"]()[2]',
    '?':   '(RegExp()+"")[2]',
    '@':   USE_CHAR_CODE,
    '[':   '(Function("return{}")()+"")[0]',
    '\\':  USE_CHAR_CODE,
    ']':   '(Function("return{}")()+"")["slice"]("-1")',
    '^':   USE_CHAR_CODE,
    '_':   USE_CHAR_CODE,
    '`':   USE_CHAR_CODE,
    '{':   '(NaN+[]["filter"])[21]',
    '|':   USE_CHAR_CODE,
    '}':   '([]["filter"]+"")["slice"]("-1")',
    '~':   USE_CHAR_CODE
  };

  var GLOBAL = 'Function("return this")()';

  function fillMissingChars(){
    for (var key in MAPPING){
      if (MAPPING[key] === USE_CHAR_CODE){
        MAPPING[key] = 'Function("return unescape")()("%"'+ key.charCodeAt(0).toString(16).replace(/(\d+)/g, "+($1)+\"") + '")';
      }
    }
  }

  function fillMissingDigits(){
    var output, number, i;

    for (number = 0; number < 10; number++){

      output = "+[]";

      if (number > 0){ output = "+!" + output; }
      for (i = 1; i < number; i++){ output = "+!+[]" + output; }
      if (number > 1){ output = output.substr(1); }

      MAPPING[number] = "[" + output + "]";
    }
  }

  function replaceMap(){
    var character = "", value, original, i, key;

    function replace(pattern, replacement){
      value = value.replace(
        new RegExp(pattern, "gi"),
        replacement
      );
    }

    function digitReplacer(_,x) { return MAPPING[x]; }

    function numberReplacer(_,y) {
      var values = y.split("");
      var head = +(values.shift());
      var output = "+[]";

      if (head > 0){ output = "+!" + output; }
      for (i = 1; i < head; i++){ output = "+!+[]" + output; }
      if (head > 1){ output = output.substr(1); }

      return [output].concat(values).join("+").replace(/(\d)/g, digitReplacer);
    }

    for (i = MIN; i <= MAX; i++){
      character = String.fromCharCode(i);
      value = MAPPING[character];
      if(!value) {continue;}
      original = value;

      for (key in CONSTRUCTORS){
        replace("\\b" + key, CONSTRUCTORS[key] + '["constructor"]');
      }

      for (key in SIMPLE){
        replace(key, SIMPLE[key]);
      }

      replace('(\\d\\d+)', numberReplacer);
      replace('\\((\\d)\\)', digitReplacer);
      replace('\\[(\\d)\\]', digitReplacer);

      replace("GLOBAL", GLOBAL);
      replace('\\+""', "+[]");
      replace('""', "[]+[]");

      MAPPING[character] = value;
    }
  }

  function replaceStrings(){
    var regEx = /[^\[\]\(\)\!\+]{1}/g,
      all, value, missing,
      count = MAX - MIN;

    function findMissing(){
      var all, value, done = false;

      missing = {};

      for (all in MAPPING){

        value = MAPPING[all];

        if (value.match(regEx)){
          missing[all] = value;
          done = true;
        }
      }

      return done;
    }

    function mappingReplacer(a, b) {
      return b.split("").join("+");
    }

    function valueReplacer(c) {
      return missing[c] ? c : MAPPING[c];
    }

    for (all in MAPPING){
      MAPPING[all] = MAPPING[all].replace(/\"([^\"]+)\"/gi, mappingReplacer);
    }

    while (findMissing()){
      for (all in missing){
        value = MAPPING[all];
        value = value.replace(regEx, valueReplacer);

        MAPPING[all] = value;
        missing[all] = value;
      }

      if (count-- === 0){
        console.error("Could not compile the following chars:", missing);
      }
    }
  }

  function encode(input, wrapWithEval){
    var output = [];

    if (!input){
      return "";
    }

    var r = "";
    for (var i in SIMPLE) {
      r += i + "|";
    }
    r+=".";

    input.replace(new RegExp(r, 'g'), function(c) {
      var replacement = SIMPLE[c];
      if (replacement) {
        output.push("[" + replacement + "]+[]");
      } else {
        replacement = MAPPING[c];
        if (replacement){
          output.push(replacement);
        } else {
          if (c === "J") {
            replacement =
              "([][" + encode("filter") + "]" +
              "[" + encode("constructor") + "]" +
              "(" + encode("return new Date(200000000)") + ")()+[])[!+[]+!+[]+!+[]+!+[]]";

            output.push(replacement);
            MAPPING[c] = replacement;
          } else {
            replacement =
              "([]+[])[" + encode("constructor") + "]" +
              "[" + encode("fromCharCode") + "]" +
              "(" + encode(c.charCodeAt(0) + "") + ")";

            output.push(replacement);
            MAPPING[c] = replacement;
          }
        }
      }
    });

    output = output.join("+");

    if (/^\d$/.test(input)){
      output += "+[]";
    }

    if (wrapWithEval){
      output = "[][" + encode("filter") + "]" +
        "[" + encode("constructor") + "]" +
        "(" + output + ")()";
    }

    return output;
  }

  fillMissingDigits();
  fillMissingChars();
  replaceMap();
  replaceStrings();

  self.JSFuck = {
    encode: encode
  };
})(typeof(exports) === "undefined" ? window : exports);
<commit_msg>Shortened code for RegExp constructor<commit_after>/*! JSFuck 0.4.0 - http://jsfuck.com */

(function(self){

  var USE_CHAR_CODE = "USE_CHAR_CODE";

  var MIN = 32, MAX = 126;

  var SIMPLE = {
    'false':      '![]',
    'true':       '!![]',
    'undefined':  '[][[]]',
    'NaN':        '+[![]]',
    'Infinity':   '+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]]+[+[]])' // +"1e1000"
  };

  var CONSTRUCTORS = {
    'Array':    '[]',
    'Number':   '(+[])',
    'String':   '([]+[])',
    'Boolean':  '(![])',
    'Function': '[]["filter"]',
    'RegExp':   'Function("return/"+false+"/")()'
  };

  var MAPPING = {
    'a':   '(false+"")[1]',
    'b':   '(Function("return{}")()+"")[2]',
    'c':   '([]["filter"]+"")[3]',
    'd':   '(undefined+"")[2]',
    'e':   '(true+"")[3]',
    'f':   '(false+"")[0]',
    'g':   '(false+[0]+String)[20]',
    'h':   '(+(101))["toString"](21)[1]',
    'i':   '([false]+undefined)[10]',
    'j':   '(Function("return{}")()+"")[10]',
    'k':   '(+(20))["toString"](21)',
    'l':   '(false+"")[2]',
    'm':   '(Number+"")[11]',
    'n':   '(undefined+"")[1]',
    'o':   '(true+[]["filter"])[10]',
    'p':   '(+(211))["toString"](31)[1]',
    'q':   '(+(212))["toString"](31)[1]',
    'r':   '(true+"")[1]',
    's':   '(false+"")[3]',
    't':   '(true+"")[0]',
    'u':   '(undefined+"")[0]',
    'v':   '(+(31))["toString"](32)',
    'w':   '(+(32))["toString"](33)',
    'x':   '(+(101))["toString"](34)[1]',
    'y':   '(NaN+[Infinity])[10]',
    'z':   '(+(35))["toString"](36)',

    'A':   '(+false+Array)[10]',
    'B':   '(+false+Boolean)[10]',
    'C':   'Function("return escape")()(("")["italics"]())[2]',
    'D':   'Function("return escape")()([]["filter"])["slice"]("-1")',
    'E':   '(RegExp+"")[12]',
    'F':   '(+false+Function)[10]',
    'G':   '(false+Function("return Date")()())[30]',
    'H':   USE_CHAR_CODE,
    'I':   '(Infinity+"")[0]',
    //'J':   USE_CHAR_CODE,
    'K':   USE_CHAR_CODE,
    'L':   USE_CHAR_CODE,
    'M':   '(true+Function("return Date")()())[30]',
    'N':   '(NaN+"")[0]',
    'O':   '(NaN+Function("return{}")())[11]',
    'P':   USE_CHAR_CODE,
    'Q':   USE_CHAR_CODE,
    'R':   '(+false+RegExp)[10]',
    'S':   '(+false+String)[10]',
    'T':   '(NaN+Function("return Date")()())[30]',
    'U':   '(NaN+Function("return{}")()["toString"]["call"]())[11]',
    'V':   USE_CHAR_CODE,
    'W':   USE_CHAR_CODE,
    'X':   USE_CHAR_CODE,
    'Y':   USE_CHAR_CODE,
    'Z':   USE_CHAR_CODE,

    ' ':   '(NaN+[]["filter"])[11]',
    '!':   USE_CHAR_CODE,
    '"':   '("")["fontcolor"]()[12]',
    '#':   USE_CHAR_CODE,
    '$':   USE_CHAR_CODE,
    '%':   'Function("return escape")()([]["filter"])[20]',
    '&':   USE_CHAR_CODE,
    '\'':  USE_CHAR_CODE,
    '(':   '(false+[]["filter"])[20]',
    ')':   '(true+[]["filter"])[20]',
    '*':   USE_CHAR_CODE,
    '+':   '(+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]])+[])[2]',
    ',':   '[[]]["concat"]([[]])+""',
    '-':   '(+(.+[0000000001])+"")[2]',
    '.':   '(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]',
    '/':   '(false+[+false])["italics"]()[10]',
    ':':   '(RegExp()+"")[3]',
    ';':   USE_CHAR_CODE,
    '<':   '("")["italics"]()[0]',
    '=':   '("")["fontcolor"]()[11]',
    '>':   '("")["italics"]()[2]',
    '?':   '(RegExp()+"")[2]',
    '@':   USE_CHAR_CODE,
    '[':   '(Function("return{}")()+"")[0]',
    '\\':  USE_CHAR_CODE,
    ']':   '(Function("return{}")()+"")["slice"]("-1")',
    '^':   USE_CHAR_CODE,
    '_':   USE_CHAR_CODE,
    '`':   USE_CHAR_CODE,
    '{':   '(NaN+[]["filter"])[21]',
    '|':   USE_CHAR_CODE,
    '}':   '([]["filter"]+"")["slice"]("-1")',
    '~':   USE_CHAR_CODE
  };

  var GLOBAL = 'Function("return this")()';

  function fillMissingChars(){
    for (var key in MAPPING){
      if (MAPPING[key] === USE_CHAR_CODE){
        MAPPING[key] = 'Function("return unescape")()("%"'+ key.charCodeAt(0).toString(16).replace(/(\d+)/g, "+($1)+\"") + '")';
      }
    }
  }

  function fillMissingDigits(){
    var output, number, i;

    for (number = 0; number < 10; number++){

      output = "+[]";

      if (number > 0){ output = "+!" + output; }
      for (i = 1; i < number; i++){ output = "+!+[]" + output; }
      if (number > 1){ output = output.substr(1); }

      MAPPING[number] = "[" + output + "]";
    }
  }

  function replaceMap(){
    var character = "", value, original, i, key;

    function replace(pattern, replacement){
      value = value.replace(
        new RegExp(pattern, "gi"),
        replacement
      );
    }

    function digitReplacer(_,x) { return MAPPING[x]; }

    function numberReplacer(_,y) {
      var values = y.split("");
      var head = +(values.shift());
      var output = "+[]";

      if (head > 0){ output = "+!" + output; }
      for (i = 1; i < head; i++){ output = "+!+[]" + output; }
      if (head > 1){ output = output.substr(1); }

      return [output].concat(values).join("+").replace(/(\d)/g, digitReplacer);
    }

    for (i = MIN; i <= MAX; i++){
      character = String.fromCharCode(i);
      value = MAPPING[character];
      if(!value) {continue;}
      original = value;

      for (key in CONSTRUCTORS){
        replace("\\b" + key, CONSTRUCTORS[key] + '["constructor"]');
      }

      for (key in SIMPLE){
        replace(key, SIMPLE[key]);
      }

      replace('(\\d\\d+)', numberReplacer);
      replace('\\((\\d)\\)', digitReplacer);
      replace('\\[(\\d)\\]', digitReplacer);

      replace("GLOBAL", GLOBAL);
      replace('\\+""', "+[]");
      replace('""', "[]+[]");

      MAPPING[character] = value;
    }
  }

  function replaceStrings(){
    var regEx = /[^\[\]\(\)\!\+]{1}/g,
      all, value, missing,
      count = MAX - MIN;

    function findMissing(){
      var all, value, done = false;

      missing = {};

      for (all in MAPPING){

        value = MAPPING[all];

        if (value.match(regEx)){
          missing[all] = value;
          done = true;
        }
      }

      return done;
    }

    function mappingReplacer(a, b) {
      return b.split("").join("+");
    }

    function valueReplacer(c) {
      return missing[c] ? c : MAPPING[c];
    }

    for (all in MAPPING){
      MAPPING[all] = MAPPING[all].replace(/\"([^\"]+)\"/gi, mappingReplacer);
    }

    while (findMissing()){
      for (all in missing){
        value = MAPPING[all];
        value = value.replace(regEx, valueReplacer);

        MAPPING[all] = value;
        missing[all] = value;
      }

      if (count-- === 0){
        console.error("Could not compile the following chars:", missing);
      }
    }
  }

  function encode(input, wrapWithEval){
    var output = [];

    if (!input){
      return "";
    }

    var r = "";
    for (var i in SIMPLE) {
      r += i + "|";
    }
    r+=".";

    input.replace(new RegExp(r, 'g'), function(c) {
      var replacement = SIMPLE[c];
      if (replacement) {
        output.push("[" + replacement + "]+[]");
      } else {
        replacement = MAPPING[c];
        if (replacement){
          output.push(replacement);
        } else {
          if (c === "J") {
            replacement =
              "([][" + encode("filter") + "]" +
              "[" + encode("constructor") + "]" +
              "(" + encode("return new Date(200000000)") + ")()+[])[!+[]+!+[]+!+[]+!+[]]";

            output.push(replacement);
            MAPPING[c] = replacement;
          } else {
            replacement =
              "([]+[])[" + encode("constructor") + "]" +
              "[" + encode("fromCharCode") + "]" +
              "(" + encode(c.charCodeAt(0) + "") + ")";

            output.push(replacement);
            MAPPING[c] = replacement;
          }
        }
      }
    });

    output = output.join("+");

    if (/^\d$/.test(input)){
      output += "+[]";
    }

    if (wrapWithEval){
      output = "[][" + encode("filter") + "]" +
        "[" + encode("constructor") + "]" +
        "(" + output + ")()";
    }

    return output;
  }

  fillMissingDigits();
  fillMissingChars();
  replaceMap();
  replaceStrings();

  self.JSFuck = {
    encode: encode
  };
})(typeof(exports) === "undefined" ? window : exports);
<|endoftext|>